Subversion Repositories XServices

Rev

Rev 150 | 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;
23
import java.text.SimpleDateFormat;
24
import java.util.Iterator;
25
import java.util.List;
26
import java.util.UUID;
27
 
28
import javax.xml.stream.XMLStreamException;
29
 
30
import net.brutex.svn.SVNCommitInfo;
31
import net.brutex.svn.SVNLookExecutor;
32
 
33
import org.apache.axiom.om.OMAbstractFactory;
34
import org.apache.axiom.om.OMComment;
35
import org.apache.axiom.om.OMElement;
36
import org.apache.axiom.om.OMFactory;
37
import org.apache.axiom.om.OMNamespace;
38
import org.apache.axiom.om.OMNode;
39
import org.apache.axiom.om.OMText;
40
import org.apache.axiom.om.OMXMLBuilderFactory;
41
import org.apache.axiom.om.xpath.AXIOMXPath;
42
import org.apache.commons.cli.CommandLine;
43
import org.apache.commons.cli.CommandLineParser;
44
import org.apache.commons.cli.HelpFormatter;
45
import org.apache.commons.cli.Option;
46
import org.apache.commons.cli.OptionBuilder;
47
import org.apache.commons.cli.Options;
48
import org.apache.commons.cli.BasicParser;
49
import org.apache.commons.cli.ParseException;
50
import org.apache.commons.configuration.Configuration;
51
import org.apache.commons.configuration.ConfigurationException;
52
import org.apache.commons.configuration.PropertiesConfiguration;
53
import org.apache.http.client.ClientProtocolException;
54
import org.apache.log4j.Logger;
55
import org.jaxen.JaxenException;
56
 
57
 
58
/**
59
 * The Class ALFEmitter.
60
 *
61
 * @author Brian Rosenberger, bru(at)brutex.de
62
 * @since 0.1
63
 */
