Subversion Repositories XServices

Rev

Rev 150 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

/*
 *   Copyright 2013 Brian Rosenberger (Brutex Network)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package net.brutex.emitter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.xml.stream.XMLStreamException;

import net.brutex.svn.SVNCommitInfo;
import net.brutex.svn.SVNLookExecutor;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMComment;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.jaxen.JaxenException;


/**
 * The Class ALFEmitter.
 *
 * @author Brian Rosenberger, bru(at)brutex.de
 * @since 0.1
 */
public class ALFEmitter {
        
        private static final String version = "0.1";
        static Logger logger = Logger.getRootLogger();
        private static final String PARAM_REPOS = "repos";
        private static final String PARAM_TXN = "txn";
        private static final String PARAM_REV = "rev";
        private static final String PARAM_CONFIG = "conf";

        /**
         * The main method.
         *
         * @param args the arguments
         */
        public static void main(String[] args) {
                long startTime = System.currentTimeMillis();
                CommandLineParser parser = new BasicParser();
                CommandLine cmd = null;;
                try {
                        cmd = parser.parse( getOptions(), args);
                } catch (ParseException e1) {
                        logger.error(e1.getMessage());
                        printHelp();
                        System.exit(1);
                }
                ALFEmitter emitter = new ALFEmitter(cmd, startTime);
                long endTime = System.currentTimeMillis();
                logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds.");
                System.exit(0);
        }
        
        private final String repos;
        private final String txn;
        private final String rev;
        private SVNCommitInfo info;
        private OMElement template;
        private Configuration config;
        private final String nss;
        private final long startTime;
                
