Subversion Repositories XServices

Rev

Rev 168 | Rev 170 | 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;
167 brianR 24
import java.net.MalformedURLException;
149 brianR 25
import java.text.SimpleDateFormat;
150 brianR 26
import java.util.ArrayList;
167 brianR 27
import java.util.HashMap;
149 brianR 28
import java.util.List;
167 brianR 29
import java.util.Map;
169 brianR 30
 
149 brianR 31
import javax.xml.stream.XMLStreamException;
150 brianR 32
import net.brutex.emitter.util.EmitterUtil;
33
import net.brutex.sbm.sbmappservices72.AEWebservicesFaultFault;
34
import net.brutex.sbm.sbmappservices72.Sbmappservices72PortType;
35
import net.brutex.sbm.sbmappservices72.api.Auth;
36
import net.brutex.sbm.sbmappservices72.api.MultipleResponseItemOptions;
37
import net.brutex.sbm.sbmappservices72.api.ObjectFactory;
38
import net.brutex.sbm.sbmappservices72.api.SectionsOption;
39
import net.brutex.sbm.sbmappservices72.api.TTItemList;
40
import net.brutex.sbm.sbmappservices72.api.TableIdentifier;
167 brianR 41
import net.brutex.svn.SVNAdminCommand;
42
import net.brutex.svn.SVNAdminExecutor;
149 brianR 43
import net.brutex.svn.SVNCommitInfo;
44
import net.brutex.svn.SVNLookExecutor;
45
 
46
import org.apache.axiom.om.OMAbstractFactory;
47
import org.apache.axiom.om.OMComment;
48
import org.apache.axiom.om.OMElement;
49
import org.apache.axiom.om.OMFactory;
50
import org.apache.axiom.om.OMNamespace;
51
import org.apache.axiom.om.OMNode;
52
import org.apache.axiom.om.OMText;
53
import org.apache.axiom.om.OMXMLBuilderFactory;
54
import org.apache.axiom.om.xpath.AXIOMXPath;
55
import org.apache.commons.cli.CommandLine;
56
import org.apache.commons.cli.CommandLineParser;
57
import org.apache.commons.cli.HelpFormatter;
58
import org.apache.commons.cli.Option;
59
import org.apache.commons.cli.OptionBuilder;
60
import org.apache.commons.cli.Options;
61
import org.apache.commons.cli.BasicParser;
62
import org.apache.commons.cli.ParseException;
63
import org.apache.commons.configuration.Configuration;
64
import org.apache.commons.configuration.ConfigurationException;
65
import org.apache.commons.configuration.PropertiesConfiguration;
150 brianR 66
import org.apache.cxf.endpoint.Client;
67
import org.apache.cxf.frontend.ClientProxy;
68
import org.apache.cxf.interceptor.LoggingInInterceptor;
69
import org.apache.cxf.interceptor.LoggingOutInterceptor;
169 brianR 70
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
149 brianR 71
import org.apache.http.client.ClientProtocolException;
72
import org.apache.log4j.Logger;
73
import org.jaxen.JaxenException;
74
 
75
 
76
/**
77
 * The Class ALFEmitter.
78
 *
79
 * @author Brian Rosenberger, bru(at)brutex.de
80
 * @since 0.1
81
 */