64
public class ALFEmitter {
65
 
66
	private static final String version = "0.1";
67
	static Logger logger = Logger.getRootLogger();
68
	private static final String PARAM_REPOS = "repos";
69
	private static final String PARAM_TXN = "txn";
70
	private static final String PARAM_REV = "rev";
71
	private static final String PARAM_CONFIG = "conf";
72
 
73
	/**
74
	 * The main method.
75
	 *
76
	 * @param args the arguments
77
	 */
78
	public static void main(String[] args) {
79
		long startTime = System.currentTimeMillis();
80
		CommandLineParser parser = new BasicParser();
81
		CommandLine cmd = null;;
82
		try {
83
			cmd = parser.parse( getOptions(), args);
84
		} catch (ParseException e1) {
85
			logger.error(e1.getMessage());
86
			printHelp();
87
			System.exit(1);
88
		}
89
		ALFEmitter emitter = new ALFEmitter(cmd, startTime);
90
		long endTime = System.currentTimeMillis();
91
		logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds.");
92
		System.exit(0);
93
	}
94
 
95
	private final String repos;
96
	private final String txn;
97
	private final String rev;
98
	private SVNCommitInfo info;
99
	private OMElement template;
100
	private Configuration config;
101
	private final String nss;
102
	private final long startTime;
103
 
104
	private ALFEmitter(CommandLine cmd, long startTime) {
105
		this.startTime = startTime;
106
		repos = cmd.getOptionValue(PARAM_REPOS);
107
		txn = cmd.getOptionValue(PARAM_TXN);
108
		rev = cmd.getOptionValue(PARAM_REV);
109
		String config_file = cmd.getOptionValue(PARAM_CONFIG, "emitter.properties");
110
 
111
		logger.debug(String.format("Using REPOS='%s' and TXN='%s'.", repos, txn));
112
 
113
		config = null;
114
		try {
115
			config = new PropertiesConfiguration(config_file);
116
		} catch (ConfigurationException e) {
117
			logger.error("Could not find/ load '"+config_file+"' file.", e);
118
			System.exit(1);
119
		}
120
 
121
		/*
122
		 * Load Properties from Configuration file
123
		 */
124
 
125
		//it might be interesting to look into SVNKit
126
		//for a pure Java implementation in future
127
		final String svnlook = config.getString("svnlook");
128
		logger.debug("Using svnlook at '" + svnlook +"'.");
129
 
130
		final String[] issuepatterns = config.getStringArray("issuepattern");
131
		StringBuilder sb = new StringBuilder(); for(String s : issuepatterns) sb.append(s);
132
		logger.debug(String.format("Using issue id patterns: '%s'.", sb.toString()));
133
 
134
		final String eventtemplate = config.getString("eventtemplate");
135
		logger.debug("Using alf event template at '" + eventtemplate +"'.");
136
 
137
		nss = config.getString("eventnamespace", "http://www.eclipse.org/alf/schema/EventBase/1");
138
		logger.debug("Using alf event namespace '" + nss +"'.");
139
 
140
		final String marker_logmessage = config.getString("marker.logmessage", "@@logmessage@@");
141
		logger.debug("Using comment marker '<!-- " + marker_logmessage +" -->' in event template for logmessage.");
142
 
143
		final String marker_author = config.getString("marker.author", "@@author@@");
144
		logger.debug("Using comment marker '<!-- " + marker_author +" -->' with event template for author.");
145
 
146
		final String marker_addedfiles = config.getString("marker.addedfiles", "@@addedfiles@@");
147
		logger.debug("Using comment marker '<!-- " + marker_addedfiles +" -->' with event template for files added during commit.");
148
 
149
		final String marker_deletedfiles = config.getString("marker.deletedfiles", "@@deletedfiles@@");
150
		logger.debug("Using comment marker '<!-- " + marker_deletedfiles +" -->' with event template for files deleted during commit.");
151
 
152
		final String marker_changedfiles = config.getString("marker.changedfiles", "@@changedfiles@@");
153
		logger.debug("Using comment marker '<!-- " + marker_changedfiles +" -->' with event template for files changed during commit.");
154
 
155
		final String marker_fileselementname = config.getString("marker.fileselementname", "file");
156
		logger.debug("Using element name '" +marker_fileselementname +"' to wrap files list.");
157
 
158
		final String marker_issues = config.getString("marker.issues", "@@issues@@");
159
		logger.debug("Using comment marker '<!-- " + marker_issues +" -->' with event template for issue list.");
160
 
161
		final String marker_issueselementname = config.getString("marker.issueselementname", "issue");
162
		logger.debug("Using element name '" +marker_issueselementname +"' to wrap issue list.");
163
 
164
		final String eventmanager = config.getString("eventmanager");
165
		logger.debug("Using eventmanager at '" +eventmanager +"'.");
166
 
167
		final String eventmanager_user = config.getString("eventmanager.user");
168
		final String eventmanager_pass = config.getString("eventmanager.password");
169
		logger.debug("Using username '" +eventmanager_user +"' and a password.");
170
 
171
		final boolean isSoapEnabled = config.getBoolean("isSoapEnabled", true);
172
		logger.debug("Sending soap message is enabled='" +isSoapEnabled +"'.");
173
 
174
		final boolean isDropResponse = config.getBoolean("isDropResponse", true);
175
		logger.debug("Receiving the soap response is enabled='" +isDropResponse +"'.");
176
 
177
 
178
		try {
179
			template = OMXMLBuilderFactory.createOMBuilder(new FileInputStream(new File(eventtemplate)))
180
					.getDocument().getOMDocumentElement();
181
		} catch (FileNotFoundException e1) {
182
			logger.error(String.format("Could not load XML event template from file '%s'.", eventtemplate), e1);
183
			System.exit(1);
184
		}
185
 
186
		/*
187
		 *
188
		 */
189
		SVNLookExecutor exec = new SVNLookExecutor(new File(svnlook), repos);
190
		if(cmd.hasOption(PARAM_TXN)) exec.setTXN(txn);
191
		if(cmd.hasOption(PARAM_REV)) exec.setRev(rev);
192
		info = exec.getCommitInfo();
193
 
194
		info.parseIssues(issuepatterns);
195
 
196
		logger.debug("SVNCommitInfo author: "+ info.getAuthor());
197
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
198
		String datestring = f.format(info.getDate());
199
		datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
200
		logger.debug("SVNCommitInfo date: "+ datestring);
201
		logger.debug("SVNCommitInfo log message: "+ info.getLogmessage());
202
		logger.debug("SVNCommitInfo file list: "+ info.getChangeFileListAsString());
203
 
204
 
205
		/**
206
		 * Event XML Erzeugen
207
		 */
208
		try {
209
			addElement( marker_logmessage, info.getLogmessage(), true);
210
			addElement(marker_author, info.getAuthor(), false);
211
			addElement("@@timestamp@@", datestring, false);
212
			addElements(marker_changedfiles, info.getChangedFiles(), marker_fileselementname);
213
			addElements(marker_deletedfiles, info.getDeletedFiles(), marker_fileselementname);
214
			addElements(marker_addedfiles, info.getAddedFiles(), marker_fileselementname);
215
			addElements(marker_issues, info.getIssues(), marker_issueselementname);
216
 
217
			AXIOMXPath path = new AXIOMXPath("//bru1:User");
218
			OMNamespace ns = template.findNamespace(nss, null);
219
			path.addNamespace("bru1", nss);
220
			OMElement n = (OMElement) path.selectSingleNode(template);
221
			if(n== null) {
222
				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));
223
			} else {
224
				/*
225
				 *  <ns:User>
226
            		<!--Optional:-->
227
               		<ns:ALFSecurity>
228
                  		<ns:UsernameToken>
229
                     		<ns:Username>admin</ns:Username>
230
                     		<ns:Password></ns:Password>
231
                  		</ns:UsernameToken>
232
               		</ns:ALFSecurity>
233
					</ns:User>
234
				 */
235
				n.removeChildren();
236
				OMFactory fac = n.getOMFactory();
237
				fac.createOMComment(n, "Generated by SVN-ALFEmitter");
238
				OMElement sec = fac.createOMElement("ALFSecurity", ns);
239
				OMElement token = fac.createOMElement("UsernameToken", ns);
240
				OMElement user = fac.createOMElement("Username", ns);
241
				user.addChild( fac.createOMText(eventmanager_user));
242
				OMElement pass = fac.createOMElement("Password", ns);
243
				pass.addChild(fac.createOMText(eventmanager_pass, OMNode.CDATA_SECTION_NODE));
244
				token.addChild( user );
245
				token.addChild( pass);
246
				sec.addChild(token);
247
				n.addChild(sec);
248
			}
249
 
250
			path = new AXIOMXPath("//bru1:Base/bru1:EventId");
251
			path.addNamespace("bru1",  nss);
252
			n = (OMElement) path.selectSingleNode(template);
253
			if(n==null) {
254
				logger.error("<Base> element in message is incomplete. <EventId> is missing.");
255
			} else {
256
				n.addChild( n.getOMFactory().createOMText(UUID.randomUUID().toString() ));
257
			}
258
 
259
			path = new AXIOMXPath("//bru1:Base/bru1:ObjectId");
260
			path.addNamespace("bru1",  nss);
261
			n = (OMElement) path.selectSingleNode(template);
262
			if(n==null) {
263
				logger.error("<Base> element in message is incomplete. <ObjectId> is missing.");
264
			} else {
265
				n.addChild( n.getOMFactory().createOMText(info.getTxn() ));
266
			}
267
 
268
			StringWriter out = new StringWriter();
269
			template.getParent().serialize(out);
270
			out.flush();
271
 
272
			String resultxml =  out.getBuffer().toString();
273
			logger.debug("ALFEvent result:\n"+resultxml);
274
 
275
			if(isSoapEnabled) {
276
				SimpleHttpEvent sender = new SimpleHttpEvent(eventmanager, resultxml);
277
				sender.sendSoap(isDropResponse);
278
				logger.debug(String.format("Sending/ receiving the soap message took '%s' milliseconds.", sender.getDuration()));
279
			} else {
280
				logger.warn("Sending soap message is deactivated.");
281
			}
282
 
283
 
284
		} catch (FileNotFoundException e) {
285
			logger.error(e.getMessage(), e);
286
			System.exit(1);
287
		} catch (ClientProtocolException e) {
288
			logger.error(e.getMessage(), e);
289
			System.exit(1);
290
		} catch (IOException e) {
291
			logger.error(e.getMessage(), e);
292
			System.exit(1);
293
		} catch (XMLStreamException e) {
294
			logger.error(e.getMessage(), e);
295
			System.exit(1);
296
		} catch (JaxenException e) {
297
			logger.error(e.getMessage(), e);
298
			System.exit(1);
299
		} finally {
300
			logger.debug("Total execution took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
301
			String forcefail = config.getString("forcefail", "");
302
			if(forcefail.length()>0) {
303
				logger.warn("Force fail is active. All commits will be blocked.");
304
				System.exit(1);
305
			}
306
 
307
		}
308
 
309
	}
