Subversion Repositories XServices

Rev

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