82
public class ALFEmitter {
83
 
150 brianR 84
	public static final String VERSION = "0.1";
85
	private static Logger logger = Logger.getRootLogger();
86
 
87
	//
88
	// Keys to read from the configuration file.
89
	//
90
	private static final String OPTION_SVNLOOK = "svnlook";
167 brianR 91
	private static final String OPTION_SVNADMIN = "svnadmin";
152 brianR 92
	private static final String OPTION_LOCALE = "env.LANG";
93
	private static final String OPTION_ENCODING = "env.encoding";
150 brianR 94
	private static final String OPTION_ISSUEPATTERN = "issuepattern";
95
 
96
	private static final String OPTION_EVENTTEMPLATE = "eventtemplate";
97
	private static final String OPTION_EVENTNAMESPACE = "eventnamespace";
98
	private static final String OPTION_EVENTMANAGER_URL = "eventmanager";
99
	private static final String OPTION_EVENTMANAGER_USER = "eventmanager.user";
100
	private static final String OPTION_EVENTMANAGER_PASSWORD = "eventmanager.password";
101
 
102
	private static final String OPTION_SBM_ENDPOINT = "sbmappservices72";
103
	private static final String OPTION_SBM_USER = "sbmuser";
104
	private static final String OPTION_SBM_PASSWORD = "sbmpassword";
105
	private static final String OPTION_SBM_TABLE = "querytable";
106
	private static final String OPTION_SBM_QUERY = "query";
107
 
108
	private static final String OPTION_MARKER_LOGMESSAGE = "marker.logmessage";
109
	private static final String OPTION_MARKER_AUTHOR = "marker.author";
110
	private static final String OPTION_MARKER_REVISION = "marker.revision";
111
	private static final String OPTION_MARKER_ADDEDFILES = "marker.addedfiles";
112
	private static final String OPTION_MARKER_DELETEDFILES = "marker.deletedfiles";
113
	private static final String OPTION_MARKER_CHANGEDFILES = "marker.changedfiles";
114
	private static final String OPTION_MARKER_ISSUES = "marker.issues";
115
	private static final String OPTION_MARKER_INTERNALISSUES = "marker.internalissues";
116
	private static final String OPTION_REMOVE_ISSUES_FROM_COMMIT = "removeissuesfromcommit";
117
 
118
	private static final String OPTION_IS_SOAPENABLED = "isSoapEnabled";
119
	private static final String OPTION_IS_DROPENABLED = "isDropResponse";
120
	private static final String OPTION_IS_FORCEFAILENABLED = "forcefail";
121
	private static final String OPTION_IS_VERIFICATIONENABLED = "isWithVerification";
167 brianR 122
	private static final String OPTION_IS_UPDATECOMMITMESSAGE = "isWithMessageUpdate";
150 brianR 123
	private static final String OPTION_IS_WSTRACE = "trace";
124
	private static final String OPTION_IS_XMLPROCESSINGENABLED = "isXmlProcessingEnabled";
125
 
126
	//
127
	// Command line parameters
128
	//
149 brianR 129
	private static final String PARAM_REPOS = "repos";
130
	private static final String PARAM_TXN = "txn";
131
	private static final String PARAM_REV = "rev";
132
	private static final String PARAM_CONFIG = "conf";
150 brianR 133
 
134
	//
169 brianR 135
	//
136
	//
137
	private static final String CACHE_SBMPORT = "sbmappservices72";
138
 
139
	//
150 brianR 140
	// Member variables
141
	//
142
	private final String repos;
143
	private final String txn;
144
	private final String rev;
145
	private SVNCommitInfo info;
146
	private OMElement template = null;
147
	private Configuration config;
148
	private String nss = null;
149
	private final long startTime;
150
 
151
	//Member for SBM endpoint configuration
152
	private final String endpoint;
153
	private final String sbm_user;
154
	private final String sbm_pass;
155
	private final String querytable;
156
	private final String query;
149 brianR 157
 
150 brianR 158
 
159
	private final List<String> internalissues = new ArrayList<String>();
167 brianR 160
	//SBM IssueTypePrefix+IssueId, Title
161
	private final Map<String, String> issues_titles = new HashMap<String, String>();
150 brianR 162
 
149 brianR 163
	/**
164
	 * The main method.
165
	 *
166
	 * @param args the arguments
167
	 */
168
	public static void main(String[] args) {
169
		long startTime = System.currentTimeMillis();
170
		CommandLineParser parser = new BasicParser();
150 brianR 171
		CommandLine cmd = null;
149 brianR 172
		try {
173
			cmd = parser.parse( getOptions(), args);
174
		} catch (ParseException e1) {
175
			logger.error(e1.getMessage());
176
			printHelp();
177
			System.exit(1);
178
		}
150 brianR 179
		try {
180
			ALFEmitter emitter = new ALFEmitter(cmd, startTime);
181
		} catch (ConfigurationException e) {
182
			System.exit(1);
167 brianR 183
		} catch (MalformedURLException e) {
184
			logger.error("Could not find/ load wsdl url.", e);
185
			System.exit(1);
150 brianR 186
		}
149 brianR 187
		long endTime = System.currentTimeMillis();
188
		logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds.");
189
		System.exit(0);
190
	}
191
 
150 brianR 192
	/**
193
	 * Read a configuration parameter from the config file
194
	 * Creates log messages according to parameters.
195
	 *
196
	 * @param key				property name
197
	 * @param defaultValue		default value or null
198
	 * @param isRequired		wether or not this is a required option
199
	 * @param logmessage		optional log message (or null)
200
	 * @return					property value
201
	 * @throws ConfigurationException
202
	 */
203
	private Object readConfProperty(String key, Object defaultValue, boolean isRequired, PropertyType type, String logmessage) throws ConfigurationException {
204
		Object value = null;
205
		switch (type) {
206
		case BOOLEAN:
207
			value = config.getBoolean(key, (Boolean) defaultValue);
208
			break;
209
		case STRINGARRAY:
210
			value = config.getStringArray(key);
211
			defaultValue = null;
212
			break;
213
 
214
		default:
215
			value = config.getString(key, (String) defaultValue);
216
			break;
217
		}
218
 
219
		if(isRequired && value == null) {
220
			//required property
221
			if(defaultValue == null) {
222
				//No value, no default
223
				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);
224
				logger.error(s);
225
				throw new ConfigurationException(s);
226
			}
227
			if(defaultValue!=null) {
228
				//No value, but default
229
				logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is required.", value, key));
230
			}
231
		}
232
		if( (! isRequired) && value == null) {
233
			//not required
234
			if(value == null && defaultValue == null) {
235
				//No value, no default
236
				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);
237
				logger.warn(s);
238
			}
239
			if(value == null && defaultValue!=null) {
240
				//No value, but default
169 brianR 241
				logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is optional.", value, key));
150 brianR 242
			}
243
		}