310
 
311
 
312
		private void addElement(String pattern, String newCdata, boolean wrapCDATA) throws JaxenException {
313
			OMComment comment = findComment(pattern);
314
			if(comment!=null) {
315
				OMFactory fac = OMAbstractFactory.getOMFactory();
316
				int type = OMNode.TEXT_NODE;
317
				if(wrapCDATA) {
318
					type = OMNode.CDATA_SECTION_NODE;
319
				}
320
				OMText text = fac.createOMText(newCdata, type);
321
				comment.insertSiblingAfter(text);
322
			}
323
		}
324
 
325
		private void addElements(String pattern, List<String> files, String elementName) throws JaxenException {
326
			if(files.size()<=0) return;
327
			OMComment comment = findComment(pattern);
328
			if(comment!=null) {
329
				OMFactory fac = OMAbstractFactory.getOMFactory();
330
				OMNamespace ns = template.findNamespace(nss, null);
331
				if(ns == null) logger.error(String.format("The namespace '%s' is not defined in the template.", nss));
332
				for(String s : files) {
333
					OMElement e = fac.createOMElement(elementName, ns);
334
					OMText text = fac.createOMText(s, OMNode.TEXT_NODE);
335
					e.addChild(text);
336
					comment.insertSiblingAfter(e);
337
				}
338
			}
339
		}
