Subversion Repositories XServices

Rev

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