152 brianR 244
		if(logmessage==null) logmessage="";
169 brianR 245
		if(key.contains("password") && value!=null ) {
246
			logger.debug(String.format("Using property value '%s' for key '%s'. %s", "******", key, logmessage));
247
		} else {
248
			if(value!=null) logger.debug(String.format("Using property value '%s' for key '%s'. %s", value, key, logmessage));
249
		}
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
 
167 brianR 265
	private ALFEmitter(CommandLine cmd, long startTime) throws ConfigurationException, MalformedURLException {
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);
167 brianR 280
			this.exit(1);
149 brianR 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);
153 brianR 291
			final String encoding			=	readConfPropertyAsString(OPTION_ENCODING, "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, "");
167 brianR 303
			final boolean isWithCommitUpdate= readConfPropertyAsBoolean(OPTION_IS_UPDATECOMMITMESSAGE, false, true, "");
150 brianR 304
 
305
			/*
306
			 * SVNLook phase
307
			 * Use svnlook to obtain information from SVN
308
			 */
309
			SVNLookExecutor exec = new SVNLookExecutor(new File(svnlook), repos);
310
			if(cmd.hasOption(PARAM_TXN)) exec.setTXN(txn);
311
			if(cmd.hasOption(PARAM_REV)) exec.setRev(rev);
152 brianR 312
			exec.setEncoding(encoding);
313
			exec.setLocale(locale);
314
 
150 brianR 315
			info = exec.getCommitInfo();
316
			info.parseIssues(issuepatterns, isRemoveIssues);
317
 
318
			logger.debug("SVNCommitInfo author: "+ info.getAuthor());
319
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
320
			String datestring = f.format(info.getDate());
321
			datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
322
			logger.debug("SVNCommitInfo date: "+ datestring);
323
			logger.debug("SVNCommitInfo log message: "+ info.getLogmessage());
324
			logger.debug("SVNCommitInfo file list: "+ info.getChangeFileListAsString());
325
 
326
			/*
327
			 * Verification phase
328
			 */
329
			boolean isTrace = false;
330
			if(isWithVerification) {
331
				sbm_user 					= 	readConfPropertyAsString(OPTION_SBM_USER, null, true, null);
332
				sbm_pass 					= 	readConfPropertyAsString(OPTION_SBM_PASSWORD, null, false, null);
333
				endpoint					= 	readConfPropertyAsString(OPTION_SBM_ENDPOINT, "http://localhost/gsoap/gsoap_ssl.dll?sbmappservices72", true, null);
334
				querytable					= 	readConfPropertyAsString(OPTION_SBM_TABLE, null, true, null);
335
				query						= 	readConfPropertyAsString(OPTION_SBM_QUERY, null, false, null);
336
				isTrace						=	readConfPropertyAsBoolean(OPTION_IS_WSTRACE, false, true, null);
337
 
338
				logger.debug(String.format("Starting verification for '%s' issues in the list.", info.getIssues().size()));
339
				boolean isOK = verify(info.getIssues(), isTrace);
340
				if(! isOK ) {
341
					logger.error("Verification of issue failed. No matching issue was found.");
167 brianR 342
					this.exit(1);
150 brianR 343
				}
344
			} else {
345
				sbm_user = null; sbm_pass=null; endpoint=null; querytable=null; query=null;
346
			}
347
 
348
			/*
167 brianR 349
			 * Modify original commit message
350
			 * using svnadmin command
351
			 */
352
			if(isWithCommitUpdate) {
353
				String svnadmin = readConfPropertyAsString(OPTION_SVNADMIN, null, true, null);
354
				EmitterUtil.verifyFile(svnadmin, false, true);
355
				/* If verification was turned on, we do already have the titles
356
				 * so only try to load the items when verification was off
357
				 */
358
				if(! isWithVerification) {
359
					verify(info.getIssues(), isTrace);
360
				}
361
				/* Append associated items information and change log message */
362
				StringBuffer newmessage = new StringBuffer();
363
				newmessage.append(info.getLogmessage());
364
				newmessage.append("\n\n Associated SBM items:\n");
365
				for(String s : issues_titles.keySet()) {
366
					newmessage.append(s+": ");
367
					newmessage.append(issues_titles.get(s));
368
					newmessage.append("\n");
369
				}
370
				postCommitUpdate(new File(svnadmin), repos, locale, encoding, rev, newmessage.toString());
371
			}
372
 
373
			/*
150 brianR 374
			 * XML processing phase
375
			 */
376
			if(isXmlProcessingEnabled) {
377
 
378
 
379
			}
380
 
167 brianR 381
 
150 brianR 382
			/*
383
			 * ALF Event Send phase
384
			 */
385
			String eventmanager = null;
386
			if(isSoapEnabled) {
387
				eventmanager 		= 	readConfPropertyAsString(OPTION_EVENTMANAGER_URL, null, true, null);
388
			}
389
 
390
 
391
 
149 brianR 392
 
150 brianR 393
		/**
394
		 * Event XML Erzeugen
395
		 */
396
		try {
397
			String resultxml=null;
398
			if(isXmlProcessingEnabled) {
399
 
400
				processXml();
401
				addALFSecurity();
402
				addEventHeader();
403
 
404
				// Serialize xml message to String
405
				StringWriter out = new StringWriter();
406
				template.getParent().serialize(out);
407
				out.flush();
408
 
409
				resultxml =  out.getBuffer().toString();
169 brianR 410
				if(isTrace) logger.debug("ALFEvent result:\n"+resultxml);
149 brianR 411
 
150 brianR 412
			} else {
413
				logger.debug("Xml processing is deactivated.");
414
			}
149 brianR 415
 
150 brianR 416
			if(isSoapEnabled && isXmlProcessingEnabled) {
417
				final boolean isDropResponse 	= readConfPropertyAsBoolean(OPTION_IS_DROPENABLED, true, true, null);
418
				SimpleHttpEvent sender = new SimpleHttpEvent(eventmanager, resultxml);
419
				sender.sendSoap(isDropResponse);
420
				logger.debug(String.format("Sending/ receiving the soap message took '%s' milliseconds.", sender.getDuration()));
421
			} else {
422
				logger.warn("Sending soap message and/ or xml processing is deactivated.");
423
			}
424
 
425
 
426
		} catch (FileNotFoundException e) {
427
			logger.error(e.getMessage(), e);
167 brianR 428
			this.exit(1);
150 brianR 429
		} catch (ClientProtocolException e) {
430
			logger.error(e.getMessage(), e);
167 brianR 431
			this.exit(1);
150 brianR 432
		} catch (IOException e) {
433
			logger.error(e.getMessage(), e);
167 brianR 434
			this.exit(1);
150 brianR 435
		} catch (XMLStreamException e) {
436
			logger.error(e.getMessage(), e);
167 brianR 437
			this.exit(1);
150 brianR 438
		} catch (JaxenException e) {
439
			logger.error(e.getMessage(), e);
167 brianR 440
			this.exit(1);
150 brianR 441
		} finally {
442
			String forcefail = config.getString(OPTION_IS_FORCEFAILENABLED, "");
443
			if(forcefail.length()>0) {
444
				logger.warn("Force fail is active. All commits will be blocked.");
167 brianR 445
				this.exit(1);
150 brianR 446
			}
447
 
149 brianR 448
		}
449
 
150 brianR 450
	}
