Subversion Repositories XServices

Rev

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