340
 
341
 
342
		private OMComment findComment(String pattern) throws JaxenException {
343
			AXIOMXPath path = new AXIOMXPath("//comment()[. = '"+pattern+"'][1]");
344
			//OMNamespace ns = template.findNamespace(nss, null);
345
			path.addNamespace("bru1", nss);
346
			OMComment n = (OMComment) path.selectSingleNode(template);
347
			if(n!=null) return n;
348
			logger.warn("Comment '"+pattern+"' was not found in the XML template.");
349
			return null;
350
		}
351
		/*
352
		private static OMComment findComment(OMElement element, String pattern) {
353
			logger.trace( String.format("Searching for comment pattern '%s' in element with name '%s'.", pattern, element.getLocalName()));
354
			Iterator iter = element.getChildren();
355
 
356
			while(iter.hasNext()) {
357
				Object o = iter.next();
358
				if(o instanceof OMNode) {
359
					OMNode node =  ((OMNode)o);
360
 
361
					switch (node.getType() ) {
362
					case OMNode.COMMENT_NODE:
363
						OMComment comment = ((OMComment)node);
364
						String value = comment.getValue().trim();
365
						if(value.equals(pattern)) {
366
							logger.debug("Found comment '" + pattern + "' in event template.");
367
							return comment;
368
						}
369
						break;
370
 
371
 
372
					case OMNode.ELEMENT_NODE:
373
						//traverse
374
						OMComment result = findComment( (OMElement)node, pattern);
375
						if(result!=null) return result;
376
						break;
377
 
378
					default:
379
						break;
380
					}
381
				}
382
			}
383
			//logger.info("Comment '" + pattern + "' was not found in event template.");
384
			return null;
385
		}
386
		*/
387
 
388
 
389
	@SuppressWarnings("static-access")
390
	private static Options getOptions() {
391
		Option repository = OptionBuilder.withArgName( "repository" )
392
											.hasArg()
393
											.withLongOpt("repository")
394
											.withDescription(  "Path or URL to the SVN repository." )
395
											.create( PARAM_REPOS );
396
		repository.setRequired(true);
397
 
398
		Option txn = OptionBuilder.withArgName( "transactionid" )
399
											.hasArg()
400
											.withLongOpt("transaction")
401
											.withDescription(  "The SVN transaction id to examine (TXN). You cannot combine txn with -rev. "
402
													+ "When a txn is given, the repository path must be a local path.")
403
											.create( PARAM_TXN );
404
		Option rev = OptionBuilder.withArgName( "revision" )
405
				.hasArg()
406
				.withDescription(  "A revision to examine. You cannot combine revision with -txn." )
407
				.create( PARAM_REV );
408
		Option config = OptionBuilder.withArgName( "config_file" )
409
				.hasArg()
410
				.withLongOpt("config")
411
				.withDescription(  "The configuration file to use. Defaults to 'emitter.properties'.")
412
				.create( PARAM_CONFIG );
413
 
414
		Options options = new Options();
415
		options.addOption(repository);
416
		options.addOption(txn);
417
		options.addOption(rev);
418
		options.addOption(config);
419
		return options;
420
	}
421
 
422
	private static void printHelp() {
423
		// automatically generate the help statement
424
		HelpFormatter formatter = new HelpFormatter();
425
		String header = "\nSVN-ALFEventEmitter " + version +", a SVN hook implemented in Java to emit Eclipse ALFEvents on commit.\n\n";
426
		String footer = "Please send bug reports to bru@brutex.de.\n(c)2013 Brian Rosenberger";
427
		formatter.printHelp("java -jar SVN-ALFEventEmitter", header, getOptions(), footer, true);
428
	}
429
 
430
 
431
}