451
		private void addEventHeader() throws JaxenException {
452
			AXIOMXPath path = new AXIOMXPath("//bru1:Base/bru1:EventId");
453
			path.addNamespace("bru1",  nss);
454
			OMElement n = (OMElement) path.selectSingleNode(template);
455
			if(n==null) {
456
				logger.error("<Base> element in message is incomplete. <EventId> is missing.");
457
			} else {
458
				n.addChild( n.getOMFactory().createOMText("1"));
459
			}
149 brianR 460
 
150 brianR 461
			path = new AXIOMXPath("//bru1:Base/bru1:ObjectId");
462
			path.addNamespace("bru1",  nss);
463
			n = (OMElement) path.selectSingleNode(template);
464
			if(n==null) {
465
				logger.error("<Base> element in message is incomplete. <ObjectId> is missing.");
466
			} else {
467
				n.addChild( n.getOMFactory().createOMText(info.getTxn() ));
468
			}
469
		}
470
 
471
		private void addALFSecurity() throws ConfigurationException, JaxenException {
472
			final String eventmanager_user 	= 	readConfPropertyAsString(OPTION_EVENTMANAGER_USER, null, false, null);
473
			final String eventmanager_pass 	= 	readConfPropertyAsString(OPTION_EVENTMANAGER_PASSWORD, null, false, null);
149 brianR 474
			AXIOMXPath path = new AXIOMXPath("//bru1:User");
475
			OMNamespace ns = template.findNamespace(nss, null);
476
			path.addNamespace("bru1", nss);
477
			OMElement n = (OMElement) path.selectSingleNode(template);
478
			if(n== null) {
479
				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));