        private ALFEmitter(CommandLine cmd, long startTime) {
                this.startTime = startTime;
                repos = cmd.getOptionValue(PARAM_REPOS);
                txn = cmd.getOptionValue(PARAM_TXN);
                rev = cmd.getOptionValue(PARAM_REV);
                String config_file = cmd.getOptionValue(PARAM_CONFIG, "emitter.properties");

                logger.debug(String.format("Using REPOS='%s' and TXN='%s'.", repos, txn));
        
                config = null;
                try {
                        config = new PropertiesConfiguration(config_file);
                } catch (ConfigurationException e) {
                        logger.error("Could not find/ load '"+config_file+"' file.", e);
                        System.exit(1);
                }
                
                /*
                 * Load Properties from Configuration file
                 */
                
                //it might be interesting to look into SVNKit
                //for a pure Java implementation in future
                final String svnlook = config.getString("svnlook"); 
                logger.debug("Using svnlook at '" + svnlook +"'.");
                
                final String[] issuepatterns = config.getStringArray("issuepattern");
                StringBuilder sb = new StringBuilder(); for(String s : issuepatterns) sb.append(s);
                logger.debug(String.format("Using issue id patterns: '%s'.", sb.toString()));
                
                final String eventtemplate = config.getString("eventtemplate");
                logger.debug("Using alf event template at '" + eventtemplate +"'.");
                
                nss = config.getString("eventnamespace", "http://www.eclipse.org/alf/schema/EventBase/1");
                logger.debug("Using alf event namespace '" + nss +"'.");
                
                final String marker_logmessage = config.getString("marker.logmessage", "@@logmessage@@");
                logger.debug("Using comment marker '<!-- " + marker_logmessage +" -->' in event template for logmessage.");
                
                final String marker_author = config.getString("marker.author", "@@author@@");
                logger.debug("Using comment marker '<!-- " + marker_author +" -->' with event template for author.");
                
                final String marker_addedfiles = config.getString("marker.addedfiles", "@@addedfiles@@");
                logger.debug("Using comment marker '<!-- " + marker_addedfiles +" -->' with event template for files added during commit.");
                
                final String marker_deletedfiles = config.getString("marker.deletedfiles", "@@deletedfiles@@");
                logger.debug("Using comment marker '<!-- " + marker_deletedfiles +" -->' with event template for files deleted during commit.");
                
                final String marker_changedfiles = config.getString("marker.changedfiles", "@@changedfiles@@");
                logger.debug("Using comment marker '<!-- " + marker_changedfiles +" -->' with event template for files changed during commit.");
                
                final String marker_fileselementname = config.getString("marker.fileselementname", "file");
                logger.debug("Using element name '" +marker_fileselementname +"' to wrap files list.");
                
                final String marker_issues = config.getString("marker.issues", "@@issues@@");
                logger.debug("Using comment marker '<!-- " + marker_issues +" -->' with event template for issue list.");
                
                final String marker_issueselementname = config.getString("marker.issueselementname", "issue");
                logger.debug("Using element name '" +marker_issueselementname +"' to wrap issue list.");
                
                final String eventmanager = config.getString("eventmanager");
                logger.debug("Using eventmanager at '" +eventmanager +"'.");
                
                final String eventmanager_user = config.getString("eventmanager.user");
                final String eventmanager_pass = config.getString("eventmanager.password");
                logger.debug("Using username '" +eventmanager_user +"' and a password.");
                
                final boolean isSoapEnabled = config.getBoolean("isSoapEnabled", true);
                logger.debug("Sending soap message is enabled='" +isSoapEnabled +"'.");
                
                final boolean isDropResponse = config.getBoolean("isDropResponse", true);
                logger.debug("Receiving the soap response is enabled='" +isDropResponse +"'.");
                
                
                try {
                        template = OMXMLBuilderFactory.createOMBuilder(new FileInputStream(new File(eventtemplate)))
                                        .getDocument().getOMDocumentElement();
                } catch (FileNotFoundException e1) {
                        logger.error(String.format("Could not load XML event template from file '%s'.", eventtemplate), e1);
                        System.exit(1);
                }
                
                /*
                 * 
                 */
                SVNLookExecutor exec = new SVNLookExecutor(new File(svnlook), repos);
                if(cmd.hasOption(PARAM_TXN)) exec.setTXN(txn);
                if(cmd.hasOption(PARAM_REV)) exec.setRev(rev);
                info = exec.getCommitInfo();
                
                info.parseIssues(issuepatterns);
                
                logger.debug("SVNCommitInfo author: "+ info.getAuthor());
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                String datestring = f.format(info.getDate());
                datestring= datestring.substring(0, 26) + ":" + datestring.substring(26); //hack into ISO 8601 format
                logger.debug("SVNCommitInfo date: "+ datestring);
                logger.debug("SVNCommitInfo log message: "+ info.getLogmessage());
                logger.debug("SVNCommitInfo file list: "+ info.getChangeFileListAsString());
                
                
                /**
                 * Event XML Erzeugen
                 */
                try {
                        addElement( marker_logmessage, info.getLogmessage(), true);
                        addElement(marker_author, info.getAuthor(), false);
                        addElement("@@timestamp@@", datestring, false);
                        addElements(marker_changedfiles, info.getChangedFiles(), marker_fileselementname);
                        addElements(marker_deletedfiles, info.getDeletedFiles(), marker_fileselementname);
                        addElements(marker_addedfiles, info.getAddedFiles(), marker_fileselementname);
                        addElements(marker_issues, info.getIssues(), marker_issueselementname);
                        
                        AXIOMXPath path = new AXIOMXPath("//bru1:User");
                        OMNamespace ns = template.findNamespace(nss, null);
                        path.addNamespace("bru1", nss);
                        OMElement n = (OMElement) path.selectSingleNode(template);
                        if(n== null) { 
                                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));
                        } else {
                                /*
                                 *  <ns:User>
                        <!--Optional:-->
                        <ns:ALFSecurity>
                                <ns:UsernameToken>
                                <ns:Username>admin</ns:Username>
                                <ns:Password></ns:Password>
                                </ns:UsernameToken>
                        </ns:ALFSecurity>
                                        </ns:User> 
                                 */
                                n.removeChildren();
                                OMFactory fac = n.getOMFactory();
                                fac.createOMComment(n, "Generated by SVN-ALFEmitter");
                                OMElement sec = fac.createOMElement("ALFSecurity", ns);
                                OMElement token = fac.createOMElement("UsernameToken", ns);
                                OMElement user = fac.createOMElement("Username", ns);
                                user.addChild( fac.createOMText(eventmanager_user));
                                OMElement pass = fac.createOMElement("Password", ns);
                                pass.addChild(fac.createOMText(eventmanager_pass, OMNode.CDATA_SECTION_NODE));
                                token.addChild( user );
                                token.addChild( pass);
                                sec.addChild(token);
                                n.addChild(sec);                                
                        }
                        
