Subversion Repositories XServices

Rev

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