Subversion Repositories XServices

Rev

Rev 150 | Rev 153 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
149 brianR 1
/*
2
 *   Copyright 2013 Brian Rosenberger (Brutex Network)
3
 *
4
 *   Licensed under the Apache License, Version 2.0 (the "License");
5
 *   you may not use this file except in compliance with the License.
6
 *   You may obtain a copy of the License at
7
 *
8
 *       http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *   Unless required by applicable law or agreed to in writing, software
11
 *   distributed under the License is distributed on an "AS IS" BASIS,
12
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *   See the License for the specific language governing permissions and
14
 *   limitations under the License.
15
 */
16
package net.brutex.emitter;
17
 
18
import java.io.File;
19
import java.io.FileInputStream;
20
import java.io.FileNotFoundException;
21
import java.io.IOException;
22
import java.io.StringWriter;
150 brianR 23
import java.math.BigInteger;
149 brianR 24
import java.text.SimpleDateFormat;
150 brianR 25
import java.util.ArrayList;
149 brianR 26
import java.util.Iterator;
27
import java.util.List;
28
import java.util.UUID;
29
 
150 brianR 30
import javax.xml.bind.JAXBContext;
31
import javax.xml.bind.JAXBElement;
32
import javax.xml.bind.Marshaller;
33
import javax.xml.namespace.QName;
149 brianR 34
import javax.xml.stream.XMLStreamException;
35
 
150 brianR 36
 
37
 
38
 
39
 
40
 
41
 
42
 
43
 
44
 
45
 
46
 
47
import javax.xml.ws.BindingProvider;
48
 
49
import net.brutex.emitter.util.EmitterUtil;
50
import net.brutex.sbm.sbmappservices72.AEWebservicesFaultFault;
51
import net.brutex.sbm.sbmappservices72.Sbmappservices72;
52
import net.brutex.sbm.sbmappservices72.Sbmappservices72PortType;
53
import net.brutex.sbm.sbmappservices72.api.Auth;
54
import net.brutex.sbm.sbmappservices72.api.MultipleResponseItemOptions;
55
import net.brutex.sbm.sbmappservices72.api.ObjectFactory;
56
import net.brutex.sbm.sbmappservices72.api.SectionsOption;
57
import net.brutex.sbm.sbmappservices72.api.TTItemList;
58
import net.brutex.sbm.sbmappservices72.api.TableIdentifier;
149 brianR 59
import net.brutex.svn.SVNCommitInfo;
60
import net.brutex.svn.SVNLookExecutor;
61
 
62
import org.apache.axiom.om.OMAbstractFactory;
63
import org.apache.axiom.om.OMComment;
64
import org.apache.axiom.om.OMElement;
65
import org.apache.axiom.om.OMFactory;
66
import org.apache.axiom.om.OMNamespace;
67
import org.apache.axiom.om.OMNode;
68
import org.apache.axiom.om.OMText;
69
import org.apache.axiom.om.OMXMLBuilderFactory;
70
import org.apache.axiom.om.xpath.AXIOMXPath;
71
import org.apache.commons.cli.CommandLine;
72
import org.apache.commons.cli.CommandLineParser;
73
import org.apache.commons.cli.HelpFormatter;
74
import org.apache.commons.cli.Option;
75
import org.apache.commons.cli.OptionBuilder;
76
import org.apache.commons.cli.Options;
77
import org.apache.commons.cli.BasicParser;
78
import org.apache.commons.cli.ParseException;
79
import org.apache.commons.configuration.Configuration;
80
import org.apache.commons.configuration.ConfigurationException;
81
import org.apache.commons.configuration.PropertiesConfiguration;
150 brianR 82
import org.apache.cxf.endpoint.Client;
83
import org.apache.cxf.frontend.ClientProxy;
84
import org.apache.cxf.interceptor.LoggingInInterceptor;
85
import org.apache.cxf.interceptor.LoggingOutInterceptor;
86
import org.apache.cxf.message.Message;
149 brianR 87
import org.apache.http.client.ClientProtocolException;
88
import org.apache.log4j.Logger;
89
import org.jaxen.JaxenException;
90
 