480
			} else {
481
				/*
482
				 *  <ns:User>
483
            		<!--Optional:-->
484
               		<ns:ALFSecurity>
485
                  		<ns:UsernameToken>
486
                     		<ns:Username>admin</ns:Username>
487
                     		<ns:Password></ns:Password>
488
                  		</ns:UsernameToken>
489
               		</ns:ALFSecurity>
490
					</ns:User>
491
				 */
492
				n.removeChildren();
493
				OMFactory fac = n.getOMFactory();
494
				fac.createOMComment(n, "Generated by SVN-ALFEmitter");
495
				OMElement sec = fac.createOMElement("ALFSecurity", ns);
496
				OMElement token = fac.createOMElement("UsernameToken", ns);
497
				OMElement user = fac.createOMElement("Username", ns);
498
				user.addChild( fac.createOMText(eventmanager_user));
499
				OMElement pass = fac.createOMElement("Password", ns);
500
				pass.addChild(fac.createOMText(eventmanager_pass, OMNode.CDATA_SECTION_NODE));
501
				token.addChild( user );
502
				token.addChild( pass);
503
				sec.addChild(token);
504
				n.addChild(sec);
505
			}
150 brianR 506
		}
507
 
508
		private void processXml() throws ConfigurationException, JaxenException {
509
			// read additional configuration
510
			final String eventtemplate 		= 	readConfPropertyAsString(OPTION_EVENTTEMPLATE, null, true, null);
511
			EmitterUtil.verifyFile(eventtemplate, false, false);
512
			try {
513
				template = OMXMLBuilderFactory.createOMBuilder(new FileInputStream(new File(eventtemplate)))
514
						.getDocument().getOMDocumentElement();
515
			} catch (FileNotFoundException e1) {
516
				logger.error(String.format("Could not load XML event template from file '%s'.", eventtemplate), e1);
167 brianR 517
				this.exit(1);
149 brianR 518
			}
150 brianR 519
			nss 	= 	readConfPropertyAsString(OPTION_EVENTNAMESPACE, "http://www.eclipse.org/alf/schema/EventBase/1", true, null);
520
			final String marker_logmessage 	= 	readConfPropertyAsString(OPTION_MARKER_LOGMESSAGE, "@@logmessage@@", true, null);
521
			final String marker_author 		= 	readConfPropertyAsString(OPTION_MARKER_AUTHOR, "@@author@@", true, null);
522
			final String marker_revision	= 	readConfPropertyAsString(OPTION_MARKER_REVISION, "@@revision@@", true, null);
523
			final String marker_addedfiles 	= 	readConfPropertyAsString(OPTION_MARKER_ADDEDFILES, "@@addedfiles@@", true, null);
524
			final String marker_deletedfiles = 	readConfPropertyAsString(OPTION_MARKER_DELETEDFILES, "@@deletedfiles@@", true, null);
525
			final String marker_changedfiles = 	readConfPropertyAsString(OPTION_MARKER_CHANGEDFILES, "@@changedfiles@@", true, null);
526
			final String marker_fileselementname = readConfPropertyAsString("marker.fileselementname", "file", true, null);
527
			final String marker_issues 		= 	readConfPropertyAsString(OPTION_MARKER_ISSUES, "@@issues@@", true, null);
528
			final String marker_issueselementname = readConfPropertyAsString("marker.issueselementname", "issue", true, null);
529
			final String marker_internalissues    = readConfPropertyAsString(OPTION_MARKER_INTERNALISSUES, "@@internalissues@@", true, null);
530
 
531
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
532
			String datestring = f.format(info.getDate());
533
			datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
149 brianR 534
 
150 brianR 535
			// add content from SVNCommitInfo object where
536
			// XML commit markers are
537
			addElement( marker_logmessage, info.getLogmessage(), true);
538
			addElement(marker_author, info.getAuthor(), false);
539
			addElement(marker_revision, info.getRev(), false);
540
			addElement("@@timestamp@@", datestring, false);
541
			addElements(marker_changedfiles, info.getChangedFiles(), marker_fileselementname);
542
			addElements(marker_deletedfiles, info.getDeletedFiles(), marker_fileselementname);
543
			addElements(marker_addedfiles, info.getAddedFiles(), marker_fileselementname);
544
			addElements(marker_issues, info.getIssues(), marker_issueselementname);
545
			addElements(marker_internalissues, internalissues, marker_issueselementname);
149 brianR 546
 
150 brianR 547
		}
