Subversion Repositories XServices

Rev

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