91
 
92
/**
93
 * The Class ALFEmitter.
94
 *
95
 * @author Brian Rosenberger, bru(at)brutex.de
96
 * @since 0.1
97
 */
98
public class ALFEmitter {
99
 
150 brianR 100
	public static final String VERSION = "0.1";
101
	private static Logger logger = Logger.getRootLogger();
102
 
103
	//
104
	// Keys to read from the configuration file.
105
	//
106
	private static final String OPTION_SVNLOOK = "svnlook";
152 brianR 107
	private static final String OPTION_LOCALE = "env.LANG";
108
	private static final String OPTION_ENCODING = "env.encoding";
150 brianR 109
	private static final String OPTION_ISSUEPATTERN = "issuepattern";
110
 
111
	private static final String OPTION_EVENTTEMPLATE = "eventtemplate";
112
	private static final String OPTION_EVENTNAMESPACE = "eventnamespace";
113
	private static final String OPTION_EVENTMANAGER_URL = "eventmanager";
114
	private static final String OPTION_EVENTMANAGER_USER = "eventmanager.user";
115
	private static final String OPTION_EVENTMANAGER_PASSWORD = "eventmanager.password";
116
 
117
	private static final String OPTION_SBM_ENDPOINT = "sbmappservices72";
118
	private static final String OPTION_SBM_USER = "sbmuser";
119
	private static final String OPTION_SBM_PASSWORD = "sbmpassword";
120
	private static final String OPTION_SBM_TABLE = "querytable";
121
	private static final String OPTION_SBM_QUERY = "query";
122
 
123
	private static final String OPTION_MARKER_LOGMESSAGE = "marker.logmessage";
124
	private static final String OPTION_MARKER_AUTHOR = "marker.author";
125
	private static final String OPTION_MARKER_REVISION = "marker.revision";
126
	private static final String OPTION_MARKER_ADDEDFILES = "marker.addedfiles";
127
	private static final String OPTION_MARKER_DELETEDFILES = "marker.deletedfiles";
128
	private static final String OPTION_MARKER_CHANGEDFILES = "marker.changedfiles";
129
	private static final String OPTION_MARKER_ISSUES = "marker.issues";
130
	private static final String OPTION_MARKER_INTERNALISSUES = "marker.internalissues";
131
	private static final String OPTION_REMOVE_ISSUES_FROM_COMMIT = "removeissuesfromcommit";
132
 
133
	private static final String OPTION_IS_SOAPENABLED = "isSoapEnabled";
134
	private static final String OPTION_IS_DROPENABLED = "isDropResponse";
135
	private static final String OPTION_IS_FORCEFAILENABLED = "forcefail";
136
	private static final String OPTION_IS_VERIFICATIONENABLED = "isWithVerification";
137
	private static final String OPTION_IS_WSTRACE = "trace";
138
	private static final String OPTION_IS_XMLPROCESSINGENABLED = "isXmlProcessingEnabled";
139
 
140
	//
141
	// Command line parameters
142
	//
149 brianR 143
	private static final String PARAM_REPOS = "repos";
144
	private static final String PARAM_TXN = "txn";
145
	private static final String PARAM_REV = "rev";
146
	private static final String PARAM_CONFIG = "conf";
150 brianR 147
 
148
	//
149
	// Member variables
150
	//
151
	private final String repos;
152
	private final String txn;
153
	private final String rev;
154
	private SVNCommitInfo info;
155
	private OMElement template = null;
156
	private Configuration config;
157
	private String nss = null;
158
	private final long startTime;
159
 
160
	//Member for SBM endpoint configuration
161
	private final String endpoint;
162
	private final String sbm_user;
163
	private final String sbm_pass;
164
	private final String querytable;
165
	private final String query;
149 brianR 166
 
150 brianR 167
 
168
	private final List<String> internalissues = new ArrayList<String>();
169
 
149 brianR 170
	/**
171
	 * The main method.
172
	 *
173
	 * @param args the arguments
174
	 */
175
	public static void main(String[] args) {
176
		long startTime = System.currentTimeMillis();
177
		CommandLineParser parser = new BasicParser();
150 brianR 178
		CommandLine cmd = null;
149 brianR 179
		try {
180
			cmd = parser.parse( getOptions(), args);
181
		} catch (ParseException e1) {
182
			logger.error(e1.getMessage());
183
			printHelp();
184
			System.exit(1);
185
		}
150 brianR 186
		try {
187
			ALFEmitter emitter = new ALFEmitter(cmd, startTime);
188
		} catch (ConfigurationException e) {
189
			System.exit(1);
190
		}
149 brianR 191
		long endTime = System.currentTimeMillis();
192
		logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds.");
193
		System.exit(0);
194
	}
195
 
150 brianR 196
	/**
197
	 * Read a configuration parameter from the config file
198
	 * Creates log messages according to parameters.
199
	 *
200
	 * @param key				property name
201
	 * @param defaultValue		default value or null
202
	 * @param isRequired		wether or not this is a required option
203
	 * @param logmessage		optional log message (or null)
204
	 * @return					property value
205
	 * @throws ConfigurationException
206
	 */
207
	private Object readConfProperty(String key, Object defaultValue, boolean isRequired, PropertyType type, String logmessage) throws ConfigurationException {
208
		Object value = null;
209
		switch (type) {
210
		case BOOLEAN:
211
			value = config.getBoolean(key, (Boolean) defaultValue);
212
			break;
213
		case STRINGARRAY:
214
			value = config.getStringArray(key);
215
			defaultValue = null;
216
			break;
217
 
218
		default:
219
			value = config.getString(key, (String) defaultValue);
220
			break;
221
		}
222
 
223
		if(isRequired && value == null) {
224
			//required property
225
			if(defaultValue == null) {
226
				//No value, no default
227
				String s = String.format("Could not load a value for the key '%s' from the configuration file. This is a required property without a default.", key);
228
				logger.error(s);
229
				throw new ConfigurationException(s);
230
			}
231
			if(defaultValue!=null) {
232
				//No value, but default
233
				logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is required.", value, key));
234
			}
235
		}
236
		if( (! isRequired) && value == null) {
237
			//not required
238
			if(value == null && defaultValue == null) {
239
				//No value, no default
240
				String s = String.format("Could not load a value for the key '%s' from the configuration file. This property has no default, but it is optional anyway.", key);
241
				logger.warn(s);
242
			}
243
			if(value == null && defaultValue!=null) {
244
				//No value, but default
245
				logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is optional.", value, key));
246
			}
247
		}
152 brianR 248
		if(logmessage==null) logmessage="";
249
		if(value!=null) logger.debug(String.format("Using property value '%s' for key '%s'. %s", value, key, logmessage));
150 brianR 250
		return value;
251
	}
252
 
253
 
254
	private String readConfPropertyAsString(String key, String defaultValue, boolean isRequired, String logmessage) throws ConfigurationException {
255
		return (String) readConfProperty(key, defaultValue, isRequired, PropertyType.STRING, logmessage);
256
	}
257
	private String[] readConfPropertyAsStringArray(String key, boolean isRequired, String logmessage) throws ConfigurationException {
258
		return (String[]) readConfProperty(key, null, isRequired, PropertyType.STRINGARRAY, logmessage);
259
	}
260
	private boolean readConfPropertyAsBoolean(String key, boolean defaultValue, boolean isRequired, String logmessage) throws ConfigurationException {
261
		Boolean b =  (Boolean) readConfProperty(key, defaultValue, isRequired, PropertyType.BOOLEAN, logmessage);
262
		return b.booleanValue();
263
	}
149 brianR 264
 
150 brianR 265
	private ALFEmitter(CommandLine cmd, long startTime) throws ConfigurationException {
149 brianR 266
		this.startTime = startTime;
267
		repos = cmd.getOptionValue(PARAM_REPOS);
268
		txn = cmd.getOptionValue(PARAM_TXN);
269
		rev = cmd.getOptionValue(PARAM_REV);
270
		String config_file = cmd.getOptionValue(PARAM_CONFIG, "emitter.properties");
150 brianR 271
		EmitterUtil.verifyFile(config_file, false, false);
149 brianR 272
 
273
		logger.debug(String.format("Using REPOS='%s' and TXN='%s'.", repos, txn));
274
 
275
		config = null;
276
		try {
277
			config = new PropertiesConfiguration(config_file);
278
		} catch (ConfigurationException e) {
279
			logger.error("Could not find/ load '"+config_file+"' file.", e);
280
			System.exit(1);
281
		}
282
 
283
		/*
284
		 * Load Properties from Configuration file
285
		 */
286
		//it might be interesting to look into SVNKit
287
		//for a pure Java implementation in future
150 brianR 288
			final String svnlook			=	readConfPropertyAsString(OPTION_SVNLOOK, null, true, null);
289
			EmitterUtil.verifyFile(svnlook, false, true);
152 brianR 290
			final String locale				=	readConfPropertyAsString(OPTION_LOCALE, "de_DE.UTF-8", true, null);
291
			final String encoding			=	readConfPropertyAsString(OPTION_LOCALE, "UTF-8", true, "Note that this should match your selected '"+OPTION_LOCALE+"'.");
150 brianR 292
 
293
			// Issue Id RegEx to parse commit message
294
			final String[] issuepatterns = readConfPropertyAsStringArray(OPTION_ISSUEPATTERN, false, null);
295
			StringBuilder sb = new StringBuilder(); for(String s : issuepatterns) sb.append(s);
296
			logger.debug(String.format("Using issue id patterns: '%s'.", sb.toString()));
297
 
298
			// Flags to indicate what should be done
299
			final boolean isSoapEnabled 	= readConfPropertyAsBoolean(OPTION_IS_SOAPENABLED, true, true, null);
300
			final boolean isXmlProcessingEnabled 	= readConfPropertyAsBoolean(OPTION_IS_XMLPROCESSINGENABLED, true, true, null);
301
			final boolean isWithVerification= readConfPropertyAsBoolean(OPTION_IS_VERIFICATIONENABLED, false, true, null);
302
			final boolean isRemoveIssues	= readConfPropertyAsBoolean(OPTION_REMOVE_ISSUES_FROM_COMMIT, false, true, "");
303
 
304
			/*
305
			 * SVNLook phase
306
			 * Use svnlook to obtain information from SVN
307
			 */
308
			SVNLookExecutor exec = new SVNLookExecutor(new File(svnlook), repos);
309
			if(cmd.hasOption(PARAM_TXN)) exec.setTXN(txn);
310
			if(cmd.hasOption(PARAM_REV)) exec.setRev(rev);
152 brianR 311
			exec.setEncoding(encoding);
312
			exec.setLocale(locale);
313
 
150 brianR 314
			info = exec.getCommitInfo();
315
			info.parseIssues(issuepatterns, isRemoveIssues);
316
 
317
			logger.debug("SVNCommitInfo author: "+ info.getAuthor());
318
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
319
			String datestring = f.format(info.getDate());
320
			datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
321
			logger.debug("SVNCommitInfo date: "+ datestring);
322
			logger.debug("SVNCommitInfo log message: "+ info.getLogmessage());
323
			logger.debug("SVNCommitInfo file list: "+ info.getChangeFileListAsString());
324
 
325
			/*
326
			 * Verification phase
327
			 */
328
			boolean isTrace = false;
329
			if(isWithVerification) {
330
				sbm_user 					= 	readConfPropertyAsString(OPTION_SBM_USER, null, true, null);
331
				sbm_pass 					= 	readConfPropertyAsString(OPTION_SBM_PASSWORD, null, false, null);
332
				endpoint					= 	readConfPropertyAsString(OPTION_SBM_ENDPOINT, "http://localhost/gsoap/gsoap_ssl.dll?sbmappservices72", true, null);
333
				querytable					= 	readConfPropertyAsString(OPTION_SBM_TABLE, null, true, null);
334
				query						= 	readConfPropertyAsString(OPTION_SBM_QUERY, null, false, null);
335
				isTrace						=	readConfPropertyAsBoolean(OPTION_IS_WSTRACE, false, true, null);
336
 
337
				logger.debug(String.format("Starting verification for '%s' issues in the list.", info.getIssues().size()));
338
				boolean isOK = verify(info.getIssues(), isTrace);
339
				if(! isOK ) {
340
					logger.error("Verification of issue failed. No matching issue was found.");
341
					System.exit(1);
342
				}
343
			} else {
344
				sbm_user = null; sbm_pass=null; endpoint=null; querytable=null; query=null;
345
			}
346
 
347
			/*
348
			 * XML processing phase
349
			 */
350
			if(isXmlProcessingEnabled) {
351
 
352
 
353
			}
354
 
355
 
356
 
357
			/*
358
			 * ALF Event Send phase
359
			 */
360
			String eventmanager = null;
361
			if(isSoapEnabled) {
362
				eventmanager 		= 	readConfPropertyAsString(OPTION_EVENTMANAGER_URL, null, true, null);
363
			}
364
 
365
 
366
 
149 brianR 367
 
150 brianR 368
		/**
369
		 * Event XML Erzeugen
370
		 */
371
		try {
372
			String resultxml=null;
373
			if(isXmlProcessingEnabled) {
374
 
375
				processXml();
376
				addALFSecurity();
377
				addEventHeader();
378
 
379
				// Serialize xml message to String
380
				StringWriter out = new StringWriter();
381
				template.getParent().serialize(out);
382
				out.flush();
383
 
384
				resultxml =  out.getBuffer().toString();
385
				logger.debug("ALFEvent result:\n"+resultxml);
149 brianR 386
 
150 brianR 387
			} else {
388
				logger.debug("Xml processing is deactivated.");
389
			}
149 brianR 390
 
150 brianR 391
			if(isSoapEnabled && isXmlProcessingEnabled) {
392
				final boolean isDropResponse 	= readConfPropertyAsBoolean(OPTION_IS_DROPENABLED, true, true, null);
393
				SimpleHttpEvent sender = new SimpleHttpEvent(eventmanager, resultxml);
394
				sender.sendSoap(isDropResponse);
395
				logger.debug(String.format("Sending/ receiving the soap message took '%s' milliseconds.", sender.getDuration()));
396
			} else {
397
				logger.warn("Sending soap message and/ or xml processing is deactivated.");
398
			}
399
 
400
 
401
		} catch (FileNotFoundException e) {
402
			logger.error(e.getMessage(), e);
149 brianR 403
			System.exit(1);
150 brianR 404
		} catch (ClientProtocolException e) {
405
			logger.error(e.getMessage(), e);
406
			System.exit(1);
407
		} catch (IOException e) {
408
			logger.error(e.getMessage(), e);
409
			System.exit(1);
410
		} catch (XMLStreamException e) {
411
			logger.error(e.getMessage(), e);
412
			System.exit(1);
413
		} catch (JaxenException e) {
414
			logger.error(e.getMessage(), e);
415
			System.exit(1);
416
		} finally {
417
			logger.debug("Total execution took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
418
			String forcefail = config.getString(OPTION_IS_FORCEFAILENABLED, "");
419
			if(forcefail.length()>0) {
420
				logger.warn("Force fail is active. All commits will be blocked.");
421
				System.exit(1);
422
			}
423
 
149 brianR 424
		}
425
 
150 brianR 426
	}
427
		private void addEventHeader() throws JaxenException {
428
			AXIOMXPath path = new AXIOMXPath("//bru1:Base/bru1:EventId");
429
			path.addNamespace("bru1",  nss);
430
			OMElement n = (OMElement) path.selectSingleNode(template);
431
			if(n==null) {
432
				logger.error("<Base> element in message is incomplete. <EventId> is missing.");
433
			} else {
434
				n.addChild( n.getOMFactory().createOMText("1"));
435
			}
149 brianR 436
 
150 brianR 437
			path = new AXIOMXPath("//bru1:Base/bru1:ObjectId");
438
			path.addNamespace("bru1",  nss);
439
			n = (OMElement) path.selectSingleNode(template);
440
			if(n==null) {
441
				logger.error("<Base> element in message is incomplete. <ObjectId> is missing.");
442
			} else {
443
				n.addChild( n.getOMFactory().createOMText(info.getTxn() ));
444
			}
445
		}
446
 
447
		private void addALFSecurity() throws ConfigurationException, JaxenException {
448
			final String eventmanager_user 	= 	readConfPropertyAsString(OPTION_EVENTMANAGER_USER, null, false, null);
449
			final String eventmanager_pass 	= 	readConfPropertyAsString(OPTION_EVENTMANAGER_PASSWORD, null, false, null);
149 brianR 450
			AXIOMXPath path = new AXIOMXPath("//bru1:User");
451
			OMNamespace ns = template.findNamespace(nss, null);
452
			path.addNamespace("bru1", nss);
453
			OMElement n = (OMElement) path.selectSingleNode(template);
454
			if(n== null) {
455
				logger.warn( String.format("<User> element was not found in namespace '%s'. Cannot add ALFSecurity elements. This is required since SBM 10.1.x.", nss));
456
			} else {
457
				/*
458
				 *  <ns:User>
459
            		<!--Optional:-->
460
               		<ns:ALFSecurity>
461
                  		<ns:UsernameToken>
462
                     		<ns:Username>admin</ns:Username>
463
                     		<ns:Password></ns:Password>
464
                  		</ns:UsernameToken>
465
               		</ns:ALFSecurity>
466
					</ns:User>
467
				 */
468
				n.removeChildren();
469
				OMFactory fac = n.getOMFactory();
470
				fac.createOMComment(n, "Generated by SVN-ALFEmitter");
471
				OMElement sec = fac.createOMElement("ALFSecurity", ns);
472
				OMElement token = fac.createOMElement("UsernameToken", ns);
473
				OMElement user = fac.createOMElement("Username", ns);
474
				user.addChild( fac.createOMText(eventmanager_user));
475
				OMElement pass = fac.createOMElement("Password", ns);
476
				pass.addChild(fac.createOMText(eventmanager_pass, OMNode.CDATA_SECTION_NODE));
477
				token.addChild( user );
478
				token.addChild( pass);
479
				sec.addChild(token);
480
				n.addChild(sec);
481
			}
150 brianR 482
		}
483
 
484
		private void processXml() throws ConfigurationException, JaxenException {
485
			// read additional configuration
486
			final String eventtemplate 		= 	readConfPropertyAsString(OPTION_EVENTTEMPLATE, null, true, null);
487
			EmitterUtil.verifyFile(eventtemplate, false, false);
488
			try {
489
				template = OMXMLBuilderFactory.createOMBuilder(new FileInputStream(new File(eventtemplate)))
490
						.getDocument().getOMDocumentElement();
491
			} catch (FileNotFoundException e1) {
492
				logger.error(String.format("Could not load XML event template from file '%s'.", eventtemplate), e1);
493
				System.exit(1);
149 brianR 494
			}
150 brianR 495
			nss 	= 	readConfPropertyAsString(OPTION_EVENTNAMESPACE, "http://www.eclipse.org/alf/schema/EventBase/1", true, null);
496
			final String marker_logmessage 	= 	readConfPropertyAsString(OPTION_MARKER_LOGMESSAGE, "@@logmessage@@", true, null);
497
			final String marker_author 		= 	readConfPropertyAsString(OPTION_MARKER_AUTHOR, "@@author@@", true, null);
498
			final String marker_revision	= 	readConfPropertyAsString(OPTION_MARKER_REVISION, "@@revision@@", true, null);
499
			final String marker_addedfiles 	= 	readConfPropertyAsString(OPTION_MARKER_ADDEDFILES, "@@addedfiles@@", true, null);
500
			final String marker_deletedfiles = 	readConfPropertyAsString(OPTION_MARKER_DELETEDFILES, "@@deletedfiles@@", true, null);
501
			final String marker_changedfiles = 	readConfPropertyAsString(OPTION_MARKER_CHANGEDFILES, "@@changedfiles@@", true, null);
502
			final String marker_fileselementname = readConfPropertyAsString("marker.fileselementname", "file", true, null);
503
			final String marker_issues 		= 	readConfPropertyAsString(OPTION_MARKER_ISSUES, "@@issues@@", true, null);
504
			final String marker_issueselementname = readConfPropertyAsString("marker.issueselementname", "issue", true, null);
505
			final String marker_internalissues    = readConfPropertyAsString(OPTION_MARKER_INTERNALISSUES, "@@internalissues@@", true, null);
506
 
507
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
508
			String datestring = f.format(info.getDate());
509
			datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
149 brianR 510
 
150 brianR 511
			// add content from SVNCommitInfo object where
512
			// XML commit markers are
513
			addElement( marker_logmessage, info.getLogmessage(), true);
514
			addElement(marker_author, info.getAuthor(), false);
515
			addElement(marker_revision, info.getRev(), false);
516
			addElement("@@timestamp@@", datestring, false);
517
			addElements(marker_changedfiles, info.getChangedFiles(), marker_fileselementname);
518
			addElements(marker_deletedfiles, info.getDeletedFiles(), marker_fileselementname);
519
			addElements(marker_addedfiles, info.getAddedFiles(), marker_fileselementname);
520
			addElements(marker_issues, info.getIssues(), marker_issueselementname);
521
			addElements(marker_internalissues, internalissues, marker_issueselementname);
149 brianR 522
 
150 brianR 523
		}
524
 
525
		private boolean verify(List<String> issues, boolean isTrace) {
526
 
527
			Sbmappservices72 ss = new Sbmappservices72(ClassLoader.getSystemResource("sbmappservices72.wsdl") );
528
			Sbmappservices72PortType port = ss.getSbmappservices72();
149 brianR 529
 
150 brianR 530
			Client client = ClientProxy.getClient(port);
531
			if(isTrace) {
532
		        client.getInInterceptors().add(new LoggingInInterceptor());
533
		        client.getOutInterceptors().add(new LoggingOutInterceptor());
149 brianR 534
			}
150 brianR 535
			BindingProvider bindingProvider = (BindingProvider) port;
536
	        bindingProvider.getRequestContext().put(
537
	        BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
149 brianR 538
 
150 brianR 539
			ObjectFactory fac = new ObjectFactory();
540
			Auth auth = fac.createAuth();
541
			auth.setUserId(fac.createAuthUserId(sbm_user));
542
			auth.setPassword(fac.createAuthPassword(sbm_pass));
149 brianR 543
 
150 brianR 544
			TableIdentifier table = fac.createTableIdentifier();
545
			table.setDbName(fac.createTableIdentifierDbName(querytable));
546
 
547
			MultipleResponseItemOptions options = fac.createMultipleResponseItemOptions();
548
			options.setSections(SectionsOption.SECTIONS_NONE);
549
 
550
			for(String issue : issues) {
551
				issue = issue.replaceAll("[^0-9]", "");
552
				String queryWhereClause = "TS_ISSUEID = '"+issue+"'";
553
				if(query!=null && query.length()>0) queryWhereClause = queryWhereClause + " And " + query;
554
				logger.debug(String.format("Using query against table '%s'. Query where clause: '%s'", querytable, queryWhereClause ));
555
				try {
556
					TTItemList items = port.getItemsByQuery(auth, table, queryWhereClause, "", null, BigInteger.valueOf(1), options);
557
 
558
					//Marshaller m = JAXBContext.newInstance(TTItemList.class).createMarshaller();
559
					//m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
560
					//m.marshal( new JAXBElement<TTItemList>(new QName("uri","local"), TTItemList.class, items), System.err);
561
 
562
					logger.debug(String.format("Got Response from getItemsByQuery"));
563
					if(items!=null) {
564
						logger.debug(String.format("Verification query matched '%s' item(s) for issue '%s.'",items.getTotalCount(), issue));
565
					}
566
					if(items.getTotalCount().intValue()<=0) {
567
						return false;
568
					} else {
569
						internalissues.add(items.getItem().get(0).getId().getValue().getTableIdItemId().getValue());
570
					}
571
 
572
				} catch (AEWebservicesFaultFault e) {
573
					logger.debug("Web service fault: " + e.getFaultInfo());
574
				} catch (Exception e) {
575
					logger.debug("Unknown Exception", e);
576
				}
149 brianR 577
			}
150 brianR 578
			return true;
149 brianR 579
 
580
	}
150 brianR 581
 
149 brianR 582
		private void addElement(String pattern, String newCdata, boolean wrapCDATA) throws JaxenException {
583
			OMComment comment = findComment(pattern);
584
			if(comment!=null) {
585
				OMFactory fac = OMAbstractFactory.getOMFactory();
586
				int type = OMNode.TEXT_NODE;
587
				if(wrapCDATA) {
588
					type = OMNode.CDATA_SECTION_NODE;
589
				}
590
				OMText text = fac.createOMText(newCdata, type);
591
				comment.insertSiblingAfter(text);
592
			}
593
		}
594
 
595
		private void addElements(String pattern, List<String> files, String elementName) throws JaxenException {
596
			if(files.size()<=0) return;
597
			OMComment comment = findComment(pattern);
598
			if(comment!=null) {
599
				OMFactory fac = OMAbstractFactory.getOMFactory();
600
				OMNamespace ns = template.findNamespace(nss, null);
601
				if(ns == null) logger.error(String.format("The namespace '%s' is not defined in the template.", nss));
602
				for(String s : files) {
603
					OMElement e = fac.createOMElement(elementName, ns);
604
					OMText text = fac.createOMText(s, OMNode.TEXT_NODE);
605
					e.addChild(text);
606
					comment.insertSiblingAfter(e);
607
				}
608
			}
609
		}
610
 
611
 
612
		private OMComment findComment(String pattern) throws JaxenException {
613
			AXIOMXPath path = new AXIOMXPath("//comment()[. = '"+pattern+"'][1]");
614
			//OMNamespace ns = template.findNamespace(nss, null);
615
			path.addNamespace("bru1", nss);
616
			OMComment n = (OMComment) path.selectSingleNode(template);
617
			if(n!=null) return n;
618
			logger.warn("Comment '"+pattern+"' was not found in the XML template.");
619
			return null;
620
		}
621
 
622
	@SuppressWarnings("static-access")
623
	private static Options getOptions() {
624
		Option repository = OptionBuilder.withArgName( "repository" )
625
											.hasArg()
626
											.withLongOpt("repository")
627
											.withDescription(  "Path or URL to the SVN repository." )
628
											.create( PARAM_REPOS );
629
		repository.setRequired(true);
630
 
631
		Option txn = OptionBuilder.withArgName( "transactionid" )
632
											.hasArg()
633
											.withLongOpt("transaction")
634
											.withDescription(  "The SVN transaction id to examine (TXN). You cannot combine txn with -rev. "
635
													+ "When a txn is given, the repository path must be a local path.")
636
											.create( PARAM_TXN );
637
		Option rev = OptionBuilder.withArgName( "revision" )
638
				.hasArg()
639
				.withDescription(  "A revision to examine. You cannot combine revision with -txn." )
640
				.create( PARAM_REV );
641
		Option config = OptionBuilder.withArgName( "config_file" )
642
				.hasArg()
643
				.withLongOpt("config")
644
				.withDescription(  "The configuration file to use. Defaults to 'emitter.properties'.")
645
				.create( PARAM_CONFIG );
646
 
647
		Options options = new Options();
648
		options.addOption(repository);
649
		options.addOption(txn);
650
		options.addOption(rev);
651
		options.addOption(config);
652
		return options;
653
	}
654
 
655
	private static void printHelp() {
656
		// automatically generate the help statement
657
		HelpFormatter formatter = new HelpFormatter();
150 brianR 658
		String header = "\nSVN-ALFEventEmitter " + VERSION +", a SVN hook implemented in Java to emit Eclipse ALFEvents on commit.\n\n";
149 brianR 659
		String footer = "Please send bug reports to bru@brutex.de.\n(c)2013 Brian Rosenberger";
660
		formatter.printHelp("java -jar SVN-ALFEventEmitter", header, getOptions(), footer, true);
661
	}
662
 
663
 
150 brianR 664
 
665
	private enum PropertyType {
666
		STRING(), STRINGARRAY(), BOOLEAN();
667
	}
668
 
669
 
149 brianR 670
}