548
 
167 brianR 549
		private boolean verify(List<String> issues, boolean isTrace) throws MalformedURLException {
150 brianR 550
 
167 brianR 551
			for(String issueid : issues) {
552
				TTItemList items = getTTItems(issueid, isTrace);
553
				if(items == null) {
554
					return false;
555
				}
556
			}
557
			return true;
558
	}
559
 
560
 
561
		private TTItemList getTTItems(String issueid, boolean isTrace) throws MalformedURLException {
562
			long startTime = System.currentTimeMillis();
169 brianR 563
			Sbmappservices72PortType port = null;
564
			//try {
565
			//	JCS cache = JCS.getInstance("FileCache");
566
 
567
				/* -- */
568
			//	port = (Sbmappservices72PortType)cache.get(CACHE_SBMPORT);
569
			/*
570
				if(port==null) {
571
					Sbmappservices72 ss = new Sbmappservices72(ClassLoader.getSystemResource("sbmappservices72.wsdl") );
572
 
573
					port = ss.getSbmappservices72();
574
 
575
 
576
					BindingProvider bindingProvider = (BindingProvider) port;
577
			        bindingProvider.getRequestContext().put(
578
			        BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
579
				}
580
				*/
581
		    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
582
		    factory.setServiceClass(Sbmappservices72PortType.class);
583
		    factory.setAddress(endpoint);
584
		    port = (Sbmappservices72PortType) factory.create();
585
		    logger.debug("Total execution of sbmappservices72 wsdl read took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
586
 
587
 
588
			//		cache.put(CACHE_SBMPORT, port);
589
			//		cache.dispose();
590
			//	} else {
591
			//		logger.debug("sbmappservices72 port was read from cache.");
592
			//	}
593
 
594
			//} catch (CacheException e1) {
595
			//	// TODO Auto-generated catch block
596
			//	e1.printStackTrace();
597
			//	this.exit(1);
598
			//}
149 brianR 599
 
150 brianR 600
			if(isTrace) {
169 brianR 601
				Client client = ClientProxy.getClient(port);
150 brianR 602
		        client.getInInterceptors().add(new LoggingInInterceptor());
603
		        client.getOutInterceptors().add(new LoggingOutInterceptor());
149 brianR 604
			}
169 brianR 605
 
167 brianR 606
	        /* -- */
607
	        logger.debug("Total execution of sbmappservices72 initialisation took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
608
 
150 brianR 609
			ObjectFactory fac = new ObjectFactory();
610
			Auth auth = fac.createAuth();
611
			auth.setUserId(fac.createAuthUserId(sbm_user));
612
			auth.setPassword(fac.createAuthPassword(sbm_pass));
149 brianR 613
 
150 brianR 614
			TableIdentifier table = fac.createTableIdentifier();
615
			table.setDbName(fac.createTableIdentifierDbName(querytable));
616
 
617
			MultipleResponseItemOptions options = fac.createMultipleResponseItemOptions();
167 brianR 618
			options.setSpecifiedSections(fac.createResponseItemOptionsSpecifiedSections("SECTION:FIXED"));
619
			options.setSections(SectionsOption.SECTIONS_SPECIFIED);
150 brianR 620
 
167 brianR 621
			issueid = issueid.replaceAll("[^0-9]", "");
622
			String queryWhereClause = "TS_ISSUEID = '"+issueid+"'";
623
			if(query!=null && query.length()>0) queryWhereClause = queryWhereClause + " And " + query;
624
			TTItemList items = null;
625
			logger.debug(String.format("Using query against table '%s'. Query where clause: '%s'", querytable, queryWhereClause ));
626
			try {
627
					startTime = System.currentTimeMillis();
628
					items = port.getItemsByQuery(auth, table, queryWhereClause, "", null, BigInteger.valueOf(1), options);
629
					logger.debug("Total execution of sbmappservices72 GetItems took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
150 brianR 630
 
631
					//Marshaller m = JAXBContext.newInstance(TTItemList.class).createMarshaller();
632
					//m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
633
					//m.marshal( new JAXBElement<TTItemList>(new QName("uri","local"), TTItemList.class, items), System.err);
634
 
635
					logger.debug(String.format("Got Response from getItemsByQuery"));
636
					if(items!=null) {
167 brianR 637
						logger.debug(String.format("Verification query matched '%s' item(s) for issue '%s.'",items.getTotalCount(), issueid));
150 brianR 638
					}
639
					if(items.getTotalCount().intValue()<=0) {
167 brianR 640
						return null;
150 brianR 641
					} else {
167 brianR 642
						/* store internal ids (tableid:itemid) */
150 brianR 643
						internalissues.add(items.getItem().get(0).getId().getValue().getTableIdItemId().getValue());
167 brianR 644
						/* Store a map entry with internal id and title */
645
						issues_titles.put(items.getItem().get(0).getId().getValue().getDisplayName().getValue(),
646
											items.getItem().get(0).getTitle().getValue());
647
 
150 brianR 648
					}
649
 
167 brianR 650
			} catch (AEWebservicesFaultFault e) {
150 brianR 651
					logger.debug("Web service fault: " + e.getFaultInfo());
167 brianR 652
			} catch (Exception e) {
150 brianR 653
					logger.debug("Unknown Exception", e);
149 brianR 654
			}
167 brianR 655
			return items;
656
		}
149 brianR 657
 
167 brianR 658
		private void postCommitUpdate(File svnadmin, String repos, String locale, String encoding, String revision, String newmessage) {
659
			SVNAdminExecutor exec = new SVNAdminExecutor(svnadmin, repos);
660
			exec.setRev(revision);
661
			exec.setMessage(newmessage);
662
			exec.setEncoding(encoding);
663
			exec.setLocale(locale);
664
			exec.executeSVNAdmin(SVNAdminCommand.SETLOG);
665
		}
150 brianR 666
 
149 brianR 667
		private void addElement(String pattern, String newCdata, boolean wrapCDATA) throws JaxenException {
668
			OMComment comment = findComment(pattern);
669
			if(comment!=null) {
670
				OMFactory fac = OMAbstractFactory.getOMFactory();
671
				int type = OMNode.TEXT_NODE;
672
				if(wrapCDATA) {
673
					type = OMNode.CDATA_SECTION_NODE;
674
				}
675
				OMText text = fac.createOMText(newCdata, type);
676
				comment.insertSiblingAfter(text);
677
			}
678
		}
679
 
680
		private void addElements(String pattern, List<String> files, String elementName) throws JaxenException {
681
			if(files.size()<=0) return;
682
			OMComment comment = findComment(pattern);
683
			if(comment!=null) {
684
				OMFactory fac = OMAbstractFactory.getOMFactory();
685
				OMNamespace ns = template.findNamespace(nss, null);
686
				if(ns == null) logger.error(String.format("The namespace '%s' is not defined in the template.", nss));
687
				for(String s : files) {
688
					OMElement e = fac.createOMElement(elementName, ns);
689
					OMText text = fac.createOMText(s, OMNode.TEXT_NODE);
690
					e.addChild(text);
691
					comment.insertSiblingAfter(e);
692
				}
693
			}
694
		}
695
 
696
 
697
		private OMComment findComment(String pattern) throws JaxenException {
698
			AXIOMXPath path = new AXIOMXPath("//comment()[. = '"+pattern+"'][1]");
699
			//OMNamespace ns = template.findNamespace(nss, null);
700
			path.addNamespace("bru1", nss);
701
			OMComment n = (OMComment) path.selectSingleNode(template);
702
			if(n!=null) return n;
703
			logger.warn("Comment '"+pattern+"' was not found in the XML template.");
704
			return null;
705
		}
167 brianR 706
 
707
	private void exit(int errorCode) {
708
		long endTime = System.currentTimeMillis();
709
		logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds.");
710
		System.exit(errorCode);
711
	}
149 brianR 712
 
713
	@SuppressWarnings("static-access")
714
	private static Options getOptions() {
715
		Option repository = OptionBuilder.withArgName( "repository" )
716
											.hasArg()
717
											.withLongOpt("repository")
718
											.withDescription(  "Path or URL to the SVN repository." )
719
											.create( PARAM_REPOS );
720
		repository.setRequired(true);
721
 
722
		Option txn = OptionBuilder.withArgName( "transactionid" )
723
											.hasArg()
724
											.withLongOpt("transaction")
725
											.withDescription(  "The SVN transaction id to examine (TXN). You cannot combine txn with -rev. "
726
													+ "When a txn is given, the repository path must be a local path.")
727
											.create( PARAM_TXN );
728
		Option rev = OptionBuilder.withArgName( "revision" )
729
				.hasArg()
730
				.withDescription(  "A revision to examine. You cannot combine revision with -txn." )
731
				.create( PARAM_REV );
732
		Option config = OptionBuilder.withArgName( "config_file" )
733
				.hasArg()
734
				.withLongOpt("config")
735
				.withDescription(  "The configuration file to use. Defaults to 'emitter.properties'.")
736
				.create( PARAM_CONFIG );
737
 
738
		Options options = new Options();
739
		options.addOption(repository);
740
		options.addOption(txn);
741
		options.addOption(rev);
742
		options.addOption(config);
743
		return options;
744
	}
745
 
746
	private static void printHelp() {
747
		// automatically generate the help statement
748
		HelpFormatter formatter = new HelpFormatter();
150 brianR 749
		String header = "\nSVN-ALFEventEmitter " + VERSION +", a SVN hook implemented in Java to emit Eclipse ALFEvents on commit.\n\n";
167 brianR 750
		String footer = "Please send bug reports to bru@brutex.de.\n(c)2014 Brian Rosenberger";
149 brianR 751
		formatter.printHelp("java -jar SVN-ALFEventEmitter", header, getOptions(), footer, true);
752
	}
753
 
754
 
150 brianR 755
 
756
	private enum PropertyType {
757
		STRING(), STRINGARRAY(), BOOLEAN();
758
	}
759
 
760
 
149 brianR 761
}