/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/svn/SVNAdminCommand.java |
---|
0,0 → 1,40 |
/* |
* Copyright 2014 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.svn; |
/** |
* The Enum SVNAdminCommand. Lists supported svnladmin commands |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
*/ |
public enum SVNAdminCommand { |
SETLOG("setlog"); |
private final String value; |
private SVNAdminCommand(String value) { |
this.value = value; |
} |
public String getValue() { |
return this.value; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/svn/SVNAdminExecutor.java |
---|
0,0 → 1,181 |
/* |
* Copyright 2014 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.svn; |
import java.io.BufferedReader; |
import java.io.BufferedWriter; |
import java.io.File; |
import java.io.FileOutputStream; |
import java.io.IOException; |
import java.io.InputStreamReader; |
import java.io.OutputStreamWriter; |
import java.util.ArrayList; |
import java.util.List; |
import java.util.Map; |
import org.apache.log4j.Logger; |
/* Executes the svnadmin utility |
* |
* @author Brian Rosenberger bru(at)brutex.de |
* @since 0.1 |
*/ |
public class SVNAdminExecutor { |
private Logger logger = Logger.getLogger(SVNAdminExecutor.class); |
private final File svnadmin; |
private final String repos; |
private String rev = null; |
private String message = null; |
private String locale = "de_DE.UTF-8"; |
private String encoding = "UTF-8"; |
private boolean useBypassHooks = true; |
/** |
* Instantiates a new SVN admin executor. |
* |
* @param svnadmin the svnadmin |
* @param repos the repos |
*/ |
public SVNAdminExecutor(File svnadmin, String repos) { |
if(! svnadmin.exists() ) throw new IllegalArgumentException( String.format("The svnadmin executable at '%s' does not exist.", svnadmin.toString())); |
if(! svnadmin.isFile() ) throw new IllegalArgumentException( String.format("The svnadmin utility at'%s' is not a file.", svnadmin.toString())); |
logger.debug(String.format("Instantiating '%s' with svnadmin at '%s'.", this.getClass().getCanonicalName(), svnadmin.toString())); |
this.svnadmin = svnadmin; |
logger.debug(String.format("Working against svn repository at '%s'.", repos)); |
this.repos = repos; |
} |
/** |
* Execute svn admin. |
* |
* @param command the command |
* @return the string |
*/ |
public String executeSVNAdmin(SVNAdminCommand command) { |
StringBuilder sb = new StringBuilder(); |
StringBuilder sberr = new StringBuilder(); |
if(rev==null) { |
logger.error("The revision can not be 'null' for the svnadmin command."); |
return null; |
} |
if(message==null) { |
logger.error("The new log message can not be 'null' for the svnadmin command."); |
return null; |
} |
File logfile = null; |
try { |
logfile = File.createTempFile("~msg"+rev+"_", ".tmp"); |
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logfile), encoding)); |
out.write(message); |
out.flush(); |
out.close(); |
} catch (IOException e) { |
logger.error("Failed to write new log message to temporary file '"+logfile.getAbsolutePath()+"'.", e); |
return null; |
} |
try { |
List<String> cmdline = new ArrayList<String>(5); |
cmdline.add(svnadmin.toString()); |
cmdline.add(command.getValue()); |
cmdline.add(repos); |
if(useBypassHooks) { |
cmdline.add("--bypass-hooks"); |
} |
cmdline.add("-r"); |
cmdline.add(rev); |
cmdline.add(logfile.getAbsolutePath()); |
ProcessBuilder pf = new ProcessBuilder(cmdline); |
logger.debug(String.format("Executing svnadmin with commandline '%s'.", pf.command())); |
Map<String, String> env = pf.environment(); |
env.put("LANG", locale); |
Process svnprocess = pf.start(); |
BufferedReader stdin = new BufferedReader(new InputStreamReader(svnprocess.getInputStream(), encoding)); |
BufferedReader stderr = new BufferedReader(new InputStreamReader(svnprocess.getErrorStream(), encoding)); |
String s; |
while( (s = stdin.readLine()) != null ) { |
sb.append(s + '\n'); |
} |
while( (s = stderr.readLine()) != null ) { |
sberr.append(s + '\n'); |
} |
stdin.close(); stderr.close(); |
} catch (IOException e) { |
logger.error( String.format( "Error calling the svnadmin utility: '%s'", e.getMessage())); |
e.printStackTrace(); |
} finally { |
logfile.deleteOnExit(); |
} |
String error = sberr.toString(); |
if( error.length()>0 ) { |
error = "Failed to call svnadmin. The STDERR was '"+error+"'"; |
logger.error(error); |
throw new IllegalArgumentException(error); |
} |
String output = sb.toString().trim(); |
logger.debug(String.format("Svnadmin output was '%s'", output)); |
return output; |
} |
public void setRev(String rev) { |
if(rev==null || rev.length()<=0) throw new IllegalArgumentException("Revision cannot be null or empty."); |
this.rev = rev; |
} |
public void setEncoding(String encoding) { |
this.encoding = encoding; |
} |
/** |
* Set the locale that will be pushed into |
* 'LANG' environment variable. |
* |
* @param locale i.e. de_DE.UTF-8 |
*/ |
public void setLocale(String locale) { |
this.locale = locale; |
} |
/** |
* Set the new log message. |
* |
* @param message new message |
*/ |
public void setMessage(String message) { |
this.message = message; |
} |
/** |
* Set this to true to bypass the pre-revprop-change and post-revprop-change |
* hooks. |
* |
* @param useBypassHooks defaults to true |
*/ |
public void setUseBypassHooks(boolean useBypassHooks) { |
this.useBypassHooks = useBypassHooks; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/svn/SVNLookExecutor.java |
---|
0,0 → 1,194 |
/* |
* 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.svn; |
import java.io.BufferedReader; |
import java.io.File; |
import java.io.IOException; |
import java.io.InputStreamReader; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.List; |
import java.util.Map; |
import java.util.StringTokenizer; |
import net.brutex.svn.SVNCommitInfo.ChangeType; |
import org.apache.log4j.Logger; |
/* Executes the svnlook utility |
* |
* @author Brian Rosenberger bru(at)brutex.de |
* @since 0.1 |
*/ |
public class SVNLookExecutor { |
private Logger logger = Logger.getLogger(SVNLookExecutor.class); |
private final File svnlook; |
private final String repos; |
private String TXN = null; |
private String rev = null; |
private String locale = "de_DE.UTF-8"; |
private String encoding = "UTF-8"; |
/** |
* Instantiates a new sVN look executor. |
* |
* @param svnlook the svnlook |
* @param repos the repos |
*/ |
public SVNLookExecutor(File svnlook, String repos) { |
if(! svnlook.exists() ) throw new IllegalArgumentException( String.format("The svnlook executable at '%s' does not exist.", svnlook.toString())); |
if(! svnlook.isFile() ) throw new IllegalArgumentException( String.format("The svnlook utility at'%s' is not a file.", svnlook.toString())); |
logger.debug(String.format("Instantiating '%s' with svnlook at '%s'.", this.getClass().getCanonicalName(), svnlook.toString())); |
this.svnlook = svnlook; |
logger.debug(String.format("Working against svn repository at '%s'.", repos)); |
this.repos = repos; |
} |
/** |
* Execute svn look. |
* |
* @param command the command |
* @return the string |
*/ |
private String executeSVNLook(SVNLookCommand command) { |
StringBuilder sb = new StringBuilder(); |
StringBuilder sberr = new StringBuilder(); |
//This throws an IllegalArgumentException when neither TXN nor REV is valid |
String[] params; |
try { |
params = getTargetParam(); |
} catch (IllegalArgumentException e) { |
logger.error(e.getMessage()); |
throw e; |
} |
try { |
List<String> cmdline = new ArrayList<String>(5); |
cmdline.add(svnlook.toString()); |
cmdline.add(command.getValue()); |
cmdline.add(params[0]); |
cmdline.add(params[1]); |
cmdline.add(repos); |
ProcessBuilder pf = new ProcessBuilder(cmdline); |
logger.debug(String.format("Executing svnlook with commandline '%s'.", pf.command())); |
Map<String, String> env = pf.environment(); |
env.put("LANG", locale); |
Process svnprocess = pf.start(); |
BufferedReader stdin = new BufferedReader(new InputStreamReader(svnprocess.getInputStream(), encoding)); |
BufferedReader stderr = new BufferedReader(new InputStreamReader(svnprocess.getErrorStream(), encoding)); |
String s; |
while( (s = stdin.readLine()) != null ) { |
sb.append(s + '\n'); |
} |
while( (s = stderr.readLine()) != null ) { |
sberr.append(s + '\n'); |
} |
stdin.close(); stderr.close(); |
} catch (IOException e) { |
logger.error( String.format( "Error calling the svnlook utility: '%s'", e.getMessage())); |
e.printStackTrace(); |
} |
String error = sberr.toString(); |
if( error.length()>0 ) { |
error = "Failed to call svnlook. The STDERR was '"+error+"'"; |
logger.error(error); |
throw new IllegalArgumentException(error); |
} |
String output = sb.toString().trim(); |
logger.debug(String.format("Svnlook output was '%s'", output)); |
return output; |
} |
/* |
* Returns either -t TXN oder -rev REVISION |
* |
* @returns |
*/ |
private String[] getTargetParam() { |
String[] result = new String[2]; |
if( (TXN==null || TXN.length()<=0) && (rev==null || rev.length()<=0) ) throw new IllegalArgumentException("Either TXN or revision must be provided."); |
if( TXN!=null && TXN.length()>0 && rev!=null && rev.length()>0 ) throw new IllegalArgumentException("Both, TXN and revision are given. Don't know what to use."); |
if( TXN!=null && TXN.length()>0) { |
result[0] = "-t"; |
result[1] = TXN; |
return result; |
} |
if( rev!=null && rev.length()>0) { |
result[0] = "-r"; |
result[1] = rev; |
return result; |
} |
throw new IllegalArgumentException("Either TXN or revision must be provided."); |
} |
public void setTXN(String TXN) { |
if(TXN==null || TXN.length()<=0) throw new IllegalArgumentException("TXN cannot be null or empty."); |
this.TXN = TXN; |
} |
public void setRev(String rev) { |
if(rev==null || rev.length()<=0) throw new IllegalArgumentException("Revision cannot be null or empty."); |
this.rev = rev; |
} |
public SVNCommitInfo getCommitInfo() { |
String author = executeSVNLook(SVNLookCommand.AUTHOR); |
String logmessage = executeSVNLook(SVNLookCommand.LOG); |
String files = executeSVNLook(SVNLookCommand.CHANGED); |
SVNCommitInfo result = new SVNCommitInfo(author, |
new Date(), |
logmessage); |
files += "\n"; |
StringTokenizer tokenizer = new StringTokenizer(files, "\n"); |
String s; |
while( tokenizer.hasMoreTokens()) { |
s=tokenizer.nextToken(); |
logger.debug(String.format("Tokenizing file list. Token '%s'.", s)); |
if(s.startsWith("A")) { result.addFileInfo(ChangeType.ADDED, s.substring(1).trim()); continue; } |
if(s.startsWith("D")) { result.addFileInfo(ChangeType.DELETED, s.substring(1).trim()); continue; } |
if(s.startsWith("UU")) { result.addFileInfo(ChangeType.BOTHUPDATE, s.substring(2).trim()); continue; } |
if(s.startsWith("_U")) { result.addFileInfo(ChangeType.METAUPDATE, s.substring(2).trim()); continue; } |
if(s.startsWith("U")) { result.addFileInfo(ChangeType.UPDATED, s.substring(1).trim()); continue; } |
} |
result.setTxn(TXN); |
result.setRev(rev); |
return result; |
} |
public void setEncoding(String encoding) { |
this.encoding = encoding; |
} |
/** |
* Set the locale that will be pushed into |
* 'LANG' environment variable. |
* |
* @param locale i.e. de_DE.UTF-8 |
*/ |
public void setLocale(String locale) { |
this.locale = locale; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/svn/SVNCommitInfo.java |
---|
0,0 → 1,361 |
/* |
* 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.svn; |
import java.util.ArrayList; |
import java.util.Date; |
import java.util.Iterator; |
import java.util.List; |
import java.util.regex.Matcher; |
import java.util.regex.Pattern; |
import org.apache.log4j.Logger; |
/** |
* The Class SVNCommitInfo represents changes commited to |
* a svn repository. The information is based on svnlook. |
* |
* 'A ' Object dem Projektarchiv hinzugefügt |
* 'D ' Objekt aus dem Projektarchiv gelöscht |
* 'U ' Dateiinhalt geändert |
* '_U' Eigenschaften eines Objektes geändert |
* 'UU' Dateiinhalt und Eigenschaften geändert |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
* |
*/ |
public class SVNCommitInfo { |
/** The logger. */ |
private final Logger logger = Logger.getLogger(SVNCommitInfo.class); |
/** The author. */ |
private final String author; |
/** The commit message */ |
private String logmessage; |
/** The date. */ |
private final Date date; |
/** The Alist. */ |
private final List<String> Alist = new ArrayList<String>(0); |
/** The Dlist. */ |
private final List<String> Dlist = new ArrayList<String>(0); |
/** The Ulist. */ |
private final List<String> Ulist = new ArrayList<String>(5); |
/** The _ ulist. */ |
private final List<String> _Ulist = new ArrayList<String>(0); |
/** The U ulist. */ |
private final List<String> UUlist = new ArrayList<String>(0); |
/** The issues. */ |
private final List<String> issues = new ArrayList<String>(1); |
/** The txn. */ |
private String txn=""; |
/** The rev. */ |
private String rev=""; |
/** |
* Instantiates a new SVN commit info. |
* |
* @param author the commiter |
* @param date the commit date |
* @param logmessage the commit message |
*/ |
public SVNCommitInfo(String author, Date date, String logmessage) { |
this.author = author; |
this.date = date; |
this.logmessage = logmessage; |
} |
/** |
* Adds the file info. |
* |
* @param t the t |
* @param file the file |
*/ |
public void addFileInfo(ChangeType t, String file) { |
switch (t) { |
case ADDED: |
Alist.add(file); |
break; |
case DELETED: |
Dlist.add(file); |
break; |
case UPDATED: |
Ulist.add(file); |
break; |
case METAUPDATE: |
_Ulist.add(file); |
break; |
case BOTHUPDATE: |
UUlist.add(file); |
break; |
default: |
break; |
} |
} |
/** |
* Gets the author. |
* |
* @return the author |
*/ |
public String getAuthor() { |
return author; |
} |
/** |
* Gets the commit message. |
* |
* @return the commit message |
*/ |
public String getLogmessage() { |
return logmessage; |
} |
/** |
* Gets the commit date. |
* |
* @return the commit date |
*/ |
public Date getDate() { |
return date; |
} |
/** |
* Gets the svn transaction id. |
* |
* @return the txn |
*/ |
public String getTxn() { |
return txn; |
} |
/** |
* Sets the txn. |
* |
* @param txn the new txn |
*/ |
public void setTxn(String txn) { |
this.txn = txn; |
} |
/** |
* Gets the id. This is either the txn or revision. |
* |
* @return the id |
*/ |
public String getId() { |
if(txn!=null) return txn; |
return rev; |
} |
/** |
* Sets the rev. |
* |
* @param rev the new rev |
*/ |
public void setRev(String rev) { |
this.rev = rev; |
} |
/** |
* Gets the rev. |
* |
* @return the rev |
*/ |
public String getRev() { |
return rev; |
} |
/* |
* http://openbook.galileocomputing.de/javainsel9/javainsel_04_007.htm#mjd5b5d84cb3f1b5bcb7638ea9221a491f |
*/ |
/** |
* Parses the issues. |
* |
* @param patterns the patterns |
* @param isRemoveIssues |
*/ |
public void parseIssues(String[] patterns, boolean isRemoveIssues) { |
issues.clear(); //reset |
int count = 0; |
for(String p : patterns) { |
Pattern regex = Pattern.compile(p); |
Matcher matcher = regex.matcher(logmessage); |
logger.debug(String.format("Matching regex pattern '%s' against logmessage '%s'.", matcher.pattern().pattern(), logmessage)); |
while( matcher.find()) { |
issues.add( matcher.group() ); |
logger.debug("Found issue '" + matcher.group() + "' in the logmessage."); |
count++; |
} |
if(isRemoveIssues) { |
logmessage = matcher.replaceAll(""); |
logger.debug("Removing all matched issues from commit message"); |
} |
} |
logger.debug("Found '" + count + "' issues in the logmessage."); |
} |
/** |
* Gets the change file list as string. |
* |
* @return the change file list as string |
*/ |
public String getChangeFileListAsString() { |
StringBuilder sb = new StringBuilder(); |
for (Iterator<String> iterator = Alist.iterator(); iterator.hasNext();) |
{ |
sb.append("A \t"); |
sb.append(iterator.next()); |
sb.append("\n"); |
} |
for (Iterator<String> iterator = Dlist.iterator(); iterator.hasNext();) |
{ |
sb.append("D \t"); |
sb.append(iterator.next()); |
sb.append("\n"); |
} |
for (Iterator<String> iterator = Ulist.iterator(); iterator.hasNext();) |
{ |
sb.append("U \t"); |
sb.append(iterator.next()); |
sb.append("\n"); |
} |
for (Iterator<String> iterator = _Ulist.iterator(); iterator.hasNext();) |
{ |
sb.append("_U\t"); |
sb.append(iterator.next()); |
sb.append("\n"); |
} |
for (Iterator<String> iterator = UUlist.iterator(); iterator.hasNext();) |
{ |
sb.append("UU\t"); |
sb.append(iterator.next()); |
sb.append("\n"); |
} |
sb.append("Summary: " + (Ulist.size()+UUlist.size()+_Ulist.size()) + " files updated, "); |
sb.append(Alist.size() + " files added, " + Dlist.size() + " files deleted."); |
return sb.toString(); |
} |
/** |
* Gets the added files. |
* |
* @return the added files |
*/ |
public List<String> getAddedFiles() { |
return Alist; |
} |
/** |
* Gets the deleted files. |
* |
* @return the deleted files |
*/ |
public List<String> getDeletedFiles() { |
return Dlist; |
} |
/** |
* Gets the changed files. |
* |
* @return the changed files |
*/ |
public List<String> getChangedFiles() { |
List<String> changed = new ArrayList<String>(); |
changed.addAll(Ulist); |
changed.addAll(UUlist); |
changed.addAll(_Ulist); |
return changed; |
} |
/** |
* Gets the issues. |
* |
* @return the issues |
*/ |
public List<String> getIssues() { |
return issues; |
} |
/** |
* The Enum ChangeType. |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
*/ |
public enum ChangeType { |
/** The added. */ |
ADDED("A "), |
/** The deleted. */ |
DELETED("D "), |
/** The updated. */ |
UPDATED("U "), |
/** The metaupdate. */ |
METAUPDATE("_U"), |
/** The bothupdate. */ |
BOTHUPDATE("UU"); |
/** The indicator. */ |
private final String indicator; |
/** |
* Instantiates a new change type. |
* |
* @param svn the svn |
*/ |
private ChangeType(String svn) { |
this.indicator = svn; |
} |
/** |
* Gets the enum. |
* |
* @param s the s |
* @return the enum |
*/ |
public static ChangeType getEnum(String s) { |
for(ChangeType e : ChangeType.values()) { |
if(s.equals(e.getIndicator())) return e; |
} |
throw new IllegalArgumentException("ChangeType enum for value '"+s+"' does not exist."); |
} |
/** |
* Gets the indicator. |
* |
* @return the indicator |
*/ |
public String getIndicator() { |
return this.indicator; |
} |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/svn/SVNLookCommand.java |
---|
0,0 → 1,42 |
/* |
* 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.svn; |
/** |
* The Enum SVNLookCommand. Lists supported svnlook commands |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
*/ |
public enum SVNLookCommand { |
CHANGED("changed"), |
LOG("log"), |
AUTHOR("author"); |
private final String value; |
private SVNLookCommand(String value) { |
this.value = value; |
} |
public String getValue() { |
return this.value; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/emitter/ALFEmitter.java |
---|
0,0 → 1,748 |
/* |
* 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.math.BigInteger; |
import java.net.MalformedURLException; |
import java.net.URL; |
import java.text.SimpleDateFormat; |
import java.util.ArrayList; |
import java.util.HashMap; |
import java.util.Iterator; |
import java.util.List; |
import java.util.Map; |
import java.util.UUID; |
import javax.xml.bind.JAXBContext; |
import javax.xml.bind.JAXBElement; |
import javax.xml.bind.Marshaller; |
import javax.xml.namespace.QName; |
import javax.xml.stream.XMLStreamException; |
import javax.xml.ws.BindingProvider; |
import net.brutex.emitter.util.EmitterUtil; |
import net.brutex.sbm.sbmappservices72.AEWebservicesFaultFault; |
import net.brutex.sbm.sbmappservices72.Sbmappservices72; |
import net.brutex.sbm.sbmappservices72.Sbmappservices72PortType; |
import net.brutex.sbm.sbmappservices72.api.Auth; |
import net.brutex.sbm.sbmappservices72.api.MultipleResponseItemOptions; |
import net.brutex.sbm.sbmappservices72.api.ObjectFactory; |
import net.brutex.sbm.sbmappservices72.api.SectionsOption; |
import net.brutex.sbm.sbmappservices72.api.TTItemList; |
import net.brutex.sbm.sbmappservices72.api.TableIdentifier; |
import net.brutex.svn.SVNAdminCommand; |
import net.brutex.svn.SVNAdminExecutor; |
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.cxf.endpoint.Client; |
import org.apache.cxf.frontend.ClientProxy; |
import org.apache.cxf.interceptor.LoggingInInterceptor; |
import org.apache.cxf.interceptor.LoggingOutInterceptor; |
import org.apache.cxf.message.Message; |
import org.apache.http.client.ClientProtocolException; |
import org.apache.log4j.Logger; |
import org.jaxen.JaxenException; |
import com.sun.xml.bind.v2.runtime.JAXBContextImpl; |
/** |
* The Class ALFEmitter. |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
*/ |
public class ALFEmitter { |
public static final String VERSION = "0.1"; |
private static Logger logger = Logger.getRootLogger(); |
// |
// Keys to read from the configuration file. |
// |
private static final String OPTION_SVNLOOK = "svnlook"; |
private static final String OPTION_SVNADMIN = "svnadmin"; |
private static final String OPTION_LOCALE = "env.LANG"; |
private static final String OPTION_ENCODING = "env.encoding"; |
private static final String OPTION_ISSUEPATTERN = "issuepattern"; |
private static final String OPTION_EVENTTEMPLATE = "eventtemplate"; |
private static final String OPTION_EVENTNAMESPACE = "eventnamespace"; |
private static final String OPTION_EVENTMANAGER_URL = "eventmanager"; |
private static final String OPTION_EVENTMANAGER_USER = "eventmanager.user"; |
private static final String OPTION_EVENTMANAGER_PASSWORD = "eventmanager.password"; |
private static final String OPTION_SBM_ENDPOINT = "sbmappservices72"; |
private static final String OPTION_SBM_USER = "sbmuser"; |
private static final String OPTION_SBM_PASSWORD = "sbmpassword"; |
private static final String OPTION_SBM_TABLE = "querytable"; |
private static final String OPTION_SBM_QUERY = "query"; |
private static final String OPTION_MARKER_LOGMESSAGE = "marker.logmessage"; |
private static final String OPTION_MARKER_AUTHOR = "marker.author"; |
private static final String OPTION_MARKER_REVISION = "marker.revision"; |
private static final String OPTION_MARKER_ADDEDFILES = "marker.addedfiles"; |
private static final String OPTION_MARKER_DELETEDFILES = "marker.deletedfiles"; |
private static final String OPTION_MARKER_CHANGEDFILES = "marker.changedfiles"; |
private static final String OPTION_MARKER_ISSUES = "marker.issues"; |
private static final String OPTION_MARKER_INTERNALISSUES = "marker.internalissues"; |
private static final String OPTION_REMOVE_ISSUES_FROM_COMMIT = "removeissuesfromcommit"; |
private static final String OPTION_IS_SOAPENABLED = "isSoapEnabled"; |
private static final String OPTION_IS_DROPENABLED = "isDropResponse"; |
private static final String OPTION_IS_FORCEFAILENABLED = "forcefail"; |
private static final String OPTION_IS_VERIFICATIONENABLED = "isWithVerification"; |
private static final String OPTION_IS_UPDATECOMMITMESSAGE = "isWithMessageUpdate"; |
private static final String OPTION_IS_WSTRACE = "trace"; |
private static final String OPTION_IS_XMLPROCESSINGENABLED = "isXmlProcessingEnabled"; |
// |
// Command line parameters |
// |
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"; |
// |
// Member variables |
// |
private final String repos; |
private final String txn; |
private final String rev; |
private SVNCommitInfo info; |
private OMElement template = null; |
private Configuration config; |
private String nss = null; |
private final long startTime; |
//Member for SBM endpoint configuration |
private final String endpoint; |
private final String sbm_user; |
private final String sbm_pass; |
private final String querytable; |
private final String query; |
private final List<String> internalissues = new ArrayList<String>(); |
//SBM IssueTypePrefix+IssueId, Title |
private final Map<String, String> issues_titles = new HashMap<String, String>(); |
/** |
* 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); |
} |
try { |
ALFEmitter emitter = new ALFEmitter(cmd, startTime); |
} catch (ConfigurationException e) { |
System.exit(1); |
} catch (MalformedURLException e) { |
logger.error("Could not find/ load wsdl url.", e); |
System.exit(1); |
} |
long endTime = System.currentTimeMillis(); |
logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds."); |
System.exit(0); |
} |
/** |
* Read a configuration parameter from the config file |
* Creates log messages according to parameters. |
* |
* @param key property name |
* @param defaultValue default value or null |
* @param isRequired wether or not this is a required option |
* @param logmessage optional log message (or null) |
* @return property value |
* @throws ConfigurationException |
*/ |
private Object readConfProperty(String key, Object defaultValue, boolean isRequired, PropertyType type, String logmessage) throws ConfigurationException { |
Object value = null; |
switch (type) { |
case BOOLEAN: |
value = config.getBoolean(key, (Boolean) defaultValue); |
break; |
case STRINGARRAY: |
value = config.getStringArray(key); |
defaultValue = null; |
break; |
default: |
value = config.getString(key, (String) defaultValue); |
break; |
} |
if(isRequired && value == null) { |
//required property |
if(defaultValue == null) { |
//No value, no default |
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); |
logger.error(s); |
throw new ConfigurationException(s); |
} |
if(defaultValue!=null) { |
//No value, but default |
logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is required.", value, key)); |
} |
} |
if( (! isRequired) && value == null) { |
//not required |
if(value == null && defaultValue == null) { |
//No value, no default |
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); |
logger.warn(s); |
} |
if(value == null && defaultValue!=null) { |
//No value, but default |
logger.debug(String.format("Using property value '%s' for key '%s'. This is the default value. The property is optional.", value, key)); |
} |
} |
if(logmessage==null) logmessage=""; |
if(value!=null) logger.debug(String.format("Using property value '%s' for key '%s'. %s", value, key, logmessage)); |
return value; |
} |
private String readConfPropertyAsString(String key, String defaultValue, boolean isRequired, String logmessage) throws ConfigurationException { |
return (String) readConfProperty(key, defaultValue, isRequired, PropertyType.STRING, logmessage); |
} |
private String[] readConfPropertyAsStringArray(String key, boolean isRequired, String logmessage) throws ConfigurationException { |
return (String[]) readConfProperty(key, null, isRequired, PropertyType.STRINGARRAY, logmessage); |
} |
private boolean readConfPropertyAsBoolean(String key, boolean defaultValue, boolean isRequired, String logmessage) throws ConfigurationException { |
Boolean b = (Boolean) readConfProperty(key, defaultValue, isRequired, PropertyType.BOOLEAN, logmessage); |
return b.booleanValue(); |
} |
private ALFEmitter(CommandLine cmd, long startTime) throws ConfigurationException, MalformedURLException { |
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"); |
EmitterUtil.verifyFile(config_file, false, false); |
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); |
this.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 = readConfPropertyAsString(OPTION_SVNLOOK, null, true, null); |
EmitterUtil.verifyFile(svnlook, false, true); |
final String locale = readConfPropertyAsString(OPTION_LOCALE, "de_DE.UTF-8", true, null); |
final String encoding = readConfPropertyAsString(OPTION_ENCODING, "UTF-8", true, "Note that this should match your selected '"+OPTION_LOCALE+"'."); |
// Issue Id RegEx to parse commit message |
final String[] issuepatterns = readConfPropertyAsStringArray(OPTION_ISSUEPATTERN, false, null); |
StringBuilder sb = new StringBuilder(); for(String s : issuepatterns) sb.append(s); |
logger.debug(String.format("Using issue id patterns: '%s'.", sb.toString())); |
// Flags to indicate what should be done |
final boolean isSoapEnabled = readConfPropertyAsBoolean(OPTION_IS_SOAPENABLED, true, true, null); |
final boolean isXmlProcessingEnabled = readConfPropertyAsBoolean(OPTION_IS_XMLPROCESSINGENABLED, true, true, null); |
final boolean isWithVerification= readConfPropertyAsBoolean(OPTION_IS_VERIFICATIONENABLED, false, true, null); |
final boolean isRemoveIssues = readConfPropertyAsBoolean(OPTION_REMOVE_ISSUES_FROM_COMMIT, false, true, ""); |
final boolean isWithCommitUpdate= readConfPropertyAsBoolean(OPTION_IS_UPDATECOMMITMESSAGE, false, true, ""); |
/* |
* SVNLook phase |
* Use svnlook to obtain information from SVN |
*/ |
SVNLookExecutor exec = new SVNLookExecutor(new File(svnlook), repos); |
if(cmd.hasOption(PARAM_TXN)) exec.setTXN(txn); |
if(cmd.hasOption(PARAM_REV)) exec.setRev(rev); |
exec.setEncoding(encoding); |
exec.setLocale(locale); |
info = exec.getCommitInfo(); |
info.parseIssues(issuepatterns, isRemoveIssues); |
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()); |
/* |
* Verification phase |
*/ |
boolean isTrace = false; |
if(isWithVerification) { |
sbm_user = readConfPropertyAsString(OPTION_SBM_USER, null, true, null); |
sbm_pass = readConfPropertyAsString(OPTION_SBM_PASSWORD, null, false, null); |
endpoint = readConfPropertyAsString(OPTION_SBM_ENDPOINT, "http://localhost/gsoap/gsoap_ssl.dll?sbmappservices72", true, null); |
querytable = readConfPropertyAsString(OPTION_SBM_TABLE, null, true, null); |
query = readConfPropertyAsString(OPTION_SBM_QUERY, null, false, null); |
isTrace = readConfPropertyAsBoolean(OPTION_IS_WSTRACE, false, true, null); |
logger.debug(String.format("Starting verification for '%s' issues in the list.", info.getIssues().size())); |
boolean isOK = verify(info.getIssues(), isTrace); |
if(! isOK ) { |
logger.error("Verification of issue failed. No matching issue was found."); |
this.exit(1); |
} |
} else { |
sbm_user = null; sbm_pass=null; endpoint=null; querytable=null; query=null; |
} |
/* |
* Modify original commit message |
* using svnadmin command |
*/ |
if(isWithCommitUpdate) { |
String svnadmin = readConfPropertyAsString(OPTION_SVNADMIN, null, true, null); |
EmitterUtil.verifyFile(svnadmin, false, true); |
/* If verification was turned on, we do already have the titles |
* so only try to load the items when verification was off |
*/ |
if(! isWithVerification) { |
verify(info.getIssues(), isTrace); |
} |
/* Append associated items information and change log message */ |
StringBuffer newmessage = new StringBuffer(); |
newmessage.append(info.getLogmessage()); |
newmessage.append("\n\n Associated SBM items:\n"); |
for(String s : issues_titles.keySet()) { |
newmessage.append(s+": "); |
newmessage.append(issues_titles.get(s)); |
newmessage.append("\n"); |
} |
postCommitUpdate(new File(svnadmin), repos, locale, encoding, rev, newmessage.toString()); |
} |
/* |
* XML processing phase |
*/ |
if(isXmlProcessingEnabled) { |
} |
/* |
* ALF Event Send phase |
*/ |
String eventmanager = null; |
if(isSoapEnabled) { |
eventmanager = readConfPropertyAsString(OPTION_EVENTMANAGER_URL, null, true, null); |
} |
/** |
* Event XML Erzeugen |
*/ |
try { |
String resultxml=null; |
if(isXmlProcessingEnabled) { |
processXml(); |
addALFSecurity(); |
addEventHeader(); |
// Serialize xml message to String |
StringWriter out = new StringWriter(); |
template.getParent().serialize(out); |
out.flush(); |
resultxml = out.getBuffer().toString(); |
logger.debug("ALFEvent result:\n"+resultxml); |
} else { |
logger.debug("Xml processing is deactivated."); |
} |
if(isSoapEnabled && isXmlProcessingEnabled) { |
final boolean isDropResponse = readConfPropertyAsBoolean(OPTION_IS_DROPENABLED, true, true, null); |
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 and/ or xml processing is deactivated."); |
} |
} catch (FileNotFoundException e) { |
logger.error(e.getMessage(), e); |
this.exit(1); |
} catch (ClientProtocolException e) { |
logger.error(e.getMessage(), e); |
this.exit(1); |
} catch (IOException e) { |
logger.error(e.getMessage(), e); |
this.exit(1); |
} catch (XMLStreamException e) { |
logger.error(e.getMessage(), e); |
this.exit(1); |
} catch (JaxenException e) { |
logger.error(e.getMessage(), e); |
this.exit(1); |
} finally { |
String forcefail = config.getString(OPTION_IS_FORCEFAILENABLED, ""); |
if(forcefail.length()>0) { |
logger.warn("Force fail is active. All commits will be blocked."); |
this.exit(1); |
} |
} |
} |
private void addEventHeader() throws JaxenException { |
AXIOMXPath path = new AXIOMXPath("//bru1:Base/bru1:EventId"); |
path.addNamespace("bru1", nss); |
OMElement 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("1")); |
} |
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() )); |
} |
} |
private void addALFSecurity() throws ConfigurationException, JaxenException { |
final String eventmanager_user = readConfPropertyAsString(OPTION_EVENTMANAGER_USER, null, false, null); |
final String eventmanager_pass = readConfPropertyAsString(OPTION_EVENTMANAGER_PASSWORD, null, false, null); |
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); |
} |
} |
private void processXml() throws ConfigurationException, JaxenException { |
// read additional configuration |
final String eventtemplate = readConfPropertyAsString(OPTION_EVENTTEMPLATE, null, true, null); |
EmitterUtil.verifyFile(eventtemplate, false, false); |
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); |
this.exit(1); |
} |
nss = readConfPropertyAsString(OPTION_EVENTNAMESPACE, "http://www.eclipse.org/alf/schema/EventBase/1", true, null); |
final String marker_logmessage = readConfPropertyAsString(OPTION_MARKER_LOGMESSAGE, "@@logmessage@@", true, null); |
final String marker_author = readConfPropertyAsString(OPTION_MARKER_AUTHOR, "@@author@@", true, null); |
final String marker_revision = readConfPropertyAsString(OPTION_MARKER_REVISION, "@@revision@@", true, null); |
final String marker_addedfiles = readConfPropertyAsString(OPTION_MARKER_ADDEDFILES, "@@addedfiles@@", true, null); |
final String marker_deletedfiles = readConfPropertyAsString(OPTION_MARKER_DELETEDFILES, "@@deletedfiles@@", true, null); |
final String marker_changedfiles = readConfPropertyAsString(OPTION_MARKER_CHANGEDFILES, "@@changedfiles@@", true, null); |
final String marker_fileselementname = readConfPropertyAsString("marker.fileselementname", "file", true, null); |
final String marker_issues = readConfPropertyAsString(OPTION_MARKER_ISSUES, "@@issues@@", true, null); |
final String marker_issueselementname = readConfPropertyAsString("marker.issueselementname", "issue", true, null); |
final String marker_internalissues = readConfPropertyAsString(OPTION_MARKER_INTERNALISSUES, "@@internalissues@@", true, null); |
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 |
// add content from SVNCommitInfo object where |
// XML commit markers are |
addElement( marker_logmessage, info.getLogmessage(), true); |
addElement(marker_author, info.getAuthor(), false); |
addElement(marker_revision, info.getRev(), 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); |
addElements(marker_internalissues, internalissues, marker_issueselementname); |
} |
private boolean verify(List<String> issues, boolean isTrace) throws MalformedURLException { |
for(String issueid : issues) { |
TTItemList items = getTTItems(issueid, isTrace); |
if(items == null) { |
return false; |
} |
} |
return true; |
} |
private TTItemList getTTItems(String issueid, boolean isTrace) throws MalformedURLException { |
long startTime = System.currentTimeMillis(); |
/* -- */ |
Sbmappservices72 ss = new Sbmappservices72(ClassLoader.getSystemResource("sbmappservices72.wsdl") ); |
logger.debug("Total execution of sbmappservices72 wsdl read took '"+(System.currentTimeMillis()-startTime)+"' milliseconds."); |
Sbmappservices72PortType port = ss.getSbmappservices72(); |
Client client = ClientProxy.getClient(port); |
if(isTrace) { |
client.getInInterceptors().add(new LoggingInInterceptor()); |
client.getOutInterceptors().add(new LoggingOutInterceptor()); |
} |
BindingProvider bindingProvider = (BindingProvider) port; |
bindingProvider.getRequestContext().put( |
BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint); |
/* -- */ |
logger.debug("Total execution of sbmappservices72 initialisation took '"+(System.currentTimeMillis()-startTime)+"' milliseconds."); |
ObjectFactory fac = new ObjectFactory(); |
Auth auth = fac.createAuth(); |
auth.setUserId(fac.createAuthUserId(sbm_user)); |
auth.setPassword(fac.createAuthPassword(sbm_pass)); |
TableIdentifier table = fac.createTableIdentifier(); |
table.setDbName(fac.createTableIdentifierDbName(querytable)); |
MultipleResponseItemOptions options = fac.createMultipleResponseItemOptions(); |
options.setSpecifiedSections(fac.createResponseItemOptionsSpecifiedSections("SECTION:FIXED")); |
options.setSections(SectionsOption.SECTIONS_SPECIFIED); |
issueid = issueid.replaceAll("[^0-9]", ""); |
String queryWhereClause = "TS_ISSUEID = '"+issueid+"'"; |
if(query!=null && query.length()>0) queryWhereClause = queryWhereClause + " And " + query; |
TTItemList items = null; |
logger.debug(String.format("Using query against table '%s'. Query where clause: '%s'", querytable, queryWhereClause )); |
try { |
startTime = System.currentTimeMillis(); |
items = port.getItemsByQuery(auth, table, queryWhereClause, "", null, BigInteger.valueOf(1), options); |
logger.debug("Total execution of sbmappservices72 GetItems took '"+(System.currentTimeMillis()-startTime)+"' milliseconds."); |
//Marshaller m = JAXBContext.newInstance(TTItemList.class).createMarshaller(); |
//m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); |
//m.marshal( new JAXBElement<TTItemList>(new QName("uri","local"), TTItemList.class, items), System.err); |
logger.debug(String.format("Got Response from getItemsByQuery")); |
if(items!=null) { |
logger.debug(String.format("Verification query matched '%s' item(s) for issue '%s.'",items.getTotalCount(), issueid)); |
} |
if(items.getTotalCount().intValue()<=0) { |
return null; |
} else { |
/* store internal ids (tableid:itemid) */ |
internalissues.add(items.getItem().get(0).getId().getValue().getTableIdItemId().getValue()); |
/* Store a map entry with internal id and title */ |
issues_titles.put(items.getItem().get(0).getId().getValue().getDisplayName().getValue(), |
items.getItem().get(0).getTitle().getValue()); |
} |
} catch (AEWebservicesFaultFault e) { |
logger.debug("Web service fault: " + e.getFaultInfo()); |
} catch (Exception e) { |
logger.debug("Unknown Exception", e); |
} |
return items; |
} |
private void postCommitUpdate(File svnadmin, String repos, String locale, String encoding, String revision, String newmessage) { |
SVNAdminExecutor exec = new SVNAdminExecutor(svnadmin, repos); |
exec.setRev(revision); |
exec.setMessage(newmessage); |
exec.setEncoding(encoding); |
exec.setLocale(locale); |
exec.executeSVNAdmin(SVNAdminCommand.SETLOG); |
} |
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 void exit(int errorCode) { |
long endTime = System.currentTimeMillis(); |
logger.debug("Total execution took '"+(endTime-startTime)+"' milliseconds."); |
System.exit(errorCode); |
} |
@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)2014 Brian Rosenberger"; |
formatter.printHelp("java -jar SVN-ALFEventEmitter", header, getOptions(), footer, true); |
} |
private enum PropertyType { |
STRING(), STRINGARRAY(), BOOLEAN(); |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/emitter/EventManagerContext.java |
---|
0,0 → 1,91 |
/* |
* Copyright 2014 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.UnsupportedEncodingException; |
import java.net.MalformedURLException; |
import java.net.URL; |
import org.apache.log4j.Logger; |
/** |
* The EventManagerContext class represents the eventmanager endpoint and authentication credentials. |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
*/ |
public class EventManagerContext { |
private Logger logger = Logger.getLogger(EventManagerContext.class); |
private final URL url; |
private final String user; |
private final byte[] pass; |
private static final String CHARSET_UTF8 = "UTF-8"; |
/** |
* Create a new Eventmanager context. |
* |
* @param url URL for the SBM ALF Eventmanager |
* @param username ALFSecurity user name |
* @param password ALFSecurity password |
* @throws MalformedURLException |
*/ |
public EventManagerContext(String url, String username, String password) throws MalformedURLException { |
//Verify URL |
try { |
this.url = new URL(url); |
} catch (MalformedURLException e) { |
logger.error(String.format("Could not parse '%s' as a valid URL. %s", url, e.getMessage())); |
throw e; |
} |
//Verify username |
this.user = username; |
if(this.user==null) { |
final String s = "Username for ALF Eventmanager cannot be null."; |
logger.error(s); |
throw new IllegalArgumentException(s); |
} |
//Verify password |
try { |
this.pass = password.getBytes(CHARSET_UTF8); |
} catch (UnsupportedEncodingException e) { |
e.printStackTrace(); |
throw new IllegalArgumentException(e.getMessage()); |
} |
if(this.pass==null) { |
final String s = "Password for ALF Eventmanager cannot be null."; |
logger.error(s); |
throw new IllegalArgumentException(s); |
} |
} |
public URL getUrl() { |
return url; |
} |
public String getUser() { |
return user; |
} |
public byte[] getPass() { |
return pass; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/emitter/SimpleHttpEvent.java |
---|
0,0 → 1,101 |
/* |
* 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.BufferedReader; |
import java.io.IOException; |
import java.io.InputStreamReader; |
import org.apache.http.HttpEntity; |
import org.apache.http.HttpResponse; |
import org.apache.http.client.ClientProtocolException; |
import org.apache.http.client.entity.EntityBuilder; |
import org.apache.http.client.methods.HttpPost; |
import org.apache.http.impl.client.CloseableHttpClient; |
import org.apache.http.impl.client.HttpClients; |
import org.apache.http.util.EntityUtils; |
import org.apache.log4j.Logger; |
/** |
* Construct a HTTP POST and send it. |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
* @since 0.1 |
*/ |
public class SimpleHttpEvent { |
private final Logger logger = Logger.getLogger(SimpleHttpEvent.class); |
private final String url; |
private final String soapBody; |
private long duration = 0; |
/** |
* Instantiates a new simple http event. |
* |
* @param url the url |
* @param soapBody the soap body |
*/ |
public SimpleHttpEvent(String url, String soapBody) { |
this.url = url; |
this.soapBody = soapBody; |
} |
/** |
* Send soap. |
* |
* @param url the url |
* @param soapBody the soap body |
* @throws ClientProtocolException the client protocol exception |
* @throws IOException Signals that an I/O exception has occurred. |
*/ |
public void sendSoap(boolean isDropResponse) throws ClientProtocolException, IOException { |
long start = System.currentTimeMillis(); |
HttpPost post = new HttpPost(url); |
post.addHeader("Accept" , "text/xml"); |
post.addHeader("SOAPAction",""); |
EntityBuilder entitybuilder = EntityBuilder.create(); |
entitybuilder.setContentEncoding("UTF-8"); |
entitybuilder.setText(soapBody); |
HttpEntity entity = entitybuilder.build(); |
post.setEntity(entity); |
CloseableHttpClient httpclient = HttpClients.createDefault(); |
HttpResponse r = httpclient.execute(post); |
logger.debug("Sending event to ALF event manager"); |
if(! isDropResponse) { |
HttpEntity e = r.getEntity(); |
StringBuilder sb = new StringBuilder(); |
BufferedReader in = new BufferedReader(new InputStreamReader(e.getContent())); |
String s; |
while( (s=in.readLine()) != null) { |
sb.append(s); |
} |
logger.debug("Response: \n " + sb.toString()); |
} else { |
logger.debug("Response was dropped."); |
} |
duration = System.currentTimeMillis() - start; |
} |
/** |
* Get the response time of the soap call in milliseconds. |
* |
* @return duration or '0' if not yet executed |
*/ |
public long getDuration() { |
return duration; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |
/SVN-ALFEventEmitter/branches/Maint 0.1 JRE6/src/net/brutex/emitter/util/EmitterUtil.java |
---|
0,0 → 1,60 |
/* |
* Copyright 2014 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.util; |
import java.io.File; |
import org.apache.log4j.Logger; |
/** |
* The Class EmitterUtil. |
* |
* @author Brian Rosenberger, bru(at)brutex.de |
*/ |
public final class EmitterUtil { |
private static Logger logger = Logger.getLogger(EmitterUtil.class); |
/** |
* Check if the file exists and is readable. |
* |
* @param file The file to check |
* @param isWritable also check if file is writable |
* @param isExecutable also check if file is executable |
* @return |
*/ |
public static boolean verifyFile(String file, boolean isWritable, boolean isExecutable) { |
logger.debug(String.format("Verifying file '%s'.", file)); |
File f = new File(file); |
String fn = f.getAbsolutePath(); |
if(f.exists() && f.isFile()) { |
if(isWritable && !f.canWrite()) { |
logger.error(String.format("Cannot write to file '%s'.", fn)); |
return false; |
} |
if(isExecutable && !f.canExecute()) { |
logger.error(String.format("Cannot execute file '%s'.", fn)); |
return false; |
} |
return true; |
} |
logger.error(String.format("Cannot read file '%s'.", fn)); |
return false; |
} |
} |
Property changes: |
Added: svn:mime-type |
+text/plain |
\ No newline at end of property |