                        path = new AXIOMXPath("//bru1:Base/bru1:EventId");
                        path.addNamespace("bru1",  nss);
                        n = (OMElement) path.selectSingleNode(template);
                        if(n==null) {
                                logger.error("<Base> element in message is incomplete. <EventId> is missing.");
                        } else {
                                n.addChild( n.getOMFactory().createOMText(UUID.randomUUID().toString() ));
                        }
                        
                        path = new AXIOMXPath("//bru1:Base/bru1:ObjectId");
                        path.addNamespace("bru1",  nss);
                        n = (OMElement) path.selectSingleNode(template);
                        if(n==null) {
                                logger.error("<Base> element in message is incomplete. <ObjectId> is missing.");
                        } else {
                                n.addChild( n.getOMFactory().createOMText(info.getTxn() ));
                        }

                        StringWriter out = new StringWriter();
                        template.getParent().serialize(out);
                        out.flush();
                        
                        String resultxml =  out.getBuffer().toString();
                        logger.debug("ALFEvent result:\n"+resultxml);
                        
                        if(isSoapEnabled) {
                                SimpleHttpEvent sender = new SimpleHttpEvent(eventmanager, resultxml);
                                sender.sendSoap(isDropResponse);
                                logger.debug(String.format("Sending/ receiving the soap message took '%s' milliseconds.", sender.getDuration()));
                        } else {
                                logger.warn("Sending soap message is deactivated.");
                        }
                        
                        
                } catch (FileNotFoundException e) {
                        logger.error(e.getMessage(), e);
                        System.exit(1);
                } catch (ClientProtocolException e) {
                        logger.error(e.getMessage(), e);
                        System.exit(1);
                } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                        System.exit(1);
                } catch (XMLStreamException e) {
                        logger.error(e.getMessage(), e);
                        System.exit(1);
                } catch (JaxenException e) {
                        logger.error(e.getMessage(), e);
                        System.exit(1);
                } finally {
                        logger.debug("Total execution took '"+(System.currentTimeMillis()-startTime)+"' milliseconds.");
                        String forcefail = config.getString("forcefail", "");
                        if(forcefail.length()>0) {
                                logger.warn("Force fail is active. All commits will be blocked.");
                                System.exit(1);
                        }
                        
                }
                
        }
        
        
                private void addElement(String pattern, String newCdata, boolean wrapCDATA) throws JaxenException {
                        OMComment comment = findComment(pattern);
                        if(comment!=null) {
                                OMFactory fac = OMAbstractFactory.getOMFactory();
                                int type = OMNode.TEXT_NODE;
                                if(wrapCDATA) {
                                        type = OMNode.CDATA_SECTION_NODE;
                                }
                                OMText text = fac.createOMText(newCdata, type);
                                comment.insertSiblingAfter(text);
                        }                       
                }
                
                private void addElements(String pattern, List<String> files, String elementName) throws JaxenException {
                        if(files.size()<=0) return;
                        OMComment comment = findComment(pattern);
                        if(comment!=null) {
                                OMFactory fac = OMAbstractFactory.getOMFactory();
                                OMNamespace ns = template.findNamespace(nss, null);
                                if(ns == null) logger.error(String.format("The namespace '%s' is not defined in the template.", nss));
                                for(String s : files) {
                                        OMElement e = fac.createOMElement(elementName, ns);
                                        OMText text = fac.createOMText(s, OMNode.TEXT_NODE);
                                        e.addChild(text);
                                        comment.insertSiblingAfter(e);
                                }                               
                        }
                }
                
        
                private OMComment findComment(String pattern) throws JaxenException {
                        AXIOMXPath path = new AXIOMXPath("//comment()[. = '"+pattern+"'][1]");
                        //OMNamespace ns = template.findNamespace(nss, null);
                        path.addNamespace("bru1", nss);
                        OMComment n = (OMComment) path.selectSingleNode(template);
                        if(n!=null) return n;
                        logger.warn("Comment '"+pattern+"' was not found in the XML template.");
                        return null;
                }
                /*
                private static OMComment findComment(OMElement element, String pattern) {
                        logger.trace( String.format("Searching for comment pattern '%s' in element with name '%s'.", pattern, element.getLocalName()));
                        Iterator iter = element.getChildren();

                        while(iter.hasNext()) {
                                Object o = iter.next(); 
                                if(o instanceof OMNode) {
                                        OMNode node =  ((OMNode)o);
                                        
                                        switch (node.getType() ) {
                                        case OMNode.COMMENT_NODE:
                                                OMComment comment = ((OMComment)node);
                                                String value = comment.getValue().trim();
                                                if(value.equals(pattern)) {
                                                        logger.debug("Found comment '" + pattern + "' in event template.");
                                                        return comment;
                                                }
                                                break;
                                                

                                        case OMNode.ELEMENT_NODE:
                                                //traverse
                                                OMComment result = findComment( (OMElement)node, pattern);
                                                if(result!=null) return result;
                                                break;
                                                
                                        default:
                                                break;
                                        }
                                }
                        }
                        //logger.info("Comment '" + pattern + "' was not found in event template.");
                        return null;
                }
                */
                
        
        @SuppressWarnings("static-access")
        private static Options getOptions() {
                Option repository = OptionBuilder.withArgName( "repository" )
                                                                                        .hasArg()
                                                                                        .withLongOpt("repository")
                                                                                        .withDescription(  "Path or URL to the SVN repository." )
                                                                                        .create( PARAM_REPOS );
                repository.setRequired(true);
                
                Option txn = OptionBuilder.withArgName( "transactionid" )
                                                                                        .hasArg()
                                                                                        .withLongOpt("transaction")
                                                                                        .withDescription(  "The SVN transaction id to examine (TXN). You cannot combine txn with -rev. "
                                                                                                        + "When a txn is given, the repository path must be a local path.")
                                                                                        .create( PARAM_TXN );
                Option rev = OptionBuilder.withArgName( "revision" )
                                .hasArg()
                                .withDescription(  "A revision to examine. You cannot combine revision with -txn." )
                                .create( PARAM_REV );
                Option config = OptionBuilder.withArgName( "config_file" )
                                .hasArg()
                                .withLongOpt("config")
                                .withDescription(  "The configuration file to use. Defaults to 'emitter.properties'.")
                                .create( PARAM_CONFIG );
                
                Options options = new Options();
                options.addOption(repository);
                options.addOption(txn);
                options.addOption(rev);
                options.addOption(config);
                return options;
        }
        
        private static void printHelp() {
                // automatically generate the help statement
                HelpFormatter formatter = new HelpFormatter();
                String header = "\nSVN-ALFEventEmitter " + version +", a SVN hook implemented in Java to emit Eclipse ALFEvents on commit.\n\n";
                String footer = "Please send bug reports to bru@brutex.de.\n(c)2013 Brian Rosenberger";
                formatter.printHelp("java -jar SVN-ALFEventEmitter", header, getOptions(), footer, true);
        }
        
        
}