diff --git a/src/main/org/apache/tools/ant/taskdefs/Delete.java b/src/main/org/apache/tools/ant/taskdefs/Delete.java index 31a358f2c..0b2b0e609 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Delete.java +++ b/src/main/org/apache/tools/ant/taskdefs/Delete.java @@ -145,7 +145,7 @@ public class Delete extends MatchingTask { * @param failonerror true or false */ public void setFailOnError(boolean failonerror) { - this.failonerror=failonerror; + this.failonerror = failonerror; } @@ -291,9 +291,9 @@ public class Delete extends MatchingTask { log("Deleting: " + file.getAbsolutePath()); if (!file.delete()) { - String message="Unable to delete file " + String message = "Unable to delete file " + file.getAbsolutePath(); - if(failonerror) { + if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE @@ -325,7 +325,7 @@ public class Delete extends MatchingTask { } // delete the files in the filesets - for (int i=0; i 0) { log("Deleting " + files.length + " files from " + d.getAbsolutePath()); - for (int j=0; j 0 && includeEmpty) { int dirCount = 0; - for (int j=dirs.length-1; j>=0; j--) { + for (int j = dirs.length - 1; j >= 0; j--) { File dir = new File(d, dirs[j]); String[] dirFiles = dir.list(); if (dirFiles == null || dirFiles.length == 0) { log("Deleting " + dir.getAbsolutePath(), verbosity); if (!dir.delete()) { - String message="Unable to delete directory " + String message = "Unable to delete directory " + dir.getAbsolutePath(); - if(failonerror) { + if (failonerror) { throw new BuildException(message); } else { log(message, @@ -454,7 +454,7 @@ public class Delete extends MatchingTask { if (dirCount > 0) { log("Deleted " + dirCount + " director" + - (dirCount==1 ? "y" : "ies") + + (dirCount == 1 ? "y" : "ies") + " from " + d.getAbsolutePath()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/DependSet.java b/src/main/org/apache/tools/ant/taskdefs/DependSet.java index 4a40635e3..ea2b1db22 100644 --- a/src/main/org/apache/tools/ant/taskdefs/DependSet.java +++ b/src/main/org/apache/tools/ant/taskdefs/DependSet.java @@ -159,12 +159,12 @@ public class DependSet extends MatchingTask { public void execute() throws BuildException { - if ( (sourceFileSets.size() == 0) && (sourceFileLists.size() == 0) ) { + if ((sourceFileSets.size() == 0) && (sourceFileLists.size() == 0)) { throw new BuildException("At least one or " + " element must be set"); } - if ( (targetFileSets.size() == 0) && (targetFileLists.size() == 0) ) { + if ((targetFileSets.size() == 0) && (targetFileLists.size() == 0)) { throw new BuildException("At least one or" + " element must be set"); } @@ -198,7 +198,7 @@ public class DependSet extends MatchingTask { allTargets.addElement(dest); if (dest.lastModified() > now) { - log("Warning: "+targetFiles[i]+" modified in the future.", + log("Warning: " + targetFiles[i] + " modified in the future.", Project.MSG_WARN); } @@ -224,7 +224,7 @@ public class DependSet extends MatchingTask { File dest = new File(targetFL.getDir(project), targetFiles[i]); if (!dest.exists()) { - log(targetFiles[i]+ " does not exist.", Project.MSG_VERBOSE); + log(targetFiles[i] + " does not exist.", Project.MSG_VERBOSE); upToDate = false; continue; } @@ -232,7 +232,7 @@ public class DependSet extends MatchingTask { allTargets.addElement(dest); } if (dest.lastModified() > now) { - log("Warning: "+targetFiles[i]+" modified in the future.", + log("Warning: " + targetFiles[i] + " modified in the future.", Project.MSG_WARN); } @@ -261,16 +261,16 @@ public class DependSet extends MatchingTask { FileList sourceFL = (FileList) enumSourceLists.nextElement(); String[] sourceFiles = sourceFL.getFiles(project); - for (int i=0; upToDate && i < sourceFiles.length; i++) { + for (int i = 0; upToDate && i < sourceFiles.length; i++) { File src = new File(sourceFL.getDir(project), sourceFiles[i]); if (src.lastModified() > now) { - log("Warning: "+sourceFiles[i]+" modified in the future.", - Project.MSG_WARN); + log("Warning: " + sourceFiles[i] + + " modified in the future.", Project.MSG_WARN); } if (!src.exists()) { - log(sourceFiles[i]+ " does not exist.", + log(sourceFiles[i] + " does not exist.", Project.MSG_VERBOSE); upToDate = false; break; @@ -296,12 +296,12 @@ public class DependSet extends MatchingTask { DirectoryScanner sourceDS = sourceFS.getDirectoryScanner(project); String[] sourceFiles = sourceDS.getIncludedFiles(); - for (int i=0; upToDate && i < sourceFiles.length; i++) { + for (int i = 0; upToDate && i < sourceFiles.length; i++) { File src = new File(sourceFS.getDir(project), sourceFiles[i]); if (src.lastModified() > now) { - log("Warning: "+sourceFiles[i]+" modified in the future.", - Project.MSG_WARN); + log("Warning: " + sourceFiles[i] + + " modified in the future.", Project.MSG_WARN); } if (src.lastModified() > oldestTargetTime) { @@ -315,8 +315,8 @@ public class DependSet extends MatchingTask { if (!upToDate) { log("Deleting all target files. ", Project.MSG_VERBOSE); - for (Enumeration e = allTargets.elements(); e.hasMoreElements(); ) { - File fileToRemove = (File)e.nextElement(); + for (Enumeration e = allTargets.elements(); e.hasMoreElements();) { + File fileToRemove = (File) e.nextElement(); log("Deleting file " + fileToRemove.getAbsolutePath(), Project.MSG_VERBOSE); fileToRemove.delete(); diff --git a/src/main/org/apache/tools/ant/taskdefs/Ear.java b/src/main/org/apache/tools/ant/taskdefs/Ear.java index 02ba03e8a..8f5737e7b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Ear.java +++ b/src/main/org/apache/tools/ant/taskdefs/Ear.java @@ -140,7 +140,7 @@ public class Ear extends Jar { if (deploymentDescriptor == null || !deploymentDescriptor.equals(file) || descriptorAdded) { - log("Warning: selected "+archiveType + log("Warning: selected " + archiveType + " files include a META-INF/application.xml which will" + " be ignored (please use appxml attribute to " + archiveType + " task)", Project.MSG_WARN); diff --git a/src/main/org/apache/tools/ant/taskdefs/Exec.java b/src/main/org/apache/tools/ant/taskdefs/Exec.java index 905da7b8b..484bf9cac 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Exec.java +++ b/src/main/org/apache/tools/ant/taskdefs/Exec.java @@ -148,8 +148,8 @@ public class Exec extends Task { // exec command on system runtime Process proc = Runtime.getRuntime().exec(command); - if( out!=null ) { - fos=new PrintWriter( new FileWriter( out ) ); + if (out != null) { + fos = new PrintWriter(new FileWriter(out)); log("Output redirected to " + out, Project.MSG_VERBOSE); } @@ -176,7 +176,7 @@ public class Exec extends Task { err = proc.exitValue(); if (err != 0) { if (failOnError) { - throw new BuildException("Exec returned: "+err, location); + throw new BuildException("Exec returned: " + err, location); } else { log("Result: " + err, Project.MSG_ERR); } diff --git a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java index 042c24e23..00962fc2d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java @@ -96,7 +96,7 @@ public class ExecTask extends Task { private ByteArrayOutputStream baos = null; private String outputprop; private String resultProperty; - private boolean failIfExecFails=true; + private boolean failIfExecFails = true; private boolean append = false; /** @@ -207,7 +207,7 @@ public class ExecTask extends Task { * @since Ant 1.5 */ public void setResultProperty(String resultProperty) { - this.resultProperty=resultProperty; + this.resultProperty = resultProperty; } /** @@ -215,9 +215,9 @@ public class ExecTask extends Task { * passed in value if appropriate */ protected void maybeSetResultPropertyValue(int result) { - String res=Integer.toString(result); - if(resultProperty!=null) { - project.setNewProperty(resultProperty,res); + String res = Integer.toString(result); + if (resultProperty != null) { + project.setNewProperty(resultProperty, res); } } @@ -226,7 +226,7 @@ public class ExecTask extends Task { * @since Ant 1.5 */ public void setFailIfExecutionFails(boolean flag) { - failIfExecFails=flag; + failIfExecFails = flag; } /** @@ -312,8 +312,8 @@ public class ExecTask extends Task { exe.setVMLauncher(vmLauncher); String[] environment = env.getVariables(); if (environment != null) { - for (int i=0; i 0) { - for (int j=0; j < filesets.size(); j++) { + for (int j = 0; j < filesets.size(); j++) { FileSet fs = (FileSet) filesets.elementAt(j); DirectoryScanner ds = fs.getDirectoryScanner(project); File fromDir = fs.getDir(project); @@ -158,7 +158,7 @@ public class Expand extends MatchingTask { ze.isDirectory()); } - log("expand complete", Project.MSG_VERBOSE ); + log("expand complete", Project.MSG_VERBOSE); } catch (IOException ioe) { throw new BuildException("Error while expanding " + srcF.getPath(), ioe); @@ -221,10 +221,10 @@ public class Expand extends MatchingTask { return; } - log("expanding " + entryName + " to "+ f, + log("expanding " + entryName + " to " + f, Project.MSG_VERBOSE); // create intermediary directories - sometimes zip don't add them - File dirF= fileUtils.getParentFile(f); + File dirF = fileUtils.getParentFile(f); dirF.mkdirs(); if (isDirectory) { @@ -253,7 +253,7 @@ public class Expand extends MatchingTask { } fileUtils.setFileLastModified(f, entryDate.getTime()); - } catch( FileNotFoundException ex ) { + } catch (FileNotFoundException ex) { log("Unable to expand to file " + f.getPath(), Project.MSG_WARN); } @@ -266,7 +266,7 @@ public class Expand extends MatchingTask { * @param d Path to the directory. */ public void setDest(File d) { - this.dest=d; + this.dest = d; } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java index 8ad68e7a7..e0591477d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java +++ b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java @@ -297,7 +297,7 @@ public class FixCRLF extends MatchingTask { * @param tlength specify the length of tab in spaces, */ public void setTablength(int tlength) throws BuildException { - if (tlength < 2 || tlength >80) { + if (tlength < 2 || tlength > 80) { throw new BuildException("tablength must be between 2 and 80", location); } @@ -366,9 +366,9 @@ public class FixCRLF extends MatchingTask { // log options used log("options:" + " eol=" + - (eol==ASIS ? "asis" : eol==CR ? "cr" : eol==LF ? "lf" : "crlf") + - " tab=" + (tabs==TABS ? "add" : tabs==ASIS ? "asis" : "remove") + - " eof=" + (ctrlz==ADD ? "add" : ctrlz==ASIS ? "asis" : "remove") + + (eol == ASIS ? "asis" : eol == CR ? "cr" : eol == LF ? "lf" : "crlf") + + " tab=" + (tabs == TABS ? "add" : tabs == ASIS ? "asis" : "remove") + + " eof=" + (ctrlz == ADD ? "add" : ctrlz == ASIS ? "asis" : "remove") + " tablength=" + tablength + " encoding=" + (encoding == null ? "default" : encoding), Project.MSG_VERBOSE); @@ -418,7 +418,7 @@ public class FixCRLF extends MatchingTask { int endComment; try { - line = (OneLiner.BufferLine)lines.nextElement(); + line = (OneLiner.BufferLine) lines.nextElement(); } catch (NoSuchElementException e) { throw new BuildException(e); } @@ -449,14 +449,13 @@ public class FixCRLF extends MatchingTask { break; case IN_MULTI_COMMENT: - if ((endComment = - lineString.indexOf("*/", line.getNext()) - ) >= 0) - { - // End of multiLineComment on this line - endComment += 2; // Include the end token - lines.setState(LOOKING); - } + endComment + = lineString.indexOf("*/", line.getNext()); + if (endComment >= 0) { + // End of multiLineComment on this line + endComment += 2; // Include the end token + lines.setState(LOOKING); + } else { endComment = linelen; } @@ -604,7 +603,7 @@ public class FixCRLF extends MatchingTask { lines.close(); } } catch (IOException io) { - log("Error closing "+srcFile, Project.MSG_ERR); + log("Error closing " + srcFile, Project.MSG_ERR); } // end of catch if (tmpFile != null) { @@ -767,14 +766,12 @@ public class FixCRLF extends MatchingTask { nextStop += tablength; } - for ( ; nextStop - placediff <= linestring.length() - ; nextStop += tablength) - { + for (; nextStop - placediff <= linestring.length() + ; nextStop += tablength) { for (tabCol = nextStop; --tabCol - placediff >= place && linestring.charAt(tabCol - placediff) == ' ' - ;) - { + ;) { ; // Loop for the side-effects } // tabCol is column index of the last non-space character @@ -863,7 +860,7 @@ public class FixCRLF extends MatchingTask { reader.mark(2); switch ((ch = reader.read())) { case '\r': - if ((char)(ch = reader.read()) == '\n') { + if ((char) (ch = reader.read()) == '\n') { eolcount += 2; eolStr.append("\r\n"); } @@ -935,7 +932,7 @@ public class FixCRLF extends MatchingTask { public Object nextElement() throws NoSuchElementException { - if (! hasMoreElements()) { + if (!hasMoreElements()) { throw new NoSuchElementException("OneLiner"); } BufferLine tmpLine = diff --git a/src/main/org/apache/tools/ant/taskdefs/GUnzip.java b/src/main/org/apache/tools/ant/taskdefs/GUnzip.java index 6eb63bbed..f5a6a8d3b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/GUnzip.java +++ b/src/main/org/apache/tools/ant/taskdefs/GUnzip.java @@ -84,7 +84,7 @@ public class GUnzip extends Unpack { protected void extract() { if (source.lastModified() > dest.lastModified()) { - log("Expanding "+ source.getAbsolutePath() + " to " + log("Expanding " + source.getAbsolutePath() + " to " + dest.getAbsolutePath()); FileOutputStream out = null; diff --git a/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java b/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java index 4ac6bdcbf..2df6191b5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java +++ b/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java @@ -111,25 +111,25 @@ public class GenerateKey extends Task { final StringBuffer sb = new StringBuffer(); boolean firstPass = true; - for( int i = 0; i < size; i++ ) { - if( !firstPass ) { + for (int i = 0; i < size; i++) { + if (!firstPass) { sb.append(" ,"); } firstPass = false; - final DnameParam param = (DnameParam)params.elementAt( i ); - sb.append( encode( param.getName() ) ); - sb.append( '=' ); - sb.append( encode( param.getValue() ) ); + final DnameParam param = (DnameParam) params.elementAt(i); + sb.append(encode(param.getName())); + sb.append('='); + sb.append(encode(param.getValue())); } return sb.toString(); } - public String encode( final String string ) { + public String encode(final String string) { int end = string.indexOf(','); - if( -1 == end ) { + if (-1 == end) { return string; } @@ -137,15 +137,15 @@ public class GenerateKey extends Task { int start = 0; - while( -1 != end ) + while (-1 != end) { - sb.append( string.substring( start, end ) ); - sb.append( "\\," ); + sb.append(string.substring(start, end)); + sb.append("\\,"); start = end + 1; - end = string.indexOf( ',', start ); + end = string.indexOf(',', start); } - sb.append( string.substring( start ) ); + sb.append(string.substring(start)); return sb.toString(); } @@ -173,24 +173,24 @@ public class GenerateKey extends Task { protected boolean verbose; public DistinguishedName createDname() throws BuildException { - if( null != expandedDname ) { - throw new BuildException( "DName sub-element can only be " - + "specified once." ); + if (null != expandedDname) { + throw new BuildException("DName sub-element can only be " + + "specified once."); } - if( null != dname ) { - throw new BuildException( "It is not possible to specify dname " + - " both " + - "as attribute and element." ); + if (null != dname) { + throw new BuildException("It is not possible to specify dname " + + " both " + + "as attribute and element."); } expandedDname = new DistinguishedName(); return expandedDname; } public void setDname(final String dname) { - if( null != expandedDname ) { - throw new BuildException( "It is not possible to specify dname " + - " both " + - "as attribute and element." ); + if (null != expandedDname) { + throw new BuildException("It is not possible to specify dname " + + " both " + + "as attribute and element."); } this.dname = dname; } @@ -224,18 +224,18 @@ public class GenerateKey extends Task { } public void setKeysize(final String keysize) throws BuildException { - try { this.keysize = Integer.parseInt(keysize); } - catch(final NumberFormatException nfe) - { - throw new BuildException( "KeySize attribute should be a integer" ); + try { + this.keysize = Integer.parseInt(keysize); + } catch (final NumberFormatException nfe) { + throw new BuildException("KeySize attribute should be a integer"); } } public void setValidity(final String validity) throws BuildException { - try { this.validity = Integer.parseInt(validity); } - catch(final NumberFormatException nfe) - { - throw new BuildException( "Validity attribute should be a integer" ); + try { + this.validity = Integer.parseInt(validity); + } catch (final NumberFormatException nfe) { + throw new BuildException("Validity attribute should be a integer"); } } @@ -245,20 +245,20 @@ public class GenerateKey extends Task { public void execute() throws BuildException { if (Project.getJavaVersion().equals(Project.JAVA_1_1)) { - throw new BuildException( "The genkey task is only available on JDK" - + " versions 1.2 or greater" ); + throw new BuildException("The genkey task is only available on JDK" + + " versions 1.2 or greater"); } if (null == alias) { - throw new BuildException( "alias attribute must be set" ); + throw new BuildException("alias attribute must be set"); } if (null == storepass) { - throw new BuildException( "storepass attribute must be set" ); + throw new BuildException("storepass attribute must be set"); } if (null == dname && null == expandedDname) { - throw new BuildException( "dname must be set" ); + throw new BuildException("dname must be set"); } final StringBuffer sb = new StringBuffer(); @@ -337,13 +337,13 @@ public class GenerateKey extends Task { sb.append("\" "); } - log("Generating Key for " + alias ); + log("Generating Key for " + alias); final ExecTask cmd = (ExecTask) project.createTask("exec"); cmd.setExecutable("keytool"); - Commandline.Argument arg=cmd.createArg(); + Commandline.Argument arg = cmd.createArg(); arg.setLine(sb.toString()); cmd.setFailonerror(true); - cmd.setTaskName( getTaskName() ); + cmd.setTaskName(getTaskName()); cmd.execute(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Get.java b/src/main/org/apache/tools/ant/taskdefs/Get.java index 5ebc560b0..fa9dedbc2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Get.java +++ b/src/main/org/apache/tools/ant/taskdefs/Get.java @@ -119,24 +119,24 @@ public class Get extends Task { log("Getting: " + source); //set the timestamp to the file date. - long timestamp=0; + long timestamp = 0; - boolean hasTimestamp=false; - if(useTimestamp && dest.exists()) { - timestamp=dest.lastModified(); - if (verbose) { - Date t=new Date(timestamp); - log("local file date : "+t.toString()); + boolean hasTimestamp = false; + if (useTimestamp && dest.exists()) { + timestamp = dest.lastModified(); + if (verbose) { + Date t = new Date(timestamp); + log("local file date : " + t.toString()); } - hasTimestamp=true; + hasTimestamp = true; } //set up the URL connection - URLConnection connection=source.openConnection(); + URLConnection connection = source.openConnection(); //modify the headers //NB: things like user authentication could go in here too. - if(useTimestamp && hasTimestamp) { + if (useTimestamp && hasTimestamp) { connection.setIfModifiedSince(timestamp); } // prepare Java 1.1 style credentials @@ -162,10 +162,11 @@ public class Get extends Task { //connect to the remote site (may take some time) connection.connect(); //next test for a 304 result (HTTP only) - if(connection instanceof HttpURLConnection) { - HttpURLConnection httpConnection=(HttpURLConnection)connection; - if(httpConnection.getResponseCode() - == HttpURLConnection.HTTP_NOT_MODIFIED) { + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection + = (HttpURLConnection) connection; + if (httpConnection.getResponseCode() + == HttpURLConnection.HTTP_NOT_MODIFIED) { //not modified so no file download. just return //instead and trace out something so the user //doesn't think that the download happened when it @@ -174,8 +175,8 @@ public class Get extends Task { return; } // test for 401 result (HTTP only) - if(httpConnection.getResponseCode() - == HttpURLConnection.HTTP_UNAUTHORIZED) { + if (httpConnection.getResponseCode() + == HttpURLConnection.HTTP_UNAUTHORIZED) { log("Not authorized - check " + dest + " for details"); return; } @@ -190,21 +191,21 @@ public class Get extends Task { FileOutputStream fos = new FileOutputStream(dest); - InputStream is=null; - for( int i=0; i< 3 ; i++ ) { + InputStream is = null; + for (int i = 0; i < 3 ; i++) { try { is = connection.getInputStream(); break; - } catch( IOException ex ) { - log( "Error opening connection " + ex ); + } catch (IOException ex) { + log("Error opening connection " + ex); } } - if( is==null ) { - log( "Can't get " + source + " to " + dest); - if(ignoreErrors) { + if (is == null) { + log("Can't get " + source + " to " + dest); + if (ignoreErrors) { return; } - throw new BuildException( "Can't get " + source + " to " + dest, + throw new BuildException("Can't get " + source + " to " + dest, location); } @@ -217,7 +218,7 @@ public class Get extends Task { System.out.print("."); } } - if(verbose) { + if (verbose) { System.out.println(); } fos.close(); @@ -226,23 +227,23 @@ public class Get extends Task { //if (and only if) the use file time option is set, then //the saved file now has its timestamp set to that of the //downloaded file - if(useTimestamp) { - long remoteTimestamp=connection.getLastModified(); + if (useTimestamp) { + long remoteTimestamp = connection.getLastModified(); if (verbose) { - Date t=new Date(remoteTimestamp); - log("last modified = "+t.toString() - +((remoteTimestamp==0) + Date t = new Date(remoteTimestamp); + log("last modified = " + t.toString() + + ((remoteTimestamp == 0) ? " - using current time instead" : "")); } - if(remoteTimestamp!=0) { + if (remoteTimestamp != 0) { FileUtils.newFileUtils() .setFileLastModified(dest, remoteTimestamp); } } } catch (IOException ioe) { - log("Error getting " + source + " to " + dest ); - if(ignoreErrors) { + log("Error getting " + source + " to " + dest); + if (ignoreErrors) { return; } throw new BuildException(ioe, location); @@ -352,67 +353,67 @@ public class Get extends Task { '4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63 - public String encode ( String s ) + public String encode(String s) { - return encode ( s.getBytes ( ) ); + return encode (s.getBytes()); } - public String encode ( byte [ ] octetString ) + public String encode(byte[ ] octetString) { int bits24; int bits6; char [ ] out - = new char [ ( ( octetString.length - 1 ) / 3 + 1 ) * 4 ]; + = new char[((octetString.length - 1) / 3 + 1) * 4]; int outIndex = 0; - int i = 0; + int i = 0; - while ( ( i + 3 ) <= octetString.length ) { + while ((i + 3) <= octetString.length) { // store the octets - bits24=( octetString [ i++ ] & 0xFF ) << 16; - bits24 |=( octetString [ i++ ] & 0xFF ) << 8; - - bits6=( bits24 & 0x00FC0000 )>> 18; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x0003F000 ) >> 12; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x00000FC0 ) >> 6; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x0000003F ); - out [ outIndex++ ] = alphabet [ bits6 ]; + bits24 = (octetString[i++] & 0xFF) << 16; + bits24 |= (octetString[i++] & 0xFF) << 8; + + bits6 = (bits24 & 0x00FC0000) >> 18; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x0003F000) >> 12; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x00000FC0) >> 6; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x0000003F); + out[outIndex++] = alphabet[bits6]; } - if ( octetString.length - i == 2 ) + if (octetString.length - i == 2) { // store the octets - bits24 = ( octetString [ i ] & 0xFF ) << 16; - bits24 |=( octetString [ i + 1 ] & 0xFF ) << 8; - bits6=( bits24 & 0x00FC0000 )>> 18; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x0003F000 ) >> 12; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x00000FC0 ) >> 6; - out [ outIndex++ ] = alphabet [ bits6 ]; + bits24 = (octetString[i] & 0xFF) << 16; + bits24 |= (octetString[i + 1] & 0xFF) << 8; + bits6 = (bits24 & 0x00FC0000) >> 18; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x0003F000) >> 12; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x00000FC0) >> 6; + out[outIndex++] = alphabet[bits6]; // padding - out [ outIndex++ ] = '='; + out[outIndex++] = '='; } - else if ( octetString.length - i == 1 ) + else if (octetString.length - i == 1) { // store the octets - bits24 = ( octetString [ i ] & 0xFF ) << 16; - bits6=( bits24 & 0x00FC0000 )>> 18; - out [ outIndex++ ] = alphabet [ bits6 ]; - bits6 = ( bits24 & 0x0003F000 ) >> 12; - out [ outIndex++ ] = alphabet [ bits6 ]; + bits24 = (octetString[i] & 0xFF) << 16; + bits6 = (bits24 & 0x00FC0000) >> 18; + out[outIndex++] = alphabet[bits6]; + bits6 = (bits24 & 0x0003F000) >> 12; + out[outIndex++] = alphabet[ bits6 ]; // padding - out [ outIndex++ ] = '='; - out [ outIndex++ ] = '='; + out[outIndex++] = '='; + out[outIndex++] = '='; } - return new String ( out ); + return new String(out); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Jar.java b/src/main/org/apache/tools/ant/taskdefs/Jar.java index 9f8ee00ff..6aa5b358d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jar.java @@ -214,7 +214,7 @@ public class Jar extends Zip { public void setFilesetmanifest(FilesetManifestConfig config) { String filesetManifestConfig = config.getValue(); - mergeManifests = ! "skip".equals(filesetManifestConfig); + mergeManifests = !("skip".equals(filesetManifestConfig)); mergeManifestsMain = "merge".equals(filesetManifestConfig); } @@ -239,28 +239,28 @@ public class Jar extends Zip { manifest = getManifest(manifestFile); finalManifest.merge(filesetManifest); finalManifest.merge(configuredManifest); - finalManifest.merge(manifest, ! mergeManifestsMain); + finalManifest.merge(manifest, !mergeManifestsMain); } else if (configuredManifest != null) { // configuredManifest is the final merge finalManifest.merge(filesetManifest); finalManifest.merge(configuredManifest, - ! mergeManifestsMain); + !mergeManifestsMain); } else if (filesetManifest != null) { // filesetManifest is the final (and only) merge - finalManifest.merge(filesetManifest, ! mergeManifestsMain); + finalManifest.merge(filesetManifest, !mergeManifestsMain); } } else { // manifest is the final merge finalManifest.merge(filesetManifest); finalManifest.merge(configuredManifest); - finalManifest.merge(manifest, ! mergeManifestsMain); + finalManifest.merge(manifest, !mergeManifestsMain); } for (Enumeration e = finalManifest.getWarnings(); - e.hasMoreElements(); ) { - log("Manifest warning: " + (String)e.nextElement(), + e.hasMoreElements();) { + log("Manifest warning: " + (String) e.nextElement(), Project.MSG_WARN); } @@ -325,7 +325,7 @@ public class Jar extends Zip { // since it will be read into a hashtable by the classloader. Enumeration enum = addedDirs.keys(); while (enum.hasMoreElements()) { - String dir = (String)enum.nextElement(); + String dir = (String) enum.nextElement(); // try to be smart, not to be fooled by a weird directory name // @fixme do we need to check for directories starting by ./ ? @@ -338,7 +338,7 @@ public class Jar extends Zip { // looks like nothing from META-INF should be added // and the check is not case insensitive. // see sun.misc.JarIndex - if ( dir.startsWith("META-INF") ){ + if (dir.startsWith("META-INF")) { continue; } // name newline diff --git a/src/main/org/apache/tools/ant/taskdefs/Java.java b/src/main/org/apache/tools/ant/taskdefs/Java.java index 2b491d956..e64f02e57 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Java.java +++ b/src/main/org/apache/tools/ant/taskdefs/Java.java @@ -106,7 +106,7 @@ public class Java extends Task { try { if ((err = executeJava()) != 0) { if (failOnError) { - throw new BuildException("Java returned: "+err, location); + throw new BuildException("Java returned: " + err, location); } else { log("Java Result: " + err, Project.MSG_ERR); } @@ -207,7 +207,7 @@ public class Java extends Task { * set the jar name... */ public void setJar(File jarfile) throws BuildException { - if ( cmdl.getClassname() != null ){ + if (cmdl.getClassname() != null){ throw new BuildException("Cannot use 'jar' and 'classname' " + "attributes in same command."); } @@ -218,7 +218,7 @@ public class Java extends Task { * Set the class name. */ public void setClassname(String s) throws BuildException { - if ( cmdl.getJar() != null ){ + if (cmdl.getJar() != null){ throw new BuildException("Cannot use 'jar' and 'classname' " + "attributes in same command"); } @@ -431,7 +431,7 @@ public class Java extends Task { dir = project.getBaseDir(); } else if (!dir.exists() || !dir.isDirectory()) { throw new BuildException(dir.getAbsolutePath() - +" is not a valid directory", + + " is not a valid directory", location); } @@ -439,8 +439,8 @@ public class Java extends Task { String[] environment = env.getVariables(); if (environment != null) { - for (int i=0; inull or empty. */ public void setName (String name) { - this.name=name; + this.name = name; } /** @@ -738,7 +738,7 @@ public class Javadoc extends Task { * Must not be null or empty. */ public void setDescription (String description) { - this.description=description; + this.description = description; } /** @@ -758,12 +758,12 @@ public class Javadoc extends Task { * specified. */ public void setScope (String verboseScope) throws BuildException { - verboseScope=verboseScope.toLowerCase (Locale.US); + verboseScope = verboseScope.toLowerCase(Locale.US); - boolean[] elements=new boolean[SCOPE_ELEMENTS.length]; + boolean[] elements = new boolean[SCOPE_ELEMENTS.length]; - boolean gotAll=false; - boolean gotNotAll=false; + boolean gotAll = false; + boolean gotNotAll = false; // Go through the tokens one at a time, updating the // elements array and issuing warnings where appropriate. @@ -775,15 +775,15 @@ public class Javadoc extends Task { getProject().log ("Repeated tag scope element: all", Project.MSG_VERBOSE); } - gotAll=true; + gotAll = true; } else { int i; - for (i=0; i < SCOPE_ELEMENTS.length; i++) { + for (i = 0; i < SCOPE_ELEMENTS.length; i++) { if (next.equals (SCOPE_ELEMENTS[i])) break; } - if (i==SCOPE_ELEMENTS.length) { + if (i == SCOPE_ELEMENTS.length) { throw new BuildException ("Unrecognised scope element: " + next); } @@ -792,8 +792,8 @@ public class Javadoc extends Task { getProject().log ("Repeated tag scope element: " + next, Project.MSG_VERBOSE); } - elements[i]=true; - gotNotAll=true; + elements[i] = true; + gotNotAll = true; } } } @@ -807,16 +807,16 @@ public class Javadoc extends Task { + "parameter."); } if (gotAll) { - this.scope="a"; + this.scope = "a"; } else { StringBuffer buff = new StringBuffer (elements.length); - for (int i=0; i < elements.length; i++) { + for (int i = 0; i < elements.length; i++) { if (elements[i]) { buff.append (SCOPE_ELEMENTS[i].charAt(0)); } } - this.scope=buff.toString(); + this.scope = buff.toString(); } } @@ -826,7 +826,7 @@ public class Javadoc extends Task { * @param enabled Whether or not this tag is enabled. */ public void setEnabled (boolean enabled) { - this.enabled=enabled; + this.enabled = enabled; } /** @@ -836,15 +836,16 @@ public class Javadoc extends Task { * is null or empty. */ public String getParameter () throws BuildException { - if (name==null || name.equals ("")) { + if (name == null || name.equals("")) { throw new BuildException ("No name specified for custom tag."); } - if (description==null || description.equals ("")){ + if (description == null || description.equals("")){ throw new BuildException - ("No description specified for custom tag "+name); + ("No description specified for custom tag " + name); } - return name+":"+(enabled ? "" : "X")+scope+":"+description; + return name + ":" + (enabled ? "" : "X") + + scope + ":" + description; } } @@ -890,10 +891,10 @@ public class Javadoc extends Task { public String getPackages() { StringBuffer p = new StringBuffer(); for (int i = 0; i < packages.size(); i++) { - if ( i > 0 ) { - p.append( ":" ); + if (i > 0) { + p.append(":"); } - p.append( packages.elementAt(i).toString() ); + p.append(packages.elementAt(i).toString()); } return p.toString(); } @@ -936,7 +937,7 @@ public class Javadoc extends Task { log("Generating Javadoc", Project.MSG_INFO); - Commandline toExecute = (Commandline)cmd.clone(); + Commandline toExecute = (Commandline) cmd.clone(); toExecute.setExecutable(JavaEnvUtils.getJdkExecutable("javadoc")); // ------------------------------------------------ general javadoc arguments @@ -1011,7 +1012,7 @@ public class Javadoc extends Task { } for (Enumeration e = doclet.getParams(); e.hasMoreElements();) { - DocletParam param = (DocletParam)e.nextElement(); + DocletParam param = (DocletParam) e.nextElement(); if (param.getName() == null) { throw new BuildException("Doclet parameters must " + "have a name"); @@ -1032,8 +1033,8 @@ public class Javadoc extends Task { // add the links arguments if (links.size() != 0) { - for (Enumeration e = links.elements(); e.hasMoreElements(); ) { - LinkArgument la = (LinkArgument)e.nextElement(); + for (Enumeration e = links.elements(); e.hasMoreElements();) { + LinkArgument la = (LinkArgument) e.nextElement(); if (la.getHref() == null) { throw new BuildException("Links must provide the URL " @@ -1100,8 +1101,8 @@ public class Javadoc extends Task { // add the group arguments if (groups.size() != 0) { - for (Enumeration e = groups.elements(); e.hasMoreElements(); ) { - GroupArgument ga = (GroupArgument)e.nextElement(); + for (Enumeration e = groups.elements(); e.hasMoreElements();) { + GroupArgument ga = (GroupArgument) e.nextElement(); String title = ga.getTitle(); String packages = ga.getPackages(); if (title == null || packages == null) { @@ -1117,7 +1118,7 @@ public class Javadoc extends Task { // JavaDoc 1.4 parameters if (javadoc4) { - for (Enumeration e = tags.elements(); e.hasMoreElements(); ) { + for (Enumeration e = tags.elements(); e.hasMoreElements();) { Object element = e.nextElement(); if (element instanceof TagArgument) { TagArgument ta = (TagArgument) element; @@ -1244,7 +1245,7 @@ public class Javadoc extends Task { exe.setCommandline(toExecute.getCommandline()); int ret = exe.execute(); if (ret != 0 && failOnError) { - throw new BuildException("Javadoc returned "+ret, location); + throw new BuildException("Javadoc returned " + ret, location); } } catch (IOException e) { throw new BuildException("Javadoc failed: " + e, e, location); @@ -1273,7 +1274,7 @@ public class Javadoc extends Task { Vector packages, Vector excludePackages) { log("Source path = " + sourcePath.toString(), Project.MSG_VERBOSE); StringBuffer msg = new StringBuffer("Packages = "); - for (int i=0; i 0) { msg.append(","); } @@ -1283,7 +1284,7 @@ public class Javadoc extends Task { msg.setLength(0); msg.append("Exclude Packages = "); - for (int i=0; i 0) { msg.append(","); } @@ -1303,8 +1304,8 @@ public class Javadoc extends Task { Enumeration e = packages.elements(); while (e.hasMoreElements()) { - String pkg = (String)e.nextElement(); - pkg = pkg.replace('.','/'); + String pkg = (String) e.nextElement(); + pkg = pkg.replace('.', '/'); if (pkg.endsWith("*")) { pkg += "*"; } @@ -1314,8 +1315,8 @@ public class Javadoc extends Task { e = excludePackages.elements(); while (e.hasMoreElements()) { - String pkg = (String)e.nextElement(); - pkg = pkg.replace('.','/'); + String pkg = (String) e.nextElement(); + pkg = pkg.replace('.', '/'); if (pkg.endsWith("*")) { pkg += "*"; } @@ -1332,14 +1333,14 @@ public class Javadoc extends Task { packageListWriter = new PrintWriter(new FileWriter(tmpList)); } - for (int j=0; j 0) { String pkgDir = - packageDirs[i].replace('/','.').replace('\\','.'); + packageDirs[i].replace('/', '.').replace('\\', '.'); if (!addedPackages.contains(pkgDir)) { if (useExternalFile) { packageListWriter.println(pkgDir); diff --git a/src/main/org/apache/tools/ant/taskdefs/Jikes.java b/src/main/org/apache/tools/ant/taskdefs/Jikes.java index c7a631522..8681a7c1f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jikes.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jikes.java @@ -84,7 +84,7 @@ public class Jikes { * @param jop - Parser to send jike's output to * @param command - name of jikes executeable */ - protected Jikes(JikesOutputParser jop,String command, Project project) { + protected Jikes(JikesOutputParser jop, String command, Project project) { super(); System.err.println("As of Ant 1.2 released in October 2000, the Jikes class"); @@ -116,7 +116,7 @@ public class Jikes { && args.length > 250) { PrintWriter out = null; try { - tmpFile = new File("jikes"+(new Random(System.currentTimeMillis())).nextLong()); + tmpFile = new File("jikes" + (new Random(System.currentTimeMillis())).nextLong()); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); @@ -132,9 +132,9 @@ public class Jikes { } } } else { - commandArray = new String[args.length+1]; + commandArray = new String[args.length + 1]; commandArray[0] = command; - System.arraycopy(args,0,commandArray,1,args.length); + System.arraycopy(args, 0, commandArray, 1, args.length); } // We assume, that everything jikes writes goes to diff --git a/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java b/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java index 196ce298b..2c06a62ea 100644 --- a/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java +++ b/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java @@ -77,7 +77,8 @@ import java.io.InputStreamReader; public class JikesOutputParser implements ExecuteStreamHandler { protected Task task; protected boolean errorFlag = false; // no errors so far - protected int errors,warnings; + protected int errors; + protected int warnings; protected boolean error = false; protected boolean emacsMode; @@ -182,7 +183,7 @@ public class JikesOutputParser implements ExecuteStreamHandler { private void setError(boolean err) { error = err; - if(error) { + if (error) { errorFlag = true; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/KeySubst.java b/src/main/org/apache/tools/ant/taskdefs/KeySubst.java index bc30deb91..a21ccb694 100644 --- a/src/main/org/apache/tools/ant/taskdefs/KeySubst.java +++ b/src/main/org/apache/tools/ant/taskdefs/KeySubst.java @@ -88,7 +88,7 @@ public class KeySubst extends Task { public void execute() throws BuildException { log("!! KeySubst is deprecated. Use Filter + Copy instead. !!"); log("Performing Substitions"); - if ( source == null || dest == null ) { + if (source == null || dest == null) { log("Source and destinations must not be null"); return; } @@ -103,11 +103,11 @@ public class KeySubst extends Task { String newline = null; line = br.readLine(); while (line != null) { - if ( line.length() == 0 ) { + if (line.length() == 0) { bw.newLine(); } else { - newline = KeySubst.replace ( line, replacements ); - bw.write ( newline ); + newline = KeySubst.replace(line, replacements); + bw.write(newline); bw.newLine(); } line = br.readLine(); @@ -173,7 +173,7 @@ public class KeySubst extends Task { String name = itok.nextToken(); String value = itok.nextToken(); - replacements.put ( name, value ); + replacements.put(name, value); } } } @@ -181,14 +181,13 @@ public class KeySubst extends Task { public static void main(String[] args) { - try{ - Hashtable hash = new Hashtable(); - hash.put ( "VERSION", "1.0.3" ); - hash.put ( "b", "ffff" ); - System.out.println ( KeySubst.replace ( "$f ${VERSION} f ${b} jj $", - hash ) ); - }catch ( Exception e) - { + try { + Hashtable hash = new Hashtable(); + hash.put("VERSION", "1.0.3"); + hash.put("b", "ffff"); + System.out.println(KeySubst.replace("$f ${VERSION} f ${b} jj $", + hash)); + } catch (Exception e) { e.printStackTrace(); } } @@ -198,23 +197,23 @@ public class KeySubst extends Task { @return the string with the replacements in it. */ - public static String replace ( String origString, Hashtable keys ) + public static String replace(String origString, Hashtable keys) throws BuildException { - StringBuffer finalString=new StringBuffer(); - int index=0; + StringBuffer finalString = new StringBuffer(); + int index = 0; int i = 0; String key = null; while ((index = origString.indexOf("${", i)) > -1) { key = origString.substring(index + 2, origString.indexOf("}", - index+3)); + index + 3)); finalString.append (origString.substring(i, index)); - if ( keys.containsKey ( key ) ) { + if (keys.containsKey(key)) { finalString.append (keys.get(key)); } else { - finalString.append ( "${" ); - finalString.append ( key ); - finalString.append ( "}" ); + finalString.append ("${"); + finalString.append (key); + finalString.append ("}"); } i = index + 3 + key.length(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/LoadFile.java b/src/main/org/apache/tools/ant/taskdefs/LoadFile.java index 56e56027c..15d24230e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/LoadFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/LoadFile.java @@ -166,12 +166,13 @@ public final class LoadFile extends Task { FileInputStream fis = null; BufferedInputStream bis = null; Reader instream = null; - log("loading "+srcFile+" into property "+property,Project.MSG_VERBOSE); + log("loading " + srcFile + " into property " + property, + Project.MSG_VERBOSE); try { final long len = srcFile.length(); - log("file size = "+len,Project.MSG_DEBUG); + log("file size = " + len, Project.MSG_DEBUG); //discard most of really big files - final int size=(int) len; + final int size = (int) len; //open up the file fis = new FileInputStream(srcFile); bis = new BufferedInputStream(fis); @@ -195,7 +196,7 @@ public final class LoadFile extends Task { project.setNewProperty(property, text); log("loaded " + text.length() + " characters", Project.MSG_VERBOSE); - log(property+" := "+text,Project.MSG_DEBUG); + log(property + " := " + text, Project.MSG_DEBUG); } } catch (final IOException ioe) { diff --git a/src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java b/src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java index c4eeedb38..f450eefa6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java +++ b/src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java @@ -99,7 +99,7 @@ public class LogOutputStream extends OutputStream { * @param cc data to log (byte). */ public void write(int cc) throws IOException { - final byte c = (byte)cc; + final byte c = (byte) cc; if ((c == '\n') || (c == '\r')) { if (!skip) { processBuffer(); diff --git a/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java b/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java index 8593af2aa..0639813dd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java @@ -152,7 +152,7 @@ public abstract class MatchingTask extends Task { while (tok.hasMoreTokens()) { String pattern = tok.nextToken().trim(); if (pattern.length() > 0) { - createInclude().setName(pattern+"/**"); + createInclude().setName(pattern + "/**"); } } } @@ -182,7 +182,7 @@ public abstract class MatchingTask extends Task { StringTokenizer tok = new StringTokenizer(ignoreString, ", ", false); while (tok.hasMoreTokens()) { - createExclude().setName("**/"+tok.nextToken().trim()+"/**"); + createExclude().setName("**/" + tok.nextToken().trim() + "/**"); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Move.java b/src/main/org/apache/tools/ant/taskdefs/Move.java index 2c02459cc..0fec7bd6d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Move.java +++ b/src/main/org/apache/tools/ant/taskdefs/Move.java @@ -120,14 +120,14 @@ public class Move extends Copy { } if (fileCopyMap.size() > 0) { // files to move log("Moving " + fileCopyMap.size() + " files to " + - destDir.getAbsolutePath() ); + destDir.getAbsolutePath()); Enumeration e = fileCopyMap.keys(); while (e.hasMoreElements()) { String fromFile = (String) e.nextElement(); String toFile = (String) fileCopyMap.get(fromFile); - if( fromFile.equals( toFile ) ) { + if (fromFile.equals(toFile)) { log("Skipping self-move of " + fromFile, verbosity); continue; } @@ -164,7 +164,7 @@ public class Move extends Copy { getFilterSets().elements(); filterEnum.hasMoreElements();) { executionFilters - .addFilterSet((FilterSet)filterEnum + .addFilterSet((FilterSet) filterEnum .nextElement()); } getFileUtils().copyFile(f, d, executionFilters, @@ -194,7 +194,7 @@ public class Move extends Copy { Enumeration e = dirCopyMap.elements(); int count = 0; while (e.hasMoreElements()) { - File d = new File((String)e.nextElement()); + File d = new File((String) e.nextElement()); if (!d.exists()) { if (!d.mkdirs()) { log("Unable to create directory " @@ -214,7 +214,7 @@ public class Move extends Copy { if (filesets.size() > 0) { Enumeration e = filesets.elements(); while (e.hasMoreElements()) { - FileSet fs = (FileSet)e.nextElement(); + FileSet fs = (FileSet) e.nextElement(); File dir = fs.getDir(project); if (okToDelete(dir)) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Pack.java b/src/main/org/apache/tools/ant/taskdefs/Pack.java index 9822657ea..140e6447a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Pack.java +++ b/src/main/org/apache/tools/ant/taskdefs/Pack.java @@ -107,10 +107,10 @@ public abstract class Pack extends Task { public void execute() throws BuildException { validate(); - if(zipFile.lastModified() < source.lastModified()){ + if (zipFile.lastModified() < source.lastModified()) { log("Building: " + zipFile.getAbsolutePath()); pack(); - }else{ + } else { log("Nothing to do: " + zipFile.getAbsolutePath() + " is up to date."); } diff --git a/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java b/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java index 5753159d2..6372c4194 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java +++ b/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java @@ -127,7 +127,7 @@ class ProcessDestroyer */ public void run() { - synchronized(processes) + synchronized (processes) { Enumeration e = processes.elements(); while (e.hasMoreElements()) diff --git a/src/main/org/apache/tools/ant/taskdefs/Property.java b/src/main/org/apache/tools/ant/taskdefs/Property.java index d4937c728..1544ba224 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Property.java +++ b/src/main/org/apache/tools/ant/taskdefs/Property.java @@ -255,7 +255,7 @@ public class Property extends Task { log("Unable to find property file: " + file.getAbsolutePath(), Project.MSG_VERBOSE); } - } catch(IOException ex) { + } catch (IOException ex) { throw new BuildException(ex, location); } } @@ -297,15 +297,15 @@ public class Property extends Task { } - protected void loadEnvironment( String prefix ) { + protected void loadEnvironment(String prefix) { Properties props = new Properties(); if (!prefix.endsWith(".")) { prefix += "."; } log("Loading Environment " + prefix, Project.MSG_VERBOSE); Vector osEnv = Execute.getProcEnvironment(); - for (Enumeration e = osEnv.elements(); e.hasMoreElements(); ) { - String entry = (String)e.nextElement(); + for (Enumeration e = osEnv.elements(); e.hasMoreElements();) { + String entry = (String) e.nextElement(); int pos = entry.indexOf('='); if (pos == -1) { log("Ignoring: " + entry, Project.MSG_WARN); @@ -335,7 +335,7 @@ public class Property extends Task { } protected void addProperty(String n, String v) { - if( userProperty ) { + if (userProperty) { if (project.getUserProperty(n) == null) { project.setUserProperty(n, v); } else { @@ -348,7 +348,7 @@ public class Property extends Task { private void resolveAllProperties(Properties props) throws BuildException { for (Enumeration e = props.keys(); e.hasMoreElements();) { - String name = (String)e.nextElement(); + String name = (String) e.nextElement(); String value = props.getProperty(name); boolean resolved = false; @@ -364,9 +364,9 @@ public class Property extends Task { Enumeration i = fragments.elements(); Enumeration j = propertyRefs.elements(); while (i.hasMoreElements()) { - String fragment = (String)i.nextElement(); + String fragment = (String) i.nextElement(); if (fragment == null) { - String propertyName = (String)j.nextElement(); + String propertyName = (String) j.nextElement(); if (propertyName.equals(name)) { throw new BuildException("Property " + name + " was circularly " diff --git a/src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java b/src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java index 585a1c871..4e219e83b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java @@ -110,10 +110,10 @@ public class PumpStreamHandler implements ExecuteStreamHandler { public void stop() { try { inputThread.join(); - } catch(InterruptedException e) {} + } catch (InterruptedException e) {} try { errorThread.join(); - } catch(InterruptedException e) {} + } catch (InterruptedException e) {} try { err.flush(); } catch (IOException e) {} diff --git a/src/main/org/apache/tools/ant/taskdefs/Recorder.java b/src/main/org/apache/tools/ant/taskdefs/Recorder.java index 47a1e4d1a..7d969eb61 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Recorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/Recorder.java @@ -51,7 +51,6 @@ * information on the Apache Software Foundation, please see * . */ - package org.apache.tools.ant.taskdefs; import org.apache.tools.ant.BuildException; @@ -59,7 +58,6 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.EnumeratedAttribute; - import org.apache.tools.ant.Task; import java.io.PrintStream; @@ -69,11 +67,12 @@ import java.io.IOException; import java.util.Hashtable; /** - * This task is the manager for RecorderEntry's. It is this class - * that holds all entries, modifies them every time the <recorder> - * task is called, and addes them to the build listener process. - * @see RecorderEntry + * This task is the manager for RecorderEntry's. It is this class that holds + * all entries, modifies them every time the <recorder> task is called, + * and addes them to the build listener process. + * * @author J D Glanville + * @see RecorderEntry * @version 0.5 * @since Ant 1.4 * @ant.task name="record" category="utility" @@ -85,19 +84,18 @@ public class Recorder extends Task { /** The name of the file to record to. */ private String filename = null; - /** Whether or not to append. Need Boolean to record an unset - * state (null). + /** + * Whether or not to append. Need Boolean to record an unset state (null). */ private Boolean append = null; - /** Whether to start or stop recording. Need Boolean to record an - * unset state (null). + /** + * Whether to start or stop recording. Need Boolean to record an unset + * state (null). */ private Boolean start = null; /** The level to log at. A level of -1 means not initialized yet. */ private int loglevel = -1; - /** - * Strip task banners if true. - */ + /** Strip task banners if true. */ private boolean emacsMode = false; /** The list of recorder entries. */ private static Hashtable recorderEntries = new Hashtable(); @@ -109,52 +107,59 @@ public class Recorder extends Task { // ACCESSOR METHODS /** - * Sets the name of the file to log to, and the name of the recorder entry. + * Sets the name of the file to log to, and the name of the recorder + * entry. + * * @param fname File name of logfile. */ - public void setName( String fname ) { + public void setName(String fname) { filename = fname; } + /** * Sets the action for the associated recorder entry. + * * @param action The action for the entry to take: start or stop. */ - public void setAction( ActionChoices action ) { - if ( action.getValue().equalsIgnoreCase( "start" ) ) { + public void setAction(ActionChoices action) { + if (action.getValue().equalsIgnoreCase("start")) { start = Boolean.TRUE; } else { start = Boolean.FALSE; } } - /** - * Whether or not the logger should append to a previous file. - */ - public void setAppend( boolean append ) { + + /** Whether or not the logger should append to a previous file. */ + public void setAppend(boolean append) { this.append = new Boolean(append); } + public void setEmacsMode(boolean emacsMode) { this.emacsMode = emacsMode; } + /** * Sets the level to which this recorder entry should log to. + * * @see VerbosityLevelChoices */ - public void setLoglevel( VerbosityLevelChoices level ){ + public void setLoglevel(VerbosityLevelChoices level) { //I hate cascading if/elseif clauses !!! String lev = level.getValue(); - if ( lev.equalsIgnoreCase("error") ) { + + if (lev.equalsIgnoreCase("error")) { loglevel = Project.MSG_ERR; - } else if ( lev.equalsIgnoreCase("warn") ){ + } else if (lev.equalsIgnoreCase("warn")) { loglevel = Project.MSG_WARN; - } else if ( lev.equalsIgnoreCase("info") ){ + } else if (lev.equalsIgnoreCase("info")) { loglevel = Project.MSG_INFO; - } else if ( lev.equalsIgnoreCase("verbose") ){ + } else if (lev.equalsIgnoreCase("verbose")) { loglevel = Project.MSG_VERBOSE; - } else if ( lev.equalsIgnoreCase("debug") ){ + } else if (lev.equalsIgnoreCase("debug")) { loglevel = Project.MSG_DEBUG; } } @@ -162,23 +167,21 @@ public class Recorder extends Task { ////////////////////////////////////////////////////////////////////// // CORE / MAIN BODY - /** - * The main execution. - */ + /** The main execution. */ public void execute() throws BuildException { - if ( filename == null ) { - throw new BuildException( "No filename specified" ); + if (filename == null) { + throw new BuildException("No filename specified"); } - getProject().log( "setting a recorder for name " + filename, - Project.MSG_DEBUG ); + getProject().log("setting a recorder for name " + filename, + Project.MSG_DEBUG); // get the recorder entry - RecorderEntry recorder = getRecorder( filename, getProject() ); + RecorderEntry recorder = getRecorder(filename, getProject()); // set the values on the recorder - recorder.setMessageOutputLevel( loglevel ); - recorder.setRecordState( start ); - recorder.setEmacsMode( emacsMode ); + recorder.setMessageOutputLevel(loglevel); + recorder.setRecordState(start); + recorder.setEmacsMode(emacsMode); } ////////////////////////////////////////////////////////////////////// @@ -190,37 +193,46 @@ public class Recorder extends Task { */ public static class ActionChoices extends EnumeratedAttribute { private final static String[] values = {"start", "stop"}; + + public String[] getValues() { return values; } } + /** * A list of possible values for the setLoglevel() method. * Possible values include: error, warn, info, verbose, debug. */ public static class VerbosityLevelChoices extends EnumeratedAttribute { - private final static String[] values = { "error", "warn", "info", + private final static String[] values = {"error", "warn", "info", "verbose", "debug"}; + + public String[] getValues() { return values; } } + /** - * Gets the recorder that's associated with the passed in name. - * If the recorder doesn't exist, then a new one is created. + * Gets the recorder that's associated with the passed in name. If the + * recorder doesn't exist, then a new one is created. */ - protected RecorderEntry getRecorder( String name, Project proj ) - throws BuildException { + protected RecorderEntry getRecorder(String name, Project proj) + throws BuildException { Object o = recorderEntries.get(name); RecorderEntry entry; - if ( o == null ) { + + if (o == null) { // create a recorder entry try { - entry = new RecorderEntry( name ); + entry = new RecorderEntry(name); + PrintStream out = null; - if ( append == null ) { + + if (append == null) { out = new PrintStream( new FileOutputStream(name)); } else { @@ -229,9 +241,9 @@ public class Recorder extends Task { } entry.setErrorPrintStream(out); entry.setOutputPrintStream(out); - } catch ( IOException ioe ) { - throw new BuildException( "Problems creating a recorder entry", - ioe ); + } catch (IOException ioe) { + throw new BuildException("Problems creating a recorder entry", + ioe); } proj.addBuildListener(entry); recorderEntries.put(name, entry); @@ -242,3 +254,4 @@ public class Recorder extends Task { } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java b/src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java index 5c8449704..a046a45d5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java +++ b/src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java @@ -51,7 +51,6 @@ * information on the Apache Software Foundation, please see * . */ - package org.apache.tools.ant.taskdefs; import org.apache.tools.ant.BuildLogger; @@ -62,42 +61,30 @@ import org.apache.tools.ant.util.StringUtils; import java.io.PrintStream; - /** - * This is a class that represents a recorder. This is the listener - * to the build process. + * This is a class that represents a recorder. This is the listener to the + * build process. + * * @author J D Glanville * @version 0.5 * @since Ant 1.4 */ -public class RecorderEntry implements BuildLogger { +public class RecorderEntry implements BuildLogger { ////////////////////////////////////////////////////////////////////// // ATTRIBUTES - /** - * The name of the file associated with this recorder entry. - */ + /** The name of the file associated with this recorder entry. */ private String filename = null; - /** - * The state of the recorder (recorder on or off). - */ + /** The state of the recorder (recorder on or off). */ private boolean record = true; - /** - * The current verbosity level to record at. - */ + /** The current verbosity level to record at. */ private int loglevel = Project.MSG_INFO; - /** - * The output PrintStream to record to. - */ + /** The output PrintStream to record to. */ private PrintStream out = null; - /** - * The start time of the last know target. - */ + /** The start time of the last know target. */ private long targetStartTime = 0l; - /** - * Strip task banners if true. - */ + /** Strip task banners if true. */ private boolean emacsMode = false; ////////////////////////////////////////////////////////////////////// @@ -105,9 +92,8 @@ public class RecorderEntry implements BuildLogger { /** * @param name The name of this recorder (used as the filename). - * */ - protected RecorderEntry( String name ) { + protected RecorderEntry(String name) { filename = name; } @@ -121,108 +107,129 @@ public class RecorderEntry implements BuildLogger { return filename; } + /** * Turns off or on this recorder. + * * @param state true for on, false for off, null for no change. */ - public void setRecordState( Boolean state ) { - if ( state != null ) { + public void setRecordState(Boolean state) { + if (state != null) { record = state.booleanValue(); } } + public void buildStarted(BuildEvent event) { - log( "> BUILD STARTED", Project.MSG_DEBUG ); + log("> BUILD STARTED", Project.MSG_DEBUG); } + public void buildFinished(BuildEvent event) { - log( "< BUILD FINISHED", Project.MSG_DEBUG ); + log("< BUILD FINISHED", Project.MSG_DEBUG); Throwable error = event.getException(); + if (error == null) { out.println(StringUtils.LINE_SEP + "BUILD SUCCESSFUL"); } else { - out.println(StringUtils.LINE_SEP + "BUILD FAILED" - + StringUtils.LINE_SEP); + out.println(StringUtils.LINE_SEP + "BUILD FAILED" + + StringUtils.LINE_SEP); error.printStackTrace(out); } out.flush(); out.close(); } + public void targetStarted(BuildEvent event) { - log( ">> TARGET STARTED -- " + event.getTarget(), Project.MSG_DEBUG ); - log( StringUtils.LINE_SEP + event.getTarget().getName() + ":", - Project.MSG_INFO ); + log(">> TARGET STARTED -- " + event.getTarget(), Project.MSG_DEBUG); + log(StringUtils.LINE_SEP + event.getTarget().getName() + ":", + Project.MSG_INFO); targetStartTime = System.currentTimeMillis(); } + public void targetFinished(BuildEvent event) { - log( "<< TARGET FINISHED -- " + event.getTarget(), Project.MSG_DEBUG ); + log("<< TARGET FINISHED -- " + event.getTarget(), Project.MSG_DEBUG); + String time = formatTime(System.currentTimeMillis() - targetStartTime); - log( event.getTarget() + ": duration " + time, Project.MSG_VERBOSE ); + + log(event.getTarget() + ": duration " + time, Project.MSG_VERBOSE); out.flush(); } + public void taskStarted(BuildEvent event) { - log( ">>> TASK STARTED -- " + event.getTask(), Project.MSG_DEBUG ); + log(">>> TASK STARTED -- " + event.getTask(), Project.MSG_DEBUG); } + public void taskFinished(BuildEvent event) { - log( "<<< TASK FINISHED -- " + event.getTask(), Project.MSG_DEBUG ); + log("<<< TASK FINISHED -- " + event.getTask(), Project.MSG_DEBUG); out.flush(); } + public void messageLogged(BuildEvent event) { - log( "--- MESSAGE LOGGED", Project.MSG_DEBUG ); + log("--- MESSAGE LOGGED", Project.MSG_DEBUG); StringBuffer buf = new StringBuffer(); - if ( event.getTask() != null ) { + + if (event.getTask() != null) { String name = event.getTask().getTaskName(); - + if (!emacsMode) { String label = "[" + name + "] "; int size = DefaultLogger.LEFT_COLUMN_SIZE - label.length(); + for (int i = 0; i < size; i++) { buf.append(" "); - } // for + }// for buf.append(label); - } // if - } // if - buf.append( event.getMessage() ); + }// if + }// if + buf.append(event.getMessage()); - log( buf.toString(), event.getPriority() ); + log(buf.toString(), event.getPriority()); } + /** * The thing that actually sends the information to the output. + * * @param mesg The message to log. * @param level The verbosity level of the message. */ - private void log( String mesg, int level ) { - if ( record && (level <= loglevel) ) { + private void log(String mesg, int level) { + if (record && (level <= loglevel)) { out.println(mesg); } } + public void setMessageOutputLevel(int level) { - if ( level >= Project.MSG_ERR && level <= Project.MSG_DEBUG ) { + if (level >= Project.MSG_ERR && level <= Project.MSG_DEBUG) { loglevel = level; } } + public void setOutputPrintStream(PrintStream output) { out = output; } + public void setEmacsMode(boolean emacsMode) { this.emacsMode = emacsMode; } + public void setErrorPrintStream(PrintStream err) { out = err; } + private static String formatTime(long millis) { long seconds = millis / 1000; long minutes = seconds / 60; @@ -230,14 +237,14 @@ public class RecorderEntry implements BuildLogger { if (minutes > 0) { return Long.toString(minutes) + " minute" - + (minutes == 1 ? " " : "s ") - + Long.toString(seconds%60) + " second" - + (seconds%60 == 1 ? "" : "s"); - } - else { + + (minutes == 1 ? " " : "s ") + + Long.toString(seconds % 60) + " second" + + (seconds % 60 == 1 ? "" : "s"); + } else { return Long.toString(seconds) + " second" - + (seconds%60 == 1 ? "" : "s"); + + (seconds % 60 == 1 ? "" : "s"); } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/Replace.java b/src/main/org/apache/tools/ant/taskdefs/Replace.java index d03132be5..9fcb639c1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Replace.java +++ b/src/main/org/apache/tools/ant/taskdefs/Replace.java @@ -228,7 +228,7 @@ public class Replace extends MatchingTask { if (replaceFilterFile != null) { Properties props = getProperties(replaceFilterFile); Enumeration enum = props.keys(); - while(enum.hasMoreElements()){ + while (enum.hasMoreElements()){ String token = enum.nextElement().toString(); Replacefilter replaceFilter = createReplacefilter(); replaceFilter.setToken(token); @@ -254,8 +254,8 @@ public class Replace extends MatchingTask { DirectoryScanner ds = super.getDirectoryScanner(dir); String[] srcs = ds.getIncludedFiles(); - for(int i=0; i 0) { log("RMI Compiling " + fileCount + - " class"+ (fileCount > 1 ? "es" : "")+" to " + baseDir, + " class" + (fileCount > 1 ? "es" : "") + " to " + baseDir, Project.MSG_INFO); // finally, lets execute the compiler!! @@ -453,7 +453,7 @@ public class Rmic extends MatchingTask { String[] generatedFiles = adapter.getMapper().mapFileName(classFileName); - for (int i=0; i= 0)) { log("Not the required version: \"" - + version +"\"", Project.MSG_VERBOSE); + + version + "\"", Project.MSG_VERBOSE); return false; } } @@ -718,7 +719,7 @@ public class SQLExec extends Task { try { totalSql++; if (!statement.execute(sql)) { - log(statement.getUpdateCount()+" rows affected", + log(statement.getUpdateCount() + " rows affected", Project.MSG_VERBOSE); } else { @@ -728,9 +729,9 @@ public class SQLExec extends Task { } SQLWarning warning = conn.getWarnings(); - while(warning!=null){ + while (warning != null){ log(warning + " sql warning", Project.MSG_VERBOSE); - warning=warning.getNextWarning(); + warning = warning.getNextWarning(); } conn.clearWarnings(); goodSql++; diff --git a/src/main/org/apache/tools/ant/taskdefs/SendEmail.java b/src/main/org/apache/tools/ant/taskdefs/SendEmail.java index f052316e9..eb89dc900 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SendEmail.java +++ b/src/main/org/apache/tools/ant/taskdefs/SendEmail.java @@ -118,8 +118,7 @@ public class SendEmail extends EmailTask * * @deprecated Use {@link #setMailport(int)} instead. */ - public void setMailport( Integer value ) - { - setMailport( value.intValue() ); + public void setMailport(Integer value) { + setMailport(value.intValue()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Sequential.java b/src/main/org/apache/tools/ant/taskdefs/Sequential.java index 8ec476e71..30364c738 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sequential.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sequential.java @@ -90,7 +90,7 @@ public class Sequential extends Task */ public void execute() throws BuildException { for (Enumeration e = nestedTasks.elements(); e.hasMoreElements();) { - Task nestedTask = (Task)e.nextElement(); + Task nestedTask = (Task) e.nextElement(); nestedTask.perform(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/SignJar.java b/src/main/org/apache/tools/ant/taskdefs/SignJar.java index b3be88658..147fb4639 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SignJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/SignJar.java @@ -172,20 +172,19 @@ public class SignJar extends Task { throw new BuildException("jar must be set through jar attribute " + "or nested filesets"); } - if( null != jar ) { + if (null != jar) { doOneJar(jar, signedjar); return; } else { //Assume null != filesets // deal with the filesets - for (int i=0; i jarFile.lastModified()) { + if (signedjarFile.lastModified() > jarFile.lastModified()) { return true; } } else { - if( lazy ) { + if (lazy) { return isSigned(jarFile); } } @@ -297,33 +296,35 @@ public class SignJar extends Task { final String SIG_START = "META-INF/"; final String SIG_END = ".SF"; - if( !file.exists() ) { + if (!file.exists()) { return false; } ZipFile jarFile = null; try { jarFile = new ZipFile(file); - if(null == alias) { + if (null == alias) { Enumeration entries = jarFile.entries(); - while(entries.hasMoreElements()) { - String name = ((ZipEntry)entries.nextElement()).getName(); - if(name.startsWith(SIG_START) && name.endsWith(SIG_END)) { + while (entries.hasMoreElements()) { + String name = ((ZipEntry) entries.nextElement()).getName(); + if (name.startsWith(SIG_START) && name.endsWith(SIG_END)) { return true; } } return false; } else { - return jarFile.getEntry(SIG_START+alias.toUpperCase()+ + return jarFile.getEntry(SIG_START + alias.toUpperCase() + SIG_END) != null; } - } catch(IOException e) { + } catch (IOException e) { return false; } finally { - if(jarFile != null) { - try {jarFile.close();} catch(IOException e) {} + if (jarFile != null) { + try { + jarFile.close(); + } catch (IOException e) { + } } } } - } diff --git a/src/main/org/apache/tools/ant/taskdefs/Sleep.java b/src/main/org/apache/tools/ant/taskdefs/Sleep.java index 244001d5b..f7e90ef46 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sleep.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sleep.java @@ -197,8 +197,8 @@ public class Sleep extends Task { throws BuildException { try { validate(); - long sleepTime=getSleepTime(); - log("sleeping for "+sleepTime+" milliseconds", + long sleepTime = getSleepTime(); + log("sleeping for " + sleepTime + " milliseconds", Project.MSG_VERBOSE); doSleep(sleepTime); } diff --git a/src/main/org/apache/tools/ant/taskdefs/StreamPumper.java b/src/main/org/apache/tools/ant/taskdefs/StreamPumper.java index 5334b3713..6197251ef 100644 --- a/src/main/org/apache/tools/ant/taskdefs/StreamPumper.java +++ b/src/main/org/apache/tools/ant/taskdefs/StreamPumper.java @@ -93,7 +93,7 @@ public class StreamPumper implements Runnable { * Terminates as soon as the input stream is closed or an error occurs. */ public void run() { - synchronized(this) { + synchronized (this) { // Just in case this object is reused in the future finished = false; } @@ -108,9 +108,9 @@ public class StreamPumper implements Runnable { Thread.sleep(SLEEP); } catch (InterruptedException e) {} } - } catch(IOException e) { + } catch (IOException e) { } finally { - synchronized(this) { + synchronized (this) { finished = true; notify(); } @@ -132,7 +132,7 @@ public class StreamPumper implements Runnable { public synchronized void waitFor() throws InterruptedException { - while(!isFinished()) { + while (!isFinished()) { wait(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Tar.java b/src/main/org/apache/tools/ant/taskdefs/Tar.java index d98fd2111..c730a6b25 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Tar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Tar.java @@ -231,7 +231,7 @@ public class Tar extends MatchingTask { // fileset boolean upToDate = true; for (Enumeration e = filesets.elements(); e.hasMoreElements();) { - TarFileSet fs = (TarFileSet)e.nextElement(); + TarFileSet fs = (TarFileSet) e.nextElement(); String[] files = fs.getFiles(project); if (!archiveIsUpToDate(files)) { @@ -248,12 +248,12 @@ public class Tar extends MatchingTask { } if (upToDate) { - log("Nothing to do: "+tarFile.getAbsolutePath() - +" is up to date.", Project.MSG_INFO); + log("Nothing to do: " + tarFile.getAbsolutePath() + + " is up to date.", Project.MSG_INFO); return; } - log("Building tar: "+ tarFile.getAbsolutePath(), Project.MSG_INFO); + log("Building tar: " + tarFile.getAbsolutePath(), Project.MSG_INFO); TarOutputStream tOut = null; try { @@ -274,7 +274,7 @@ public class Tar extends MatchingTask { longWarningGiven = false; for (Enumeration e = filesets.elements(); e.hasMoreElements();) { - TarFileSet fs = (TarFileSet)e.nextElement(); + TarFileSet fs = (TarFileSet) e.nextElement(); String[] files = fs.getFiles(project); if (files.length > 1 && fs.getFullpath().length() > 0) { throw new BuildException("fullpath attribute may only " @@ -284,7 +284,7 @@ public class Tar extends MatchingTask { } for (int i = 0; i < files.length; i++) { File f = new File(fs.getDir(project), files[i]); - String name = files[i].replace(File.separatorChar,'/'); + String name = files[i].replace(File.separatorChar, '/'); tarFile(f, tOut, name, fs); } } @@ -344,10 +344,10 @@ public class Tar extends MatchingTask { try { if (vPath.length() >= TarConstants.NAMELEN) { if (longFileMode.isOmitMode()) { - log("Omitting: "+ vPath, Project.MSG_INFO); + log("Omitting: " + vPath, Project.MSG_INFO); return; } else if (longFileMode.isWarnMode()) { - log("Entry: "+ vPath + " longer than " + + log("Entry: " + vPath + " longer than " + TarConstants.NAMELEN + " characters.", Project.MSG_WARN); if (!longWarningGiven) { @@ -358,7 +358,7 @@ public class Tar extends MatchingTask { } } else if (longFileMode.isFailMode()) { throw new BuildException( - "Entry: "+ vPath + " longer than " + + "Entry: " + vPath + " longer than " + TarConstants.NAMELEN + "characters.", location); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java b/src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java index b20b41e9c..742989c34 100644 --- a/src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java +++ b/src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java @@ -103,7 +103,7 @@ public class TaskOutputStream extends OutputStream { */ public void write(int c) throws IOException { - char cc = (char)c; + char cc = (char) c; if (cc == '\r' || cc == '\n') { // line feed if (line.length() > 0) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Touch.java b/src/main/org/apache/tools/ant/taskdefs/Touch.java index 494e1e0c4..8c2df49d2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Touch.java +++ b/src/main/org/apache/tools/ant/taskdefs/Touch.java @@ -179,11 +179,11 @@ public class Touch extends Task { protected void touch() throws BuildException { if (file != null) { if (!file.exists()) { - log("Creating "+file, Project.MSG_INFO); + log("Creating " + file, Project.MSG_INFO); try { fileUtils.createNewFile(file); } catch (IOException ioe) { - throw new BuildException("Could not create "+file, ioe, + throw new BuildException("Could not create " + file, ioe, location); } } @@ -206,7 +206,7 @@ public class Touch extends Task { } // deal with the filesets - for (int i=0; i < filesets.size(); i++) { + for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(project); File fromDir = fs.getDir(project); @@ -214,11 +214,11 @@ public class Touch extends Task { String[] srcFiles = ds.getIncludedFiles(); String[] srcDirs = ds.getIncludedDirectories(); - for(int j=0; j < srcFiles.length ; j++) { + for (int j = 0; j < srcFiles.length ; j++) { touch(new File(fromDir, srcFiles[j])); } - for(int j=0; j < srcDirs.length ; j++) { + for (int j = 0; j < srcDirs.length ; j++) { touch(new File(fromDir, srcDirs[j])); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Tstamp.java b/src/main/org/apache/tools/ant/taskdefs/Tstamp.java index c57653315..1f2c6a3ad 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Tstamp.java +++ b/src/main/org/apache/tools/ant/taskdefs/Tstamp.java @@ -111,9 +111,9 @@ public class Tstamp extends Task { project.setNewProperty(prefix + "TODAY", today.format(d)); Enumeration i = customFormats.elements(); - while(i.hasMoreElements()) { - CustomFormat cts = (CustomFormat)i.nextElement(); - cts.execute(project,d, location); + while (i.hasMoreElements()) { + CustomFormat cts = (CustomFormat) i.nextElement(); + cts.execute(project, d, location); } } catch (Exception e) { @@ -138,7 +138,7 @@ public class Tstamp extends Task { private String variant; private int offset = 0; private int field = Calendar.DATE; - private String prefix=""; + private String prefix = ""; public CustomFormat(String prefix) { @@ -157,7 +157,7 @@ public class Tstamp extends Task { public void setLocale(String locale) { - StringTokenizer st = new StringTokenizer( locale, " \t\n\r\f,"); + StringTokenizer st = new StringTokenizer(locale, " \t\n\r\f,"); try { language = st.nextToken(); if (st.hasMoreElements()) { @@ -165,7 +165,7 @@ public class Tstamp extends Task { if (st.hasMoreElements()) { variant = st.nextToken(); if (st.hasMoreElements()) { - throw new BuildException( "bad locale format", + throw new BuildException("bad locale format", getLocation()); } } @@ -175,8 +175,8 @@ public class Tstamp extends Task { } } catch (NoSuchElementException e) { - throw new BuildException( "bad locale format", e, - getLocation()); + throw new BuildException("bad locale format", e, + getLocation()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Unpack.java b/src/main/org/apache/tools/ant/taskdefs/Unpack.java index 567a46264..3cca0a11a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Unpack.java +++ b/src/main/org/apache/tools/ant/taskdefs/Unpack.java @@ -132,9 +132,9 @@ public abstract class Unpack extends Task { int len = sourceName.length(); if (defaultExtension != null && len > defaultExtension.length() - && defaultExtension.equalsIgnoreCase(sourceName.substring(len-defaultExtension.length()))) { + && defaultExtension.equalsIgnoreCase(sourceName.substring(len - defaultExtension.length()))) { dest = new File(dest, sourceName.substring(0, - len-defaultExtension.length())); + len - defaultExtension.length())); } else { dest = new File(dest, sourceName); } diff --git a/src/main/org/apache/tools/ant/taskdefs/Untar.java b/src/main/org/apache/tools/ant/taskdefs/Untar.java index bf2ee4109..8d79eede1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Untar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Untar.java @@ -88,7 +88,7 @@ public class Untar extends Expand { extractFile(fileUtils, srcF, dir, tis, te.getName(), te.getModTime(), te.isDirectory()); } - log("expand complete", Project.MSG_VERBOSE ); + log("expand complete", Project.MSG_VERBOSE); } catch (IOException ioe) { throw new BuildException("Error while expanding " + srcF.getPath(), diff --git a/src/main/org/apache/tools/ant/taskdefs/UpToDate.java b/src/main/org/apache/tools/ant/taskdefs/UpToDate.java index 737c8436f..688ced635 100644 --- a/src/main/org/apache/tools/ant/taskdefs/UpToDate.java +++ b/src/main/org/apache/tools/ant/taskdefs/UpToDate.java @@ -116,7 +116,7 @@ public class UpToDate extends Task implements Condition { * Returns the value, or "true" if a specific value wasn't provided. */ private String getValue() { - return ( _value != null ) ? _value : "true"; + return (_value != null) ? _value : "true"; } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java index 231d994f6..c756b60e0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java @@ -193,7 +193,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { // check if liaison wants to log errors using us as logger if (liaison instanceof XSLTLoggerAware) { - ((XSLTLoggerAware)liaison).setLogger(this); + ((XSLTLoggerAware) liaison).setLogger(this); } log("Using " + liaison.getClass().toString(), Project.MSG_VERBOSE); @@ -224,7 +224,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { */ //-- make sure Source directory exists... - if (destDir == null ) { + if (destDir == null) { String msg = "destdir attributes must be set!"; throw new BuildException(msg); } @@ -234,7 +234,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { // Process all the files marked for styling list = scanner.getIncludedFiles(); for (int i = 0; i < list.length; ++i) { - process( baseDir, list[i], destDir, stylesheet ); + process(baseDir, list[i], destDir, stylesheet); } if (performDirectoryScan) { // Process all the directories marked for styling @@ -242,7 +242,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { for (int j = 0; j < dirs.length; ++j){ list = new File(baseDir, dirs[j]).list(); for (int i = 0; i < list.length; ++i) { - process( baseDir, list[i], destDir, stylesheet ); + process(baseDir, list[i], destDir, stylesheet); } } } @@ -359,7 +359,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private void resolveProcessor(String proc) throws Exception { if (proc.equals("trax")) { final Class clazz = loadClass(TRAX_LIAISON_CLASS); - liaison = (XSLTLiaison)clazz.newInstance(); + liaison = (XSLTLiaison) clazz.newInstance(); } else if (proc.equals("xslp")) { log("DEPRECATED - xslp processor is deprecated. Use trax or " + "xalan instead."); @@ -367,7 +367,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { liaison = (XSLTLiaison) clazz.newInstance(); } else if (proc.equals("xalan")) { final Class clazz = loadClass(XALAN_LIASON_CLASS); - liaison = (XSLTLiaison)clazz.newInstance(); + liaison = (XSLTLiaison) clazz.newInstance(); } else { liaison = (XSLTLiaison) loadClass(proc).newInstance(); } @@ -448,7 +448,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { if (force || inFile.lastModified() > outFile.lastModified() || styleSheetLastModified > outFile.lastModified()) { - ensureDirectoryFor( outFile ); + ensureDirectoryFor(outFile); log("Processing " + inFile + " to " + outFile); configureLiaison(stylesheet); @@ -489,7 +489,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { if (force || inFile.lastModified() > outFile.lastModified() || styleSheetLastModified > outFile.lastModified()) { - ensureDirectoryFor( outFile ); + ensureDirectoryFor(outFile); log("Processing " + inFile + " to " + outFile, Project.MSG_INFO); configureLiaison(stylesheet); @@ -516,7 +516,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { if (!directory.exists()) { if (!directory.mkdirs()) { throw new BuildException("Unable to create directory: " - + directory.getAbsolutePath() ); + + directory.getAbsolutePath()); } } } @@ -647,11 +647,11 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { stylesheetLoaded = true; try { - log( "Loading stylesheet " + stylesheet, Project.MSG_INFO); - liaison.setStylesheet( stylesheet ); - for (Enumeration e = params.elements(); e.hasMoreElements(); ) { - Param p = (Param)e.nextElement(); - liaison.addParam( p.getName(), p.getExpression() ); + log("Loading stylesheet " + stylesheet, Project.MSG_INFO); + liaison.setStylesheet(stylesheet); + for (Enumeration e = params.elements(); e.hasMoreElements();) { + Param p = (Param) e.nextElement(); + liaison.addParam(p.getName(), p.getExpression()); } // if liaison is a TraxLiason, use XMLCatalog as the entity // resolver diff --git a/src/main/org/apache/tools/ant/taskdefs/Zip.java b/src/main/org/apache/tools/ant/taskdefs/Zip.java index 3b4770c15..587376f72 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Zip.java +++ b/src/main/org/apache/tools/ant/taskdefs/Zip.java @@ -265,9 +265,9 @@ public class Zip extends MatchingTask { public void execute() throws BuildException { if (baseDir == null && filesets.size() == 0 && groupfilesets.size() == 0 && "zip".equals(archiveType)) { - throw new BuildException( "basedir attribute must be set, " - + "or at least " - + "one fileset must be given!" ); + throw new BuildException("basedir attribute must be set, " + + "or at least " + + "one fileset must be given!"); } if (zipFile == null) { @@ -304,14 +304,14 @@ public class Zip extends MatchingTask { } // Add the files found in groupfileset to fileset - for (int i=0; i 0) { return false; @@ -665,7 +665,7 @@ public class Zip extends MatchingTask { protected static String[][] grabFileNames(FileScanner[] scanners) { String[][] result = new String[scanners.length][]; - for (int i=0; i= 0 || osName.indexOf("2000") >= 0 || - osName.indexOf("xp") >= 0 ); + osName.indexOf("xp") >= 0); } else { throw new BuildException( "Don\'t know how to detect os family \"" diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java index 04f0055dd..ce6e0686f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java @@ -63,52 +63,44 @@ import java.util.Date; * @author Peter Donald * @version $Revision$ $Date$ */ -class CVSEntry -{ +class CVSEntry { private Date m_date; private final String m_author; private final String m_comment; private final Vector m_files = new Vector(); - public CVSEntry( Date date, String author, String comment ) - { + public CVSEntry(Date date, String author, String comment) { m_date = date; m_author = author; m_comment = comment; } - public void addFile( String file, String revision ) - { - m_files.addElement( new RCSFile( file, revision ) ); + public void addFile(String file, String revision) { + m_files.addElement(new RCSFile(file, revision)); } - public void addFile( String file, String revision, String previousRevision ) - { - m_files.addElement( new RCSFile( file, revision, previousRevision ) ); + public void addFile(String file, String revision, String previousRevision) { + m_files.addElement(new RCSFile(file, revision, previousRevision)); } - Date getDate() - { + Date getDate() { return m_date; } - String getAuthor() - { + String getAuthor() { return m_author; } - String getComment() - { + String getComment() { return m_comment; } - Vector getFiles() - { + Vector getFiles() { return m_files; } - public String toString() - { - return getAuthor() + "\n" + getDate() + "\n" + getFiles() + "\n" + getComment(); + public String toString() { + return getAuthor() + "\n" + getDate() + "\n" + getFiles() + "\n" + + getComment(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java index 76c8bef24..309506dce 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java @@ -66,8 +66,7 @@ import java.util.Properties; * @author Peter Donald * @version $Revision$ $Date$ */ -class ChangeLogParser -{ +class ChangeLogParser { //private static final int GET_ENTRY = 0; private static final int GET_FILE = 1; private static final int GET_DATE = 2; @@ -76,7 +75,8 @@ class ChangeLogParser private static final int GET_PREVIOUS_REV = 5; /** input format for dates read in from cvs log */ - private static final SimpleDateFormat c_inputDate = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss" ); + private static final SimpleDateFormat c_inputDate + = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); //The following is data used while processing stdout of CVS command private String m_file; @@ -98,8 +98,7 @@ class ChangeLogParser * * @param userList the userlist */ - public ChangeLogParser( Properties userList ) - { + public ChangeLogParser(Properties userList) { m_userList = userList; } @@ -108,8 +107,7 @@ class ChangeLogParser * * @return a list of rcs entrys as an array */ - CVSEntry[] getEntrySetAsArray() - { + CVSEntry[] getEntrySetAsArray() { final CVSEntry[] array = new CVSEntry[ m_entries.size() ]; Enumeration enum = m_entries.elements(); int i = 0; @@ -123,27 +121,25 @@ class ChangeLogParser * Receive notification about the process writing * to standard output. */ - public void stdout( final String line ) - { - switch( m_status ) - { + public void stdout(final String line) { + switch(m_status) { case GET_FILE: - processFile( line ); + processFile(line); break; case GET_REVISION: - processRevision( line ); + processRevision(line); break; case GET_DATE: - processDate( line ); + processDate(line); break; case GET_COMMENT: - processComment( line ); + processComment(line); break; case GET_PREVIOUS_REV: - processGetPreviousRevision( line ); + processGetPreviousRevision(line); break; } } @@ -153,22 +149,19 @@ class ChangeLogParser * * @param line the line */ - private void processComment( final String line ) - { - final String lineSeparator = System.getProperty( "line.separator" ); - if( line.startsWith( "======" ) ) - { + private void processComment(final String line) { + final String lineSeparator = System.getProperty("line.separator"); + if (line.startsWith("======")) { //We have ended changelog for that particular file //so we can save it final int end = m_comment.length() - lineSeparator.length(); //was -1 - m_comment = m_comment.substring( 0, end ); + m_comment = m_comment.substring(0, end); saveEntry(); m_status = GET_FILE; } - else if( line.startsWith( "------" ) ) - { + else if (line.startsWith("------")) { final int end = m_comment.length() - lineSeparator.length(); //was -1 - m_comment = m_comment.substring( 0, end ); + m_comment = m_comment.substring(0, end); m_status = GET_PREVIOUS_REV; } else @@ -182,11 +175,9 @@ class ChangeLogParser * * @param line the line */ - private void processFile( final String line ) - { - if( line.startsWith( "Working file:" ) ) - { - m_file = line.substring( 14, line.length() ); + private void processFile(final String line) { + if (line.startsWith("Working file:")) { + m_file = line.substring(14, line.length()); m_status = GET_REVISION; } } @@ -196,15 +187,12 @@ class ChangeLogParser * * @param line the line */ - private void processRevision( final String line ) - { - if( line.startsWith( "revision" ) ) - { - m_revision = line.substring( 9 ); + private void processRevision(final String line) { + if (line.startsWith("revision")) { + m_revision = line.substring(9); m_status = GET_DATE; } - else if( line.startsWith( "======" ) ) - { + else if (line.startsWith("======")) { //There was no revisions in this changelog //entry so lets move unto next file m_status = GET_FILE; @@ -216,17 +204,14 @@ class ChangeLogParser * * @param line the line */ - private void processDate( final String line ) - { - if( line.startsWith( "date:" ) ) - { - m_date = line.substring( 6, 25 ); - String lineData = line.substring( line.indexOf( ";" ) + 1 ); - m_author = lineData.substring( 10, lineData.indexOf( ";" ) ); + private void processDate(final String line) { + if (line.startsWith("date:")) { + m_date = line.substring(6, 25); + String lineData = line.substring(line.indexOf(";") + 1); + m_author = lineData.substring(10, lineData.indexOf(";")); - if( m_userList.containsKey( m_author ) ) - { - m_author = m_userList.getProperty( m_author ); + if (m_userList.containsKey(m_author)) { + m_author = m_userList.getProperty(m_author); } m_status = GET_COMMENT; @@ -242,13 +227,12 @@ class ChangeLogParser * * @param line the line */ - private void processGetPreviousRevision( final String line ) - { - if( !line.startsWith( "revision" ) ) - { - throw new IllegalStateException( "Unexpected line from CVS: " + line ); + private void processGetPreviousRevision(final String line) { + if (!line.startsWith("revision")) { + throw new IllegalStateException("Unexpected line from CVS: " + + line); } - m_previousRevision = line.substring( 9 ); + m_previousRevision = line.substring(9); saveEntry(); @@ -259,21 +243,17 @@ class ChangeLogParser /** * Utility method that saves the current entry. */ - private void saveEntry() - { + private void saveEntry() { final String entryKey = m_date + m_author + m_comment; CVSEntry entry; - if( !m_entries.containsKey( entryKey ) ) - { - entry = new CVSEntry( parseDate( m_date ), m_author, m_comment ); - m_entries.put( entryKey, entry ); - } - else - { - entry = (CVSEntry)m_entries.get( entryKey ); + if (!m_entries.containsKey(entryKey)) { + entry = new CVSEntry(parseDate(m_date), m_author, m_comment); + m_entries.put(entryKey, entry); + } else { + entry = (CVSEntry) m_entries.get(entryKey); } - entry.addFile( m_file, m_revision, m_previousRevision ); + entry.addFile(m_file, m_revision, m_previousRevision); } /** @@ -282,14 +262,10 @@ class ChangeLogParser * @param date the string holding dat * @return the date object or null if unknown date format */ - private Date parseDate( final String date ) - { - try - { - return c_inputDate.parse( date ); - } - catch( ParseException e ) - { + private Date parseDate(final String date) { + try { + return c_inputDate.parse(date); + } catch (ParseException e) { //final String message = REZ.getString( "changelog.bat-date.error", date ); //getContext().error( message ); return null; diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java index 539935772..3ee14379d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java @@ -104,9 +104,7 @@ import org.apache.tools.ant.types.FileSet; * @since Ant 1.5 * @ant.task name="changelog" */ -public class ChangeLogTask - extends Task -{ +public class ChangeLogTask extends Task { /** User list */ private File m_usersFile; @@ -119,14 +117,10 @@ public class ChangeLogTask /** Output file */ private File m_destfile; - /** - * The earliest date at which to start processing entrys. - */ + /** The earliest date at which to start processing entrys. */ private Date m_start; - /** - * The latest date at which to stop processing entrys. - */ + /** The latest date at which to stop processing entrys. */ private Date m_stop; /** @@ -136,287 +130,297 @@ public class ChangeLogTask */ private final Vector m_filesets = new Vector(); + /** * Set the base dir for cvs. + * + * @param dir The new dir value */ - public void setDir( final File dir ) - { + public void setDir(final File dir) { m_dir = dir; } + /** * Set the output file for the log. + * + * @param destfile The new destfile value */ - public void setDestfile( final File destfile ) - { + public void setDestfile(final File destfile) { m_destfile = destfile; } + /** * Set a lookup list of user names & addresses + * + * @param usersFile The file containing the users info. */ - public void setUsersfile( final File usersFile ) - { + public void setUsersfile(final File usersFile) { m_usersFile = usersFile; } + /** * Add a user to list changelog knows about. * * @param user the user */ - public void addUser( final CvsUser user ) - { - m_cvsUsers.addElement( user ); + public void addUser(final CvsUser user) { + m_cvsUsers.addElement(user); } + /** * Set the date at which the changelog should start. * * @param start The date at which the changelog should start. */ - public void setStart( final Date start ) - { + public void setStart(final Date start) { m_start = start; } + /** * Set the date at which the changelog should stop. * * @param stop The date at which the changelog should stop. */ - public void setEnd( final Date stop ) - { + public void setEnd(final Date stop) { m_stop = stop; } + /** * Set the numbers of days worth of log entries to process. + * + * @param days the number of days of log to process. */ - public void setDaysinpast( final int days ) - { - final long time = System.currentTimeMillis() - - (long)days * 24 * 60 * 60 * 1000; - setStart( new Date( time ) ); + public void setDaysinpast(final int days) { + final long time = System.currentTimeMillis() + - (long) days * 24 * 60 * 60 * 1000; + + setStart(new Date(time)); } + /** * Adds a set of files about which cvs logs will be generated. * * @param fileSet a set of files about which cvs logs will be generated. */ - public void addFileset( final FileSet fileSet ) - { - m_filesets.addElement( fileSet ); + public void addFileset(final FileSet fileSet) { + m_filesets.addElement(fileSet); } + /** * Execute task + * + * @exception BuildException if something goes wrong executing the + * cvs command */ - public void execute() throws BuildException - { - File savedDir = m_dir; // may be altered in validate + public void execute() throws BuildException { + File savedDir = m_dir;// may be altered in validate + try { validate(); final Properties userList = new Properties(); - - loadUserlist( userList ); - - for( Enumeration e = m_cvsUsers.elements(); - e.hasMoreElements(); ) { - final CvsUser user = (CvsUser)e.nextElement(); + + loadUserlist(userList); + + for (Enumeration e = m_cvsUsers.elements(); + e.hasMoreElements();) { + final CvsUser user = (CvsUser) e.nextElement(); + user.validate(); - userList.put( user.getUserID(), user.getDisplayname() ); + userList.put(user.getUserID(), user.getDisplayname()); } - + final Commandline command = new Commandline(); - command.setExecutable( "cvs" ); - command.createArgument().setValue( "log" ); - if( null != m_start ) { + command.setExecutable("cvs"); + command.createArgument().setValue("log"); + + if (null != m_start) { final SimpleDateFormat outputDate = - new SimpleDateFormat( "yyyy-MM-dd" ); - + new SimpleDateFormat("yyyy-MM-dd"); + // We want something of the form: -d ">=YYYY-MM-dd" - final String dateRange = "-d >=" - + outputDate.format( m_start ); - command.createArgument().setValue( dateRange ); - } + final String dateRange = "-d >=" + + outputDate.format(m_start); + command.createArgument().setValue(dateRange); + } // Check if list of files to check has been specified - if( !m_filesets.isEmpty() ) { + if (!m_filesets.isEmpty()) { final Enumeration e = m_filesets.elements(); - while( e.hasMoreElements() ) { - final FileSet fileSet = (FileSet)e.nextElement(); - final DirectoryScanner scanner = - fileSet.getDirectoryScanner( project ); + + while (e.hasMoreElements()) { + final FileSet fileSet = (FileSet) e.nextElement(); + final DirectoryScanner scanner = + fileSet.getDirectoryScanner(project); final String[] files = scanner.getIncludedFiles(); - for( int i = 0; i < files.length; i++ ) { - command.createArgument().setValue( files[ i ] ); + + for (int i = 0; i < files.length; i++) { + command.createArgument().setValue(files[i]); } } } - final ChangeLogParser parser = new ChangeLogParser( userList ); + final ChangeLogParser parser = new ChangeLogParser(userList); final RedirectingStreamHandler handler = - new RedirectingStreamHandler( parser ); + new RedirectingStreamHandler(parser); - log( "ChangeLog command: [" + command.toString() + "]", - Project.MSG_VERBOSE ); + log("ChangeLog command: [" + command.toString() + "]", + Project.MSG_VERBOSE); - final Execute exe = new Execute( handler ); - exe.setWorkingDirectory( m_dir ); - exe.setCommandline( command.getCommandline() ); - exe.setAntRun( getProject() ); + final Execute exe = new Execute(handler); + + exe.setWorkingDirectory(m_dir); + exe.setCommandline(command.getCommandline()); + exe.setAntRun(getProject()); try { final int resultCode = exe.execute(); - if( 0 != resultCode ) { - throw new BuildException( "Error running cvs log" ); + + if (0 != resultCode) { + throw new BuildException("Error running cvs log"); } - } catch( final IOException ioe ) { - throw new BuildException( ioe.toString() ); + } catch (final IOException ioe) { + throw new BuildException(ioe.toString()); } final String errors = handler.getErrors(); - if( null != errors ) { - log( errors, Project.MSG_ERR ); + + if (null != errors) { + log(errors, Project.MSG_ERR); } final CVSEntry[] entrySet = parser.getEntrySetAsArray(); - final CVSEntry[] filteredEntrySet = filterEntrySet( entrySet ); - writeChangeLog( filteredEntrySet ); + final CVSEntry[] filteredEntrySet = filterEntrySet(entrySet); + + writeChangeLog(filteredEntrySet); } finally { m_dir = savedDir; } } + /** * Validate the parameters specified for task. * * @throws BuildException if fails validation checks */ private void validate() - throws BuildException - { - if( null == m_dir ) - { + throws BuildException { + if (null == m_dir) { m_dir = getProject().getBaseDir(); } - if( null == m_destfile ) - { + if (null == m_destfile) { final String message = "Destfile must be set."; - throw new BuildException( message ); + + throw new BuildException(message); } - if( !m_dir.exists() ) - { - final String message = "Cannot find base dir " - + m_dir.getAbsolutePath(); - throw new BuildException( message ); + if (!m_dir.exists()) { + final String message = "Cannot find base dir " + + m_dir.getAbsolutePath(); + + throw new BuildException(message); } - if( null != m_usersFile && !m_usersFile.exists() ) - { - final String message = "Cannot find user lookup list " - + m_usersFile.getAbsolutePath(); - throw new BuildException( message ); + if (null != m_usersFile && !m_usersFile.exists()) { + final String message = "Cannot find user lookup list " + + m_usersFile.getAbsolutePath(); + + throw new BuildException(message); } } + /** - * Load the userli4st from the userList file (if specified) and - * add to list of users. + * Load the userlist from the userList file (if specified) and add to + * list of users. * + * @param userList the file of users * @throws BuildException if file can not be loaded for some reason */ - private void loadUserlist( final Properties userList ) - throws BuildException - { - if( null != m_usersFile ) - { - try - { - userList.load( new FileInputStream( m_usersFile ) ); - } - catch( final IOException ioe ) - { - throw new BuildException( ioe.toString(), ioe ); + private void loadUserlist(final Properties userList) + throws BuildException { + if (null != m_usersFile) { + try { + userList.load(new FileInputStream(m_usersFile)); + } catch (final IOException ioe) { + throw new BuildException(ioe.toString(), ioe); } } } + /** - * Filter the specified entrys accoridn to an appropriate - * rule. + * Filter the specified entrys accoridn to an appropriate rule. * * @param entrySet the entry set to filter * @return the filtered entry set */ - private CVSEntry[] filterEntrySet( final CVSEntry[] entrySet ) - { + private CVSEntry[] filterEntrySet(final CVSEntry[] entrySet) { final Vector results = new Vector(); - for( int i = 0; i < entrySet.length; i++ ) - { - final CVSEntry cvsEntry = entrySet[ i ]; + + for (int i = 0; i < entrySet.length; i++) { + final CVSEntry cvsEntry = entrySet[i]; final Date date = cvsEntry.getDate(); - if( null != m_start && m_start.after( date ) ) - { + + if (null != m_start && m_start.after(date)) { //Skip dates that are too early continue; } - if( null != m_stop && m_stop.before( date ) ) - { + if (null != m_stop && m_stop.before(date)) { //Skip dates that are too late continue; } - results.addElement( cvsEntry ); + results.addElement(cvsEntry); } - final CVSEntry[] resultArray = new CVSEntry[ results.size() ]; - results.copyInto( resultArray ); + final CVSEntry[] resultArray = new CVSEntry[results.size()]; + + results.copyInto(resultArray); return resultArray; } + /** * Print changelog to file specified in task. * - * @throws BuildException if theres an error writing changelog + * @param entrySet the entry set to write. + * @throws BuildException if theres an error writing changelog. */ - private void writeChangeLog( final CVSEntry[] entrySet ) - throws BuildException - { + private void writeChangeLog(final CVSEntry[] entrySet) + throws BuildException { FileOutputStream output = null; - try - { - output = new FileOutputStream( m_destfile ); + + try { + output = new FileOutputStream(m_destfile); + final PrintWriter writer = - new PrintWriter( new OutputStreamWriter( output, "UTF-8" ) ); + new PrintWriter(new OutputStreamWriter(output, "UTF-8")); final ChangeLogWriter serializer = new ChangeLogWriter(); - serializer.printChangeLog( writer, entrySet ); - } - catch( final UnsupportedEncodingException uee ) - { - getProject().log( uee.toString(), Project.MSG_ERR ); - } - catch( final IOException ioe ) - { - throw new BuildException( ioe.toString(), ioe ); - } - finally - { - if( null != output ) - { - try - { + + serializer.printChangeLog(writer, entrySet); + } catch (final UnsupportedEncodingException uee) { + getProject().log(uee.toString(), Project.MSG_ERR); + } catch (final IOException ioe) { + throw new BuildException(ioe.toString(), ioe); + } finally { + if (null != output) { + try { output.close(); - } - catch( final IOException ioe ) - { + } catch (final IOException ioe) { } } } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java index ea608ce44..6ccbd9dd3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java @@ -63,60 +63,65 @@ import java.util.Enumeration; * @author Peter Donald * @version $Revision$ $Date$ */ -class ChangeLogWriter -{ +class ChangeLogWriter { /** output format for dates writtn to xml file */ - private static final SimpleDateFormat c_outputDate = new SimpleDateFormat( "yyyy-MM-dd" ); + private static final SimpleDateFormat c_outputDate = new SimpleDateFormat("yyyy-MM-dd"); /** output format for times writtn to xml file */ - private static final SimpleDateFormat c_outputTime = new SimpleDateFormat( "hh:mm" ); + private static final SimpleDateFormat c_outputTime = new SimpleDateFormat("hh:mm"); + /** * Print out the specifed entrys. + * + * @param output writer to which to send output. + * @param entries the entries to be written. */ - public void printChangeLog( final PrintWriter output, - final CVSEntry[] entries ) - { - output.println( "" ); - output.println( "" ); - for( int i = 0; i < entries.length; i++ ) - { - final CVSEntry entry = entries[ i ]; - printEntry( output, entry ); + public void printChangeLog(final PrintWriter output, + final CVSEntry[] entries) { + output.println(""); + output.println(""); + for (int i = 0; i < entries.length; i++) { + final CVSEntry entry = entries[i]; + + printEntry(output, entry); } - output.println( "" ); + output.println(""); output.flush(); output.close(); } + /** * Print out an individual entry in changelog. * * @param entry the entry to print + * @param output writer to which to send output. */ - private void printEntry( final PrintWriter output, final CVSEntry entry ) - { - output.println( "\t" ); - output.println( "\t\t" + c_outputDate.format( entry.getDate() ) + "" ); - output.println( "\t\t" ); - output.println( "\t\t" ); + private void printEntry(final PrintWriter output, final CVSEntry entry) { + output.println("\t"); + output.println("\t\t" + c_outputDate.format(entry.getDate()) + ""); + output.println("\t\t"); + output.println("\t\t"); final Enumeration enumeration = entry.getFiles().elements(); - while( enumeration.hasMoreElements() ) - { - final RCSFile file = (RCSFile)enumeration.nextElement(); - output.println( "\t\t" ); - output.println( "\t\t\t" + file.getName() + "" ); - output.println( "\t\t\t" + file.getRevision() + "" ); + + while (enumeration.hasMoreElements()) { + final RCSFile file = (RCSFile) enumeration.nextElement(); + + output.println("\t\t"); + output.println("\t\t\t" + file.getName() + ""); + output.println("\t\t\t" + file.getRevision() + ""); final String previousRevision = file.getPreviousRevision(); - if( previousRevision != null ) - { - output.println( "\t\t\t" + previousRevision + "" ); + + if (previousRevision != null) { + output.println("\t\t\t" + previousRevision + ""); } - output.println( "\t\t" ); + output.println("\t\t"); } - output.println( "\t\t" ); - output.println( "\t" ); + output.println("\t\t"); + output.println("\t"); } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java index ce33fb3ad..5f5737a77 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java @@ -62,44 +62,71 @@ import org.apache.tools.ant.BuildException; * @author Jeff Martin * @version $Revision$ $Date$ */ -public class CvsUser -{ +public class CvsUser { + /** The user's Id */ private String m_userID; + /** The user's full name */ private String m_displayName; - public void setDisplayname( final String displayName ) - { + + /** + * Set the user's fullname + * + * @param displayName the user's full name + */ + public void setDisplayname(final String displayName) { m_displayName = displayName; } - public void setUserid( final String userID ) - { + + /** + * Set the user's id + * + * @param userID the user's new id value. + */ + public void setUserid(final String userID) { m_userID = userID; } - String getUserID() - { + + /** + * Get the user's id. + * + * @return The userID value + */ + String getUserID() { return m_userID; } - String getDisplayname() - { + + /** + * Get the user's full name + * + * @return the usre's full name + */ + String getDisplayname() { return m_displayName; } - void validate() - throws BuildException - { - if( null == m_userID ) - { + + /** + * validate that this objetc is configured. + * + * @exception BuildException if the instance has not be correctly + * configured. + */ + void validate() throws BuildException { + if (null == m_userID) { final String message = "Username attribute must be set."; - throw new BuildException( message ); + + throw new BuildException(message); } - if( null == m_displayName ) - { + if (null == m_displayName) { final String message = "Displayname attribute must be set for userID " + m_userID; - throw new BuildException( message ); + + throw new BuildException(message); } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java index c8bc7a3c3..3c2bbc4ac 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java @@ -60,41 +60,40 @@ package org.apache.tools.ant.taskdefs.cvslib; * @author Jeff Martin * @version $Revision$ $Date$ */ -class RCSFile -{ +class RCSFile { private String m_name; private String m_revision; private String m_previousRevision; - RCSFile( final String name, final String rev ) - { - this( name, rev, null ); + + RCSFile(final String name, final String rev) { + this(name, rev, null); } - RCSFile( final String name, - final String revision, - final String previousRevision ) - { + + RCSFile(final String name, + final String revision, + final String previousRevision) { m_name = name; m_revision = revision; - if( !revision.equals( previousRevision ) ) - { + if (!revision.equals(previousRevision)) { m_previousRevision = previousRevision; } } - String getName() - { + + String getName() { return m_name; } - String getRevision() - { + + String getRevision() { return m_revision; } - String getPreviousRevision() - { + + String getPreviousRevision() { return m_previousRevision; } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java index e457a788d..e09fe2090 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java @@ -51,7 +51,6 @@ * information on the Apache Software Foundation, please see * . */ - package org.apache.tools.ant.taskdefs.cvslib; import org.apache.tools.ant.taskdefs.LogOutputStream; @@ -62,28 +61,29 @@ import org.apache.tools.ant.taskdefs.LogOutputStream; * @author Peter Donald * @version $Revision$ $Date$ */ -class RedirectingOutputStream - extends LogOutputStream -{ +class RedirectingOutputStream + extends LogOutputStream { private final ChangeLogParser m_parser; + /** * Creates a new instance of this class. * + * @param parser the parser to which output is sent. */ - public RedirectingOutputStream( final ChangeLogParser parser ) - { - super( null, 0 ); + public RedirectingOutputStream(final ChangeLogParser parser) { + super(null, 0); m_parser = parser; } + /** * Logs a line to the log system of ant. * * @param line the line to log. */ - protected void processLine( final String line ) - { - m_parser.stdout( line ); + protected void processLine(final String line) { + m_parser.stdout(line); } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java index fb469d5a4..10294c051 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java @@ -65,40 +65,33 @@ import org.apache.tools.ant.BuildException; * @version $Revision$ $Date$ */ class RedirectingStreamHandler - extends PumpStreamHandler -{ - RedirectingStreamHandler( final ChangeLogParser parser ) - { - super( new RedirectingOutputStream( parser ), - new ByteArrayOutputStream() ); + extends PumpStreamHandler { + RedirectingStreamHandler(final ChangeLogParser parser) { + super(new RedirectingOutputStream(parser), + new ByteArrayOutputStream()); } - String getErrors() - { - try - { - final ByteArrayOutputStream error = (ByteArrayOutputStream)getErr(); - return error.toString( "ASCII" ); - } - catch( final Exception e ) - { + + String getErrors() { + try { + final ByteArrayOutputStream error = (ByteArrayOutputStream) getErr(); + + return error.toString("ASCII"); + } catch (final Exception e) { return null; } } - public void stop() - { + public void stop() { super.stop(); - try - { + try { getErr().close(); getOut().close(); - } - catch( final IOException e ) - { + } catch (final IOException e) { // plain impossible - throw new BuildException( e ); + throw new BuildException(e); } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java b/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java index d4e4b22a2..d237cefa6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java @@ -59,75 +59,77 @@ package org.apache.tools.ant.taskdefs.email; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -public class EmailAddress -{ +public class EmailAddress { private String name; private String address; - /** Creates an empty email address - */ - public EmailAddress() - { + + /** Creates an empty email address */ + public EmailAddress() { } - /** + + /** * Creates a new email address based on the given string + * * @param address the email address */ - public EmailAddress( String address ) - { + public EmailAddress(String address) { this.address = address; } - /** + + /** * Sets the personal / display name of the address + * * @param name the display name */ - public void setName( String name ) - { + public void setName(String name) { this.name = name; } - /** + + /** * Sets the email address + * * @param address the actual email address */ - public void setAddress( String address ) - { + public void setAddress(String address) { this.address = address; } - /** + + /** * Constructs a string "name <address>" or "address" + * * @return a string representation of the address */ - public String toString() - { - if( name == null ) - { + public String toString() { + if (name == null) { return address; - } - else - { + } else { return name + " <" + address + ">"; } } - /** + + /** * Returns the address + * * @return the address part */ - public String getAddress() - { + public String getAddress() { return address; } - /** + + /** * Returns the display name + * * @return the display name part */ - public String getName() - { + public String getName() { return name; } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java b/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java index 084907c69..aebc04f54 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java @@ -67,8 +67,8 @@ import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.FileSet; /** - * A task to send SMTP email. This is a refactoring of the SendMail - * and MimeMail tasks such that both are within a single task. + * A task to send SMTP email. This is a refactoring of the SendMail and + * MimeMail tasks such that both are within a single task. * * @author Magesh Umasankar * @author glenn_twiggs@bmc.com @@ -77,480 +77,443 @@ import org.apache.tools.ant.types.FileSet; * @author paulo.gaspar@krankikom.de Paulo Gaspar * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 - * * @ant.task name="mail" category="network" */ public class EmailTask - extends Task -{ - /** Constant to show that the best available mailer should be used. - */ + extends Task { + /** Constant to show that the best available mailer should be used. */ public final static String AUTO = "auto"; - /** Constant to allow the Mime mailer to be requested - */ + /** Constant to allow the Mime mailer to be requested */ public final static String MIME = "mime"; - /** Constant to allow the UU mailer to be requested - */ + /** Constant to allow the UU mailer to be requested */ public final static String UU = "uu"; - /** Constant to allow the plaintext mailer to be requested - */ + /** Constant to allow the plaintext mailer to be requested */ public final static String PLAIN = "plain"; - /** Enumerates the encoding constants + + /** + * Enumerates the encoding constants */ - public static class Encoding extends EnumeratedAttribute - { - /** finds the valid encoding values + public static class Encoding extends EnumeratedAttribute { + /** + * finds the valid encoding values + * * @return a list of valid entries */ - public String[] getValues() - { + public String[] getValues() { return new String[] - {AUTO, MIME, UU, PLAIN}; + {AUTO, MIME, UU, PLAIN}; } } + private String encoding = AUTO; - /** - * host running SMTP - */ + /** host running SMTP */ private String host = "localhost"; private int port = 25; - /** - * subject field - */ + /** subject field */ private String subject = null; - /** - * any text - */ + /** any text */ private Message message = null; /** failure flag */ private boolean failOnError = true; private boolean includeFileNames = false; private String messageMimeType = null; - /** - * sender - */ + /** sender */ private EmailAddress from = null; - /** - * TO recipients - */ + /** TO recipients */ private Vector toList = new Vector(); - /** - * CC (Carbon Copy) recipients - */ + /** CC (Carbon Copy) recipients */ private Vector ccList = new Vector(); - /** - * BCC (Blind Carbon Copy) recipients - */ + /** BCC (Blind Carbon Copy) recipients */ private Vector bccList = new Vector(); - /** - * file list - */ + /** file list */ private Vector files = new Vector(); private Vector filesets = new Vector(); - /** + + /** * Allows the build writer to choose the preferred encoding method + * * @param encoding The encoding (one of AUTO,MIME,UU,PLAIN) */ - public void setEncoding( Encoding encoding ) - { + public void setEncoding(Encoding encoding) { this.encoding = encoding.getValue(); } - /** + + /** * Sets the mail server port + * * @param port The port to use */ - public void setMailport( int port ) - { + public void setMailport(int port) { this.port = port; } - /** + + /** * Sets the host + * * @param host The host to connect to */ - public void setMailhost( String host ) - { + public void setMailhost(String host) { this.host = host; } - /** + + /** * Sets the subject line of the email * * @param subject Subject of this email. */ - public void setSubject( String subject ) - { + public void setSubject(String subject) { this.subject = subject; } - /** + + /** * Shorthand method to set the message + * * @param message Message body of this email. */ - public void setMessage( String message ) - { - if( this.message != null ) - { - throw new BuildException( "Only one message can be sent in an " - + "email" ); + public void setMessage(String message) { + if (this.message != null) { + throw new BuildException("Only one message can be sent in an " + + "email"); } - this.message = new Message( message ); + this.message = new Message(message); } - /** + + /** * Shorthand method to set the message from a file + * * @param file The file from which to take the message */ - public void setMessageFile( File file ) - { - if( this.message != null ) - { - throw new BuildException( "Only one message can be sent in an " - + "email" ); + public void setMessageFile(File file) { + if (this.message != null) { + throw new BuildException("Only one message can be sent in an " + + "email"); } - this.message = new Message( file ); + this.message = new Message(file); } - /** - * Shorthand method to set type of the text message, text/plain by - * default but text/html or text/xml is quite feasible. + + /** + * Shorthand method to set type of the text message, text/plain by default + * but text/html or text/xml is quite feasible. * * @param type The new MessageMimeType value */ - public void setMessageMimeType( String type ) - { + public void setMessageMimeType(String type) { this.messageMimeType = type; } - /** + + /** * Add a message elemnt + * * @param message The message object * @throws BuildException if a message has already been added */ - public void addMessage( Message message ) - throws BuildException - { - if( this.message != null ) - { - throw new BuildException( "Only one message can be sent in an " - + "email" ); + public void addMessage(Message message) + throws BuildException { + if (this.message != null) { + throw new BuildException("Only one message can be sent in an " + + "email"); } this.message = message; } - /** + + /** * Adds a from address element + * * @param address The address to send from */ - public void addFrom( EmailAddress address ) - { - if( this.from != null ) - { - throw new BuildException( "Emails can only be from one address" ); + public void addFrom(EmailAddress address) { + if (this.from != null) { + throw new BuildException("Emails can only be from one address"); } this.from = address; } - /** + + /** * Shorthand to set the from address element * * @param address The address to send mail from */ - public void setFrom( String address ) - { - if( this.from != null ) - { - throw new BuildException( "Emails can only be from one address" ); + public void setFrom(String address) { + if (this.from != null) { + throw new BuildException("Emails can only be from one address"); } - this.from = new EmailAddress( address ); + this.from = new EmailAddress(address); } - /** + + /** * Adds a to address element + * * @param address An email address */ - public void addTo( EmailAddress address ) - { - toList.addElement( address ); + public void addTo(EmailAddress address) { + toList.addElement(address); } - /** + + /** * Adds "to" address elements * * @param list Comma separated list of addresses */ - public void setToList( String list ) - { - StringTokenizer tokens = new StringTokenizer( list, "," ); + public void setToList(String list) { + StringTokenizer tokens = new StringTokenizer(list, ","); - while( tokens.hasMoreTokens() ) - { - toList.addElement( new EmailAddress( tokens.nextToken() ) ); + while (tokens.hasMoreTokens()) { + toList.addElement(new EmailAddress(tokens.nextToken())); } } - /** + + /** * Adds "cc" address element + * * @param address The email address */ - public void addCc( EmailAddress address ) - { - ccList.addElement( address ); + public void addCc(EmailAddress address) { + ccList.addElement(address); } - /** + + /** * Adds "cc" address elements * * @param list Comma separated list of addresses */ - public void setCcList( String list ) - { - StringTokenizer tokens = new StringTokenizer( list, "," ); + public void setCcList(String list) { + StringTokenizer tokens = new StringTokenizer(list, ","); - while( tokens.hasMoreTokens() ) - { - ccList.addElement( new EmailAddress( tokens.nextToken() ) ); + while (tokens.hasMoreTokens()) { + ccList.addElement(new EmailAddress(tokens.nextToken())); } } - /** + + /** * Adds "bcc" address elements + * * @param address The email address */ - public void addBcc( EmailAddress address ) - { - bccList.addElement( address ); + public void addBcc(EmailAddress address) { + bccList.addElement(address); } - /** + + /** * Adds "bcc" address elements * * @param list comma separated list of addresses */ - public void setBccList( String list ) - { - StringTokenizer tokens = new StringTokenizer( list, "," ); + public void setBccList(String list) { + StringTokenizer tokens = new StringTokenizer(list, ","); - while( tokens.hasMoreTokens() ) - { - bccList.addElement( new EmailAddress( tokens.nextToken() ) ); + while (tokens.hasMoreTokens()) { + bccList.addElement(new EmailAddress(tokens.nextToken())); } } - /** + + /** * Indicates whether BuildExceptions should be passed back to the core * * @param failOnError The new FailOnError value */ - public void setFailOnError( boolean failOnError ) - { + public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } - /** + + /** * Adds a list of files to be attached * * @param filenames Comma separated list of files */ - public void setFiles( String filenames ) - { - StringTokenizer t = new StringTokenizer( filenames, ", " ); + public void setFiles(String filenames) { + StringTokenizer t = new StringTokenizer(filenames, ", "); - while( t.hasMoreTokens() ) - { - files.addElement( project.resolveFile( t.nextToken() ) ); + while (t.hasMoreTokens()) { + files.addElement(project.resolveFile(t.nextToken())); } } - /** + + /** * Adds a set of files (nested fileset attribute). + * * @param fs The fileset */ - public void addFileset( FileSet fs ) - { - filesets.addElement( fs ); + public void addFileset(FileSet fs) { + filesets.addElement(fs); } - /** + + /** * Sets Includefilenames attribute * - * @param includeFileNames Whether to include filenames in the - * text of the message + * @param includeFileNames Whether to include filenames in the text of the + * message */ - public void setIncludefilenames( boolean includeFileNames ) - { + public void setIncludefilenames(boolean includeFileNames) { this.includeFileNames = includeFileNames; } - /** + + /** * Identifies whether file names should be included + * * @return Identifies whether file names should be included */ - public boolean getIncludeFileNames() - { + public boolean getIncludeFileNames() { return includeFileNames; } - /** - * Sends an email - */ - public void execute() - { + + /** Sends an email */ + public void execute() { Message savedMessage = message; Vector savedFiles = (Vector) files.clone(); - try - { + + try { Mailer mailer = null; // prepare for the auto select mechanism boolean autoFound = false; // try MIME format - if( encoding.equals( MIME ) - || ( encoding.equals( AUTO ) && !autoFound ) ) - { - try - { - mailer = - (Mailer) Class.forName( "org.apache.tools.ant.taskdefs.email.MimeMailer" ) + if (encoding.equals(MIME) + || (encoding.equals(AUTO) && !autoFound)) { + try { + mailer = + (Mailer) Class.forName("org.apache.tools.ant.taskdefs.email.MimeMailer") .newInstance(); autoFound = true; - log( "Using MIME mail", Project.MSG_VERBOSE ); - } - catch( Throwable e ) - { - log( "Failed to initialise MIME mail", Project.MSG_WARN ); + log("Using MIME mail", Project.MSG_VERBOSE); + } catch (Throwable e) { + log("Failed to initialise MIME mail", Project.MSG_WARN); } } // try UU format - if( encoding.equals( UU ) - || ( encoding.equals( AUTO ) && !autoFound ) ) - { - try - { - mailer = - (Mailer)Class.forName( "org.apache.tools.ant.taskdefs.email.UUMailer" ) + if (encoding.equals(UU) + || (encoding.equals(AUTO) && !autoFound)) { + try { + mailer = + (Mailer) Class.forName("org.apache.tools.ant.taskdefs.email.UUMailer") .newInstance(); autoFound = true; - log( "Using UU mail", Project.MSG_VERBOSE ); - } - catch( Throwable e ) - { - log( "Failed to initialise UU mail", Project.MSG_WARN ); + log("Using UU mail", Project.MSG_VERBOSE); + } catch (Throwable e) { + log("Failed to initialise UU mail", Project.MSG_WARN); } } // try plain format - if( encoding.equals( PLAIN ) - || ( encoding.equals( AUTO ) && !autoFound ) ) - { + if (encoding.equals(PLAIN) + || (encoding.equals(AUTO) && !autoFound)) { mailer = new PlainMailer(); autoFound = true; - log( "Using plain mail", Project.MSG_VERBOSE ); + log("Using plain mail", Project.MSG_VERBOSE); } // a valid mailer must be present by now - if( mailer == null ) - { - throw new BuildException( "Failed to initialise encoding: " - + encoding ); + if (mailer == null) { + throw new BuildException("Failed to initialise encoding: " + + encoding); } // a valid message is required - if( message == null ) - { + if (message == null) { message = new Message(); } // an address to send from is required - if( from == null || from.getAddress() == null ) - { - throw new BuildException( "A from element is required" ); + if (from == null || from.getAddress() == null) { + throw new BuildException("A from element is required"); } // at least one address to send to/cc/bcc is required - if( toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty() ) - { - throw new BuildException( "At least one of to,cc or bcc must " - + "be supplied" ); + if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) { + throw new BuildException("At least one of to,cc or bcc must " + + "be supplied"); } // set the mimetype if not done already (and required) - if( messageMimeType != null ) - { - if( message.isMimeTypeSpecified() ) - { - throw new BuildException( "The mime type can only be " - + "specified in one location" ); - } - else - { - message.setMimeType( messageMimeType ); + if (messageMimeType != null) { + if (message.isMimeTypeSpecified()) { + throw new BuildException("The mime type can only be " + + "specified in one location"); + } else { + message.setMimeType(messageMimeType); } } // identify which files should be attached Enumeration e = filesets.elements(); - while( e.hasMoreElements() ) - { - FileSet fs = (FileSet)e.nextElement(); - DirectoryScanner ds = fs.getDirectoryScanner( project ); + while (e.hasMoreElements()) { + FileSet fs = (FileSet) e.nextElement(); + + DirectoryScanner ds = fs.getDirectoryScanner(project); String[] includedFiles = ds.getIncludedFiles(); File baseDir = ds.getBasedir(); - for( int j = 0; j < includedFiles.length; ++j ) - { - File file = new File( baseDir, includedFiles[ j ] ); - files.addElement( file ); + for (int j = 0; j < includedFiles.length; ++j) { + File file = new File(baseDir, includedFiles[j]); + + files.addElement(file); } } // let the user know what's going to happen - log( "Sending email: " + subject, Project.MSG_INFO ); - log( "From " + from, Project.MSG_VERBOSE ); - log( "To " + toList, Project.MSG_VERBOSE ); - log( "Cc " + ccList, Project.MSG_VERBOSE ); - log( "Bcc " + bccList, Project.MSG_VERBOSE ); + log("Sending email: " + subject, Project.MSG_INFO); + log("From " + from, Project.MSG_VERBOSE); + log("To " + toList, Project.MSG_VERBOSE); + log("Cc " + ccList, Project.MSG_VERBOSE); + log("Bcc " + bccList, Project.MSG_VERBOSE); // pass the params to the mailer - mailer.setHost( host ); - mailer.setPort( port ); - mailer.setMessage( message ); - mailer.setFrom( from ); - mailer.setToList( toList ); - mailer.setCcList( ccList ); - mailer.setBccList( bccList ); - mailer.setFiles( files ); - mailer.setSubject( subject ); - mailer.setTask( this ); - mailer.setIncludeFileNames( includeFileNames ); + mailer.setHost(host); + mailer.setPort(port); + mailer.setMessage(message); + mailer.setFrom(from); + mailer.setToList(toList); + mailer.setCcList(ccList); + mailer.setBccList(bccList); + mailer.setFiles(files); + mailer.setSubject(subject); + mailer.setTask(this); + mailer.setIncludeFileNames(includeFileNames); // send the email mailer.send(); // let the user know what happened int count = files.size(); - log( "Sent email with " + count + " attachment" - + ( count == 1?"":"s" ), Project.MSG_INFO ); - } - catch( BuildException e ) - { - log( "Failed to send email", Project.MSG_WARN ); - if( failOnError ) - { + + log("Sent email with " + count + " attachment" + + (count == 1 ? "" : "s"), Project.MSG_INFO); + } catch (BuildException e) { + log("Failed to send email", Project.MSG_WARN); + if (failOnError) { throw e; } } finally { diff --git a/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java b/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java index 8cef2371a..14c5b3804 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java @@ -63,8 +63,7 @@ import org.apache.tools.ant.Task; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -abstract class Mailer -{ +abstract class Mailer { protected String host = null; protected int port = -1; protected Message message; @@ -77,109 +76,123 @@ abstract class Mailer protected Task task; protected boolean includeFileNames = false; - /** + + /** * Sets the mail server + * * @param host */ - public void setHost( String host ) - { + public void setHost(String host) { this.host = host; } - /** + + /** * Sets the smtp port + * * @param port */ - public void setPort( int port ) - { + public void setPort(int port) { this.port = port; } - /** + + /** * Sets the message + * * @param m */ - public void setMessage( Message m ) - { + public void setMessage(Message m) { this.message = m; } - /** + + /** * Sets the address to send from + * * @param from */ - public void setFrom( EmailAddress from ) - { + public void setFrom(EmailAddress from) { this.from = from; } - /** + + /** * Set the to addresses + * * @param list */ - public void setToList( Vector list ) - { + public void setToList(Vector list) { this.toList = list; } - /** + + /** * Sets the cc addresses + * * @param list */ - public void setCcList( Vector list ) - { + public void setCcList(Vector list) { this.ccList = list; } - /** + + /** * Sets the bcc addresses + * * @param list */ - public void setBccList( Vector list ) - { + public void setBccList(Vector list) { this.bccList = list; } - /** + + /** * Sets the files to attach + * * @param files */ - public void setFiles( Vector files ) - { + public void setFiles(Vector files) { this.files = files; } - /** + + /** * Sets the subject + * * @param subject */ - public void setSubject( String subject ) - { + public void setSubject(String subject) { this.subject = subject; } - /** + + /** * Sets the owning task + * * @param task */ - public void setTask( Task task ) - { + public void setTask(Task task) { this.task = task; } - /** + + /** * Indicates whether filenames should be listed in the body + * * @param b */ - public void setIncludeFileNames( boolean b ) - { + public void setIncludeFileNames(boolean b) { this.includeFileNames = b; } - /** + + /** * This method should send the email + * * @throws BuildException */ public abstract void send() - throws BuildException; + throws BuildException; } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/Message.java b/src/main/org/apache/tools/ant/taskdefs/email/Message.java index c89816a4e..b39243884 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/Message.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/Message.java @@ -65,113 +65,114 @@ import java.io.PrintStream; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -public class Message -{ +public class Message { private File messageSource = null; private StringBuffer buffer = new StringBuffer(); private String mimeType = "text/plain"; private boolean specified = false; - /** - * Creates a new empty message - */ - public Message() - { + + /** Creates a new empty message */ + public Message() { } - /** + + /** * Creates a new message based on the given string + * * @param text the message */ - public Message( String text ) - { - addText( text ); + public Message(String text) { + addText(text); } - /** + + /** * Creates a new message using the contents of the given file. + * * @param file the source of the message */ - public Message( File file ) - { + public Message(File file) { messageSource = file; } - /** + + /** * Adds a textual part of the message + * * @param text some text to add */ - public void addText( String text ) - { - buffer.append( text ); + public void addText(String text) { + buffer.append(text); } - /** + + /** * Sets the source file of the message + * * @param src the source of the message */ - public void setSrc( File src ) - { + public void setSrc(File src) { this.messageSource = src; } - /** + + /** * Sets the content type for the message + * * @param mimeType a mime type e.g. "text/plain" */ - public void setMimeType( String mimeType ) - { + public void setMimeType(String mimeType) { this.mimeType = mimeType; specified = true; } - /** + + /** * Returns the content type + * * @return the mime type */ - public String getMimeType() - { + public String getMimeType() { return mimeType; } - /** + + /** * Prints the message onto an output stream + * * @param out The print stream to write to * @throws IOException if an error occurs */ - public void print( PrintStream out ) - throws IOException - { - if( messageSource != null ) - { + public void print(PrintStream out) + throws IOException { + if (messageSource != null) { // Read message from a file - FileReader freader = new FileReader( messageSource ); - try - { - BufferedReader in = new BufferedReader( freader ); + FileReader freader = new FileReader(messageSource); + + try { + BufferedReader in = new BufferedReader(freader); String line = null; - while( ( line = in.readLine() ) != null ) - { - out.println( line ); + while ((line = in.readLine()) != null) { + out.println(line); } - } - finally { + } finally { freader.close(); } - } - else - { - out.println( buffer ); + } else { + out.println(buffer); } } - /** + + /** * Returns true iff the mimeType has been set. + * * @return false if the default value is in use */ - public boolean isMimeTypeSpecified() - { + public boolean isMimeTypeSpecified() { return specified; } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java index 1ab652fcc..3374c0aa6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java @@ -80,112 +80,101 @@ import org.apache.tools.ant.BuildException; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -class MimeMailer - extends Mailer -{ - /** Sends the email - */ - public void send() - { - try - { +class MimeMailer extends Mailer { + /** Sends the email */ + public void send() { + try { Properties props = new Properties(); - props.put( "mail.smtp.host", host ); - props.put( "mail.smtp.port", String.valueOf( port ) ); + + props.put("mail.smtp.host", host); + props.put("mail.smtp.port", String.valueOf(port)); // Aside, the JDK is clearly unaware of the scottish // 'session', which //involves excessive quantities of // alcohol :-) - Session sesh = Session.getDefaultInstance( props, null ); + Session sesh = Session.getDefaultInstance(props, null); //create the message - MimeMessage msg = new MimeMessage( sesh ); + MimeMessage msg = new MimeMessage(sesh); MimeMultipart attachments = new MimeMultipart(); //set the sender - if( from.getName() == null ) - { - msg.setFrom( new InternetAddress( from.getAddress() ) ); - } - else - { - msg.setFrom( new InternetAddress( from.getAddress(), - from.getName() ) ); + if (from.getName() == null) { + msg.setFrom(new InternetAddress(from.getAddress())); + } else { + msg.setFrom(new InternetAddress(from.getAddress(), + from.getName())); } - msg.setRecipients( Message.RecipientType.TO, - internetAddresses( toList ) ); - msg.setRecipients( Message.RecipientType.CC, - internetAddresses( ccList ) ); - msg.setRecipients( Message.RecipientType.BCC, - internetAddresses( bccList ) ); + msg.setRecipients(Message.RecipientType.TO, + internetAddresses(toList)); + msg.setRecipients(Message.RecipientType.CC, + internetAddresses(ccList)); + msg.setRecipients(Message.RecipientType.BCC, + internetAddresses(bccList)); - if( subject != null ) - { - msg.setSubject( subject ); + if (subject != null) { + msg.setSubject(subject); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream out = new PrintStream( baos ); - message.print( out ); + PrintStream out = new PrintStream(baos); + + message.print(out); out.close(); MimeBodyPart textbody = new MimeBodyPart(); - textbody.setContent( baos.toString(), message.getMimeType() ); - attachments.addBodyPart( textbody ); + + textbody.setContent(baos.toString(), message.getMimeType()); + attachments.addBodyPart(textbody); Enumeration e = files.elements(); - while( e.hasMoreElements() ) - { - File file = (File)e.nextElement(); + + while (e.hasMoreElements()) { + File file = (File) e.nextElement(); MimeBodyPart body; + body = new MimeBodyPart(); - if( !file.exists() || !file.canRead() ) - { - throw new BuildException( "File \"" + file.getAbsolutePath() - + "\" does not exist or is not " - + "readable." ); + if (!file.exists() || !file.canRead()) { + throw new BuildException("File \"" + file.getAbsolutePath() + + "\" does not exist or is not " + + "readable."); } - FileDataSource fileData = new FileDataSource( file ); - DataHandler fileDataHandler = new DataHandler( fileData ); - body.setDataHandler( fileDataHandler ); - body.setFileName( file.getName() ); - attachments.addBodyPart( body ); + FileDataSource fileData = new FileDataSource(file); + DataHandler fileDataHandler = new DataHandler(fileData); + + body.setDataHandler(fileDataHandler); + body.setFileName(file.getName()); + attachments.addBodyPart(body); } - msg.setContent( attachments ); - Transport.send( msg ); - } - catch( MessagingException e ) - { - throw new BuildException( "Problem while sending mime mail:", e ); - } - catch( IOException e ) - { - throw new BuildException( "Problem while sending mime mail:", e ); + msg.setContent(attachments); + Transport.send(msg); + } catch (MessagingException e) { + throw new BuildException("Problem while sending mime mail:", e); + } catch (IOException e) { + throw new BuildException("Problem while sending mime mail:", e); } } - private static InternetAddress[] internetAddresses( Vector list ) - throws AddressException, UnsupportedEncodingException - { - InternetAddress[] addrs = new InternetAddress[ list.size() ]; - for( int i = 0; i < list.size(); ++i ) - { - EmailAddress addr = (EmailAddress)list.elementAt( i ); - - if( addr.getName() == null ) - { - addrs[ i ] = new InternetAddress( addr.getAddress() ); - } - else - { - addrs[ i ] = new InternetAddress( addr.getAddress(), - addr.getName() ); + + private static InternetAddress[] internetAddresses(Vector list) + throws AddressException, UnsupportedEncodingException { + InternetAddress[] addrs = new InternetAddress[list.size()]; + + for (int i = 0; i < list.size(); ++i) { + EmailAddress addr = (EmailAddress) list.elementAt(i); + + if (addr.getName() == null) { + addrs[i] = new InternetAddress(addr.getAddress()); + } else { + addrs[i] = new InternetAddress(addr.getAddress(), + addr.getName()); } } return addrs; } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java index d8e3926dc..0e2465a7c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java @@ -68,112 +68,103 @@ import org.apache.tools.mail.MailMessage; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -class PlainMailer - extends Mailer -{ - /** +class PlainMailer extends Mailer { + /** * Sends the email using the apache MailMessage class. + * * @see org.apache.tools.mail.MailMessage */ - public void send() - { - try - { - MailMessage mailMessage = new MailMessage( host ); - mailMessage.setPort( port ); + public void send() { + try { + MailMessage mailMessage = new MailMessage(host); - mailMessage.from( from.toString() ); + mailMessage.setPort(port); + + mailMessage.from(from.toString()); Enumeration e; e = toList.elements(); - while( e.hasMoreElements() ) - { - mailMessage.to( e.nextElement().toString() ); + while (e.hasMoreElements()) { + mailMessage.to(e.nextElement().toString()); } e = ccList.elements(); - while( e.hasMoreElements() ) - { - mailMessage.cc( e.nextElement().toString() ); + while (e.hasMoreElements()) { + mailMessage.cc(e.nextElement().toString()); } e = bccList.elements(); - while( e.hasMoreElements() ) - { - mailMessage.bcc( e.nextElement().toString() ); + while (e.hasMoreElements()) { + mailMessage.bcc(e.nextElement().toString()); } - if( subject != null ) - { - mailMessage.setSubject( subject ); + if (subject != null) { + mailMessage.setSubject(subject); } - mailMessage.setHeader( "Content-Type", message.getMimeType() ); + mailMessage.setHeader("Content-Type", message.getMimeType()); PrintStream out = mailMessage.getPrintStream(); - message.print( out ); + message.print(out); e = files.elements(); - while( e.hasMoreElements() ) - { - File file = (File)e.nextElement(); - attach( file, out ); + while (e.hasMoreElements()) { + File file = (File) e.nextElement(); + + attach(file, out); } mailMessage.sendAndClose(); - } - catch( IOException ioe ) - { - throw new BuildException( "IO error sending mail", ioe ); + } catch (IOException ioe) { + throw new BuildException("IO error sending mail", ioe); } } - /** + + /** * Attaches a file to this email + * * @param file The file to attache * @param out The message stream to add to * @throws IOException if errors occur */ - protected void attach( File file, PrintStream out ) - throws IOException - { - if( !file.exists() || !file.canRead() ) - { - throw new BuildException( "File \"" + file.getName() - + "\" does not exist or is not " - + "readable." ); + protected void attach(File file, PrintStream out) + throws IOException { + if (!file.exists() || !file.canRead()) { + throw new BuildException("File \"" + file.getName() + + "\" does not exist or is not " + + "readable."); } - if( includeFileNames ) - { + if (includeFileNames) { out.println(); + String filename = file.getName(); int filenamelength = filename.length(); - out.println( filename ); - for( int star = 0; star < filenamelength; star++ ) - { - out.print( '=' ); + + out.println(filename); + for (int star = 0; star < filenamelength; star++) { + out.print('='); } out.println(); } int length; - byte[] buf = new byte[ 1024 ]; - FileInputStream finstr = new FileInputStream( file ); - try - { - BufferedInputStream in = new BufferedInputStream( finstr, buf.length ); - while( ( length = in.read( buf ) ) != -1 ) - { - out.write( buf, 0, length ); + byte[] buf = new byte[1024]; + FileInputStream finstr = new FileInputStream(file); + + try { + BufferedInputStream in = new BufferedInputStream(finstr, buf.length); + + while ((length = in.read(buf)) != -1) { + out.write(buf, 0, length); } - } - finally - { + } finally { finstr.close(); } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java index 386682573..16f828419 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java @@ -67,30 +67,26 @@ import sun.misc.UUEncoder; * @author roxspring@yahoo.com Rob Oxspring * @since Ant 1.5 */ -class UUMailer - extends PlainMailer -{ - protected void attach( File file, PrintStream out ) - throws IOException - { - if( !file.exists() || !file.canRead() ) - { - throw new BuildException( "File \"" + file.getName() - + "\" does not exist or is not " - + "readable." ); +class UUMailer extends PlainMailer { + protected void attach(File file, PrintStream out) + throws IOException { + if (!file.exists() || !file.canRead()) { + throw new BuildException("File \"" + file.getName() + + "\" does not exist or is not " + + "readable."); } - FileInputStream finstr = new FileInputStream( file ); - try - { - BufferedInputStream in = new BufferedInputStream( finstr ); - UUEncoder encoder = new UUEncoder( file.getName() ); - encoder.encode( in, out ); + FileInputStream finstr = new FileInputStream(file); - } - finally - { + try { + BufferedInputStream in = new BufferedInputStream(finstr); + UUEncoder encoder = new UUEncoder(file.getName()); + + encoder.encode(in, out); + + } finally { finstr.close(); } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java index 92a337fbd..cc3e168a5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java @@ -320,12 +320,12 @@ public class Cab extends MatchingTask { outLog.close(); errPump.waitFor(); errLog.close(); - } catch(InterruptedException ie) { + } catch (InterruptedException ie) { log("Thread interrupted: " + ie); } // Informative summary message in case of errors - if(result != 0) { + if (result != 0) { log("Error executing listcab; error code: " + result); } } catch (IOException ex) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java index cd48ed126..73bdf24d4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java @@ -211,12 +211,12 @@ public class EchoProperties extends Task { while (enum.hasMoreElements()) { String name = (String) enum.nextElement(); String value = (String) allProps.get(name); - if (prefix == null || name.indexOf(prefix) == 0 ) { + if (prefix == null || name.indexOf(prefix) == 0) { props.put(name, value); } } try { - jdkSaveProperties( props, os, "Ant properties" ); + jdkSaveProperties(props, os, "Ant properties"); } finally { os.close(); } @@ -237,32 +237,31 @@ public class EchoProperties extends Task { *@exception IOException on an I/O error during a write. Only thrown * for JDK 1.2+. */ - protected void jdkSaveProperties( Properties props, OutputStream os, - String header ) - throws IOException { + protected void jdkSaveProperties(Properties props, OutputStream os, + String header) throws IOException { try { java.lang.reflect.Method m = props.getClass().getMethod( - "store", new Class[] { OutputStream.class, String.class } ); - m.invoke( props, new Object[] { os, header } ); + "store", new Class[]{OutputStream.class, String.class}); + m.invoke(props, new Object[]{os, header}); } catch (java.lang.reflect.InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t instanceof IOException) { - throw (IOException)t; + throw (IOException) t; } if (t instanceof RuntimeException) { - throw (RuntimeException)t; + throw (RuntimeException) t; } // not an expected exception. Resort to JDK 1.0 to execute // this method - jdk10SaveProperties( props, os, header ); + jdk10SaveProperties(props, os, header); } catch (ThreadDeath td) { // don't trap thread death errors. throw td; } catch (Throwable ex) { // this 'store' method is not available, so resort to the JDK 1.0 // compatible method. - jdk10SaveProperties( props, os, header ); + jdk10SaveProperties(props, os, header); } } @@ -275,10 +274,10 @@ public class EchoProperties extends Task { *@param os record the properties to this output stream *@param header prepend this header to the property output */ - protected void jdk10SaveProperties( Properties props, OutputStream os, - String header ) + protected void jdk10SaveProperties(Properties props, OutputStream os, + String header) { - props.save( os, header ); + props.save(os, header); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/IContract.java b/src/main/org/apache/tools/ant/taskdefs/optional/IContract.java index eacd0f740..9058b0542 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/IContract.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/IContract.java @@ -55,9 +55,6 @@ package org.apache.tools.ant.taskdefs.optional; - - - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -89,7 +86,7 @@ import org.apache.tools.ant.types.Reference; *

* Thanks to Rainer Schmitz for enhancements and comments. * - * @author Aslak Hellesøy + * @author Aslak Helles�a> * *

* @@ -233,7 +230,7 @@ public class IContract extends MatchingTask { "You should probably modify icontrol.properties' classRoot to where comiled (uninstrumented) classes go."; /** \ on windows, / on linux/unix */ - private final static String ps = System.getProperty( "path.separator" ); + private final static String ps = System.getProperty("path.separator"); /** compiler to use for instrumenation */ private String icCompiler = "javac"; @@ -241,7 +238,10 @@ public class IContract extends MatchingTask { /** temporary file with file names of all java files to be instrumented */ private File targets = null; - /** will be set to true if any of the sourca files are newer than the instrumented files */ + /** + * will be set to true if any of the sourca files are newer than the + * instrumented files + */ private boolean dirty = false; /** set to true if the iContract jar is missing */ @@ -297,166 +297,182 @@ public class IContract extends MatchingTask { private boolean instrumentall = false; /** - * Indicates the name of a properties file (intentionally for iControl) where the classpath - * property should be updated. + * Indicates the name of a properties file (intentionally for iControl) + * where the classpath property should be updated. */ private boolean updateIcontrol = false; - /** - * Regular compilation class root - */ + /** Regular compilation class root */ private File classDir = null; + /** * Sets the source directory * * @param srcDir the source directory */ - public void setSrcdir( File srcDir ) { + public void setSrcdir(File srcDir) { this.srcDir = srcDir; } + /** * Sets the class directory (uninstrumented classes) * * @param srcDir the source directory */ - public void setClassdir( File classDir ) { + public void setClassdir(File classDir) { this.classDir = classDir; } + /** * Sets the instrumentation directory * * @param instrumentDir the source directory */ - public void setInstrumentdir( File instrumentDir ) { + public void setInstrumentdir(File instrumentDir) { this.instrumentDir = instrumentDir; - if ( this.buildDir == null ) { - setBuilddir( instrumentDir ); + if (this.buildDir == null) { + setBuilddir(instrumentDir); } } + /** * Sets the build directory for instrumented classes * * @param buildDir the build directory */ - public void setBuilddir( File buildDir ) { + public void setBuilddir(File buildDir) { this.buildDir = buildDir; } + /** * Sets the build directory for repository classes * * @param repositoryDir the source directory */ - public void setRepositorydir( File repositoryDir ) { + public void setRepositorydir(File repositoryDir) { this.repositoryDir = repositoryDir; - if( this.repBuildDir == null ) { - setRepbuilddir( repositoryDir ); + if (this.repBuildDir == null) { + setRepbuilddir(repositoryDir); } } + /** * Sets the build directory for instrumented classes * * @param buildDir the build directory */ - public void setRepbuilddir( File repBuildDir ) { + public void setRepbuilddir(File repBuildDir) { this.repBuildDir = repBuildDir; } + /** * Turns on/off precondition instrumentation * * @param pre true turns it on */ - public void setPre( boolean pre ) { + public void setPre(boolean pre) { this.pre = pre; preModified = true; } + /** * Turns on/off postcondition instrumentation * * @param post true turns it on */ - public void setPost( boolean post ) { + public void setPost(boolean post) { this.post = post; postModified = true; } + /** * Turns on/off invariant instrumentation * * @param invariant true turns it on */ - public void setInvariant( boolean invariant ) { + public void setInvariant(boolean invariant) { this.invariant = invariant; invariantModified = true; } + /** * Sets the Throwable (Exception) to be thrown on assertion violation * * @param clazz the fully qualified Throwable class name */ - public void setFailthrowable( String clazz ) { + public void setFailthrowable(String clazz) { this.failThrowable = clazz; } + /** * Sets the verbosity level of iContract. Any combination of - * error*,warning*,note*,info*,progress*,debug* (comma separated) - * can be used. Defaults to error*,warning* + * error*,warning*,note*,info*,progress*,debug* (comma separated) can be + * used. Defaults to error*,warning* * * @param verbosity verbosity level */ - public void setVerbosity( String verbosity ) { + public void setVerbosity(String verbosity) { this.verbosity = verbosity; } + /** * Tells iContract to be quiet. * * @param quiet true if iContract should be quiet. */ - public void setQuiet( boolean quiet ) { + public void setQuiet(boolean quiet) { this.quiet = quiet; } + /** - * Sets the name of the file where targets will be written. - * That is the file that tells iContract what files to process. + * Sets the name of the file where targets will be written. That is the + * file that tells iContract what files to process. * * @param targets the targets file name */ - public void setTargets( File targets ) { + public void setTargets(File targets) { this.targets = targets; } + /** * Sets the control file to pass to iContract. * * @param controlFile the control file */ - public void setControlfile( File controlFile ) { - if( !controlFile.exists() ) { - log( "WARNING: Control file " + controlFile.getAbsolutePath() + " doesn't exist. iContract will be run without control file." ); + public void setControlfile(File controlFile) { + if (!controlFile.exists()) { + log("WARNING: Control file " + controlFile.getAbsolutePath() + + " doesn't exist. iContract will be run " + + "without control file."); } this.controlFile = controlFile; } + /** * Sets the classpath to be used for invocation of iContract. * * @param path the classpath */ - public void setClasspath( Path path ) { - createClasspath().append( path ); + public void setClasspath(Path path) { + createClasspath().append(path); } + /** * Creates a nested classpath element * @@ -464,29 +480,33 @@ public class IContract extends MatchingTask { */ public Path createClasspath() { if (classpath == null) { - classpath = new Path( getProject() ); + classpath = new Path(getProject()); } return classpath; } + /** * Adds a reference to a classpath defined elsewhere. * * @param reference referenced classpath */ - public void setClasspathRef( Reference reference ) { - createClasspath().setRefid( reference ); + public void setClasspathRef(Reference reference) { + createClasspath().setRefid(reference); } + /** * Decides whether or not to update iControl properties file * - * @param updateIcontrol true if iControl properties file should be updated + * @param updateIcontrol true if iControl properties file should be + * updated */ - public void setUpdateicontrol( boolean updateIcontrol ) { + public void setUpdateicontrol(boolean updateIcontrol) { this.updateIcontrol = updateIcontrol; } + /** * Executes the task * @@ -495,39 +515,41 @@ public class IContract extends MatchingTask { public void execute() throws BuildException { preconditions(); scan(); - if( dirty ) { + if (dirty) { // turn off assertions if we're using controlfile, unless they are not explicitly set. boolean useControlFile = (controlFile != null) && controlFile.exists(); - if( useControlFile && !preModified ) { + + if (useControlFile && !preModified) { pre = false; } - if( useControlFile && !postModified ) { + if (useControlFile && !postModified) { post = false; } - if( useControlFile && !invariantModified ) { + if (useControlFile && !invariantModified) { invariant = false; } // issue warning if pre,post or invariant is used together with controlfile - if( ( pre || post || invariant ) && controlFile != null ) { - log( "WARNING: specifying pre,post or invariant will override control file settings" ); + if ((pre || post || invariant) && controlFile != null) { + log("WARNING: specifying pre,post or invariant will " + + "override control file settings"); } - // We want to be notified if iContract jar is missing. This makes life easier for the user // who didn't understand that iContract is a separate library (duh!) - getProject().addBuildListener( new IContractPresenceDetector() ); + getProject().addBuildListener(new IContractPresenceDetector()); // Prepare the directories for iContract. iContract will make them if they // don't exist, but for some reason I don't know, it will complain about the REP files // afterwards - Mkdir mkdir = (Mkdir) project.createTask( "mkdir" ); - mkdir.setDir( instrumentDir ); + Mkdir mkdir = (Mkdir) project.createTask("mkdir"); + + mkdir.setDir(instrumentDir); mkdir.execute(); - mkdir.setDir( buildDir ); + mkdir.setDir(buildDir); mkdir.execute(); - mkdir.setDir( repositoryDir ); + mkdir.setDir(repositoryDir); mkdir.execute(); // Set the classpath that is needed for regular Javac compilation @@ -535,161 +557,174 @@ public class IContract extends MatchingTask { // Might need to add the core classes if we're not using Sun's Javac (like Jikes) String compiler = project.getProperty("build.compiler"); - ClasspathHelper classpathHelper = new ClasspathHelper( compiler ); - classpathHelper.modify( baseClasspath ); + ClasspathHelper classpathHelper = new ClasspathHelper(compiler); + + classpathHelper.modify(baseClasspath); // Create the classpath required to compile the sourcefiles BEFORE instrumentation Path beforeInstrumentationClasspath = ((Path) baseClasspath.clone()); - beforeInstrumentationClasspath.append( new Path( getProject(), srcDir.getAbsolutePath() ) ); + + beforeInstrumentationClasspath.append(new Path(getProject(), + srcDir.getAbsolutePath())); // Create the classpath required to compile the sourcefiles AFTER instrumentation Path afterInstrumentationClasspath = ((Path) baseClasspath.clone()); - afterInstrumentationClasspath.append( new Path( getProject(), instrumentDir.getAbsolutePath() ) ); - afterInstrumentationClasspath.append( new Path( getProject(), repositoryDir.getAbsolutePath() ) ); - afterInstrumentationClasspath.append( new Path( getProject(), srcDir.getAbsolutePath() ) ); - afterInstrumentationClasspath.append( new Path( getProject(), buildDir.getAbsolutePath() ) ); + + afterInstrumentationClasspath.append(new Path(getProject(), instrumentDir.getAbsolutePath())); + afterInstrumentationClasspath.append(new Path(getProject(), repositoryDir.getAbsolutePath())); + afterInstrumentationClasspath.append(new Path(getProject(), srcDir.getAbsolutePath())); + afterInstrumentationClasspath.append(new Path(getProject(), buildDir.getAbsolutePath())); // Create the classpath required to automatically compile the repository files Path repositoryClasspath = ((Path) baseClasspath.clone()); - repositoryClasspath.append( new Path( getProject(), instrumentDir.getAbsolutePath() ) ); - repositoryClasspath.append( new Path( getProject(), srcDir.getAbsolutePath() ) ); - repositoryClasspath.append( new Path( getProject(), repositoryDir.getAbsolutePath() ) ); - repositoryClasspath.append( new Path( getProject(), buildDir.getAbsolutePath() ) ); + + repositoryClasspath.append(new Path(getProject(), instrumentDir.getAbsolutePath())); + repositoryClasspath.append(new Path(getProject(), srcDir.getAbsolutePath())); + repositoryClasspath.append(new Path(getProject(), repositoryDir.getAbsolutePath())); + repositoryClasspath.append(new Path(getProject(), buildDir.getAbsolutePath())); // Create the classpath required for iContract itself Path iContractClasspath = ((Path) baseClasspath.clone()); - iContractClasspath.append( new Path( getProject(), System.getProperty( "java.home" ) + File.separator + ".." + File.separator + "lib" + File.separator + "tools.jar" ) ); - iContractClasspath.append( new Path( getProject(), srcDir.getAbsolutePath() ) ); - iContractClasspath.append( new Path( getProject(), repositoryDir.getAbsolutePath() ) ); - iContractClasspath.append( new Path( getProject(), instrumentDir.getAbsolutePath() ) ); - iContractClasspath.append( new Path( getProject(), buildDir.getAbsolutePath() ) ); + + iContractClasspath.append(new Path(getProject(), System.getProperty("java.home") + File.separator + ".." + File.separator + "lib" + File.separator + "tools.jar")); + iContractClasspath.append(new Path(getProject(), srcDir.getAbsolutePath())); + iContractClasspath.append(new Path(getProject(), repositoryDir.getAbsolutePath())); + iContractClasspath.append(new Path(getProject(), instrumentDir.getAbsolutePath())); + iContractClasspath.append(new Path(getProject(), buildDir.getAbsolutePath())); // Create a forked java process - Java iContract = (Java) project.createTask( "java" ); - iContract.setTaskName( getTaskName() ); - iContract.setFork( true ); - iContract.setClassname( "com.reliablesystems.iContract.Tool" ); - iContract.setClasspath( iContractClasspath ); + Java iContract = (Java) project.createTask("java"); + + iContract.setTaskName(getTaskName()); + iContract.setFork(true); + iContract.setClassname("com.reliablesystems.iContract.Tool"); + iContract.setClasspath(iContractClasspath); // Build the arguments to iContract StringBuffer args = new StringBuffer(); - args.append( directiveString() ); - args.append( "-v" ).append( verbosity ).append( " " ); - args.append( "-b" ).append( "\"" ).append( icCompiler ).append( " -classpath " ).append( beforeInstrumentationClasspath ).append( "\" " ); - args.append( "-c" ).append( "\"" ).append( icCompiler ).append( " -classpath " ).append( afterInstrumentationClasspath ).append( " -d " ).append( buildDir ).append( "\" " ); - args.append( "-n" ).append( "\"" ).append( icCompiler ).append( " -classpath " ).append( repositoryClasspath ).append( "\" " ); - args.append( "-d" ).append( failThrowable ).append( " " ); - args.append( "-o" ).append( instrumentDir ).append( File.separator ).append( "@p" ).append( File.separator ).append( "@f.@e " ); - args.append( "-k" ).append( repositoryDir ).append( File.separator ).append( "@p " ); - args.append( quiet ? "-q " : "" ); - args.append( instrumentall ? "-a " : "" ); // reinstrument everything if controlFile exists and is newer than any class - args.append( "@" ).append( targets.getAbsolutePath() ); - iContract.createArg().setLine( args.toString() ); + + args.append(directiveString()); + args.append("-v").append(verbosity).append(" "); + args.append("-b").append("\"").append(icCompiler).append(" -classpath ").append(beforeInstrumentationClasspath).append("\" "); + args.append("-c").append("\"").append(icCompiler).append(" -classpath ").append(afterInstrumentationClasspath).append(" -d ").append(buildDir).append("\" "); + args.append("-n").append("\"").append(icCompiler).append(" -classpath ").append(repositoryClasspath).append("\" "); + args.append("-d").append(failThrowable).append(" "); + args.append("-o").append(instrumentDir).append(File.separator).append("@p").append(File.separator).append("@f.@e "); + args.append("-k").append(repositoryDir).append(File.separator).append("@p "); + args.append(quiet ? "-q " : ""); + args.append(instrumentall ? "-a " : "");// reinstrument everything if controlFile exists and is newer than any class + args.append("@").append(targets.getAbsolutePath()); + iContract.createArg().setLine(args.toString()); //System.out.println( "JAVA -classpath " + iContractClasspath + " com.reliablesystems.iContract.Tool " + args.toString() ); // update iControlProperties if it's set. - if( updateIcontrol ) { + if (updateIcontrol) { Properties iControlProps = new Properties(); - try { // to read existing propertiesfile - iControlProps.load( new FileInputStream( "icontrol.properties" ) ); - } catch( IOException e ) { - log( "File icontrol.properties not found. That's ok. Writing a default one." ); + + try {// to read existing propertiesfile + iControlProps.load(new FileInputStream("icontrol.properties")); + } catch (IOException e) { + log("File icontrol.properties not found. That's ok. Writing a default one."); } - iControlProps.setProperty( "sourceRoot", srcDir.getAbsolutePath() ); - iControlProps.setProperty( "classRoot", classDir.getAbsolutePath() ); - iControlProps.setProperty( "classpath", afterInstrumentationClasspath.toString() ); - iControlProps.setProperty( "controlFile", controlFile.getAbsolutePath() ); - iControlProps.setProperty( "targetsFile", targets.getAbsolutePath() ); - - try { // to read existing propertiesfile - iControlProps.store( new FileOutputStream( "icontrol.properties" ), ICONTROL_PROPERTIES_HEADER ); - log( "Updated icontrol.properties" ); - } catch( IOException e ) { - log( "Couldn't write icontrol.properties." ); + iControlProps.setProperty("sourceRoot", srcDir.getAbsolutePath()); + iControlProps.setProperty("classRoot", classDir.getAbsolutePath()); + iControlProps.setProperty("classpath", afterInstrumentationClasspath.toString()); + iControlProps.setProperty("controlFile", controlFile.getAbsolutePath()); + iControlProps.setProperty("targetsFile", targets.getAbsolutePath()); + + try {// to read existing propertiesfile + iControlProps.store(new FileOutputStream("icontrol.properties"), ICONTROL_PROPERTIES_HEADER); + log("Updated icontrol.properties"); + } catch (IOException e) { + log("Couldn't write icontrol.properties."); } } // do it! int result = iContract.executeJava(); - if( result != 0 ) { - if( iContractMissing ) { - log( "iContract can't be found on your classpath. Your classpath is:" ); - log( classpath.toString() ); - log( "If you don't have the iContract jar, go get it at http://www.reliable-systems.com/tools/" ); + + if (result != 0) { + if (iContractMissing) { + log("iContract can't be found on your classpath. Your classpath is:"); + log(classpath.toString()); + log("If you don't have the iContract jar, go get it at http://www.reliable-systems.com/tools/"); } - throw new BuildException( "iContract instrumentation failed. Code=" + result ); + throw new BuildException("iContract instrumentation failed. Code=" + result); } - - } else { // not dirty + } else {// not dirty //log( "Nothing to do. Everything up to date." ); } } - /** - * Checks that the required attributes are set. - */ + + /** Checks that the required attributes are set. */ private void preconditions() throws BuildException { if (srcDir == null) { - throw new BuildException( "srcdir attribute must be set!", location ); + throw new BuildException("srcdir attribute must be set!", location); } if (!srcDir.exists()) { - throw new BuildException( "srcdir \"" + srcDir.getPath() + "\" does not exist!", location ); + throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", location); } if (instrumentDir == null) { - throw new BuildException( "instrumentdir attribute must be set!", location ); + throw new BuildException("instrumentdir attribute must be set!", location); } if (repositoryDir == null) { - throw new BuildException( "repositorydir attribute must be set!", location ); + throw new BuildException("repositorydir attribute must be set!", location); } if (updateIcontrol == true && classDir == null) { - throw new BuildException( "classdir attribute must be specified when updateicontrol=true!", location ); + throw new BuildException("classdir attribute must be specified when updateicontrol=true!", location); } - if( updateIcontrol == true && controlFile == null ) { - throw new BuildException( "controlfile attribute must be specified when updateicontrol=true!", location ); + if (updateIcontrol == true && controlFile == null) { + throw new BuildException("controlfile attribute must be specified when updateicontrol=true!", location); } } + /** - * Verifies whether any of the source files have changed. Done by comparing date of source/class files. - * The whole lot is "dirty" if at least one source file or the control file is newer than the instrumented - * files. If not dirty, iContract will not be executed. - *
- * Also creates a temporary file with a list of the source files, that will be deleted upon exit. + * Verifies whether any of the source files have changed. Done by + * comparing date of source/class files. The whole lot is "dirty" if at + * least one source file or the control file is newer than the + * instrumented files. If not dirty, iContract will not be executed.
+ * Also creates a temporary file with a list of the source files, that + * will be deleted upon exit. */ private void scan() throws BuildException { long now = (new Date()).getTime(); DirectoryScanner ds = null; - ds = getDirectoryScanner( srcDir ); + ds = getDirectoryScanner(srcDir); + String[] files = ds.getIncludedFiles(); FileOutputStream targetOutputStream = null; PrintStream targetPrinter = null; boolean writeTargets = false; + try { - if( targets == null ) { - targets = new File( "targets" ); - log( "Warning: targets file not specified. generating file: " + targets.getName() ); + if (targets == null) { + targets = new File("targets"); + log("Warning: targets file not specified. generating file: " + targets.getName()); writeTargets = true; - } else if( !targets.exists() ) { - log( "Specified targets file doesn't exist. generating file: " + targets.getName() ); + } else if (!targets.exists()) { + log("Specified targets file doesn't exist. generating file: " + targets.getName()); writeTargets = true; } - if( writeTargets ) { - log( "You should consider using iControl to create a target file." ); - targetOutputStream = new FileOutputStream( targets ); - targetPrinter = new PrintStream( targetOutputStream ); + if (writeTargets) { + log("You should consider using iControl to create a target file."); + targetOutputStream = new FileOutputStream(targets); + targetPrinter = new PrintStream(targetOutputStream); } - for (int i = 0; i < files.length; i++ ) { + for (int i = 0; i < files.length; i++) { File srcFile = new File(srcDir, files[i]); + if (files[i].endsWith(".java")) { // print the target, while we're at here. (Only if generatetarget=true). - if( targetPrinter != null ) { - targetPrinter.println( srcFile.getAbsolutePath() ); + if (targetPrinter != null) { + targetPrinter.println(srcFile.getAbsolutePath()); } - File classFile = new File( buildDir, files[i].substring( 0, files[i].indexOf( ".java" ) ) + ".class" ); + File classFile = new File(buildDir, files[i].substring(0, files[i].indexOf(".java")) + ".class"); if (srcFile.lastModified() > now) { log("Warning: file modified in the future: " + @@ -702,28 +737,30 @@ public class IContract extends MatchingTask { } } } - if( targetPrinter != null ) { + if (targetPrinter != null) { targetPrinter.flush(); targetPrinter.close(); } - } catch( IOException e ) { - throw new BuildException( "Could not create target file:" + e.getMessage() ); + } catch (IOException e) { + throw new BuildException("Could not create target file:" + e.getMessage()); } // also, check controlFile timestamp long controlFileTime = -1; + try { - if( controlFile != null ) { - if( controlFile.exists() && buildDir.exists() ) { + if (controlFile != null) { + if (controlFile.exists() && buildDir.exists()) { controlFileTime = controlFile.lastModified(); - ds = getDirectoryScanner( buildDir ); + ds = getDirectoryScanner(buildDir); files = ds.getIncludedFiles(); - for( int i = 0; i < files.length; i++ ) { - File srcFile = new File( srcDir, files[i] ); - if( files[i].endsWith( ".class" ) ) { - if( controlFileTime > srcFile.lastModified() ) { - if( !dirty ) { - log( "Control file " + controlFile.getAbsolutePath() + " has been updated. Instrumenting all files..." ); + for (int i = 0; i < files.length; i++) { + File srcFile = new File(srcDir, files[i]); + + if (files[i].endsWith(".class")) { + if (controlFileTime > srcFile.lastModified()) { + if (!dirty) { + log("Control file " + controlFile.getAbsolutePath() + " has been updated. Instrumenting all files..."); } dirty = true; instrumentall = true; @@ -732,95 +769,128 @@ public class IContract extends MatchingTask { } } } - } catch( Throwable t ) { - throw new BuildException( "Got an interesting exception:" + t.getMessage() ); + } catch (Throwable t) { + throw new BuildException("Got an interesting exception:" + t.getMessage()); } } /** - * Creates the -m option based on the values of controlFile, pre, post and invariant. + * Creates the -m option based on the values of controlFile, pre, post and + * invariant. */ private final String directiveString() { StringBuffer sb = new StringBuffer(); boolean comma = false; boolean useControlFile = (controlFile != null) && controlFile.exists(); - if( useControlFile || pre || post || invariant ) { - sb.append( "-m" ); + + if (useControlFile || pre || post || invariant) { + sb.append("-m"); } - if( useControlFile ) { - sb.append( "@" ).append( controlFile ); + if (useControlFile) { + sb.append("@").append(controlFile); comma = true; } - if( pre ) { - if( comma ) { - sb.append( "," ); + if (pre) { + if (comma) { + sb.append(","); } - sb.append( "pre" ); + sb.append("pre"); comma = true; } - if( post ) { - if( comma ) { - sb.append( "," ); + if (post) { + if (comma) { + sb.append(","); } - sb.append( "post" ); + sb.append("post"); comma = true; } - if( invariant ) { - if( comma ) { - sb.append( "," ); + if (invariant) { + if (comma) { + sb.append(","); } - sb.append( "inv" ); + sb.append("inv"); } - sb.append( " " ); + sb.append(" "); return sb.toString(); } + /** - * BuildListener that sets the iContractMissing flag to true if a - * message about missing iContract is missing. Used to indicate - * a more verbose error to the user, with advice about how to solve - * the problem + * BuildListener that sets the iContractMissing flag to true if a message + * about missing iContract is missing. Used to indicate a more verbose + * error to the user, with advice about how to solve the problem + * + * @author Conor MacNeill */ private class IContractPresenceDetector implements BuildListener { - public void buildFinished(BuildEvent event) {} - public void buildStarted(BuildEvent event) {} + public void buildFinished(BuildEvent event) { + } + + + public void buildStarted(BuildEvent event) { + } + + public void messageLogged(BuildEvent event) { - if( "java.lang.NoClassDefFoundError: com/reliablesystems/iContract/Tool".equals( event.getMessage() ) ) { + if ("java.lang.NoClassDefFoundError: com/reliablesystems/iContract/Tool".equals(event.getMessage())) { iContractMissing = true; } } - public void targetFinished(BuildEvent event) {} - public void targetStarted(BuildEvent event) {} - public void taskFinished(BuildEvent event) {} - public void taskStarted(BuildEvent event) {} + + + public void targetFinished(BuildEvent event) { + } + + + public void targetStarted(BuildEvent event) { + } + + + public void taskFinished(BuildEvent event) { + } + + + public void taskStarted(BuildEvent event) { + } } + /** - * This class is a helper to set correct classpath for other compilers, like Jikes. - * It reuses the logic from DefaultCompilerAdapter, which is protected, so we have - * to subclass it. + * This class is a helper to set correct classpath for other compilers, + * like Jikes. It reuses the logic from DefaultCompilerAdapter, which is + * protected, so we have to subclass it. + * + * @author Conor MacNeill */ private class ClasspathHelper extends DefaultCompilerAdapter { private final String compiler; - public ClasspathHelper( String compiler ) { + + + public ClasspathHelper(String compiler) { super(); this.compiler = compiler; } // make it public - public void modify( Path path ) { + public void modify(Path path) { // depending on what compiler to use, set the includeJavaRuntime flag - if( "jikes".equals( compiler ) ) { + if ("jikes".equals(compiler)) { icCompiler = compiler; includeJavaRuntime = true; - path.append( getCompileClasspath() ); + path.append(getCompileClasspath()); } } // dummy implementation. Never called - public void setJavac( Javac javac ) {} - public boolean execute() { return true; } + public void setJavac(Javac javac) { + } + + + public boolean execute() { + return true; + } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java index 897c81d8b..b4cdb033c 100755 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java @@ -136,7 +136,7 @@ public class Javah extends Task { public void setName(String name) { this.name = name; - log("ClassArgument.name="+name); + log("ClassArgument.name=" + name); } public String getName() { @@ -318,7 +318,8 @@ public class Javah extends Task { // dynamically. However, javah has a different interface and this // makes it harder, so here's a simple alternative. //------------------------------------------------------------------ - com.sun.tools.javah.Main main = new com.sun.tools.javah.Main( cmd.getArguments() ); + com.sun.tools.javah.Main main + = new com.sun.tools.javah.Main(cmd.getArguments()); main.run(); } //catch (ClassNotFoundException ex) { @@ -411,7 +412,7 @@ public class Javah extends Task { Enumeration enum = classes.elements(); while (enum.hasMoreElements()) { - ClassArgument arg = (ClassArgument)enum.nextElement(); + ClassArgument arg = (ClassArgument) enum.nextElement(); String aClass = arg.getName(); cmd.createArgument().setValue(aClass); niceClassList.append(" " + aClass + lSep); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java index c07d7e6af..cb3d82b8e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java @@ -189,7 +189,7 @@ public class Native2Ascii extends MatchingTask { if (count == 0) { return; } - String message = "Converting "+ count + " file" + String message = "Converting " + count + " file" + (count != 1 ? "s" : "") + " from "; log(message + srcDir + " to " + destDir); for (int i = 0; i < files.length; i++){ @@ -237,7 +237,7 @@ public class Native2Ascii extends MatchingTask { if (parentName != null){ File parentFile = new File(parentName); - if ((! parentFile.exists()) && ( ! parentFile.mkdirs())){ + if ((!parentFile.exists()) && (!parentFile.mkdirs())){ throw new BuildException("cannot create parent directory " + parentName); } @@ -246,7 +246,7 @@ public class Native2Ascii extends MatchingTask { log("converting " + srcName, Project.MSG_VERBOSE); sun.tools.native2ascii.Main n2a = new sun.tools.native2ascii.Main(); - if(! n2a.convert(cmd.getArguments())){ + if (!n2a.convert(cmd.getArguments())){ throw new BuildException("conversion failed"); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java index 830830f84..e750e915f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java @@ -124,14 +124,13 @@ import org.apache.tools.ant.types.EnumeratedAttribute; * * @author dIon Gillard dion@multitask.com.au */ - public class NetRexxC extends MatchingTask { // variables to hold arguments private boolean binary; private String classpath; private boolean comments; - private boolean compact = true; // should be the default, as it integrates better in ant. + private boolean compact = true;// should be the default, as it integrates better in ant. private boolean compile = true; private boolean console; private boolean crossref; @@ -146,7 +145,7 @@ public class NetRexxC extends MatchingTask { private boolean replace; private boolean savelog; private File srcDir; - private boolean sourcedir = true; // ?? Should this be the default for ant? + private boolean sourcedir = true;// ?? Should this be the default for ant? private boolean strictargs; private boolean strictassign; private boolean strictcase; @@ -165,17 +164,18 @@ public class NetRexxC extends MatchingTask { private boolean suppressDeprecation = false; // constants for the messages to suppress by flags and their corresponding properties - static final String MSG_METHOD_ARGUMENT_NOT_USED = "Warning: Method argument is not used"; - static final String MSG_PRIVATE_PROPERTY_NOT_USED = "Warning: Private property is defined but not used"; - static final String MSG_VARIABLE_NOT_USED = "Warning: Variable is set but not used"; - static final String MSG_EXCEPTION_NOT_SIGNALLED = "is in SIGNALS list but is not signalled within the method"; - static final String MSG_DEPRECATION = "has been deprecated"; + final static String MSG_METHOD_ARGUMENT_NOT_USED = "Warning: Method argument is not used"; + final static String MSG_PRIVATE_PROPERTY_NOT_USED = "Warning: Private property is defined but not used"; + final static String MSG_VARIABLE_NOT_USED = "Warning: Variable is set but not used"; + final static String MSG_EXCEPTION_NOT_SIGNALLED = "is in SIGNALS list but is not signalled within the method"; + final static String MSG_DEPRECATION = "has been deprecated"; // other implementation variables private Vector compileList = new Vector(); private Hashtable filecopyList = new Hashtable(); private String oldClasspath = System.getProperty("java.class.path"); + /** * Set whether literals are treated as binary, rather than NetRexx types */ @@ -183,78 +183,83 @@ public class NetRexxC extends MatchingTask { this.binary = binary; } - /** - * Set the classpath used for NetRexx compilation - */ + + /** Set the classpath used for NetRexx compilation */ public void setClasspath(String classpath) { this.classpath = classpath; } + /** * Set whether comments are passed through to the generated java source. - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is false */ public void setComments(boolean comments) { this.comments = comments; } + /** - * Set whether error messages come out in compact or verbose format. - * Valid true values are "on" or "true". Anything else sets the flag to false. + * Set whether error messages come out in compact or verbose format. Valid + * true values are "on" or "true". Anything else sets the flag to false. * The default value is false */ public void setCompact(boolean compact) { this.compact = compact; } + /** * Set whether the NetRexx compiler should compile the generated java code - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is true. - * Setting this flag to false, will automatically set the keep flag to true. + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is true. Setting this flag to false, will + * automatically set the keep flag to true. */ public void setCompile(boolean compile) { this.compile = compile; if (!this.compile && !this.keep) { - this.keep = true; + this.keep = true; } } + /** - * Set whether or not messages should be displayed on the 'console' - * Valid true values are "on" or "true". Anything else sets the flag to false. + * Set whether or not messages should be displayed on the 'console' Valid + * true values are "on" or "true". Anything else sets the flag to false. * The default value is true. */ public void setConsole(boolean console) { this.console = console; } - /** - * Whether variable cross references are generated - */ + + /** Whether variable cross references are generated */ public void setCrossref(boolean crossref) { this.crossref = crossref; } + /** * Set whether decimal arithmetic should be used for the netrexx code. - * Binary arithmetic is used when this flag is turned off. - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is true. + * Binary arithmetic is used when this flag is turned off. Valid true + * values are "on" or "true". Anything else sets the flag to false. The + * default value is true. */ public void setDecimal(boolean decimal) { this.decimal = decimal; } + /** - * Set the destination directory into which the NetRexx source - * files should be copied and then compiled. + * Set the destination directory into which the NetRexx source files + * should be copied and then compiled. */ public void setDestDir(File destDirName) { destDir = destDirName; } + /** * Whether diagnostic information about the compile is generated */ @@ -262,27 +267,30 @@ public class NetRexxC extends MatchingTask { this.diag = diag; } + /** - * Sets whether variables must be declared explicitly before use. - * Valid true values are "on" or "true". Anything else sets the flag to false. + * Sets whether variables must be declared explicitly before use. Valid + * true values are "on" or "true". Anything else sets the flag to false. * The default value is false. */ public void setExplicit(boolean explicit) { this.explicit = explicit; } + /** - * Whether the generated java code is formatted nicely or left to match NetRexx - * line numbers for call stack debugging + * Whether the generated java code is formatted nicely or left to match + * NetRexx line numbers for call stack debugging */ public void setFormat(boolean format) { this.format = format; } + /** - * Whether the generated java code is produced - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Whether the generated java code is produced Valid true values are "on" + * or "true". Anything else sets the flag to false. The default value is + * false. */ public void setJava(boolean java) { this.java = java; @@ -290,69 +298,71 @@ public class NetRexxC extends MatchingTask { /** - * Sets whether the generated java source file should be kept after compilation. - * The generated files will have an extension of .java.keep, not .java - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Sets whether the generated java source file should be kept after + * compilation. The generated files will have an extension of .java.keep, + * not .java Valid true values are "on" or "true". Anything else + * sets the flag to false. The default value is false. */ public void setKeep(boolean keep) { this.keep = keep; } - /** - * Whether the compiler text logo is displayed when compiling - */ + + /** Whether the compiler text logo is displayed when compiling */ public void setLogo(boolean logo) { this.logo = logo; } + /** * Whether the generated .java file should be replaced when compiling - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is false. */ public void setReplace(boolean replace) { this.replace = replace; } + /** * Sets whether the compiler messages will be written to NetRexxC.log as - * well as to the console - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * well as to the console Valid true values are "on" or "true". Anything + * else sets the flag to false. The default value is false. */ public void setSavelog(boolean savelog) { this.savelog = savelog; } + /** - * Tells the NetRexx compiler to store the class files in the same directory - * as the source files. The alternative is the working directory - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is true. + * Tells the NetRexx compiler to store the class files in the same + * directory as the source files. The alternative is the working directory + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is true. */ public void setSourcedir(boolean sourcedir) { this.sourcedir = sourcedir; } - /** - * Set the source dir to find the source Java files. - */ + + /** Set the source dir to find the source Java files. */ public void setSrcDir(File srcDirName) { srcDir = srcDirName; } + /** * Tells the NetRexx compiler that method calls always need parentheses, * even if no arguments are needed, e.g. aStringVar.getBytes - * vs. aStringVar.getBytes() - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * vs. aStringVar.getBytes() Valid true values are "on" or + * "true". Anything else sets the flag to false. The default value is + * false. */ public void setStrictargs(boolean strictargs) { this.strictargs = strictargs; } + /** * Tells the NetRexx compile that assignments must match exactly on type */ @@ -360,6 +370,7 @@ public class NetRexxC extends MatchingTask { this.strictassign = strictassign; } + /** * Specifies whether the NetRexx compiler should be case sensitive or not */ @@ -367,21 +378,22 @@ public class NetRexxC extends MatchingTask { this.strictcase = strictcase; } + /** - * Sets whether classes need to be imported explicitly using an - * import statement. By default the NetRexx compiler will import - * certain packages automatically - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Sets whether classes need to be imported explicitly using an import + * statement. By default the NetRexx compiler will import certain packages + * automatically Valid true values are "on" or "true". Anything else sets + * the flag to false. The default value is false. */ public void setStrictimport(boolean strictimport) { this.strictimport = strictimport; } + /** - * Sets whether local properties need to be qualified explicitly using this - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Sets whether local properties need to be qualified explicitly using + * this Valid true values are "on" or "true". Anything else + * sets the flag to false. The default value is false. */ public void setStrictprops(boolean strictprops) { this.strictprops = strictprops; @@ -389,231 +401,247 @@ public class NetRexxC extends MatchingTask { /** - * Whether the compiler should force catching of exceptions by explicitly named types + * Whether the compiler should force catching of exceptions by explicitly + * named types */ public void setStrictsignal(boolean strictsignal) { this.strictsignal = strictsignal; } + /** * Sets whether debug symbols should be generated into the class file - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is false. */ public void setSymbols(boolean symbols) { this.symbols = symbols; } + /** * Asks the NetRexx compiler to print compilation times to the console - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Valid true values are "on" or "true". Anything else sets the flag to + * false. The default value is false. */ public void setTime(boolean time) { this.time = time; } + public void setTrace(TraceAttr trace) { this.trace = trace.getValue(); } + /** - * Turns on or off tracing and directs the resultant trace output - * Valid values are: "trace", "trace1", "trace2" and "notrace". - * "trace" and "trace2" + * Turns on or off tracing and directs the resultant trace output Valid + * values are: "trace", "trace1", "trace2" and "notrace". "trace" and + * "trace2" */ public void setTrace(String trace) { TraceAttr t = new TraceAttr(); + t.setValue(trace); setTrace(t); } + /** - * Tells the NetRexx compiler that the source is in UTF8 - * Valid true values are "on" or "true". Anything else sets the flag to false. - * The default value is false. + * Tells the NetRexx compiler that the source is in UTF8 Valid true values + * are "on" or "true". Anything else sets the flag to false. The default + * value is false. */ public void setUtf8(boolean utf8) { this.utf8 = utf8; } + /** * Whether lots of warnings and error messages should be generated */ public void setVerbose(VerboseAttr verbose) { this.verbose = verbose.getValue(); } - + /** * Whether lots of warnings and error messages should be generated */ public void setVerbose(String verbose) { VerboseAttr v = new VerboseAttr(); + v.setValue(verbose); setVerbose(v); } + /** - * Whether the task should suppress the "Method argument is not used" - * in strictargs-Mode, which can not be suppressed by the compiler itself. + * Whether the task should suppress the "Method argument is not used" in + * strictargs-Mode, which can not be suppressed by the compiler itself. * The warning is logged as verbose message, though. */ public void setSuppressMethodArgumentNotUsed(boolean suppressMethodArgumentNotUsed) { this.suppressMethodArgumentNotUsed = suppressMethodArgumentNotUsed; } + /** * Whether the task should suppress the "Private property is defined but - * not used" in strictargs-Mode, which can be quite annoying while developing. - * The warning is logged as verbose message, though. + * not used" in strictargs-Mode, which can be quite annoying while + * developing. The warning is logged as verbose message, though. */ public void setSuppressPrivatePropertyNotUsed(boolean suppressPrivatePropertyNotUsed) { this.suppressPrivatePropertyNotUsed = suppressPrivatePropertyNotUsed; } + /** - * Whether the task should suppress the "Variable is set but not used" - * in strictargs-Mode. Be careful with this one! - * The warning is logged as verbose message, though. + * Whether the task should suppress the "Variable is set but not used" in + * strictargs-Mode. Be careful with this one! The warning is logged as + * verbose message, though. */ public void setSuppressVariableNotUsed(boolean suppressVariableNotUsed) { this.suppressVariableNotUsed = suppressVariableNotUsed; } + /** - * Whether the task should suppress the "FooException is in SIGNALS list but - * is not signalled within the method", which is sometimes rather useless. - * The warning is logged as verbose message, though. + * Whether the task should suppress the "FooException is in SIGNALS list + * but is not signalled within the method", which is sometimes rather + * useless. The warning is logged as verbose message, though. */ public void setSuppressExceptionNotSignalled(boolean suppressExceptionNotSignalled) { this.suppressExceptionNotSignalled = suppressExceptionNotSignalled; } + /** - * Whether the task should suppress the "FooException is in SIGNALS list but - * is not signalled within the method", which is sometimes rather useless. - * The warning is logged as verbose message, though. + * Whether the task should suppress the "FooException is in SIGNALS list + * but is not signalled within the method", which is sometimes rather + * useless. The warning is logged as verbose message, though. */ public void setSuppressDeprecation(boolean suppressDeprecation) { this.suppressDeprecation = suppressDeprecation; } + /** - * init-Method sets defaults from Properties. That way, when ant is called with arguments - * like -Dant.netrexxc.verbose=verbose5 one can easily take control of all netrexxc-tasks. + * init-Method sets defaults from Properties. That way, when ant is called + * with arguments like -Dant.netrexxc.verbose=verbose5 one can easily take + * control of all netrexxc-tasks. */ // Sorry for the formatting, but that way it's easier to keep in sync with the private properties (line by line). public void init() { String p; - if ((p=project.getProperty("ant.netrexxc.binary"))!=null) { - this.binary=Project.toBoolean(p); + + if ((p = project.getProperty("ant.netrexxc.binary")) != null) { + this.binary = Project.toBoolean(p); } // classpath makes no sense - if ((p=project.getProperty("ant.netrexxc.comments"))!=null) { - this.comments=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.comments")) != null) { + this.comments = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.compact"))!=null) { - this.compact=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.compact")) != null) { + this.compact = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.compile"))!=null) { - this.compile=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.compile")) != null) { + this.compile = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.console"))!=null) { - this.console=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.console")) != null) { + this.console = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.crossref"))!=null) { - this.crossref=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.crossref")) != null) { + this.crossref = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.decimal"))!=null) { - this.decimal=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.decimal")) != null) { + this.decimal = Project.toBoolean(p); // destDir } - if ((p=project.getProperty("ant.netrexxc.diag"))!=null) { - this.diag=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.diag")) != null) { + this.diag = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.explicit"))!=null) { - this.explicit=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.explicit")) != null) { + this.explicit = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.format"))!=null) { - this.format=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.format")) != null) { + this.format = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.java"))!=null) { - this.java=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.java")) != null) { + this.java = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.keep"))!=null) { - this.keep=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.keep")) != null) { + this.keep = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.logo"))!=null) { - this.logo=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.logo")) != null) { + this.logo = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.replace"))!=null) { - this.replace=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.replace")) != null) { + this.replace = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.savelog"))!=null) { - this.savelog=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.savelog")) != null) { + this.savelog = Project.toBoolean(p); // srcDir } - if ((p=project.getProperty("ant.netrexxc.sourcedir"))!=null) { - this.sourcedir=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.sourcedir")) != null) { + this.sourcedir = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictargs"))!=null) { - this.strictargs=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictargs")) != null) { + this.strictargs = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictassign"))!=null) { - this.strictassign=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictassign")) != null) { + this.strictassign = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictcase"))!=null) { - this.strictcase=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictcase")) != null) { + this.strictcase = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictimport"))!=null) { - this.strictimport=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictimport")) != null) { + this.strictimport = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictprops"))!=null) { - this.strictprops=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictprops")) != null) { + this.strictprops = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.strictsignal"))!=null) { - this.strictsignal=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.strictsignal")) != null) { + this.strictsignal = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.symbols"))!=null) { - this.symbols=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.symbols")) != null) { + this.symbols = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.time"))!=null) { - this.time=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.time")) != null) { + this.time = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.trace"))!=null) { + if ((p = project.getProperty("ant.netrexxc.trace")) != null) { setTrace(p); } - if ((p=project.getProperty("ant.netrexxc.utf8"))!=null) { - this.utf8=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.utf8")) != null) { + this.utf8 = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.verbose"))!=null) { + if ((p = project.getProperty("ant.netrexxc.verbose")) != null) { setVerbose(p); } - if ((p=project.getProperty("ant.netrexxc.suppressMethodArgumentNotUsed"))!=null) { - this.suppressMethodArgumentNotUsed=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.suppressMethodArgumentNotUsed")) != null) { + this.suppressMethodArgumentNotUsed = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.suppressPrivatePropertyNotUsed"))!=null) { - this.suppressPrivatePropertyNotUsed=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.suppressPrivatePropertyNotUsed")) != null) { + this.suppressPrivatePropertyNotUsed = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.suppressVariableNotUsed"))!=null) { - this.suppressVariableNotUsed=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.suppressVariableNotUsed")) != null) { + this.suppressVariableNotUsed = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.suppressExceptionNotSignalled"))!=null) { - this.suppressExceptionNotSignalled=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.suppressExceptionNotSignalled")) != null) { + this.suppressExceptionNotSignalled = Project.toBoolean(p); } - if ((p=project.getProperty("ant.netrexxc.suppressDeprecation"))!=null) { - this.suppressDeprecation=Project.toBoolean(p); + if ((p = project.getProperty("ant.netrexxc.suppressDeprecation")) != null) { + this.suppressDeprecation = Project.toBoolean(p); } } - /** - * Executes the task - performs the actual compiler call. - */ + + /** Executes the task - performs the actual compiler call. */ public void execute() throws BuildException { // first off, make sure that we've got a srcdir and destdir - if (srcDir == null || destDir == null ) { + if (srcDir == null || destDir == null) { throw new BuildException("srcDir and destDir attributes must be set!"); } @@ -632,15 +660,16 @@ public class NetRexxC extends MatchingTask { // compile the source files if (compileList.size() > 0) { log("Compiling " + compileList.size() + " source file" - + (compileList.size() == 1 ? "" : "s") - + " to " + destDir); + + (compileList.size() == 1 ? "" : "s") + + " to " + destDir); doNetRexxCompile(); } } + /** - * Scans the directory looking for source files to be compiled and - * support files to be copied. + * Scans the directory looking for source files to be compiled and support + * files to be copied. */ private void scanDir(File srcDir, File destDir, String[] files) { for (int i = 0; i < files.length; i++) { @@ -654,7 +683,7 @@ public class NetRexxC extends MatchingTask { if (filename.toLowerCase().endsWith(".nrx")) { File classFile = new File(destDir, - filename.substring(0, filename.lastIndexOf('.')) + ".class"); + filename.substring(0, filename.lastIndexOf('.')) + ".class"); if (!compile || srcFile.lastModified() > classFile.lastModified()) { filecopyList.put(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); @@ -668,34 +697,37 @@ public class NetRexxC extends MatchingTask { } } - /** - * Copy eligible files from the srcDir to destDir - */ + + /** Copy eligible files from the srcDir to destDir */ private void copyFilesToDestination() { if (filecopyList.size() > 0) { log("Copying " + filecopyList.size() + " file" - + (filecopyList.size() == 1 ? "" : "s") - + " to " + destDir.getAbsolutePath()); + + (filecopyList.size() == 1 ? "" : "s") + + " to " + destDir.getAbsolutePath()); + Enumeration enum = filecopyList.keys(); + while (enum.hasMoreElements()) { - String fromFile = (String)enum.nextElement(); - String toFile = (String)filecopyList.get(fromFile); + String fromFile = (String) enum.nextElement(); + String toFile = (String) filecopyList.get(fromFile); + try { project.copyFile(fromFile, toFile); } catch (IOException ioe) { String msg = "Failed to copy " + fromFile + " to " + toFile - + " due to " + ioe.getMessage(); + + " due to " + ioe.getMessage(); + throw new BuildException(msg, ioe); } } } } - /** - * Peforms a copmile using the NetRexx 1.1.x compiler - */ + + /** Peforms a copmile using the NetRexx 1.1.x compiler */ private void doNetRexxCompile() throws BuildException { log("Using NetRexx compiler", Project.MSG_VERBOSE); + String classpath = getCompileClasspath(); StringBuffer compileOptions = new StringBuffer(); StringBuffer fileList = new StringBuffer(); @@ -706,17 +738,19 @@ public class NetRexxC extends MatchingTask { String[] fileListArray = new String[compileList.size()]; Enumeration e = compileList.elements(); int j = 0; + while (e.hasMoreElements()) { - fileListArray[j] = (String)e.nextElement(); + fileListArray[j] = (String) e.nextElement(); j++; } // create a single array of arguments for the compiler String compileArgs[] = new String[compileOptionsArray.length + fileListArray.length]; + for (int i = 0; i < compileOptionsArray.length; i++) { compileArgs[i] = compileOptionsArray[i]; } for (int i = 0; i < fileListArray.length; i++) { - compileArgs[i+compileOptionsArray.length] = fileListArray[i]; + compileArgs[i + compileOptionsArray.length] = fileListArray[i]; } // print nice output about what we are doing for the log @@ -742,49 +776,52 @@ public class NetRexxC extends MatchingTask { // since the NetRexx compiler has no option for the classpath String currentClassPath = System.getProperty("java.class.path"); Properties currentProperties = System.getProperties(); + currentProperties.put("java.class.path", classpath); try { StringWriter out = new StringWriter(); - int rc = COM.ibm.netrexx.process.NetRexxC. - main(new Rexx(compileArgs), new PrintWriter(out)); - String sdir=srcDir.getAbsolutePath(); - String ddir=destDir.getAbsolutePath(); - boolean doReplace=!(sdir.equals(ddir)); - int dlen=ddir.length(); + int rc = + COM.ibm.netrexx.process.NetRexxC.main(new Rexx(compileArgs), new PrintWriter(out)); + String sdir = srcDir.getAbsolutePath(); + String ddir = destDir.getAbsolutePath(); + boolean doReplace = !(sdir.equals(ddir)); + int dlen = ddir.length(); String l; - BufferedReader in=new BufferedReader(new StringReader(out.toString())); - log("replacing destdir '"+ddir+"' through sourcedir '"+sdir+"'", Project.MSG_VERBOSE); - while ((l=in.readLine())!=null) { + BufferedReader in = new BufferedReader(new StringReader(out.toString())); + + log("replacing destdir '" + ddir + "' through sourcedir '" + sdir + "'", Project.MSG_VERBOSE); + while ((l = in.readLine()) != null) { int idx; - while (doReplace && ((idx=l.indexOf(ddir))!=-1)) { // path is mentioned in the message - l=(new StringBuffer(l)).replace(idx,idx+dlen,sdir).toString(); + + while (doReplace && ((idx = l.indexOf(ddir)) != -1)) {// path is mentioned in the message + l = (new StringBuffer(l)).replace(idx, idx + dlen, sdir).toString(); } // verbose level logging for suppressed messages - if (suppressMethodArgumentNotUsed && l.indexOf(MSG_METHOD_ARGUMENT_NOT_USED)!=-1) { + if (suppressMethodArgumentNotUsed && l.indexOf(MSG_METHOD_ARGUMENT_NOT_USED) != -1) { log(l, Project.MSG_VERBOSE); - } else if (suppressPrivatePropertyNotUsed && l.indexOf(MSG_PRIVATE_PROPERTY_NOT_USED)!=-1) { + } else if (suppressPrivatePropertyNotUsed && l.indexOf(MSG_PRIVATE_PROPERTY_NOT_USED) != -1) { log(l, Project.MSG_VERBOSE); - } else if (suppressVariableNotUsed && l.indexOf(MSG_VARIABLE_NOT_USED)!=-1) { + } else if (suppressVariableNotUsed && l.indexOf(MSG_VARIABLE_NOT_USED) != -1) { log(l, Project.MSG_VERBOSE); - } else if (suppressExceptionNotSignalled && l.indexOf(MSG_EXCEPTION_NOT_SIGNALLED)!=-1) { + } else if (suppressExceptionNotSignalled && l.indexOf(MSG_EXCEPTION_NOT_SIGNALLED) != -1) { log(l, Project.MSG_VERBOSE); - } else if (suppressDeprecation && l.indexOf(MSG_DEPRECATION)!=-1) { + } else if (suppressDeprecation && l.indexOf(MSG_DEPRECATION) != -1) { log(l, Project.MSG_VERBOSE); - } else if (l.indexOf("Error:")!=-1) { // error level logging for compiler errors + } else if (l.indexOf("Error:") != -1) {// error level logging for compiler errors log(l, Project.MSG_ERR); - } else if (l.indexOf("Warning:")!=-1) { // warning for all warning messages + } else if (l.indexOf("Warning:") != -1) {// warning for all warning messages log(l, Project.MSG_WARN); } else { - log(l, Project.MSG_INFO); // info level for the rest. + log(l, Project.MSG_INFO);// info level for the rest. } } - if (rc>1) { + if (rc > 1) { throw new BuildException("Compile failed, messages should have been provided."); } } catch (IOException ioe) { throw new BuildException("Unexpected IOException while playing with Strings", - ioe); + ioe); } finally { // need to reset java.class.path property // since the NetRexx compiler has no option for the classpath @@ -794,9 +831,8 @@ public class NetRexxC extends MatchingTask { } - /** - * Builds the compilation classpath. - */ + + /** Builds the compilation classpath. */ private String getCompileClasspath() { StringBuffer classpath = new StringBuffer(); @@ -814,11 +850,11 @@ public class NetRexxC extends MatchingTask { return classpath.toString(); } - /** - * This - */ + + /** This */ private String[] getCompileOptionsAsArray() { Vector options = new Vector(); + options.addElement(binary ? "-binary" : "-nobinary"); options.addElement(comments ? "-comments" : "-nocomments"); options.addElement(compile ? "-compile" : "-nocompile"); @@ -827,7 +863,7 @@ public class NetRexxC extends MatchingTask { options.addElement(crossref ? "-crossref" : "-nocrossref"); options.addElement(decimal ? "-decimal" : "-nodecimal"); options.addElement(diag ? "-diag" : "-nodiag"); - options.addElement(explicit ? "-explicit": "-noexplicit"); + options.addElement(explicit ? "-explicit" : "-noexplicit"); options.addElement(format ? "-format" : "-noformat"); options.addElement(keep ? "-keep" : "-nokeep"); options.addElement(logo ? "-logo" : "-nologo"); @@ -836,7 +872,7 @@ public class NetRexxC extends MatchingTask { options.addElement(sourcedir ? "-sourcedir" : "-nosourcedir"); options.addElement(strictargs ? "-strictargs" : "-nostrictargs"); options.addElement(strictassign ? "-strictassign" : "-nostrictassign"); - options.addElement(strictcase ? "-strictcase": "-nostrictcase"); + options.addElement(strictcase ? "-strictcase" : "-nostrictcase"); options.addElement(strictimport ? "-strictimport" : "-nostrictimport"); options.addElement(strictprops ? "-strictprops" : "-nostrictprops"); options.addElement(strictsignal ? "-strictsignal" : "-nostrictsignal"); @@ -845,24 +881,28 @@ public class NetRexxC extends MatchingTask { options.addElement("-" + trace); options.addElement(utf8 ? "-utf8" : "-noutf8"); options.addElement("-" + verbose); + String[] results = new String[options.size()]; + options.copyInto(results); return results; } + + /** - * Takes a classpath-like string, and adds each element of - * this string to a new classpath, if the components exist. - * Components that don't exist, aren't added. - * We do this, because jikes issues warnings for non-existant - * files/dirs in his classpath, and these warnings are pretty + * Takes a classpath-like string, and adds each element of this string to + * a new classpath, if the components exist. Components that don't exist, + * aren't added. We do this, because jikes issues warnings for + * non-existant files/dirs in his classpath, and these warnings are pretty * annoying. + * * @param target - target classpath - * @param source - source classpath - * to get file objects. + * @param source - source classpath to get file objects. */ - private void addExistingToClasspath(StringBuffer target,String source) { + private void addExistingToClasspath(StringBuffer target, String source) { StringTokenizer tok = new StringTokenizer(source, - System.getProperty("path.separator"), false); + System.getProperty("path.separator"), false); + while (tok.hasMoreTokens()) { File f = project.resolveFile(tok.nextToken()); @@ -870,24 +910,27 @@ public class NetRexxC extends MatchingTask { target.append(File.pathSeparator); target.append(f.getAbsolutePath()); } else { - log("Dropping from classpath: "+ + log("Dropping from classpath: " + f.getAbsolutePath(), Project.MSG_VERBOSE); } } } + public static class TraceAttr extends EnumeratedAttribute { public String[] getValues() { - return new String[] {"trace", "trace1", "trace2", "notrace"}; + return new String[]{"trace", "trace1", "trace2", "notrace"}; } } + public static class VerboseAttr extends EnumeratedAttribute { public String[] getValues() { - return new String[] {"verbose", "verbose0", "verbose1", - "verbose2", "verbose3", "verbose4", - "verbose5", "noverbose"}; + return new String[]{"verbose", "verbose0", "verbose1", + "verbose2", "verbose3", "verbose4", + "verbose5", "noverbose"}; } } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java index 71fb1270b..6abe159be 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java @@ -197,9 +197,9 @@ public class PropertyFile extends Task private void executeOperation() throws BuildException { - for (Enumeration e = entries.elements(); e.hasMoreElements(); ) + for (Enumeration e = entries.elements(); e.hasMoreElements();) { - Entry entry = (Entry)e.nextElement(); + Entry entry = (Entry) e.nextElement(); entry.executeOn(properties); } } @@ -212,7 +212,8 @@ public class PropertyFile extends Task { if (propertyfile.exists()) { - log("Updating property file: "+propertyfile.getAbsolutePath()); + log("Updating property file: " + + propertyfile.getAbsolutePath()); FileInputStream fis = null; try { fis = new FileInputStream(propertyfile); @@ -226,8 +227,8 @@ public class PropertyFile extends Task } else { - log("Creating new property file: "+ - propertyfile.getAbsolutePath()); + log("Creating new property file: " + + propertyfile.getAbsolutePath()); FileOutputStream out = null; try { out = new FileOutputStream(propertyfile.getAbsolutePath()); @@ -238,9 +239,7 @@ public class PropertyFile extends Task } } } - } - catch(IOException ioe) - { + } catch (IOException ioe) { throw new BuildException(ioe.toString()); } } @@ -275,8 +274,7 @@ public class PropertyFile extends Task Properties.class.getMethod("store", new Class[] { OutputStream.class, - String.class} - ); + String.class}); m.invoke(properties, new Object[] {bos, comment}); } catch (NoSuchMethodException nsme) { @@ -287,9 +285,7 @@ public class PropertyFile extends Task } catch (IllegalAccessException iae) { // impossible throw new BuildException(iae, location); - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new BuildException(ioe, location); } finally { @@ -369,7 +365,7 @@ public class PropertyFile extends Task checkParameters(); // type may be null because it wasn't set - String oldValue = (String)props.get(key); + String oldValue = (String) props.get(key); try { if (type == Type.INTEGER_TYPE) { @@ -385,7 +381,8 @@ public class PropertyFile extends Task } else { - throw new BuildException("Unknown operation type: "+type+""); + throw new BuildException("Unknown operation type: " + + type); } } catch (NullPointerException npe) { // Default to string type diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java b/src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java index a84bbb2a5..86855404a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java @@ -129,24 +129,24 @@ public class RenameExtensions extends MatchingTask { // first off, make sure that we've got a from and to extension if (fromExtension == null || toExtension == null || srcDir == null) { - throw new BuildException( "srcDir, fromExtension and toExtension " + - "attributes must be set!" ); + throw new BuildException("srcDir, fromExtension and toExtension " + + "attributes must be set!"); } log("DEPRECATED - The renameext task is deprecated. Use move instead.", Project.MSG_WARN); log("Replace this with:", Project.MSG_INFO); - log("", + log("", Project.MSG_INFO); - log(" ", Project.MSG_INFO); + log(" ", Project.MSG_INFO); log(" ", Project.MSG_INFO); + log(" from=\"*" + fromExtension + "\"", Project.MSG_INFO); + log(" to=\"*" + toExtension + "\" />", Project.MSG_INFO); log("", Project.MSG_INFO); log("using the same patterns on as you\'ve used here", Project.MSG_INFO); - Move move = (Move)project.createTask("move"); + Move move = (Move) project.createTask("move"); move.setOwningTarget(target); move.setTaskName(getTaskName()); move.setLocation(getLocation()); @@ -158,8 +158,8 @@ public class RenameExtensions extends MatchingTask { Mapper me = move.createMapper(); me.setType(globType); - me.setFrom("*"+fromExtension); - me.setTo("*"+toExtension); + me.setFrom("*" + fromExtension); + me.setTo("*" + toExtension); move.execute(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java index 42853331b..d8103a9ab 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java @@ -1,7 +1,7 @@ /* * The Apache Software License, Version 1.1 * - * Copyright (c) 2001-2002 The Apache Software Foundation. All rights + * Copyright (c) 2001-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without @@ -73,7 +73,7 @@ import java.io.PrintWriter; import java.util.Vector; -/*** +/** *
  * Task to do regular expression string replacements in a text
  * file.  The input file(s) must be able to be properly processed by
@@ -85,7 +85,6 @@ import java.util.Vector;
  * is org.apache.tools.ant.util.regexp.JakartaOroRegexp and
  * requires the Jakarta Oro Package).
  *
- * 
  * For jdk  <= 1.3, there are two available implementations:
  *   org.apache.tools.ant.util.regexp.JakartaOroRegexp (the default)
  *        Requires  the jakarta-oro package
@@ -96,7 +95,6 @@ import java.util.Vector;
  * For jdk >= 1.4 an additional implementation is available:
  *   org.apache.tools.ant.util.regexp.Jdk14RegexpRegexp
  *        Requires the jdk 1.4 built in regular expression package.
- * 
* * Usage: * @@ -146,23 +144,20 @@ import java.util.Vector; * * @author Matthew Inger */ -public class ReplaceRegExp extends Task -{ +public class ReplaceRegExp extends Task { private File file; private String flags; private boolean byline; - private Vector filesets; // Keep jdk 1.1 compliant so others can use this + private Vector filesets;// Keep jdk 1.1 compliant so others can use this private RegularExpression regex; private Substitution subs; private FileUtils fileUtils = FileUtils.newFileUtils(); - /*** - * Default Constructor - */ - public ReplaceRegExp() - { + + /** Default Constructor */ + public ReplaceRegExp() { super(); this.file = null; this.filesets = new Vector(); @@ -173,13 +168,13 @@ public class ReplaceRegExp extends Task this.subs = null; } - public void setFile(File file) - { + + public void setFile(File file) { this.file = file; } - public void setMatch(String match) - { + + public void setMatch(String match) { if (regex != null) { throw new BuildException("Only one regular expression is allowed"); } @@ -188,8 +183,8 @@ public class ReplaceRegExp extends Task regex.setPattern(match); } - public void setReplace(String replace) - { + + public void setReplace(String replace) { if (subs != null) { throw new BuildException("Only one substitution expression is allowed"); } @@ -198,27 +193,28 @@ public class ReplaceRegExp extends Task subs.setExpression(replace); } - public void setFlags(String flags) - { + + public void setFlags(String flags) { this.flags = flags; } - public void setByLine(String byline) - { + + public void setByLine(String byline) { Boolean res = Boolean.valueOf(byline); + if (res == null) { res = Boolean.FALSE; } this.byline = res.booleanValue(); } - public void addFileset(FileSet set) - { + + public void addFileset(FileSet set) { filesets.addElement(set); } - public RegularExpression createRegexp() - { + + public RegularExpression createRegexp() { if (regex != null) { throw new BuildException("Only one regular expression is allowed."); } @@ -227,8 +223,8 @@ public class ReplaceRegExp extends Task return regex; } - public Substitution createSubstitution() - { + + public Substitution createSubstitution() { if (subs != null) { throw new BuildException("Only one substitution expression is allowed"); } @@ -236,38 +232,33 @@ public class ReplaceRegExp extends Task subs = new Substitution(); return subs; } - + protected String doReplace(RegularExpression r, Substitution s, String input, - int options) - { + int options) { String res = input; Regexp regexp = r.getRegexp(project); - if (regexp.matches(input, options)) - { + if (regexp.matches(input, options)) { res = regexp.substitute(input, s.getExpression(project), options); } return res; } - /*** - * Perform the replace on the entire file - */ + + /** Perform the replace on the entire file */ protected void doReplace(File f, int options) - throws IOException - { + throws IOException { File parentDir = new File(new File(f.getAbsolutePath()).getParent()); File temp = fileUtils.createTempFile("replace", ".txt", parentDir); FileReader r = null; FileWriter w = null; - try - { + try { r = new FileReader(f); w = new FileWriter(temp); @@ -277,45 +268,43 @@ public class ReplaceRegExp extends Task boolean changes = false; - log("Replacing pattern '" + regex.getPattern(project) + "' with '" + subs.getExpression(project) + - "' in '" + f.getPath() + "'" + + log("Replacing pattern '" + regex.getPattern(project) + "' with '" + subs.getExpression(project) + + "' in '" + f.getPath() + "'" + (byline ? " by line" : "") + (flags.length() > 0 ? " with flags: '" + flags + "'" : "") + ".", Project.MSG_WARN); - if (byline) - { + if (byline) { LineNumberReader lnr = new LineNumberReader(br); String line = null; - - while ((line = lnr.readLine()) != null) - { + + while ((line = lnr.readLine()) != null) { String res = doReplace(regex, subs, line, options); - if (! res.equals(line)) { + + if (!res.equals(line)) { changes = true; } pw.println(res); } pw.flush(); - } - else - { - int flen = (int)(f.length()); + } else { + int flen = (int) f.length(); char tmpBuf[] = new char[flen]; int numread = 0; int totread = 0; - while (numread != -1 && totread < flen) - { + + while (numread != -1 && totread < flen) { numread = br.read(tmpBuf, totread, flen); totread += numread; } String buf = new String(tmpBuf); - + String res = doReplace(regex, subs, buf, options); - if (! res.equals(buf)) { + + if (!res.equals(buf)) { changes = true; } @@ -328,33 +317,34 @@ public class ReplaceRegExp extends Task w.close(); w = null; - if (changes) - { + if (changes) { f.delete(); temp.renameTo(f); - } - else - { + } else { temp.delete(); } - } - finally - { - try { if (r != null) { + } finally { + try { + if (r != null) { r.close(); - } } - catch (Exception e) { }; + } + } catch (Exception e) { + } + ; - try { if (w != null) { + try { + if (w != null) { r.close(); - } } - catch (Exception e) { }; + } + } catch (Exception e) { + } + ; } } + public void execute() - throws BuildException - { + throws BuildException { if (regex == null) { throw new BuildException("No expression to match."); } @@ -366,9 +356,8 @@ public class ReplaceRegExp extends Task throw new BuildException("You cannot supply the 'file' attribute and filesets at the same time."); } - int options = 0; - + if (flags.indexOf('g') != -1) { options |= Regexp.REPLACE_ALL; } @@ -385,48 +374,37 @@ public class ReplaceRegExp extends Task options |= Regexp.MATCH_SINGLELINE; } - if (file != null && file.exists()) - { - try - { + if (file != null && file.exists()) { + try { doReplace(file, options); - } - catch (IOException e) - { + } catch (IOException e) { log("An error occurred processing file: '" + file.getAbsolutePath() + "': " + e.toString(), Project.MSG_ERR); } - } - else if (file != null) - { + } else if (file != null) { log("The following file is missing: '" + file.getAbsolutePath() + "'", Project.MSG_ERR); } int sz = filesets.size(); - for (int i=0;i0 && + boolean isValid = key.length() > 0 && Character.isJavaIdentifierStart(key.charAt(0)); - for (int i=1; isValid && iPeter Donald - * @author Marcus Börger + * @author Marcus + * Börger */ public class StyleBook - extends Java -{ - protected File m_targetDirectory; - protected File m_skinDirectory; - protected String m_loaderConfig; - protected File m_book; + extends Java { + protected File m_targetDirectory; + protected File m_skinDirectory; + protected String m_loaderConfig; + protected File m_book; + public StyleBook() { - setClassname( "org.apache.stylebook.StyleBook" ); - setFork( true ); - setFailonerror( true ); + setClassname("org.apache.stylebook.StyleBook"); + setFork(true); + setFailonerror(true); } - public void setBook( final File book ) { + + public void setBook(final File book) { m_book = book; } - public void setSkinDirectory( final File skinDirectory ) { + + public void setSkinDirectory(final File skinDirectory) { m_skinDirectory = skinDirectory; } - public void setTargetDirectory( final File targetDirectory ) { + + public void setTargetDirectory(final File targetDirectory) { m_targetDirectory = targetDirectory; } - public void setLoaderConfig( final String loaderConfig ) { + + public void setLoaderConfig(final String loaderConfig) { m_loaderConfig = loaderConfig; } + public void execute() - throws BuildException { + throws BuildException { - if( null == m_targetDirectory ) { - throw new BuildException( "TargetDirectory attribute not set." ); + if (null == m_targetDirectory) { + throw new BuildException("TargetDirectory attribute not set."); } - if( null == m_skinDirectory ) { - throw new BuildException( "SkinDirectory attribute not set." ); + if (null == m_skinDirectory) { + throw new BuildException("SkinDirectory attribute not set."); } - if( null == m_book ) { - throw new BuildException( "book attribute not set." ); + if (null == m_book) { + throw new BuildException("book attribute not set."); } - createArg().setValue( "targetDirectory=" + m_targetDirectory ); - createArg().setValue( m_book.toString() ); - createArg().setValue( m_skinDirectory.toString() ); - if( null != m_loaderConfig ) { - createArg().setValue( "loaderConfig=" + m_loaderConfig ); + createArg().setValue("targetDirectory=" + m_targetDirectory); + createArg().setValue(m_book.toString()); + createArg().setValue(m_skinDirectory.toString()); + if (null != m_loaderConfig) { + createArg().setValue("loaderConfig=" + m_loaderConfig); } super.execute(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Test.java b/src/main/org/apache/tools/ant/taskdefs/optional/Test.java index ed6e55908..5ce125114 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Test.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Test.java @@ -52,70 +52,79 @@ * . */ package org.apache.tools.ant.taskdefs.optional; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.Java; -import java.util.Vector; - -/** - * - * @author Peter Donald - */ -public class Test - extends Java { - - protected Vector m_tests = new Vector(); + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Java; +import java.util.Vector; + +/** + * @author Peter Donald + */ +public class Test extends Java { + + protected Vector m_tests = new Vector(); + protected final static class TestletEntry { protected String m_testname = ""; - public void addText( final String testname ) { + + public void addText(final String testname) { m_testname += testname; } + public String toString() { return m_testname; } } + public Test() { - setClassname( "org.apache.testlet.engine.TextTestEngine" ); + setClassname("org.apache.testlet.engine.TextTestEngine"); } + public TestletEntry createTestlet() { final TestletEntry entry = new TestletEntry(); - m_tests.addElement( entry ); + + m_tests.addElement(entry); return entry; } - - public void setShowSuccess( final boolean showSuccess ) { - createArg().setValue( "-s=" + showSuccess ); - } - - public void setShowBanner( final String showBanner ) { - createArg().setValue( "-b=" + showBanner ); - } - - public void setShowTrace( final boolean showTrace ) { - createArg().setValue( "-t=" + showTrace ); - } - - public void setForceShowTrace( final boolean forceShowTrace ) { - createArg().setValue( "-f=" + forceShowTrace ); - } - - public void execute() - throws BuildException { + + + public void setShowSuccess(final boolean showSuccess) { + createArg().setValue("-s=" + showSuccess); + } + + + public void setShowBanner(final String showBanner) { + createArg().setValue("-b=" + showBanner); + } + + + public void setShowTrace(final boolean showTrace) { + createArg().setValue("-t=" + showTrace); + } + + + public void setForceShowTrace(final boolean forceShowTrace) { + createArg().setValue("-f=" + forceShowTrace); + } + + + public void execute() + throws BuildException { final int size = m_tests.size(); - for( int i = 0; i < size; i ++ ) { - createArg().setValue( m_tests.elementAt( i ).toString() ); + for (int i = 0; i < size; i++) { + createArg().setValue(m_tests.elementAt(i).toString()); } super.execute(); - } -} - - + } +} + + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java b/src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java index 9b2f698b6..f9806049a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java @@ -89,13 +89,13 @@ public class XslpLiaison implements XSLTLiaison { XSLReader xslReader = new XSLReader(); // a file:/// + getAbsolutePath() does not work here // it is really the pathname - xslSheet = xslReader.read( fileName.getAbsolutePath() ); + xslSheet = xslReader.read(fileName.getAbsolutePath()); } public void transform(File infile, File outfile) throws Exception { FileOutputStream fos = new FileOutputStream(outfile); // XSLP does not support encoding...we're in hot water. - OutputStreamWriter out = new OutputStreamWriter(fos,"UTF8"); + OutputStreamWriter out = new OutputStreamWriter(fos, "UTF8"); processor.process(infile.getAbsolutePath(), xslSheet, out); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java index 788295cea..e077701a0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java @@ -143,7 +143,7 @@ public class CCCheckin extends ClearCase { checkOptions(commandLine); result = run(commandLine); - if ( result != 0 ) { + if (result != 0) { String msg = "Failed executing: " + commandLine.toString(); throw new BuildException(msg, location); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java index b427c8f3d..f34e8e670 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java @@ -155,7 +155,7 @@ public class CCCheckout extends ClearCase { checkOptions(commandLine); result = run(commandLine); - if ( result != 0 ) { + if (result != 0) { String msg = "Failed executing: " + commandLine.toString(); throw new BuildException(msg, location); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java index a1c2d46cf..a3b726119 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java @@ -113,7 +113,7 @@ public class CCUnCheckout extends ClearCase { checkOptions(commandLine); result = run(commandLine); - if ( result != 0 ) { + if (result != 0) { String msg = "Failed executing: " + commandLine.toString(); throw new BuildException(msg, location); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java index 5508b6422..5b4e394bc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java @@ -148,7 +148,7 @@ public class CCUpdate extends ClearCase { System.out.println(commandLine.toString()); result = run(commandLine); - if ( result != 0 ) { + if (result != 0) { String msg = "Failed executing: " + commandLine.toString(); throw new BuildException(msg, location); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java index a9ee6307c..f06cccf59 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java @@ -97,7 +97,7 @@ public abstract class ClearCase extends Task { */ protected final String getClearToolCommand() { String toReturn = m_ClearToolDir; - if ( !toReturn.equals("") && !toReturn.endsWith("/") ) { + if (!toReturn.equals("") && !toReturn.endsWith("/")) { toReturn += "/"; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java index 955ed7eb6..04d07459f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java @@ -88,8 +88,8 @@ public class AntAnalyzer extends AbstractAnalyzer { Hashtable dependencies = new Hashtable(); Hashtable containers = new Hashtable(); Hashtable toAnalyze = new Hashtable(); - for (Enumeration e = getRootClasses(); e.hasMoreElements(); ) { - String classname = (String)e.nextElement(); + for (Enumeration e = getRootClasses(); e.hasMoreElements();) { + String classname = (String) e.nextElement(); toAnalyze.put(classname, classname); } @@ -97,8 +97,8 @@ public class AntAnalyzer extends AbstractAnalyzer { int maxCount = isClosureRequired() ? MAX_LOOPS : 2; while (toAnalyze.size() != 0 && count++ < maxCount) { Hashtable analyzedDeps = new Hashtable(); - for (Enumeration e = toAnalyze.keys(); e.hasMoreElements(); ) { - String classname = (String)e.nextElement(); + for (Enumeration e = toAnalyze.keys(); e.hasMoreElements();) { + String classname = (String) e.nextElement(); dependencies.put(classname, classname); try { File container = getClassContainer(classname); @@ -125,7 +125,7 @@ public class AntAnalyzer extends AbstractAnalyzer { Vector dependencyList = classFile.getClassRefs(); Enumeration depEnum = dependencyList.elements(); while (depEnum.hasMoreElements()) { - String dependency = (String)depEnum.nextElement(); + String dependency = (String) depEnum.nextElement(); analyzedDeps.put(dependency, dependency); } } finally { @@ -146,7 +146,7 @@ public class AntAnalyzer extends AbstractAnalyzer { // now recover all the dependencies collected and add to the list. Enumeration depsEnum = analyzedDeps.elements(); while (depsEnum.hasMoreElements()) { - String className = (String)depsEnum.nextElement(); + String className = (String) depsEnum.nextElement(); if (!dependencies.containsKey(className)) { toAnalyze.put(className, className); } @@ -154,13 +154,13 @@ public class AntAnalyzer extends AbstractAnalyzer { } files.removeAllElements(); - for (Enumeration e = containers.keys(); e.hasMoreElements(); ) { - files.addElement((File)e.nextElement()); + for (Enumeration e = containers.keys(); e.hasMoreElements();) { + files.addElement((File) e.nextElement()); } classes.removeAllElements(); - for (Enumeration e = dependencies.keys(); e.hasMoreElements(); ) { - classes.addElement((String)e.nextElement()); + for (Enumeration e = dependencies.keys(); e.hasMoreElements();) { + classes.addElement((String) e.nextElement()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java index 81d110241..1a19db525 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java @@ -114,7 +114,7 @@ public class ClassFile { int thisClassIndex = classStream.readUnsignedShort(); int superClassIndex = classStream.readUnsignedShort(); ClassCPInfo classInfo - = (ClassCPInfo)constantPool.getEntry(thisClassIndex); + = (ClassCPInfo) constantPool.getEntry(thisClassIndex); className = classInfo.getClassName(); } @@ -133,7 +133,7 @@ public class ClassFile { if (entry != null && entry.getTag() == ConstantPoolEntry.CONSTANT_CLASS) { - ClassCPInfo classEntry = (ClassCPInfo)entry; + ClassCPInfo classEntry = (ClassCPInfo) entry; if (!classEntry.getClassName().equals(className)) { classRefs.addElement(ClassFileUtils.convertSlashName(classEntry.getClassName())); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java index 2609071fb..460185a15 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java @@ -246,12 +246,12 @@ public class Depend extends MatchingTask { pw = new PrintWriter(new FileWriter(depFile)); Enumeration e = dependencyMap.keys(); while (e.hasMoreElements()) { - String className = (String)e.nextElement(); + String className = (String) e.nextElement(); pw.println(CLASSNAME_PREPEND + className); Vector dependencyList - = (Vector)dependencyMap.get(className); + = (Vector) dependencyMap.get(className); int size = dependencyList.size(); for (int x = 0; x < size; x++) { pw.println(dependencyList.elementAt(x)); @@ -339,7 +339,7 @@ public class Depend extends MatchingTask { } Enumeration classfileEnum = getClassFiles(destPath).elements(); while (classfileEnum.hasMoreElements()) { - ClassFileInfo info = (ClassFileInfo)classfileEnum.nextElement(); + ClassFileInfo info = (ClassFileInfo) classfileEnum.nextElement(); log("Adding class info for " + info.className, Project.MSG_DEBUG); classFileInfoMap.put(info.className, info); @@ -352,7 +352,7 @@ public class Depend extends MatchingTask { && cacheLastModified > info.absoluteFile.lastModified()) { // depFile exists and is newer than the class file // need to get dependency list from the map. - dependencyList = (Vector)dependencyMap.get(info.className); + dependencyList = (Vector) dependencyMap.get(info.className); } } @@ -377,10 +377,10 @@ public class Depend extends MatchingTask { // one of those, add this class into their affected classes list Enumeration depEnum = dependencyList.elements(); while (depEnum.hasMoreElements()) { - String dependentClass = (String)depEnum.nextElement(); + String dependentClass = (String) depEnum.nextElement(); Hashtable affectedClasses - = (Hashtable)affectedClassMap.get(dependentClass); + = (Hashtable) affectedClassMap.get(dependentClass); if (affectedClasses == null) { affectedClasses = new Hashtable(); affectedClassMap.put(dependentClass, affectedClasses); @@ -401,13 +401,13 @@ public class Depend extends MatchingTask { Hashtable classpathFileCache = new Hashtable(); Object nullFileMarker = new Object(); for (Enumeration e = dependencyMap.keys(); e.hasMoreElements();) { - String className = (String)e.nextElement(); - Vector dependencyList = (Vector)dependencyMap.get(className); + String className = (String) e.nextElement(); + Vector dependencyList = (Vector) dependencyMap.get(className); Hashtable dependencies = new Hashtable(); classpathDependencies.put(className, dependencies); Enumeration e2 = dependencyList.elements(); while (e2.hasMoreElements()) { - String dependency = (String)e2.nextElement(); + String dependency = (String) e2.nextElement(); Object classpathFileObject = classpathFileCache.get(dependency); if (classpathFileObject == null) { @@ -437,7 +437,7 @@ public class Depend extends MatchingTask { } if (classpathFileObject != null && classpathFileObject != nullFileMarker) { // we need to add this jar to the list for this class. - File jarFile = (File)classpathFileObject; + File jarFile = (File) classpathFileObject; dependencies.put(jarFile, jarFile); } } @@ -459,10 +459,10 @@ public class Depend extends MatchingTask { private int deleteAllAffectedFiles() { int count = 0; for (Enumeration e = outOfDateClasses.elements(); e.hasMoreElements();) { - String className = (String)e.nextElement(); + String className = (String) e.nextElement(); count += deleteAffectedFiles(className); ClassFileInfo classInfo - = (ClassFileInfo)classFileInfoMap.get(className); + = (ClassFileInfo) classFileInfoMap.get(className); if (classInfo != null && classInfo.absoluteFile.exists()) { classInfo.absoluteFile.delete(); count++; @@ -481,14 +481,14 @@ public class Depend extends MatchingTask { private int deleteAffectedFiles(String className) { int count = 0; - Hashtable affectedClasses = (Hashtable)affectedClassMap.get(className); + Hashtable affectedClasses = (Hashtable) affectedClassMap.get(className); if (affectedClasses == null) { return count; } for (Enumeration e = affectedClasses.keys(); e.hasMoreElements();) { - String affectedClass = (String)e.nextElement(); + String affectedClass = (String) e.nextElement(); ClassFileInfo affectedClassInfo - = (ClassFileInfo)affectedClasses.get(affectedClass); + = (ClassFileInfo) affectedClasses.get(affectedClass); if (!affectedClassInfo.absoluteFile.exists()) { continue; @@ -526,7 +526,7 @@ public class Depend extends MatchingTask { log("Top level class = " + topLevelClassName, Project.MSG_VERBOSE); ClassFileInfo topLevelClassInfo - = (ClassFileInfo)classFileInfoMap.get(topLevelClassName); + = (ClassFileInfo) classFileInfoMap.get(topLevelClassName); if (topLevelClassInfo != null && topLevelClassInfo.absoluteFile.exists()) { log("Deleting file " @@ -553,15 +553,15 @@ public class Depend extends MatchingTask { Enumeration classEnum = affectedClassMap.keys(); while (classEnum.hasMoreElements()) { - String className = (String)classEnum.nextElement(); + String className = (String) classEnum.nextElement(); log(" Class " + className + " affects:", Project.MSG_DEBUG); Hashtable affectedClasses - = (Hashtable)affectedClassMap.get(className); + = (Hashtable) affectedClassMap.get(className); Enumeration affectedClassEnum = affectedClasses.keys(); while (affectedClassEnum.hasMoreElements()) { - String affectedClass = (String)affectedClassEnum.nextElement(); + String affectedClass = (String) affectedClassEnum.nextElement(); ClassFileInfo info - = (ClassFileInfo)affectedClasses.get(affectedClass); + = (ClassFileInfo) affectedClasses.get(affectedClass); log(" " + affectedClass + " in " + info.absoluteFile.getPath(), Project.MSG_DEBUG); } @@ -572,14 +572,14 @@ public class Depend extends MatchingTask { Enumeration classpathEnum = classpathDependencies.keys(); while (classpathEnum.hasMoreElements()) { - String className = (String)classpathEnum.nextElement(); + String className = (String) classpathEnum.nextElement(); log(" Class " + className + " depends on:", Project.MSG_DEBUG); Hashtable dependencies - = (Hashtable)classpathDependencies.get(className); + = (Hashtable) classpathDependencies.get(className); Enumeration classpathFileEnum = dependencies.elements(); while (classpathFileEnum.hasMoreElements()) { - File classpathFile = (File)classpathFileEnum.nextElement(); + File classpathFile = (File) classpathFileEnum.nextElement(); log(" " + classpathFile.getPath(), Project.MSG_DEBUG); } } @@ -589,7 +589,7 @@ public class Depend extends MatchingTask { private void determineOutOfDateClasses() { outOfDateClasses = new Hashtable(); for (int i = 0; i < srcPathList.length; i++) { - File srcDir = (File)project.resolveFile(srcPathList[i]); + File srcDir = (File) project.resolveFile(srcPathList[i]); if (srcDir.exists()) { DirectoryScanner ds = this.getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); @@ -604,18 +604,20 @@ public class Depend extends MatchingTask { Enumeration classpathDepsEnum = classpathDependencies.keys(); while (classpathDepsEnum.hasMoreElements()) { - String className = (String)classpathDepsEnum.nextElement(); + String className = (String) classpathDepsEnum.nextElement(); if (outOfDateClasses.containsKey(className)) { continue; } - ClassFileInfo info = (ClassFileInfo)classFileInfoMap.get(className); + ClassFileInfo info + = (ClassFileInfo) classFileInfoMap.get(className); // if we have no info about the class - it may have been deleted already and we // are using cached info. if (info != null) { - Hashtable dependencies = (Hashtable)classpathDependencies.get(className); - for (Enumeration e2 = dependencies.elements(); e2.hasMoreElements(); ) { - File classpathFile = (File)e2.nextElement(); + Hashtable dependencies + = (Hashtable) classpathDependencies.get(className); + for (Enumeration e2 = dependencies.elements(); e2.hasMoreElements();) { + File classpathFile = (File) e2.nextElement(); if (classpathFile.lastModified() > info.absoluteFile.lastModified()) { log("Class " + className + @@ -692,10 +694,12 @@ public class Depend extends MatchingTask { File srcFile = new File(srcDir, files[i]); if (files[i].endsWith(".java")) { String filePath = srcFile.getPath(); - String className = filePath.substring(srcDir.getPath().length() + 1, - filePath.length() - ".java".length()); + String className + = filePath.substring(srcDir.getPath().length() + 1, + filePath.length() - ".java".length()); className = ClassFileUtils.convertSlashName(className); - ClassFileInfo info = (ClassFileInfo)classFileInfoMap.get(className); + ClassFileInfo info + = (ClassFileInfo) classFileInfoMap.get(className); if (info == null) { // there was no class file. add this class to the list outOfDateClasses.put(className, className); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java index 48764fab1..4a4a86b20 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java @@ -165,7 +165,7 @@ public class DirectoryIterator implements ClassFileIterator { try { while (nextElement == null) { if (currentEnum.hasMoreElements()) { - File element = (File)currentEnum.nextElement(); + File element = (File) currentEnum.nextElement(); if (element.isDirectory()) { @@ -198,7 +198,7 @@ public class DirectoryIterator implements ClassFileIterator { if (enumStack.empty()) { break; } else { - currentEnum = (Enumeration)enumStack.pop(); + currentEnum = (Enumeration) enumStack.pop(); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java index 29233c20c..c65ced59d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java @@ -112,7 +112,7 @@ public class ClassCPInfo extends ConstantPoolEntry { * class. */ public void resolve(ConstantPool constantPool) { - className = ((Utf8CPInfo)constantPool.getEntry(index)).getValue(); + className = ((Utf8CPInfo) constantPool.getEntry(index)).getValue(); super.resolve(constantPool); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java index 641daaf68..eb1878c46 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java @@ -100,7 +100,7 @@ public class ConstantPool { public void read(DataInputStream classStream) throws IOException { int numEntries = classStream.readUnsignedShort(); - for (int i = 1; i < numEntries; ) { + for (int i = 1; i < numEntries;) { ConstantPoolEntry nextEntry = ConstantPoolEntry.readEntry(classStream); @@ -139,7 +139,7 @@ public class ConstantPool { } if (entry instanceof Utf8CPInfo) { - Utf8CPInfo utf8Info = (Utf8CPInfo)entry; + Utf8CPInfo utf8Info = (Utf8CPInfo) entry; utf8Indexes.put(utf8Info.getValue(), new Integer(index)); } @@ -153,8 +153,8 @@ public class ConstantPool { * into the actual data for that entry. */ public void resolve() { - for (Enumeration i = entries.elements(); i.hasMoreElements(); ) { - ConstantPoolEntry poolInfo = (ConstantPoolEntry)i.nextElement(); + for (Enumeration i = entries.elements(); i.hasMoreElements();) { + ConstantPoolEntry poolInfo = (ConstantPoolEntry) i.nextElement(); if (poolInfo != null && !poolInfo.isResolved()) { poolInfo.resolve(this); @@ -170,7 +170,7 @@ public class ConstantPool { * @return the constant pool entry at that index. */ public ConstantPoolEntry getEntry(int index) { - return (ConstantPoolEntry)entries.elementAt(index); + return (ConstantPoolEntry) entries.elementAt(index); } /** @@ -182,7 +182,7 @@ public class ConstantPool { */ public int getUTF8Entry(String value) { int index = -1; - Integer indexInteger = (Integer)utf8Indexes.get(value); + Integer indexInteger = (Integer) utf8Indexes.get(value); if (indexInteger != null) { index = indexInteger.intValue(); @@ -206,7 +206,7 @@ public class ConstantPool { Object element = entries.elementAt(i); if (element instanceof ClassCPInfo) { - ClassCPInfo classinfo = (ClassCPInfo)element; + ClassCPInfo classinfo = (ClassCPInfo) element; if (classinfo.getClassName().equals(className)) { index = i; @@ -232,7 +232,7 @@ public class ConstantPool { Object element = entries.elementAt(i); if (element instanceof ConstantCPInfo) { - ConstantCPInfo constantEntry = (ConstantCPInfo)element; + ConstantCPInfo constantEntry = (ConstantCPInfo) element; if (constantEntry.getValue().equals(constantValue)) { index = i; @@ -262,7 +262,7 @@ public class ConstantPool { Object element = entries.elementAt(i); if (element instanceof MethodRefCPInfo) { - MethodRefCPInfo methodRefEntry = (MethodRefCPInfo)element; + MethodRefCPInfo methodRefEntry = (MethodRefCPInfo) element; if (methodRefEntry.getMethodClassName().equals(methodClassName) && methodRefEntry.getMethodName().equals(methodName) @@ -297,7 +297,7 @@ public class ConstantPool { if (element instanceof InterfaceMethodRefCPInfo) { InterfaceMethodRefCPInfo interfaceMethodRefEntry - = (InterfaceMethodRefCPInfo)element; + = (InterfaceMethodRefCPInfo) element; if (interfaceMethodRefEntry.getInterfaceMethodClassName().equals(interfaceMethodClassName) && interfaceMethodRefEntry.getInterfaceMethodName().equals(interfaceMethodName) @@ -329,7 +329,7 @@ public class ConstantPool { Object element = entries.elementAt(i); if (element instanceof FieldRefCPInfo) { - FieldRefCPInfo fieldRefEntry = (FieldRefCPInfo)element; + FieldRefCPInfo fieldRefEntry = (FieldRefCPInfo) element; if (fieldRefEntry.getFieldClassName().equals(fieldClassName) && fieldRefEntry.getFieldName().equals(fieldName) @@ -358,7 +358,8 @@ public class ConstantPool { Object element = entries.elementAt(i); if (element instanceof NameAndTypeCPInfo) { - NameAndTypeCPInfo nameAndTypeEntry = (NameAndTypeCPInfo)element; + NameAndTypeCPInfo nameAndTypeEntry + = (NameAndTypeCPInfo) element; if (nameAndTypeEntry.getName().equals(name) && nameAndTypeEntry.getType().equals(type)) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java index a34e8c72d..00f46c539 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java @@ -99,14 +99,15 @@ public class FieldRefCPInfo extends ConstantPoolEntry { * and against which this entry is to be resolved. */ public void resolve(ConstantPool constantPool) { - ClassCPInfo fieldClass = (ClassCPInfo)constantPool.getEntry(classIndex); + ClassCPInfo fieldClass + = (ClassCPInfo) constantPool.getEntry(classIndex); fieldClass.resolve(constantPool); fieldClassName = fieldClass.getClassName(); NameAndTypeCPInfo nt - = (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex); + = (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex); nt.resolve(constantPool); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java index 1c57a314a..66531c305 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java @@ -106,14 +106,14 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry { */ public void resolve(ConstantPool constantPool) { ClassCPInfo interfaceMethodClass - = (ClassCPInfo)constantPool.getEntry(classIndex); + = (ClassCPInfo) constantPool.getEntry(classIndex); interfaceMethodClass.resolve(constantPool); interfaceMethodClassName = interfaceMethodClass.getClassName(); NameAndTypeCPInfo nt - = (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex); + = (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex); nt.resolve(constantPool); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java index fd524b081..fc8593f27 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java @@ -122,14 +122,14 @@ public class MethodRefCPInfo extends ConstantPoolEntry { */ public void resolve(ConstantPool constantPool) { ClassCPInfo methodClass - = (ClassCPInfo)constantPool.getEntry(classIndex); + = (ClassCPInfo) constantPool.getEntry(classIndex); methodClass.resolve(constantPool); methodClassName = methodClass.getClassName(); NameAndTypeCPInfo nt - = (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex); + = (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex); nt.resolve(constantPool); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java index 0ebceb5b4..f596a56e5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java @@ -107,8 +107,8 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry { * and against which this entry is to be resolved. */ public void resolve(ConstantPool constantPool) { - name = ((Utf8CPInfo)constantPool.getEntry(nameIndex)).getValue(); - type = ((Utf8CPInfo)constantPool.getEntry(descriptorIndex)).getValue(); + name = ((Utf8CPInfo) constantPool.getEntry(nameIndex)).getValue(); + type = ((Utf8CPInfo) constantPool.getEntry(descriptorIndex)).getValue(); super.resolve(constantPool); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java index 88fbcc0c4..f4098de6f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java @@ -101,7 +101,7 @@ public class StringCPInfo extends ConstantCPInfo { * and against which this entry is to be resolved. */ public void resolve(ConstantPool constantPool) { - setValue(((Utf8CPInfo)constantPool.getEntry(index)).getValue()); + setValue(((Utf8CPInfo) constantPool.getEntry(index)).getValue()); super.resolve(constantPool); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java index 8c6ecf12d..c45c47188 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java @@ -241,7 +241,7 @@ public class CSharp /** * file alignment; 0 means let the compiler decide */ - private int fileAlign=0; + private int fileAlign = 0; /** * Fix C# reference inclusion. C# is really dumb in how it handles @@ -1033,7 +1033,7 @@ public class CSharp includeDefaultReferences = true; extraOptions = null; fullpaths = true; - fileAlign=0; + fileAlign = 0; } @@ -1053,7 +1053,7 @@ public class CSharp */ protected void validate() throws BuildException { - if(outputFile!=null && outputFile.isDirectory()) { + if (outputFile != null && outputFile.isDirectory()) { throw new BuildException("destFile cannot be a directory"); } } @@ -1068,7 +1068,7 @@ public class CSharp if (srcDir == null) { srcDir = project.resolveFile("."); } - log("CSC working from source directory "+srcDir,Project.MSG_VERBOSE); + log("CSC working from source directory " + srcDir, Project.MSG_VERBOSE); validate(); NetCommand command = new NetCommand(this, "CSC", csc_exe_name); @@ -1100,36 +1100,36 @@ public class CSharp command.addArgument(getFileAlignParameter()); long outputTimestamp; - if(outputFile!=null && outputFile.exists()) { + if (outputFile != null && outputFile.exists()) { outputTimestamp = outputFile.lastModified(); } else { outputTimestamp = 0; } - int filesOutOfDate=0; + int filesOutOfDate = 0; //get dependencies list. DirectoryScanner scanner = super.getDirectoryScanner(srcDir); String[] dependencies = scanner.getIncludedFiles(); log("compiling " + dependencies.length + " file" + ((dependencies.length == 1) ? "" : "s")); String baseDir = scanner.getBasedir().toString(); - File base=scanner.getBasedir(); + File base = scanner.getBasedir(); //add to the command for (int i = 0; i < dependencies.length; i++) { - File targetFile = new File(base,dependencies[i]); - log(targetFile.toString(),Project.MSG_VERBOSE); + File targetFile = new File(base, dependencies[i]); + log(targetFile.toString(), Project.MSG_VERBOSE); command.addArgument(targetFile.toString()); - if(targetFile.lastModified()>outputTimestamp) { + if (targetFile.lastModified() > outputTimestamp) { filesOutOfDate++; - log("Source file "+targetFile.toString()+" is out of date", + log("Source file " + targetFile.toString() + " is out of date", Project.MSG_VERBOSE); } else { - log("Source file "+targetFile.toString()+" is up to date", + log("Source file " + targetFile.toString() + " is up to date", Project.MSG_VERBOSE); } } //now run the command of exe + settings + files - if(filesOutOfDate>0) { + if (filesOutOfDate > 0) { command.runCommand(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java index e69d0dbdc..d2cad5028 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java @@ -204,9 +204,9 @@ public class NetCommand { } } - public void addArgument(String argument1,String argument2) { + public void addArgument(String argument1, String argument2) { if (argument2 != null && argument2.length() != 0) { - commandLine.createArgument().setValue(argument1+argument2); + commandLine.createArgument().setValue(argument1 + argument2); } } @@ -215,10 +215,10 @@ public class NetCommand { */ protected void prepareExecutor() { // default directory to the project's base directory - if(owner==null) { + if (owner == null) { throw new RuntimeException("no owner"); } - if(owner.getProject()==null) { + if (owner.getProject() == null) { throw new RuntimeException("Owner has no project"); } File dir = owner.getProject().getBaseDir(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java index c62bd2be9..717b19cb7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java @@ -72,42 +72,42 @@ public class WsdlToDotnet extends Task { /** * name of output file (required) */ - private File destFile=null; + private File destFile = null; /** * url to retrieve */ - private String url=null; + private String url = null; /** * name of source file */ - private File srcFile=null; + private File srcFile = null; /** * language; defaults to C# */ - private String language="CS"; + private String language = "CS"; /** * flag set to true to generate server side skeleton */ - private boolean server=false; + private boolean server = false; /** * namespace */ - private String namespace=null; + private String namespace = null; /** * flag to control action on execution trouble */ - private boolean failOnError=true; + private boolean failOnError = true; /** * any extra command options? */ - protected String extraOptions=null; + protected String extraOptions = null; /** * @@ -155,27 +155,27 @@ public class WsdlToDotnet extends Task { */ protected void validate() throws BuildException { - if(destFile==null) { + if (destFile == null) { throw new BuildException("destination file must be specified"); } - if(destFile.isDirectory() ) { + if (destFile.isDirectory()) { throw new BuildException( "destination file is a directory"); } - if(url!=null && srcFile!=null) { + if (url != null && srcFile != null) { throw new BuildException( "you can not specify both a source file and a URL"); } - if(url==null && srcFile==null) { + if (url == null && srcFile == null) { throw new BuildException( "you must specify either a source file or a URL"); } - if(srcFile!=null) { - if(!srcFile.exists() ) { + if (srcFile != null) { + if (!srcFile.exists()) { throw new BuildException( "source file does not exist"); } - if(srcFile.isDirectory() ) { + if (srcFile.isDirectory()) { throw new BuildException( "source file is a directory"); } @@ -197,12 +197,12 @@ public class WsdlToDotnet extends Task { command.setTraceCommandLine(true); //fill in args command.addArgument("/nologo"); - command.addArgument("/out:"+destFile); - command.addArgument("/language:",language); - if(server) { + command.addArgument("/out:" + destFile); + command.addArgument("/language:", language); + if (server) { command.addArgument("/server"); } - command.addArgument("/namespace:",namespace); + command.addArgument("/namespace:", namespace); command.addArgument(extraOptions); //because these args arent added when null, we can //set both of these and let either of them @@ -210,12 +210,12 @@ public class WsdlToDotnet extends Task { command.addArgument(url); //rebuild unless the dest file is newer than the source file - boolean rebuild=true; - if(srcFile.exists() && destFile.exists() && - srcFile.lastModified()<=destFile.lastModified()) { - rebuild=false; + boolean rebuild = true; + if (srcFile.exists() && destFile.exists() && + srcFile.lastModified() <= destFile.lastModified()) { + rebuild = false; } - if(rebuild) { + if (rebuild) { command.runCommand(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java index 9b43a098b..861c34ccd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java @@ -202,8 +202,9 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe // Get the filename of vendor specific descriptor String fileNameWithMETA = currentText; //trim the META_INF\ off of the file name - String fileName = fileNameWithMETA.substring(META_DIR.length(), - fileNameWithMETA.length() ); + String fileName + = fileNameWithMETA.substring(META_DIR.length(), + fileNameWithMETA.length()); File descriptorFile = new File(srcDir, fileName); ejbFiles.put(fileNameWithMETA, descriptorFile); @@ -214,7 +215,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe borlandDTD == null ? DEFAULT_BAS_DTD_LOCATION : borlandDTD); for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation)i.next(); + EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; @@ -226,9 +227,9 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe */ protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { - File borlandDD = new File(getConfig().descriptorDir,ddPrefix + BAS_DD); + File borlandDD = new File(getConfig().descriptorDir, ddPrefix + BAS_DD); if (borlandDD.exists()) { - log("Borland specific file found "+ borlandDD, Project.MSG_VERBOSE); + log("Borland specific file found " + borlandDD, Project.MSG_VERBOSE); ejbFiles.put(META_DIR + BAS_DD, borlandDD); } else { @@ -252,11 +253,11 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe */ private void verifyBorlandJar(File sourceJar) { org.apache.tools.ant.taskdefs.Java javaTask = null; - log("verify "+sourceJar,Project.MSG_INFO); + log("verify " + sourceJar, Project.MSG_INFO); try { String args = verifyArgs; - args += " "+sourceJar.getPath(); + args += " " + sourceJar.getPath(); javaTask = (Java) getTask().getProject().createTask("java"); javaTask.setTaskName("verify"); @@ -270,12 +271,14 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe javaTask.setFork(true); } - log("Calling "+VERIFY+" for " + sourceJar.toString(), Project.MSG_VERBOSE); + log("Calling " + VERIFY + " for " + sourceJar.toString(), + Project.MSG_VERBOSE); javaTask.execute(); } catch (Exception e) { //TO DO : delete the file if it is not a valid file. - String msg = "Exception while calling "+VERIFY+" Details: " + e.toString(); + String msg = "Exception while calling " + VERIFY + " Details: " + + e.toString(); throw new BuildException(msg, e); } } @@ -287,13 +290,13 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe */ private void generateClient(File sourceJar) { getTask().getProject().addTaskDefinition("internal_bas_generateclient", - org.apache.tools.ant.taskdefs.optional.ejb.BorlandGenerateClient.class); + org.apache.tools.ant.taskdefs.optional.ejb.BorlandGenerateClient.class); org.apache.tools.ant.taskdefs.optional.ejb.BorlandGenerateClient gentask = null; - log("generate client for "+sourceJar,Project.MSG_INFO); + log("generate client for " + sourceJar, Project.MSG_INFO); try { String args = verifyArgs; - args += " "+sourceJar.getPath(); + args += " " + sourceJar.getPath(); gentask = (BorlandGenerateClient) getTask().getProject().createTask("internal_bas_generateclient"); gentask.setEjbjar(sourceJar); @@ -307,7 +310,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe } catch (Exception e) { //TO DO : delete the file if it is not a valid file. - String msg = "Exception while calling "+VERIFY+" Details: " + e.toString(); + String msg = "Exception while calling " + VERIFY + " Details: " + + e.toString(); throw new BuildException(msg, e); } } @@ -318,7 +322,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe * @param ithomes : iterator on home class * @param files : file list , updated by the adding generated files */ - private void buildBorlandStubs(Iterator ithomes,Hashtable files ) { + private void buildBorlandStubs(Iterator ithomes, Hashtable files) { Execute execTask = null; execTask = new Execute(this); @@ -329,7 +333,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe Commandline commandline = new Commandline(); commandline.setExecutable(JAVA2IIOP); //debug ? - if ( java2iiopdebug ) { + if (java2iiopdebug) { commandline.createArgument().setValue("-VBJdebug"); } // end of if () //set the classpath @@ -345,23 +349,24 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe //compiling order commandline.createArgument().setValue("-compile"); //add the home class - while ( ithomes.hasNext()) { + while (ithomes.hasNext()) { commandline.createArgument().setValue(ithomes.next().toString()); } // end of while () try { - log("Calling java2iiop",Project.MSG_VERBOSE); - log(commandline.toString(),Project.MSG_DEBUG); + log("Calling java2iiop", Project.MSG_VERBOSE); + log(commandline.toString(), Project.MSG_DEBUG); execTask.setCommandline(commandline.getCommandline()); int result = execTask.execute(); - if ( result != 0 ) { - String msg = "Failed executing java2iiop (ret code is "+result+")"; + if (result != 0) { + String msg = "Failed executing java2iiop (ret code is " + + result + ")"; throw new BuildException(msg, getTask().getLocation()); } } catch (java.io.IOException e) { - log("java2iiop exception :"+e.getMessage(),Project.MSG_ERR); - throw new BuildException(e,getTask().getLocation()); + log("java2iiop exception :" + e.getMessage(), Project.MSG_ERR); + throw new BuildException(e, getTask().getLocation()); } } @@ -375,28 +380,28 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe //build the home classes list. Vector homes = new Vector(); Iterator it = files.keySet().iterator(); - while ( it.hasNext()) { + while (it.hasNext()) { String clazz = (String) it.next(); - if ( clazz.endsWith("Home.class") ) { + if (clazz.endsWith("Home.class")) { //remove .class extension String home = toClass(clazz); homes.add(home); - log(" Home "+home,Project.MSG_VERBOSE); + log(" Home " + home, Project.MSG_VERBOSE); } // end of if () } // end of while () - buildBorlandStubs(homes.iterator(),files); + buildBorlandStubs(homes.iterator(), files); //add the gen files to the collection files.putAll(_genfiles); super.writeJar(baseName, jarFile, files, publicId); - if ( verify ) { + if (verify) { verifyBorlandJar(jarFile); } // end of if () - if ( generateclient) { + if (generateclient) { generateClient(jarFile); } // end of if () } @@ -407,8 +412,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe */ private String toClass(String filename) { //remove the .class - String classname = filename.substring(0,filename.lastIndexOf(".class")); - classname = classname.replace('\\','.'); + String classname = filename.substring(0, filename.lastIndexOf(".class")); + classname = classname.replace('\\', '.'); return classname; } @@ -418,8 +423,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe */ private String toClassFile(String filename) { //remove the .class - String classfile = filename.substring(0,filename.lastIndexOf(".java")); - classfile = classfile+".class"; + String classfile = filename.substring(0, filename.lastIndexOf(".java")); + classfile = classfile + ".class"; return classfile; } @@ -439,19 +444,19 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String javafile; - while ( ( javafile = reader.readLine()) != null) { - log("buffer:" +javafile,Project.MSG_DEBUG); - if ( javafile.endsWith(".java") ) { + while ((javafile = reader.readLine()) != null) { + log("buffer:" + javafile, Project.MSG_DEBUG); + if (javafile.endsWith(".java")) { String classfile = toClassFile(javafile); - String key = classfile.substring(getConfig().srcDir.getAbsolutePath().length()+1); - log(" generated : "+ classfile ,Project.MSG_DEBUG); - log(" key : "+ key ,Project.MSG_DEBUG); + String key = classfile.substring(getConfig().srcDir.getAbsolutePath().length() + 1); + log(" generated : " + classfile, Project.MSG_DEBUG); + log(" key : " + key, Project.MSG_DEBUG); _genfiles.put(key, new File(classfile)); } // end of if () } // end of while () reader.close(); } - catch(Exception e) { + catch (Exception e) { String msg = "Exception while parsing java2iiop output. Details: " + e.toString(); throw new BuildException(msg, e); } @@ -465,10 +470,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String s = reader.readLine(); - if ( s != null) - { - log("[java2iiop] "+s,Project.MSG_DEBUG); + if (s != null) { + log("[java2iiop] " + s, Project.MSG_DEBUG); } // end of if () } - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java index 20c61659f..265e4dcbf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java @@ -144,30 +144,28 @@ public class BorlandGenerateClient extends Task * @exception BuildException if someting goes wrong with the build */ public void execute() throws BuildException { - if ( ejbjarfile == null || - ejbjarfile.isDirectory()) { + if (ejbjarfile == null || ejbjarfile.isDirectory()) { throw new BuildException("invalid ejb jar file."); } // end of if () - if ( clientjarfile == null || - clientjarfile.isDirectory()) { - log("invalid or missing client jar file.",Project.MSG_VERBOSE); + if (clientjarfile == null || clientjarfile.isDirectory()) { + log("invalid or missing client jar file.", Project.MSG_VERBOSE); String ejbjarname = ejbjarfile.getAbsolutePath(); //clientname = ejbjarfile+client.jar - String clientname = ejbjarname.substring(0,ejbjarname.lastIndexOf(".")); + String clientname = ejbjarname.substring(0, ejbjarname.lastIndexOf(".")); clientname = clientname + "client.jar"; clientjarfile = new File(clientname); } // end of if () - if ( mode == null ) { + if (mode == null) { log("mode is null default mode is java"); setMode(JAVA_MODE); } // end of if () log("client jar file is " + clientjarfile); - if ( mode.equalsIgnoreCase(FORK_MODE)) { + if (mode.equalsIgnoreCase(FORK_MODE)) { executeFork(); } // end of if () else { @@ -192,7 +190,7 @@ public class BorlandGenerateClient extends Task execTask.setFork(true); execTask.createArg().setValue("generateclient"); - if ( debug ) { + if (debug) { execTask.createArg().setValue("-trace"); } // end of if () @@ -206,7 +204,7 @@ public class BorlandGenerateClient extends Task execTask.createArg().setValue("-clientjarfile"); execTask.createArg().setValue(clientjarfile.getAbsolutePath()); - log("Calling EJBUtilities",Project.MSG_VERBOSE); + log("Calling EJBUtilities", Project.MSG_VERBOSE); execTask.execute(); } @@ -228,7 +226,7 @@ public class BorlandGenerateClient extends Task execTask.setDir(new File(".")); execTask.setExecutable("iastool"); execTask.createArg().setValue("generateclient"); - if ( debug ){ + if (debug) { execTask.createArg().setValue("-trace"); } // end of if () @@ -242,12 +240,13 @@ public class BorlandGenerateClient extends Task execTask.createArg().setValue("-clientjarfile"); execTask.createArg().setValue(clientjarfile.getAbsolutePath()); - log("Calling java2iiop",Project.MSG_VERBOSE); + log("Calling java2iiop", Project.MSG_VERBOSE); execTask.execute(); } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling generateclient Details: " + e.toString(); + String msg = "Exception while calling generateclient Details: " + + e.toString(); throw new BuildException(msg, e); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DDCreator.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DDCreator.java index 52bde39d9..8aa7b3b06 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DDCreator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DDCreator.java @@ -126,7 +126,7 @@ public class DDCreator extends MatchingTask { String systemClassPath = System.getProperty("java.class.path"); String execClassPath = project.translatePath(systemClassPath + ":" + classpath); - Java ddCreatorTask = (Java)project.createTask("java"); + Java ddCreatorTask = (Java) project.createTask("java"); ddCreatorTask.setTaskName(getTaskName()); ddCreatorTask.setFork(true); ddCreatorTask.setClassname("org.apache.tools.ant.taskdefs.optional.ejb.DDCreatorHelper"); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java index 818ab0a59..24f481ba9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java @@ -181,7 +181,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { URL urldtd = new URL(location); urlDTDs.put(publicId, urldtd); } - } catch ( java.net.MalformedURLException e) { + } catch (java.net.MalformedURLException e) { //ignored } @@ -197,12 +197,12 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { try { owningTask.log("Resolved " + publicId + " to local file " + dtdFile, Project.MSG_VERBOSE); return new InputSource(new FileInputStream(dtdFile)); - } catch( FileNotFoundException ex ) { + } catch (FileNotFoundException ex) { // ignore } } - String dtdResourceName = (String)resourceDTDs.get(publicId); + String dtdResourceName = (String) resourceDTDs.get(publicId); if (dtdResourceName != null) { InputStream is = this.getClass().getResourceAsStream(dtdResourceName); if (is != null) { @@ -212,12 +212,12 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { } URL dtdUrl = (URL) urlDTDs.get(publicId); - if ( dtdUrl != null ) { + if (dtdUrl != null) { try { InputStream is = dtdUrl.openStream(); owningTask.log("Resolved " + publicId + " to url " + dtdUrl, Project.MSG_VERBOSE); return new InputSource(is); - } catch ( IOException ioe) { + } catch (IOException ioe) { //ignore } } @@ -283,10 +283,10 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { else if (parseState == STATE_IN_BEANS && name.equals(SESSION_BEAN)) { parseState = STATE_IN_SESSION; } - else if (parseState == STATE_IN_BEANS && name.equals(ENTITY_BEAN )) { + else if (parseState == STATE_IN_BEANS && name.equals(ENTITY_BEAN)) { parseState = STATE_IN_ENTITY; } - else if (parseState == STATE_IN_BEANS && name.equals(MESSAGE_BEAN )) { + else if (parseState == STATE_IN_BEANS && name.equals(MESSAGE_BEAN)) { parseState = STATE_IN_MESSAGE; } } @@ -379,7 +379,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { // Get the value of the tag. Only the first occurence. if (currentElement.equals(EJB_NAME)) { - if ( ejbName == null ) { + if (ejbName == null) { ejbName = currentText.trim(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java index 121872c11..69d0c9f88 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java @@ -563,8 +563,8 @@ public class EjbJar extends MatchingTask { deploymentTools.add(genericTool); } - for (Iterator i = deploymentTools.iterator(); i.hasNext(); ) { - EJBDeploymentTool tool = (EJBDeploymentTool)i.next(); + for (Iterator i = deploymentTools.iterator(); i.hasNext();) { + EJBDeploymentTool tool = (EJBDeploymentTool) i.next(); tool.configure(config); tool.validateConfigured(); } @@ -587,8 +587,8 @@ public class EjbJar extends MatchingTask { // descriptor, and hence one bean in our model. for (int index = 0; index < files.length; ++index) { // process the deployment descriptor in each tool - for (Iterator i = deploymentTools.iterator(); i.hasNext(); ) { - EJBDeploymentTool tool = (EJBDeploymentTool)i.next(); + for (Iterator i = deploymentTools.iterator(); i.hasNext();) { + EJBDeploymentTool tool = (EJBDeploymentTool) i.next(); tool.processDescriptor(files[index], saxParser); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/Ejbc.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/Ejbc.java index 6b55d2ecb..5f615521e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/Ejbc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/Ejbc.java @@ -138,7 +138,7 @@ public class Ejbc extends MatchingTask { String[] files = ds.getIncludedFiles(); - Java helperTask = (Java)project.createTask("java"); + Java helperTask = (Java) project.createTask("java"); helperTask.setTaskName(getTaskName()); helperTask.setFork(true); helperTask.setClassname("org.apache.tools.ant.taskdefs.optional.ejb.EjbcHelper"); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbcHelper.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbcHelper.java index 3c96df2b1..6ebac9371 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbcHelper.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbcHelper.java @@ -175,14 +175,14 @@ public class EjbcHelper { try { fis = new FileInputStream(descriptorFile); ObjectInputStream ois = new ObjectInputStream(fis); - DeploymentDescriptor dd = (DeploymentDescriptor)ois.readObject(); + DeploymentDescriptor dd = (DeploymentDescriptor) ois.readObject(); fis.close(); String homeInterfacePath = dd.getHomeInterfaceClassName().replace('.', '/') + ".java"; String remoteInterfacePath = dd.getRemoteInterfaceClassName().replace('.', '/') + ".java"; String primaryKeyClassPath = null; if (dd instanceof EntityDescriptor) { - primaryKeyClassPath = ((EntityDescriptor)dd).getPrimaryKeyClassName().replace('.', '/') + ".java";; + primaryKeyClassPath = ((EntityDescriptor) dd).getPrimaryKeyClassName().replace('.', '/') + ".java";; } File homeInterfaceSource = new File(sourceDirectory, homeInterfacePath); @@ -281,7 +281,7 @@ public class EjbcHelper { // create a Java task to do the rebuild - String[] args = getCommandLine(false,descriptorFile); + String[] args = getCommandLine(false, descriptorFile); try { weblogic.ejbc.main(args); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java index d4c495b7c..bc9839f42 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java @@ -309,7 +309,8 @@ public class GenericDeploymentTool implements EJBDeploymentTool { try { Class analyzerClass = Class.forName(analyzerClassName); - dependencyAnalyzer = (DependencyAnalyzer)analyzerClass.newInstance(); + dependencyAnalyzer + = (DependencyAnalyzer) analyzerClass.newInstance(); dependencyAnalyzer.addClassPath(new Path(task.getProject(), config.srcDir.getPath())); dependencyAnalyzer.addClassPath(config.classpath); @@ -394,7 +395,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { // register any DTDs supplied by the user for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation)i.next(); + EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; @@ -456,7 +457,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { // Check to see if we need a build and start doing the work! if (needToRebuild(ejbFiles, jarFile)) { // Log that we are going to build... - log( "building " + log("building " + jarFile.getName() + " with " + String.valueOf(ejbFiles.size()) @@ -565,7 +566,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { // add in support classes if any Project project = task.getProject(); for (Iterator i = config.supportFileSets.iterator(); i.hasNext();) { - FileSet supportFileSet = (FileSet)i.next(); + FileSet supportFileSet = (FileSet) i.next(); File supportBaseDir = supportFileSet.getDir(project); DirectoryScanner supportScanner = supportFileSet.getDirectoryScanner(project); supportScanner.scan(); @@ -766,14 +767,14 @@ public class GenericDeploymentTool implements EJBDeploymentTool { in = new FileInputStream(manifestFile); } else if (config.manifest != null) { in = new FileInputStream(config.manifest); - if ( in == null ) { + if (in == null) { throw new BuildException("Could not find manifest file: " + config.manifest, getLocation()); } } else { String defaultManifest = "/org/apache/tools/ant/defaultManifest.mf"; in = this.getClass().getResourceAsStream(defaultManifest); - if ( in == null ) { + if (in == null) { throw new BuildException("Could not find default manifest: " + defaultManifest, getLocation()); } @@ -794,7 +795,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { jarStream.setMethod(JarOutputStream.DEFLATED); // Loop through all the class files found and add them to the jar - for (Iterator entryIterator = files.keySet().iterator(); entryIterator.hasNext(); ) { + for (Iterator entryIterator = files.keySet().iterator(); entryIterator.hasNext();) { String entryName = (String) entryIterator.next(); File entryFile = (File) files.get(entryName); @@ -812,7 +813,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { //get and clean up innerclass name int entryIndex = entryName.lastIndexOf(entryFile.getName()) - 1; - if ( entryIndex < 0) { + if (entryIndex < 0) { entryName = innerfiles[i]; } else { entryName = entryName.substring(0, entryIndex) + File.separatorChar + innerfiles[i]; @@ -859,7 +860,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { Iterator i = checkEntries.keySet().iterator(); while (i.hasNext()) { - String entryName = (String)i.next(); + String entryName = (String) i.next(); if (entryName.endsWith(".class")) { String className = entryName.substring(0, entryName.length() - ".class".length()); @@ -873,7 +874,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { Enumeration e = dependencyAnalyzer.getClassDependencies(); while (e.hasMoreElements()) { - String classname = (String)e.nextElement(); + String classname = (String) e.nextElement(); String location = classname.replace('.', File.separatorChar) + ".class"; File classFile = new File(config.srcDir, location); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java index edd97dc59..a9bb01535 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java @@ -184,7 +184,7 @@ public class IPlanetEjbc { elements.add(st.nextToken()); } classpathElements - = (String[])elements.toArray(new String[elements.size()]); + = (String[]) elements.toArray(new String[elements.size()]); } } @@ -414,7 +414,7 @@ public class IPlanetEjbc { log(ejbs[i].toString()); } - for (int i=0; i < ejbs.length; i++) { + for (int i = 0; i < ejbs.length; i++) { EjbInfo ejb = ejbs[i]; ejb.checkConfiguration(destDirectory); // Throws EjbcException @@ -592,7 +592,7 @@ public class IPlanetEjbc { arguments.add(ejb.getImplementation().getQualifiedClassName()); /* Convert the List into an Array and return it */ - return (String[])arguments.toArray(new String[arguments.size()]); + return (String[]) arguments.toArray(new String[arguments.size()]); } /** @@ -689,7 +689,7 @@ public class IPlanetEjbc { * parsing. */ public EjbInfo[] getEjbs() { - return (EjbInfo[])ejbs.values().toArray(new EjbInfo[ejbs.size()]); + return (EjbInfo[]) ejbs.values().toArray(new EjbInfo[ejbs.size()]); } /** @@ -751,12 +751,12 @@ public class IPlanetEjbc { /* Search the resource Map and (if not found) file Map */ - String location = (String)resourceDtds.get(publicId); + String location = (String) resourceDtds.get(publicId); if (location != null) { inputStream = ClassLoader.getSystemResource(location).openStream(); } else { - location = (String)fileDtds.get(publicId); + location = (String) fileDtds.get(publicId); if (location != null) { inputStream = new FileInputStream(location); } @@ -1275,7 +1275,7 @@ public class IPlanetEjbc { * Loop through each stub/skeleton class that must be generated, and * determine (if all exist) which file has the most recent timestamp */ - for (int i=0; i < classnames.length; i++) { + for (int i = 0; i < classnames.length; i++) { String pathToClass = classnames[i].replace('.', File.separatorChar) + ".class"; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java index 0b2babc87..5ca406fe5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java @@ -62,9 +62,9 @@ public class InnerClassFilenameFilter implements FilenameFilter { InnerClassFilenameFilter(String baseclass){ int extidx = baseclass.lastIndexOf(".class"); if (extidx == -1) { - extidx = baseclass.length()-1; + extidx = baseclass.length() - 1; } - baseClassName = baseclass.substring(0,extidx); + baseClassName = baseclass.substring(0, extidx); } public boolean accept (File Dir, String filename){ diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java index 30da2f432..a7aaebc12 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java @@ -63,13 +63,12 @@ import java.io.File; import java.io.IOException; import java.util.Hashtable; - /** - * The deployment tool to add the jonas specific deployment descriptors to - * the ejb jar file. JONAS only requires one additional file jonas-ejb-jar.xml. + * The deployment tool to add the jonas specific deployment descriptors to the + * ejb jar file. JONAS only requires one additional file jonas-ejb-jar.xml. * - * @author Cyrille Morvan, - * Ingenosya France + * @author Cyrille Morvan , Ingenosya France * @version 1.0 * @see EjbJar#createJonas */ @@ -78,10 +77,10 @@ public class JonasDeploymentTool extends GenericDeploymentTool { protected static final String JONAS_DD = "jonas-ejb-jar.xml"; protected static final String GENIC_CLASS = - "org.objectweb.jonas_ejb.tools.GenWholeIC"; + "org.objectweb.jonas_ejb.tools.GenWholeIC"; protected static final String OLD_GENIC_CLASS = - "org.objectweb.jonas_ejb.tools.GenIC"; + "org.objectweb.jonas_ejb.tools.GenIC"; protected static final String DEFAULT_ORB = "RMI"; @@ -89,25 +88,28 @@ public class JonasDeploymentTool extends GenericDeploymentTool { private String jarSuffix = ".jar"; /** - * Instance variable that stores the fully qualified classname - * of the JOnAS GenIC compiler. - **/ + * Instance variable that stores the fully qualified classname of the + * JOnAS GenIC compiler. + */ private String genicClass; private String additionalArgs = ""; - /** Instance variable that determines do not delete intermediate generated source files */ + /** + * Instance variable that determines do not delete intermediate generated + * source files + */ private boolean keepgenerated = false; - + /** as websphere and WebLogic taskes */ - private boolean keepGeneric = false; - + private boolean keepGeneric = false; + /** Instance variable that determines the JOnAS Root directory */ private File jonasroot; /** Instance variable that determines if we could -secpropag */ private boolean secpropag = false; - + /** Instance variable that determines the ouput directory */ private File ouputdirectory; @@ -117,483 +119,527 @@ public class JonasDeploymentTool extends GenericDeploymentTool { /** Instance variable that determines if GenIC is verbose */ private boolean verbose; - /** Instance variable that determines the ORB to use (RMI, JEREMIE, DAVID)*/ + /** Instance variable that determines the ORB to use (RMI, JEREMIE, DAVID) */ private String orb; - /** clean the working directory after work **/ + /** clean the working directory after work * */ private boolean cleanWorkDir = false; private boolean noGENIC = false; - /** - * set the name of the GenIC compiler class. - **/ + + /** set the name of the GenIC compiler class. */ public void setGenicClass(final String inGenicClass) { - genicClass = inGenicClass; + genicClass = inGenicClass; } /** * Set the ORB to construct classpath. + * * @param inValue RMI, JEREMIE, DAVID,... - **/ + */ public void setOrb(final String inValue) { - orb = inValue; + orb = inValue; } - /** - * The compiler (switch -javac) to use. - **/ + + /** The compiler (switch -javac) to use. */ public void setCompiler(final String inCompiler) { compiler = inCompiler; - } - + } + + /** * Setter used to store the value of keepGeneric + * * @param inValue a string, either 'true' or 'false'. */ public void setKeepgeneric(boolean inValue) { this.keepGeneric = inValue; } - + + /** * GenIC verbose or not + * * @param inValue either 'true' or 'false' - **/ + */ public void setVerbose(final boolean inValue) { verbose = inValue; } + /** * GenIC run or not. + * * @param inValue run or not - **/ + */ public void setNoGENIC(final boolean inValue) { noGENIC = inValue; } + /** - * Sets whether -keepgenerated is passed to GenIC (that is, - * the .java source files are kept). + * Sets whether -keepgenerated is passed to GenIC (that is, the .java + * source files are kept). + * * @param inValue either 'true' or 'false' - **/ + */ public void setKeepgenerated(final boolean inValue) { keepgenerated = inValue; } + /** * set the jonas root directory (-Dinstall.root=). - * + * * @throws BuildException if the file doesn't exist. - **/ + */ public void setJonasroot(final File inValue) { - jonasroot = inValue; + jonasroot = inValue; } + /** - * Modify the RMI Skeleton and Stub to implement - * the implicit propagation of the transactionnal - * context and security context. - * For JOnAS 2.4 and next. + * Modify the RMI Skeleton and Stub to implement the implicit propagation + * of the transactionnal context and security context. For JOnAS 2.4 and + * next. */ public void setSecpropag(final boolean inValue) { - secpropag = inValue; + secpropag = inValue; } - + + /** - * set the output directory (-d ...). - *
- * - * It's the GenIC working directory. It's not the - * DestDir, which is the 'jar' destination directory. - * - * @param inValue a file - **/ + * set the output directory (-d ...).
+ * It's the GenIC working directory. It's not the DestDir, which is the + * 'jar' destination directory. + * + * @param inValue a file + */ public void setOuputdir(final File inValue) { ouputdirectory = inValue; } - - + + /** - * set the output directory (-d ...). - * Same as setOuputdir(). - *
+ * set the output directory (-d ...). Same as setOuputdir().
* But do not override setDestDir() - **/ + */ public void setWorkdir(final File inValue) { setOuputdir(inValue); } + /** * Clean the specified Work dir after work. + * * @param inValue true : clean ; false : not clean - **/ + */ public void setCleanworkdir(final boolean inValue) { cleanWorkDir = inValue; } - + + /** * Setter used to store the suffix for the generated JOnAS jar file. + * * @param inString the string to use as the suffix. - **/ + */ public void setSuffix(String inString) { this.jarSuffix = inString; } - /** - * sets some additional args to send to GenIC. - **/ + + /** sets some additional args to send to GenIC. */ public void setArgs(final String inArgs) { additionalArgs = inArgs; } + /** - * Add any vendor specific files which should be included in the - * EJB Jar. - * @param aDdPrefix MyDirectories/MyEjb- or MyDirectories/ - **/ - protected void addVendorFiles(final Hashtable someEjbFiles,final String aDdPrefix) { + * Add any vendor specific files which should be included in the EJB Jar. + * + * @param aDdPrefix MyDirectories/MyEjb- or MyDirectories/ + */ + protected void addVendorFiles(final Hashtable someEjbFiles, + final String aDdPrefix) { // Use Ant Naming convention - File aJonasDD = new File(getConfig().descriptorDir,aDdPrefix + JONAS_DD); - if ( aJonasDD.exists() ) { + File aJonasDD + = new File(getConfig().descriptorDir, aDdPrefix + JONAS_DD); + + if (aJonasDD.exists()) { someEjbFiles.put(META_DIR + JONAS_DD, aJonasDD); } else { // try with JOnAS Naming convention - if( ! addJonasVendorFiles(someEjbFiles,aDdPrefix) ) { - log("Unable to locate JOnAS deployment descriptor. It was expected to be in " - + aJonasDD.getPath() + ". Or please use JOnAS naming convention.", - Project.MSG_WARN); + if (!addJonasVendorFiles(someEjbFiles, aDdPrefix)) { + log("Unable to locate JOnAS deployment descriptor. It was " + + "expected to be in " + aJonasDD.getPath() + + ". Alternatively, please use JOnAS naming convention.", + Project.MSG_WARN); } } } + /** - * try to add JOnAS specific file, using JOnAS naming convention. - * For example : jonas-Account.xml or jonas-ejb-jar.xml - * @param aDdPrefix MyDirectories/MyEjb- or MyDirectories/ + * try to add JOnAS specific file, using JOnAS naming convention. For + * example : jonas-Account.xml or jonas-ejb-jar.xml + * + * @param aDdPrefix MyDirectories/MyEjb- or MyDirectories/ * @return true if Ok */ - private boolean addJonasVendorFiles(final Hashtable someEjbFiles,final String aDdPrefix) { - // replace \ by /, remove the last letter ( a dash - ) - final String aCanonicalDD = aDdPrefix.replace('\\', '/').substring(0,aDdPrefix.length()-1); - final int index = aCanonicalDD.lastIndexOf('/') + 1; - String anEjbJarName = aCanonicalDD.substring(index); - if( "ejb".equals( anEjbJarName ) ) { - anEjbJarName = "ejb-jar"; - } - final String aNewDdPrefix = - aDdPrefix.substring(0,index) + "jonas-" + anEjbJarName + ".xml"; - File aConventionNamingJonasDD = new File(getConfig().descriptorDir,aNewDdPrefix); - - log("look for jonas specific file using jonas naming convention " + aConventionNamingJonasDD, - Project.MSG_VERBOSE); - - if( aConventionNamingJonasDD.exists() ) { - someEjbFiles.put(META_DIR + JONAS_DD,aConventionNamingJonasDD); - return true; - } else { - return false; - } + private boolean addJonasVendorFiles(final Hashtable someEjbFiles, + final String aDdPrefix) { + // replace \ by /, remove the last letter ( a dash - ) + final String aCanonicalDD + = aDdPrefix.replace('\\', '/').substring(0, aDdPrefix.length() - 1); + final int index = aCanonicalDD.lastIndexOf('/') + 1; + String anEjbJarName = aCanonicalDD.substring(index); + + if ("ejb".equals(anEjbJarName)) { + anEjbJarName = "ejb-jar"; + } + final String aNewDdPrefix = + aDdPrefix.substring(0, index) + "jonas-" + anEjbJarName + ".xml"; + File aConventionNamingJonasDD + = new File(getConfig().descriptorDir, aNewDdPrefix); + + log("look for jonas specific file using jonas naming convention " + + aConventionNamingJonasDD, + Project.MSG_VERBOSE); + + if (aConventionNamingJonasDD.exists()) { + someEjbFiles.put(META_DIR + JONAS_DD, aConventionNamingJonasDD); + return true; + } else { + return false; + } } - + // include javadoc // Determine the JAR filename (without filename extension) protected String getJarBaseName(String aDescriptorFileName) { - String aBaseName = null; - EjbJar.Config aConfig = super.getConfig(); - if (aConfig.namingScheme.getValue().equals(EjbJar.NamingScheme.DESCRIPTOR)) { - // try to find JOnAS specific convention name - // ??/MyEJB.xml ( I will find later the ??/jonas-MyEJB.xml file ) - if( aDescriptorFileName.indexOf(aConfig.baseNameTerminator) == -1 ) { - String aCanonicalDescriptor = aDescriptorFileName.replace('\\','/'); - int lastSeparatorIndex = aCanonicalDescriptor.lastIndexOf('/'); - int endBaseName; - if (lastSeparatorIndex != -1) { - endBaseName = aDescriptorFileName.indexOf(".xml", lastSeparatorIndex); - } else { - endBaseName = aDescriptorFileName.indexOf(".xml"); + String aBaseName = null; + EjbJar.Config aConfig = super.getConfig(); + + if (aConfig.namingScheme.getValue().equals(EjbJar.NamingScheme.DESCRIPTOR)) { + // try to find JOnAS specific convention name + // ??/MyEJB.xml ( I will find later the ??/jonas-MyEJB.xml file ) + if (aDescriptorFileName.indexOf(aConfig.baseNameTerminator) == -1) { + String aCanonicalDescriptor = aDescriptorFileName.replace('\\', '/'); + int lastSeparatorIndex = aCanonicalDescriptor.lastIndexOf('/'); + int endBaseName; + + if (lastSeparatorIndex != -1) { + endBaseName = aDescriptorFileName.indexOf(".xml", lastSeparatorIndex); + } else { + endBaseName = aDescriptorFileName.indexOf(".xml"); + } + + if (endBaseName != -1) { + aBaseName = aDescriptorFileName.substring(0, endBaseName); + } } + } - if (endBaseName != -1) { - aBaseName = aDescriptorFileName.substring(0, endBaseName); - } - } - } - - if( aBaseName == null ) { - // else get standard BaseName - aBaseName = super.getJarBaseName(aDescriptorFileName); - } - return aBaseName; + if (aBaseName == null) { + // else get standard BaseName + aBaseName = super.getJarBaseName(aDescriptorFileName); + } + return aBaseName; } + /** - * Method used to encapsulate the writing of the JAR file. Iterates over the - * filenames/java.io.Files in the Hashtable stored on the instance variable - * ejbFiles. - **/ + * Method used to encapsulate the writing of the JAR file. Iterates over + * the filenames/java.io.Files in the Hashtable stored on the instance + * variable ejbFiles. + */ protected void writeJar(String baseName, File jarFile, Hashtable files, String publicId) throws BuildException { // need to create a generic jar first. File genericJarFile = super.getVendorOutputJarFile(baseName); + super.writeJar(baseName, genericJarFile, files, publicId); // todo ? if (alwaysRebuild || isRebuildRequired(genericJarFile, jarFile)) - buildJOnASJar(baseName,genericJarFile, jarFile,files,publicId); - + buildJOnASJar(baseName, genericJarFile, jarFile, files, publicId); + if (!keepGeneric) { - log("deleting generic jar " + genericJarFile.toString(), - Project.MSG_VERBOSE); - genericJarFile.delete(); + log("deleting generic jar " + genericJarFile.toString(), + Project.MSG_VERBOSE); + genericJarFile.delete(); } } + /** * Helper method invoked by execute() for each JOnAS jar to be built. - * Encapsulates the logic of constructing a java task for calling - * GenIC and executing it. + * Encapsulates the logic of constructing a java task for calling GenIC + * and executing it. + * * @param inBaseName the base name of the jar - * @param inSourceJar java.io.File representing the source (EJB1.1) jarfile. + * @param inSourceJar java.io.File representing the source (EJB1.1) + * jarfile. * @param someFiles list of files in the jar. Add all the new genererated - * files. + * files. * @param inPublicId the link to DTD (to rewrite JAR). - **/ + */ private void buildJOnASJar(final String inBaseName, - final File inSourceJar,final File inDestJar, - final Hashtable someFiles,String inPublicId) { - org.apache.tools.ant.taskdefs.Java aJavaTask = null; - String aGenIcClassName = genicClass; - boolean isOldGenIC = false; - boolean isTempDirectory = false; - File anOutputDirectoryFile = null; - - // do not call GenIC - // only copy file - if (noGENIC) { - try { - FileUtils.newFileUtils().copyFile(inSourceJar, inDestJar); - return; - } catch (IOException anIOException) { - throw new BuildException("Unable to write EJB jar", anIOException); - } - } - - // call GenIC - try { - aJavaTask = (Java) getTask().getProject().createTask("java"); - aJavaTask.setTaskName("genic"); - if(aGenIcClassName == null) { - aGenIcClassName = GENIC_CLASS; - } else if( OLD_GENIC_CLASS.equals(aGenIcClassName) ){ - isOldGenIC = true; - } - // ClassName - aJavaTask.setClassname(aGenIcClassName); - - // JVM Args - if( jonasroot == null ) { - throw new BuildException("Error : set the jonasroot parameter"); - } else if ( ! jonasroot.isDirectory() ) { - log("jonasroot attribut '" + jonasroot + "' is not a valid directory", - Project.MSG_ERR); - } - aJavaTask.createJvmarg().setValue("-Dinstall.root=" + jonasroot); - File aJavaPolicyFile = new File(jonasroot,"config/java.policy"); - if( aJavaPolicyFile.exists() ) { - aJavaTask.createJvmarg().setValue("-Djava.security.policy=" - + aJavaPolicyFile.toString() ); - } - - // Find output directory - if( ouputdirectory == null ) { - anOutputDirectoryFile = createTempDir(); - isTempDirectory = true; - log("Use temporary output directory : " + - anOutputDirectoryFile, Project.MSG_VERBOSE); - } else { - anOutputDirectoryFile = ouputdirectory; - log("Use temporary specific output directory : " + - anOutputDirectoryFile, Project.MSG_VERBOSE); - } - aJavaTask.createArg().setValue("-d"); - aJavaTask.createArg().setFile(anOutputDirectoryFile); - - // Additionnal args - aJavaTask.createArg().setLine(additionalArgs); - // KeepGenerated - if (keepgenerated) { - aJavaTask.createArg().setValue("-keepgenerated"); - } - - // Verbose - if( verbose ) { - aJavaTask.createArg().setValue("-verbose"); - } - - // -secpropag - if( secpropag ) { - aJavaTask.createArg().setValue("-secpropag"); - } - - // The compiler - if (compiler == null) { - // try to use the compiler specified by build.compiler. Right now we are just going - // to allow Jikes - String aBuildCompiler = getTask().getProject().getProperty("build.compiler"); - if ("jikes".equals(aBuildCompiler) ) { - aJavaTask.createArg().setValue("-javac"); - aJavaTask.createArg().setValue("jikes"); - } - } else { - if( ! "default".equals( compiler ) ) { - aJavaTask.createArg().setValue("-javac"); - aJavaTask.createArg().setLine(compiler); + final File inSourceJar, final File inDestJar, + final Hashtable someFiles, String inPublicId) { + org.apache.tools.ant.taskdefs.Java aJavaTask = null; + String aGenIcClassName = genicClass; + boolean isOldGenIC = false; + boolean isTempDirectory = false; + File anOutputDirectoryFile = null; + + // do not call GenIC + // only copy file + if (noGENIC) { + try { + FileUtils.newFileUtils().copyFile(inSourceJar, inDestJar); + return; + } catch (IOException anIOException) { + throw new BuildException("Unable to write EJB jar", anIOException); + } + } + + // call GenIC + try { + aJavaTask = (Java) getTask().getProject().createTask("java"); + aJavaTask.setTaskName("genic"); + if (aGenIcClassName == null) { + aGenIcClassName = GENIC_CLASS; + } else if (OLD_GENIC_CLASS.equals(aGenIcClassName)) { + isOldGenIC = true; + } + // ClassName + aJavaTask.setClassname(aGenIcClassName); + + // JVM Args + if (jonasroot == null) { + throw new BuildException("Error : set the jonasroot parameter"); + } else if (!jonasroot.isDirectory()) { + log("jonasroot attribut '" + jonasroot + "' is not a valid directory", + Project.MSG_ERR); + } + aJavaTask.createJvmarg().setValue("-Dinstall.root=" + jonasroot); + + File aJavaPolicyFile = new File(jonasroot, "config/java.policy"); + + if (aJavaPolicyFile.exists()) { + aJavaTask.createJvmarg().setValue("-Djava.security.policy=" + + aJavaPolicyFile.toString()); + } + + // Find output directory + if (ouputdirectory == null) { + anOutputDirectoryFile = createTempDir(); + isTempDirectory = true; + log("Use temporary output directory : " + + anOutputDirectoryFile, Project.MSG_VERBOSE); + } else { + anOutputDirectoryFile = ouputdirectory; + log("Use temporary specific output directory : " + + anOutputDirectoryFile, Project.MSG_VERBOSE); + } + aJavaTask.createArg().setValue("-d"); + aJavaTask.createArg().setFile(anOutputDirectoryFile); + + // Additionnal args + aJavaTask.createArg().setLine(additionalArgs); + // KeepGenerated + if (keepgenerated) { + aJavaTask.createArg().setValue("-keepgenerated"); + } + + // Verbose + if (verbose) { + aJavaTask.createArg().setValue("-verbose"); + } + + // -secpropag + if (secpropag) { + aJavaTask.createArg().setValue("-secpropag"); + } + + // The compiler + if (compiler == null) { + // try to use the compiler specified by build.compiler. Right now we are just going + // to allow Jikes + String aBuildCompiler = getTask().getProject().getProperty("build.compiler"); + + if ("jikes".equals(aBuildCompiler)) { + aJavaTask.createArg().setValue("-javac"); + aJavaTask.createArg().setValue("jikes"); + } + } else { + if (!"default".equals(compiler)) { + aJavaTask.createArg().setValue("-javac"); + aJavaTask.createArg().setLine(compiler); + } + } + + if (!isOldGenIC) { + // the add in jar features is buggy... + aJavaTask.createArg().setValue("-noaddinjar"); + } + + aJavaTask.createArg().setValue(inSourceJar.getPath()); + + // try to create the classpath for the correct ORB + Path aClasspath = getCombinedClasspath(); + + if (aClasspath == null) { + aClasspath = new Path(getTask().getProject()); + } + if (orb != null) { + String aOrbJar = new File(jonasroot, "lib/" + orb + "_jonas.jar").toString(); + String aConfigDir = new File(jonasroot, "config/").toString(); + Path aJOnASOrbPath = new Path(aClasspath.getProject(), + aOrbJar + File.pathSeparator + aConfigDir); + + aClasspath.append(aJOnASOrbPath); + } else { + log("No ORB propertie setup (RMI, JEREMIE, DAVID).", Project.MSG_WARN); + } + + // append the output directory + aClasspath.append(new Path(aClasspath.getProject(), anOutputDirectoryFile.getPath())); + aJavaTask.setClasspath(aClasspath); + + aJavaTask.setFork(true); + + log("Calling " + aGenIcClassName + " for " + inSourceJar.toString(), + Project.MSG_VERBOSE); + + if (aJavaTask.executeJava() != 0) { + throw new BuildException("GenIC reported an error"); + } + // Update the list of files. + addAllFiles(anOutputDirectoryFile, "", someFiles); + + // rewrite the jar with the new files + super.writeJar(inBaseName, inDestJar, someFiles, inPublicId); + } catch (BuildException aBuildException) { + throw aBuildException; + } catch (Exception e) { + // Have to catch this because of the semantics of calling main() + String msg = "Exception while calling " + aGenIcClassName + ". Details: " + e.toString(); + + throw new BuildException(msg, e); + } finally { + if (isTempDirectory && anOutputDirectoryFile != null) { + dellAllFiles(anOutputDirectoryFile); + } else if (cleanWorkDir && anOutputDirectoryFile != null) { + dellAllFilesInside(anOutputDirectoryFile); } - } - - if( ! isOldGenIC ) { - // the add in jar features is buggy... - aJavaTask.createArg().setValue("-noaddinjar"); - } - - aJavaTask.createArg().setValue(inSourceJar.getPath()); - - // try to create the classpath for the correct ORB - Path aClasspath = getCombinedClasspath(); - if( aClasspath == null ) { - aClasspath = new Path(getTask().getProject()); - } - if( orb != null ) { - String aOrbJar = new File(jonasroot,"lib/" + orb + "_jonas.jar").toString(); - String aConfigDir = new File(jonasroot,"config/").toString(); - Path aJOnASOrbPath = new Path(aClasspath.getProject(), - aOrbJar + File.pathSeparator + aConfigDir ); - aClasspath.append( aJOnASOrbPath ); - } else { - log("No ORB propertie setup (RMI, JEREMIE, DAVID).", Project.MSG_WARN); - } - - // append the output directory - aClasspath.append( new Path(aClasspath.getProject(), anOutputDirectoryFile.getPath())); - aJavaTask.setClasspath(aClasspath); - - - aJavaTask.setFork(true); - - log("Calling " + aGenIcClassName + " for " + inSourceJar.toString(), - Project.MSG_VERBOSE); - - if (aJavaTask.executeJava() != 0) { - throw new BuildException("GenIC reported an error"); - } - // Update the list of files. - addAllFiles(anOutputDirectoryFile,"",someFiles); - - // rewrite the jar with the new files - super.writeJar(inBaseName, inDestJar, someFiles, inPublicId); - } catch(BuildException aBuildException) { - throw aBuildException; - } catch (Exception e) { - // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling " + aGenIcClassName + ". Details: " + e.toString(); - throw new BuildException(msg, e); - } finally { - if( isTempDirectory && anOutputDirectoryFile != null) { - dellAllFiles(anOutputDirectoryFile); - } else if( cleanWorkDir && anOutputDirectoryFile != null) { - dellAllFilesInside(anOutputDirectoryFile); } - } - } + } + /** * Get the vendor specific name of the Jar that will be output. The * modification date of this jar will be checked against the dependent * bean classes. - **/ + */ File getVendorOutputJarFile(final String aBaseName) { return new File(getDestDir(), aBaseName + jarSuffix); } - /** - * Create a free tempory directory for GenIC output. - * @return directory file - * @throws BuildException if impossible to find a tempory directory - **/ - private File createTempDir() { - String theTempDir = System.getProperty("java.io.tmpdir"); - int anIndice = 0; - File aFile = null; - // try 50 times to find a free tempory directory - while( anIndice < 50 && aFile == null) { - aFile = new File(theTempDir,"GenicTemp" + anIndice); - if(aFile.exists()) { - anIndice++; - aFile = null; - } - } - - if( aFile == null ) { - // problem in temp directory - throw new BuildException("Impossible to find a free temp directory for output."); - } else { - aFile.mkdirs(); - return(aFile); - } - } - - - /** - * add all files in anOutputDir + ' / ' + aRootDir to the HashTable someFiles. - * - * @param anOutputDir - start directory - * @param aCurrentDirOrFile - a sub-directory to scan or a file to add. - * @param someFiles - where to add the files - **/ - private void addAllFiles(final File anOutputDir, String aCurrentDirOrFile, Hashtable someFiles) { - File aFile = new File(anOutputDir,aCurrentDirOrFile); - if( aFile.isDirectory() ) { - String aCurrentDir = ""; - if( aCurrentDirOrFile.length() > 0 ) { - aCurrentDir = aCurrentDirOrFile + '/'; - } - File theFiles[] = aFile.listFiles(); - for(int i=0;i 0) { + aCurrentDir = aCurrentDirOrFile + '/'; + } + File theFiles[] = aFile.listFiles(); + + for (int i = 0; i < theFiles.length; i++) { + addAllFiles(anOutputDir, aCurrentDir + theFiles[i].getName(), someFiles); + } + } else { + // is a file + someFiles.put(aCurrentDirOrFile, aFile); + } + } + + + /** + * Delete all the files in a directory + * + * @param aFile file to delete recursivly + */ + private void dellAllFiles(File aFile) { + if (aFile.isDirectory()) { + File someFiles[] = aFile.listFiles(); + + for (int i = 0; i < someFiles.length; i++) { + dellAllFiles(someFiles[i]); + } + } + aFile.delete(); + } + + + /** + * Delete all the files in a directory, but don't delete the directory + * + * @param aFile file to delete recursivly + */ + private void dellAllFilesInside(File aFile) { + if (aFile.isDirectory()) { + File someFiles[] = aFile.listFiles(); + + for (int i = 0; i < someFiles.length; i++) { + dellAllFiles(someFiles[i]); + } + } + } + } -// eof. + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WLRun.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WLRun.java index 2e00a3457..93275c736 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WLRun.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WLRun.java @@ -195,7 +195,7 @@ public class WLRun extends Task { if (securityPolicy == null) { securityPolicy = defaultSecurityPolicy; } - File securityPolicyFile = new File( weblogicSystemHome, securityPolicy ); + File securityPolicyFile = new File(weblogicSystemHome, securityPolicy); // If an explicit securityPolicy file was specified, it maybe an // absolute path. Use the project to resolve it. if (this.securityPolicy != null && !securityPolicyFile.exists()) { @@ -210,22 +210,25 @@ public class WLRun extends Task { } private void executeWLS6() { - File securityPolicyFile = findSecurityPolicyFile( DEFAULT_WL60_POLICY_FILE ); + File securityPolicyFile + = findSecurityPolicyFile(DEFAULT_WL60_POLICY_FILE); if (!beaHome.isDirectory()) { throw new BuildException("BEA home " + beaHome.getPath() + " is not valid"); } - File configFile = new File(weblogicSystemHome, "config/" + weblogicDomainName + "/config.xml"); + File configFile = new File(weblogicSystemHome, "config/" + + weblogicDomainName + "/config.xml"); if (!configFile.exists()) { - throw new BuildException("Server config file " + configFile + " not found."); + throw new BuildException("Server config file " + configFile + + " not found."); } if (managementPassword == null) { throw new BuildException("You must supply a management password to start the server"); } - Java weblogicServer = (Java)project.createTask("java"); + Java weblogicServer = (Java) project.createTask("java"); weblogicServer.setTaskName(getTaskName()); weblogicServer.setFork(true); weblogicServer.setDir(weblogicSystemHome); @@ -260,7 +263,8 @@ public class WLRun extends Task { } private void executeWLS() { - File securityPolicyFile = findSecurityPolicyFile( DEFAULT_WL51_POLICY_FILE ); + File securityPolicyFile + = findSecurityPolicyFile(DEFAULT_WL51_POLICY_FILE); File propertiesFile = null; @@ -278,7 +282,7 @@ public class WLRun extends Task { } } - Java weblogicServer = (Java)project.createTask("java"); + Java weblogicServer = (Java) project.createTask("java"); weblogicServer.setTaskName(getTaskName()); weblogicServer.setFork(true); weblogicServer.setClassname(weblogicMainClass); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java index 3da160bb3..e6cc05d8d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java @@ -51,7 +51,6 @@ * information on the Apache Software Foundation, please see * . */ - package org.apache.tools.ant.taskdefs.optional.ejb; import java.io.File; @@ -66,7 +65,6 @@ import java.util.Hashtable; import java.util.Iterator; import java.util.Enumeration; - import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import org.xml.sax.InputSource; @@ -80,27 +78,27 @@ import org.apache.tools.ant.util.FileUtils; public class WeblogicDeploymentTool extends GenericDeploymentTool { public final static String PUBLICID_EJB11 - = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"; + = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"; public final static String PUBLICID_EJB20 - = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"; + = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"; public final static String PUBLICID_WEBLOGIC_EJB510 - = "-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN"; + = "-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN"; public final static String PUBLICID_WEBLOGIC_EJB600 - = "-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN"; + = "-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN"; protected final static String DEFAULT_WL51_EJB11_DTD_LOCATION - = "/weblogic/ejb/deployment/xml/ejb-jar.dtd"; + = "/weblogic/ejb/deployment/xml/ejb-jar.dtd"; protected final static String DEFAULT_WL60_EJB11_DTD_LOCATION - = "/weblogic/ejb20/dd/xml/ejb11-jar.dtd"; + = "/weblogic/ejb20/dd/xml/ejb11-jar.dtd"; protected final static String DEFAULT_WL60_EJB20_DTD_LOCATION - = "/weblogic/ejb20/dd/xml/ejb20-jar.dtd"; + = "/weblogic/ejb20/dd/xml/ejb20-jar.dtd"; protected final static String DEFAULT_WL51_DTD_LOCATION - = "/weblogic/ejb/deployment/xml/weblogic-ejb-jar.dtd"; + = "/weblogic/ejb/deployment/xml/weblogic-ejb-jar.dtd"; protected final static String DEFAULT_WL60_51_DTD_LOCATION - = "/weblogic/ejb20/dd/xml/weblogic510-ejb-jar.dtd"; + = "/weblogic/ejb20/dd/xml/weblogic510-ejb-jar.dtd"; protected final static String DEFAULT_WL60_DTD_LOCATION - = "/weblogic/ejb20/dd/xml/weblogic600-ejb-jar.dtd"; + = "/weblogic/ejb20/dd/xml/weblogic600-ejb-jar.dtd"; protected final static String DEFAULT_COMPILER = "default"; @@ -122,7 +120,10 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { /** Instance variable that determines whether generic ejb jars are kept. */ private boolean keepgenerated = false; - /** Instance variable that stores the fully qualified classname of the weblogic EJBC compiler */ + /** + * Instance variable that stores the fully qualified classname of the + * weblogic EJBC compiler + */ private String ejbcClass = null; private String additionalArgs = ""; @@ -136,26 +137,24 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { /** controls whether ejbc is run on the generated jar */ private boolean noEJBC = false; - /** - * Indicates if the old CMP location convention is to be used. - */ + /** Indicates if the old CMP location convention is to be used. */ private boolean newCMP = false; /** The classpath to the weblogic classes. */ private Path wlClasspath = null; /** - * The weblogic.StdoutSeverityLevel to use when running the JVM that executes ejbc. - * Set to 16 to avoid the warnings about EJB Home and Remotes being in the classpath + * The weblogic.StdoutSeverityLevel to use when running the JVM that + * executes ejbc. Set to 16 to avoid the warnings about EJB Home and + * Remotes being in the classpath */ private Integer jvmDebugLevel = null; /** File utilities instance for copying jars */ private FileUtils fileUtils = FileUtils.newFileUtils(); - - /** - * Get the classpath to the weblogic classpaths - */ + + + /** Get the classpath to the weblogic classpaths */ public Path createWLClasspath() { if (wlClasspath == null) { wlClasspath = new Path(getTask().getProject()); @@ -163,36 +162,38 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { return wlClasspath.createPath(); } + public void setWLClasspath(Path wlClasspath) { this.wlClasspath = wlClasspath; } - /** - * The compiler (switch -compiler) to use - */ + + /** The compiler (switch -compiler) to use */ public void setCompiler(String compiler) { this.compiler = compiler; } + /** - * Set the rebuild flag to false to only update changes in the - * jar rather than rerunning ejbc + * Set the rebuild flag to false to only update changes in the jar rather + * than rerunning ejbc */ public void setRebuild(boolean rebuild) { this.alwaysRebuild = rebuild; } + /** - * Sets the weblogic.StdoutSeverityLevel to use when running the JVM that executes ejbc. - * Set to 16 to avoid the warnings about EJB Home and Remotes being in the classpath + * Sets the weblogic.StdoutSeverityLevel to use when running the JVM that + * executes ejbc. Set to 16 to avoid the warnings about EJB Home and + * Remotes being in the classpath */ - public void setJvmDebugLevel(Integer jvmDebugLevel) - { + public void setJvmDebugLevel(Integer jvmDebugLevel) { this.jvmDebugLevel = jvmDebugLevel; } - public Integer getJvmDebugLevel() - { + + public Integer getJvmDebugLevel() { return jvmDebugLevel; } @@ -200,110 +201,113 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { /** * Setter used to store the suffix for the generated weblogic jar file. + * * @param inString the string to use as the suffix. */ public void setSuffix(String inString) { this.jarSuffix = inString; } + /** * Setter used to store the value of keepGeneric + * * @param inValue a string, either 'true' or 'false'. */ public void setKeepgeneric(boolean inValue) { this.keepGeneric = inValue; } + /** - * Sets whether -keepgenerated is passed to ejbc (that is, - * the .java source files are kept). + * Sets whether -keepgenerated is passed to ejbc (that is, the .java + * source files are kept). + * * @param inValue either 'true' or 'false' */ public void setKeepgenerated(String inValue) { this.keepgenerated = Boolean.valueOf(inValue).booleanValue(); } - /** - * sets some additional args to send to ejbc. - */ + + /** sets some additional args to send to ejbc. */ public void setArgs(String args) { this.additionalArgs = args; } - /** - * Set the classname of the ejbc compiler - */ - public void setEjbcClass(String ejbcClass) - { + + /** Set the classname of the ejbc compiler */ + public void setEjbcClass(String ejbcClass) { this.ejbcClass = ejbcClass; } - /** - * Get the ejbc compiler class - */ - public String getEjbcClass() - { + + /** Get the ejbc compiler class */ + public String getEjbcClass() { return ejbcClass; } /** - * Setter used to store the location of the ejb-jar DTD. This can be a file on the system - * or a resource on the classpath. + * Setter used to store the location of the ejb-jar DTD. This can be a + * file on the system or a resource on the classpath. + * * @param inString the string to use as the DTD location. */ public void setWeblogicdtd(String inString) { setEJBdtd(inString); } + /** - * Setter used to store the location of the weblogic DTD. This can be a file on the system - * or a resource on the classpath. + * Setter used to store the location of the weblogic DTD. This can be a + * file on the system or a resource on the classpath. + * * @param inString the string to use as the DTD location. */ public void setWLdtd(String inString) { this.weblogicDTD = inString; } + /** - * Setter used to store the location of the Sun's Generic EJB DTD. - * This can be a file on the system or a resource on the classpath. + * Setter used to store the location of the Sun's Generic EJB DTD. This + * can be a file on the system or a resource on the classpath. + * * @param inString the string to use as the DTD location. */ public void setEJBdtd(String inString) { this.ejb11DTD = inString; } + /** - * Set the value of the oldCMP scheme. This is an antonym for - * newCMP + * Set the value of the oldCMP scheme. This is an antonym for newCMP */ public void setOldCMP(boolean oldCMP) { this.newCMP = !oldCMP; } + /** * Set the value of the newCMP scheme. The old CMP scheme locates the * weblogic CMP descriptor based on the naming convention where the - * weblogic CMP file is expected to be named with the bean name as the prefix. - * - * Under this scheme the name of the CMP descriptor does not match the name - * actually used in the main weblogic EJB descriptor. Also, descriptors which - * contain multiple CMP references could not be used. - * + * weblogic CMP file is expected to be named with the bean name as the + * prefix. Under this scheme the name of the CMP descriptor does not match + * the name actually used in the main weblogic EJB descriptor. Also, + * descriptors which contain multiple CMP references could not be used. */ public void setNewCMP(boolean newCMP) { this.newCMP = newCMP; } - /** - * Do not EJBC the jar after it has been put together. - * - */ + + /** Do not EJBC the jar after it has been put together. */ public void setNoEJBC(boolean noEJBC) { this.noEJBC = noEJBC; } + protected void registerKnownDTDs(DescriptorHandler handler) { // register all the known DTDs handler.registerDTD(PUBLICID_EJB11, DEFAULT_WL51_EJB11_DTD_LOCATION); @@ -312,6 +316,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { handler.registerDTD(PUBLICID_EJB20, DEFAULT_WL60_EJB20_DTD_LOCATION); } + protected DescriptorHandler getWeblogicDescriptorHandler(final File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir) { @@ -320,8 +325,9 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { // Get the filename of vendor specific descriptor String fileNameWithMETA = currentText; //trim the META_INF\ off of the file name - String fileName = fileNameWithMETA.substring(META_DIR.length(), - fileNameWithMETA.length() ); + String fileName + = fileNameWithMETA.substring(META_DIR.length(), + fileNameWithMETA.length()); File descriptorFile = new File(srcDir, fileName); ejbFiles.put(fileNameWithMETA, descriptorFile); @@ -336,24 +342,24 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { handler.registerDTD(PUBLICID_WEBLOGIC_EJB600, weblogicDTD); for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation)i.next(); + EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); + handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; } + /** - * Add any vendor specific files which should be included in the - * EJB Jar. + * Add any vendor specific files which should be included in the EJB Jar. */ protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { File weblogicDD = new File(getConfig().descriptorDir, ddPrefix + WL_DD); if (weblogicDD.exists()) { ejbFiles.put(META_DIR + WL_DD, - weblogicDD); - } - else { + weblogicDD); + } else { log("Unable to locate weblogic deployment descriptor. It was expected to be in " + weblogicDD.getPath(), Project.MSG_WARN); return; @@ -368,56 +374,62 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { if (weblogicCMPDD.exists()) { ejbFiles.put(META_DIR + WL_CMP_DD, - weblogicCMPDD); + weblogicCMPDD); } - } - else { + } else { // now that we have the weblogic descriptor, we parse the file // to find other descriptors needed to deploy the bean. // this could be the weblogic-cmp-rdbms.xml or any other O/R // mapping tool descriptors. - try - { - File ejbDescriptor = (File)ejbFiles.get(META_DIR + EJB_DD); + try { + File ejbDescriptor = (File) ejbFiles.get(META_DIR + EJB_DD); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); + saxParserFactory.setValidating(true); + SAXParser saxParser = saxParserFactory.newSAXParser(); DescriptorHandler handler = getWeblogicDescriptorHandler(ejbDescriptor.getParentFile()); + saxParser.parse(new InputSource - (new FileInputStream - (weblogicDD)), - handler); + (new FileInputStream + (weblogicDD)), + handler); Hashtable ht = handler.getFiles(); Enumeration e = ht.keys(); - while(e.hasMoreElements()){ - String key = (String)e.nextElement(); + + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + ejbFiles.put(key, ht.get(key)); } - } - catch(Exception e) - { + } catch (Exception e) { String msg = "Exception while adding Vendor specific files: " + e.toString(); + throw new BuildException(msg, e); } } } + /** - * Get the vendor specific name of the Jar that will be output. The modification date - * of this jar will be checked against the dependent bean classes. + * Get the vendor specific name of the Jar that will be output. The + * modification date of this jar will be checked against the dependent + * bean classes. */ File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + jarSuffix); } + /** * Helper method invoked by execute() for each WebLogic jar to be built. * Encapsulates the logic of constructing a java task for calling * weblogic.ejbc and executing it. + * * @param sourceJar java.io.File representing the source (EJB1.1) jarfile. * @param destJar java.io.File representing the destination, WebLogic - * jarfile. + * jarfile. */ private void buildWeblogicJar(File sourceJar, File destJar, String publicId) { org.apache.tools.ant.taskdefs.Java javaTask = null; @@ -429,8 +441,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { sourceJar.delete(); } return; - } - catch (IOException e) { + } catch (IOException e) { throw new BuildException("Unable to write EJB jar", e); } } @@ -441,20 +452,17 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { javaTask = (Java) getTask().getProject().createTask("java"); javaTask.setTaskName("ejbc"); - if (getJvmDebugLevel() != null) - { - javaTask.createJvmarg().setLine(" -Dweblogic.StdoutSeverityLevel=" + jvmDebugLevel); + if (getJvmDebugLevel() != null) { + javaTask.createJvmarg().setLine(" -Dweblogic.StdoutSeverityLevel=" + jvmDebugLevel); } if (ejbcClassName == null) { // try to determine it from publicId if (PUBLICID_EJB11.equals(publicId)) { ejbcClassName = COMPILER_EJB11; - } - else if (PUBLICID_EJB20.equals(publicId)) { + } else if (PUBLICID_EJB20.equals(publicId)) { ejbcClassName = COMPILER_EJB20; - } - else { + } else { log("Unrecognized publicId " + publicId + " - using EJB 1.1 compiler", Project.MSG_WARN); ejbcClassName = COMPILER_EJB11; } @@ -469,12 +477,12 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { // try to use the compiler specified by build.compiler. Right now we are just going // to allow Jikes String buildCompiler = getTask().getProject().getProperty("build.compiler"); + if (buildCompiler != null && buildCompiler.equals("jikes")) { javaTask.createArg().setValue("-compiler"); javaTask.createArg().setValue("jikes"); } - } - else { + } else { if (!compiler.equals(DEFAULT_COMPILER)) { javaTask.createArg().setValue("-compiler"); javaTask.createArg().setLine(compiler); @@ -484,6 +492,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { javaTask.createArg().setValue(destJar.getPath()); Path classpath = wlClasspath; + if (classpath == null) { classpath = getCombinedClasspath(); } @@ -494,44 +503,45 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { } log("Calling " + ejbcClassName + " for " + sourceJar.toString(), - Project.MSG_VERBOSE); + Project.MSG_VERBOSE); if (javaTask.executeJava() != 0) { throw new BuildException("Ejbc reported an error"); } - } - catch (Exception e) { + } catch (Exception e) { // Have to catch this because of the semantics of calling main() String msg = "Exception while calling " + ejbcClassName + ". Details: " + e.toString(); + throw new BuildException(msg, e); } } + /** - * Method used to encapsulate the writing of the JAR file. Iterates over the - * filenames/java.io.Files in the Hashtable stored on the instance variable - * ejbFiles. + * Method used to encapsulate the writing of the JAR file. Iterates over + * the filenames/java.io.Files in the Hashtable stored on the instance + * variable ejbFiles. */ protected void writeJar(String baseName, File jarFile, Hashtable files, String publicId) throws BuildException { // need to create a generic jar first. File genericJarFile = super.getVendorOutputJarFile(baseName); + super.writeJar(baseName, genericJarFile, files, publicId); - if (alwaysRebuild || isRebuildRequired(genericJarFile, jarFile)) - { + if (alwaysRebuild || isRebuildRequired(genericJarFile, jarFile)) { buildWeblogicJar(genericJarFile, jarFile, publicId); } if (!keepGeneric) { - log("deleting generic jar " + genericJarFile.toString(), - Project.MSG_VERBOSE); - genericJarFile.delete(); + log("deleting generic jar " + genericJarFile.toString(), + Project.MSG_VERBOSE); + genericJarFile.delete(); } } + /** * Called to validate that the tool parameters have been configured. - * */ public void validateConfigured() throws BuildException { super.validateConfigured(); @@ -539,26 +549,30 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { /** - * Helper method to check to see if a weblogic EBJ1.1 jar needs to be rebuilt using - * ejbc. Called from writeJar it sees if the "Bean" classes are the only thing that needs - * to be updated and either updates the Jar with the Bean classfile or returns true, - * saying that the whole weblogic jar needs to be regened with ejbc. This allows faster - * build times for working developers. - *

- * The way weblogic ejbc works is it creates wrappers for the publicly defined methods as - * they are exposed in the remote interface. If the actual bean changes without changing the - * the method signatures then only the bean classfile needs to be updated and the rest of the - * weblogic jar file can remain the same. If the Interfaces, ie. the method signatures change - * or if the xml deployment dicriptors changed, the whole jar needs to be rebuilt with ejbc. - * This is not strictly true for the xml files. If the JNDI name changes then the jar doesnt - * have to be rebuild, but if the resources references change then it does. At this point the - * weblogic jar gets rebuilt if the xml files change at all. + * Helper method to check to see if a weblogic EBJ1.1 jar needs to be + * rebuilt using ejbc. Called from writeJar it sees if the "Bean" classes + * are the only thing that needs to be updated and either updates the Jar + * with the Bean classfile or returns true, saying that the whole weblogic + * jar needs to be regened with ejbc. This allows faster build times for + * working developers.

+ * + * The way weblogic ejbc works is it creates wrappers for the publicly + * defined methods as they are exposed in the remote interface. If the + * actual bean changes without changing the the method signatures then + * only the bean classfile needs to be updated and the rest of the + * weblogic jar file can remain the same. If the Interfaces, ie. the + * method signatures change or if the xml deployment dicriptors changed, + * the whole jar needs to be rebuilt with ejbc. This is not strictly true + * for the xml files. If the JNDI name changes then the jar doesnt have to + * be rebuild, but if the resources references change then it does. At + * this point the weblogic jar gets rebuilt if the xml files change at + * all. * * @param genericJarFile java.io.File The generic jar file. - * @param weblogicJarFile java.io.File The weblogic jar file to check to see if it needs to be rebuilt. + * @param weblogicJarFile java.io.File The weblogic jar file to check to + * see if it needs to be rebuilt. */ - protected boolean isRebuildRequired(File genericJarFile, File weblogicJarFile) - { + protected boolean isRebuildRequired(File genericJarFile, File weblogicJarFile) { boolean rebuild = false; JarFile genericJar = null; @@ -566,14 +580,12 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { File newWLJarFile = null; JarOutputStream newJarStream = null; - try - { + try { log("Checking if weblogic Jar needs to be rebuilt for jar " + weblogicJarFile.getName(), Project.MSG_VERBOSE); // Only go forward if the generic and the weblogic file both exist if (genericJarFile.exists() && genericJarFile.isFile() - && weblogicJarFile.exists() && weblogicJarFile.isFile()) - { + && weblogicJarFile.exists() && weblogicJarFile.isFile()) { //open jar files genericJar = new JarFile(genericJarFile); wlJar = new JarFile(weblogicJarFile); @@ -583,73 +595,70 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { Hashtable replaceEntries = new Hashtable(); //get the list of generic jar entries - for (Enumeration e = genericJar.entries(); e.hasMoreElements();) - { - JarEntry je = (JarEntry)e.nextElement(); + for (Enumeration e = genericJar.entries(); e.hasMoreElements();) { + JarEntry je = (JarEntry) e.nextElement(); + genericEntries.put(je.getName().replace('\\', '/'), je); } //get the list of weblogic jar entries - for (Enumeration e = wlJar.entries() ; e.hasMoreElements();) - { - JarEntry je = (JarEntry)e.nextElement(); + for (Enumeration e = wlJar.entries(); e.hasMoreElements();) { + JarEntry je = (JarEntry) e.nextElement(); + wlEntries.put(je.getName(), je); } //Cycle Through generic and make sure its in weblogic ClassLoader genericLoader = getClassLoaderFromJar(genericJarFile); - for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) - { - String filepath = (String)e.nextElement(); - if (wlEntries.containsKey(filepath)) // File name/path match - { + + for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) { + String filepath = (String) e.nextElement(); + + if (wlEntries.containsKey(filepath)) {// File name/path match + // Check files see if same - JarEntry genericEntry = (JarEntry)genericEntries.get(filepath); - JarEntry wlEntry = (JarEntry)wlEntries.get(filepath); - if ((genericEntry.getCrc() != wlEntry.getCrc()) || // Crc's Match - (genericEntry.getSize() != wlEntry.getSize()) ) // Size Match - { - if (genericEntry.getName().endsWith(".class")) - { + JarEntry genericEntry = (JarEntry) genericEntries.get(filepath); + JarEntry wlEntry = (JarEntry) wlEntries.get(filepath); + + if ((genericEntry.getCrc() != wlEntry.getCrc()) || // Crc's Match + (genericEntry.getSize() != wlEntry.getSize())) {// Size Match + + if (genericEntry.getName().endsWith(".class")) { //File are different see if its an object or an interface - String classname = genericEntry.getName().replace(File.separatorChar,'.'); - classname = classname.substring(0,classname.lastIndexOf(".class")); + String classname = genericEntry.getName().replace(File.separatorChar, '.'); + + classname = classname.substring(0, classname.lastIndexOf(".class")); + Class genclass = genericLoader.loadClass(classname); - if (genclass.isInterface()) - { + + if (genclass.isInterface()) { //Interface changed rebuild jar. - log("Interface " + genclass.getName() + " has changed",Project.MSG_VERBOSE); + log("Interface " + genclass.getName() + " has changed", Project.MSG_VERBOSE); rebuild = true; break; - } - else - { + } else { //Object class Changed update it. replaceEntries.put(filepath, genericEntry); } - } - else - { + } else { // is it the manifest. If so ignore it if (!genericEntry.getName().equals("META-INF/MANIFEST.MF")) { //File other then class changed rebuild - log("Non class file " + genericEntry.getName() + " has changed",Project.MSG_VERBOSE); + log("Non class file " + genericEntry.getName() + " has changed", Project.MSG_VERBOSE); rebuild = true; break; } } } - } - else // a file doesnt exist rebuild - { - log("File " + filepath + " not present in weblogic jar",Project.MSG_VERBOSE); - rebuild = true; + } else {// a file doesnt exist rebuild + + log("File " + filepath + " not present in weblogic jar", Project.MSG_VERBOSE); + rebuild = true; break; } } - if (!rebuild) - { - log("No rebuild needed - updating jar",Project.MSG_VERBOSE); + if (!rebuild) { + log("No rebuild needed - updating jar", Project.MSG_VERBOSE); newWLJarFile = new File(weblogicJarFile.getAbsolutePath() + ".temp"); if (newWLJarFile.exists()) { newWLJarFile.delete(); @@ -659,85 +668,76 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { newJarStream.setLevel(0); //Copy files from old weblogic jar - for (Enumeration e = wlEntries.elements() ; e.hasMoreElements();) - { + for (Enumeration e = wlEntries.elements(); e.hasMoreElements();) { byte[] buffer = new byte[1024]; int bytesRead; InputStream is; - JarEntry je = (JarEntry)e.nextElement(); + JarEntry je = (JarEntry) e.nextElement(); + if (je.getCompressedSize() == -1 || - je.getCompressedSize() == je.getSize()) { + je.getCompressedSize() == je.getSize()) { newJarStream.setLevel(0); - } - else { + } else { newJarStream.setLevel(9); } // Update with changed Bean class - if (replaceEntries.containsKey(je.getName())) - { - log("Updating Bean class from generic Jar " + je.getName(),Project.MSG_VERBOSE); + if (replaceEntries.containsKey(je.getName())) { + log("Updating Bean class from generic Jar " + je.getName(), Project.MSG_VERBOSE); // Use the entry from the generic jar - je = (JarEntry)replaceEntries.get(je.getName()); + je = (JarEntry) replaceEntries.get(je.getName()); is = genericJar.getInputStream(je); - } - else //use fle from original weblogic jar - { + } else {//use fle from original weblogic jar + is = wlJar.getInputStream(je); } newJarStream.putNextEntry(new JarEntry(je.getName())); - while ((bytesRead = is.read(buffer)) != -1) - { - newJarStream.write(buffer,0,bytesRead); + while ((bytesRead = is.read(buffer)) != -1) { + newJarStream.write(buffer, 0, bytesRead); } is.close(); } + } else { + log("Weblogic Jar rebuild needed due to changed " + + "interface or XML", Project.MSG_VERBOSE); } - else - { - log("Weblogic Jar rebuild needed due to changed interface or XML",Project.MSG_VERBOSE); - } - } - else - { + } else { rebuild = true; } - } - catch(ClassNotFoundException cnfe) - { + } catch (ClassNotFoundException cnfe) { String cnfmsg = "ClassNotFoundException while processing ejb-jar file" - + ". Details: " - + cnfe.getMessage(); + + ". Details: " + + cnfe.getMessage(); + throw new BuildException(cnfmsg, cnfe); - } - catch(IOException ioe) { + } catch (IOException ioe) { String msg = "IOException while processing ejb-jar file " - + ". Details: " - + ioe.getMessage(); + + ". Details: " + + ioe.getMessage(); + throw new BuildException(msg, ioe); - } - finally { + } finally { // need to close files and perhaps rename output if (genericJar != null) { try { genericJar.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} } if (wlJar != null) { try { wlJar.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} } if (newJarStream != null) { try { newJarStream.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} weblogicJarFile.delete(); newWLJarFile.renameTo(weblogicJarFile); @@ -750,18 +750,20 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { return rebuild; } + /** - * Helper method invoked by isRebuildRequired to get a ClassLoader for - * a Jar File passed to it. - * - * @param classjar java.io.File representing jar file to get classes from. - */ - protected ClassLoader getClassLoaderFromJar(File classjar) throws IOException - { + * Helper method invoked by isRebuildRequired to get a ClassLoader for a + * Jar File passed to it. + * + * @param classjar java.io.File representing jar file to get classes from. + */ + protected ClassLoader getClassLoaderFromJar(File classjar) throws IOException { Path lookupPath = new Path(getTask().getProject()); + lookupPath.setLocation(classjar); Path classpath = getCombinedClasspath(); + if (classpath != null) { lookupPath.append(classpath); } @@ -769,3 +771,4 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { return new AntClassLoader(getTask().getProject(), lookupPath); } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java index a1c2fa075..b4053fb0c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java @@ -128,7 +128,8 @@ public class WeblogicTOPLinkDeploymentTool extends WeblogicDeploymentTool { public void validateConfigured() throws BuildException { super.validateConfigured(); if (toplinkDescriptor == null) { - throw new BuildException( "The toplinkdescriptor attribute must be specified" ); + throw new BuildException("The toplinkdescriptor attribute must " + + "be specified"); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java index 66d443261..ff2121a22 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java @@ -51,7 +51,6 @@ * information on the Apache Software Foundation, please see * . */ - package org.apache.tools.ant.taskdefs.optional.ejb; import java.io.File; @@ -73,9 +72,6 @@ import java.util.Hashtable; import java.util.Enumeration; - - - import org.apache.tools.ant.Project; import org.apache.tools.ant.BuildException; @@ -92,55 +88,57 @@ import org.apache.tools.ant.types.Commandline; /** * Websphere deployment tool that augments the ejbjar task. + * * @author Maneesh Sahu */ public class WebsphereDeploymentTool extends GenericDeploymentTool { /** * Enumerated attribute with the values for the database vendor types + * + * @author Conor MacNeill */ public static class DBVendor extends EnumeratedAttribute { public String[] getValues() { - return new String[] { + return new String[]{ "SQL92", "SQL99", "DB2UDBWIN_V71", "DB2UDBOS390_V6", "DB2UDBAS400_V4R5", - "ORACLE_V8", "INFORMIX_V92", "SYBASE_V1192", "MSSQLSERVER_V7", "MYSQL_V323" - }; + "ORACLE_V8", "INFORMIX_V92", "SYBASE_V1192", "MSSQLSERVER_V7", "MYSQL_V323" + }; } } - + + public final static String PUBLICID_EJB11 - = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"; + = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"; public final static String PUBLICID_EJB20 - = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"; + = "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"; protected final static String SCHEMA_DIR = "Schema/"; - + protected final static String WAS_EXT = "ibm-ejb-jar-ext.xmi"; protected final static String WAS_BND = "ibm-ejb-jar-bnd.xmi"; protected final static String WAS_CMP_MAP = "Map.mapxmi"; protected final static String WAS_CMP_SCHEMA = "Schema.dbxmi"; - + /** Instance variable that stores the suffix for the websphere jarfile. */ private String jarSuffix = ".jar"; - + /** Instance variable that stores the location of the ejb 1.1 DTD file. */ private String ejb11DTD; - + /** Instance variable that determines whether generic ejb jars are kept. */ - + private boolean keepgenerated = false; - + private String additionalArgs = ""; - + private boolean keepGeneric = false; - + private String compiler = null; - + private boolean alwaysRebuild = true; private boolean ejbdeploy = true; - /** - * Indicates if the old CMP location convention is to be used. - */ + /** Indicates if the old CMP location convention is to be used. */ private boolean newCMP = false; /** The classpath to the websphere classes. */ @@ -148,389 +146,426 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { /** The DB Vendor name, the EJB is persisted against */ private String dbVendor; - + /** The name of the database to create. (For top-down mapping only) */ private String dbName; - + /** The name of the schema to create. (For top-down mappings only) */ private String dbSchema; - + /** true - Only generate the deployment code, do not run RMIC or Javac */ private boolean codegen; - + /** true - Only output error messages, suppress informational messages */ private boolean quiet = true; - + /** true - Disable the validation steps */ private boolean novalidate; - + /** true - Disable warning and informational messages */ private boolean nowarn; - + /** true - Disable informational messages */ private boolean noinform; - + /** true - Enable internal tracing */ private boolean trace; - + /** Additional options for RMIC */ private String rmicOptions; - - /** true- Use the WebSphere 3.5 compatible mapping rules */ + + /** true- Use the WebSphere 3.5 compatible mapping rules */ private boolean use35MappingRules; - + /** the scratchdir for the ejbdeploy operation */ private String tempdir = "_ejbdeploy_temp"; - - /** - * Get the classpath to the websphere classpaths - */ + + + /** Get the classpath to the websphere classpaths */ public Path createWASClasspath() { if (wasClasspath == null) { wasClasspath = new Path(getTask().getProject()); } return wasClasspath.createPath(); } - + + public void setWASClasspath(Path wasClasspath) { this.wasClasspath = wasClasspath; } - - /** - * Sets the DB Vendor for the Entity Bean mapping - */ + + + /** Sets the DB Vendor for the Entity Bean mapping */ public void setDbvendor(DBVendor dbvendor) { this.dbVendor = dbvendor.getValue(); } - + + /** * Sets the name of the Database to create + * * @param String */ public void setDbname(String dbName) { this.dbName = dbName; } - + + /** * Sets the name of the schema to create + * * @param String */ public void setDbschema(String dbSchema) { this.dbSchema = dbSchema; } - + + /** * (true) Only generate the deployment code, do not run RMIC or Javac + * * @param boolean */ public void setCodegen(boolean codegen) { this.codegen = codegen; } - + + /** * (true) Only output error messages, suppress informational messages + * * @param boolean */ public void setQuiet(boolean quiet) { this.quiet = quiet; } - + + /** * (true) Disable the validation steps + * * @param boolean */ public void setNovalidate(boolean novalidate) { this.novalidate = novalidate; } - + + /** * (true) Disable warning and informational messages + * * @param boolean */ public void setNowarn(boolean nowarn) { this.nowarn = nowarn; } - + + /** * (true) Disable informational messages + * * @param boolean */ public void setNoinform(boolean noinfom) { this.noinform = noinform; } - + + /** - * (true) Enable internal tracing + * (true) Enable internal tracing + * * @param boolean */ public void setTrace(boolean trace) { this.trace = trace; } - + + /** * (true) Use the WebSphere 3.5 compatible mapping rules + * * @param boolean */ public void setUse35(boolean attr) { use35MappingRules = attr; } - - /** - * The compiler (switch -compiler) to use - */ + + + /** The compiler (switch -compiler) to use */ public void setCompiler(String compiler) { this.compiler = compiler; } - + + /** - * Set the rebuild flag to false to only update changes in the - * jar rather than rerunning ejbdeploy + * Set the rebuild flag to false to only update changes in the jar rather + * than rerunning ejbdeploy */ public void setRebuild(boolean rebuild) { this.alwaysRebuild = rebuild; } - - + + /** * Setter used to store the suffix for the generated websphere jar file. + * * @param inString the string to use as the suffix. */ public void setSuffix(String inString) { this.jarSuffix = inString; } - + + /** * Setter used to store the value of keepGeneric + * * @param inValue a string, either 'true' or 'false'. */ public void setKeepgeneric(boolean inValue) { this.keepGeneric = inValue; } - + + /** - * Sets whether -keepgenerated is passed to ejbdeploy (that is, - * the .java source files are kept). + * Sets whether -keepgenerated is passed to ejbdeploy (that is, the .java + * source files are kept). + * * @param inValue either 'true' or 'false' */ public void setKeepgenerated(String inValue) { this.keepgenerated = Boolean.valueOf(inValue).booleanValue(); } - + + /** * Decide, wether ejbdeploy should be called or not - * @param ejbdeploy + * + * @param ejbdeploy */ public void setEjbdeploy(boolean ejbdeploy) { this.ejbdeploy = ejbdeploy; } - /** - * sets some additional args to send to ejbdeploy. - */ + + /** sets some additional args to send to ejbdeploy. */ public void setArgs(String args) { this.additionalArgs = args; } - + + /** - * Setter used to store the location of the Sun's Generic EJB DTD. - * This can be a file on the system or a resource on the classpath. + * Setter used to store the location of the Sun's Generic EJB DTD. This + * can be a file on the system or a resource on the classpath. + * * @param inString the string to use as the DTD location. */ public void setEJBdtd(String inString) { this.ejb11DTD = inString; } - + + /** - * Set the value of the oldCMP scheme. This is an antonym for - * newCMP + * Set the value of the oldCMP scheme. This is an antonym for newCMP */ public void setOldCMP(boolean oldCMP) { this.newCMP = !oldCMP; } - + + /** * Set the value of the newCMP scheme. The old CMP scheme locates the * websphere CMP descriptor based on the naming convention where the - * websphere CMP file is expected to be named with the bean name as the prefix. - * - * Under this scheme the name of the CMP descriptor does not match the name - * actually used in the main websphere EJB descriptor. Also, descriptors which - * contain multiple CMP references could not be used. - * + * websphere CMP file is expected to be named with the bean name as the + * prefix. Under this scheme the name of the CMP descriptor does not match + * the name actually used in the main websphere EJB descriptor. Also, + * descriptors which contain multiple CMP references could not be used. */ public void setNewCMP(boolean newCMP) { this.newCMP = newCMP; } - - /** - * Sets the temporary directory for the ejbdeploy task - */ + + + /** Sets the temporary directory for the ejbdeploy task */ public void setTempdir(String tempdir) { this.tempdir = tempdir; } - + + protected DescriptorHandler getDescriptorHandler(File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir); // register all the DTDs, both the ones that are known and // any supplied by the user handler.registerDTD(PUBLICID_EJB11, ejb11DTD); - + for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation)i.next(); + EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); + handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } - + return handler; } - + + protected DescriptorHandler getWebsphereDescriptorHandler(final File srcDir) { - DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir) { + DescriptorHandler handler = + new DescriptorHandler(getTask(), srcDir) { protected void processElement() { } }; - + for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation)i.next(); + EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); + handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; } - + + /** - * Add any vendor specific files which should be included in the - * EJB Jar. + * Add any vendor specific files which should be included in the EJB Jar. */ protected void addVendorFiles(Hashtable ejbFiles, String baseName) { String ddPrefix = (usingBaseJarName() ? "" : baseName); - String dbPrefix = (dbVendor == null)? "": dbVendor + "-"; - + String dbPrefix = (dbVendor == null) ? "" : dbVendor + "-"; + // Get the Extensions document File websphereEXT = new File(getConfig().descriptorDir, ddPrefix + WAS_EXT); + if (websphereEXT.exists()) { ejbFiles.put(META_DIR + WAS_EXT, - websphereEXT); + websphereEXT); } else { log("Unable to locate websphere extensions. It was expected to be in " + websphereEXT.getPath(), Project.MSG_VERBOSE); } - + File websphereBND = new File(getConfig().descriptorDir, ddPrefix + WAS_BND); + if (websphereBND.exists()) { ejbFiles.put(META_DIR + WAS_BND, - websphereBND); - }else { + websphereBND); + } else { log("Unable to locate websphere bindings. It was expected to be in " + websphereBND.getPath(), Project.MSG_VERBOSE); } - + if (!newCMP) { log("The old method for locating CMP files has been DEPRECATED.", Project.MSG_VERBOSE); log("Please adjust your websphere descriptor and set newCMP=\"true\" " + "to use the new CMP descriptor inclusion mechanism. ", Project.MSG_VERBOSE); - } - else { + } else { // We attempt to put in the MAP and Schema files of CMP beans - try - { - // Add the Map file - File websphereMAP = new File(getConfig().descriptorDir, - ddPrefix + dbPrefix + WAS_CMP_MAP); - if (websphereMAP.exists()) { - ejbFiles.put(META_DIR + WAS_CMP_MAP, - websphereMAP); - } else { - log("Unable to locate the websphere Map: " + - websphereMAP.getPath(), Project.MSG_VERBOSE); - } - File websphereSchema = new File(getConfig().descriptorDir, - ddPrefix + dbPrefix + WAS_CMP_SCHEMA); - if (websphereSchema.exists()) { - ejbFiles.put(META_DIR + SCHEMA_DIR + WAS_CMP_SCHEMA, - websphereSchema); - } else { - log("Unable to locate the websphere Schema: " + - websphereSchema.getPath(), Project.MSG_VERBOSE); - } - // Theres nothing else to see here...keep moving sonny + try { + // Add the Map file + File websphereMAP = new File(getConfig().descriptorDir, + ddPrefix + dbPrefix + WAS_CMP_MAP); + + if (websphereMAP.exists()) { + ejbFiles.put(META_DIR + WAS_CMP_MAP, + websphereMAP); + } else { + log("Unable to locate the websphere Map: " + + websphereMAP.getPath(), Project.MSG_VERBOSE); } - catch(Exception e) - { - String msg = "Exception while adding Vendor specific files: " + - e.toString(); - throw new BuildException(msg, e); + + File websphereSchema = new File(getConfig().descriptorDir, + ddPrefix + dbPrefix + WAS_CMP_SCHEMA); + + if (websphereSchema.exists()) { + ejbFiles.put(META_DIR + SCHEMA_DIR + WAS_CMP_SCHEMA, + websphereSchema); + } else { + log("Unable to locate the websphere Schema: " + + websphereSchema.getPath(), Project.MSG_VERBOSE); } + // Theres nothing else to see here...keep moving sonny + } catch (Exception e) { + String msg = "Exception while adding Vendor specific files: " + + e.toString(); + + throw new BuildException(msg, e); + } } } - + + /** - * Get the vendor specific name of the Jar that will be output. The modification date - * of this jar will be checked against the dependent bean classes. + * Get the vendor specific name of the Jar that will be output. The + * modification date of this jar will be checked against the dependent + * bean classes. */ File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + jarSuffix); } - + + /** * Gets the options for the EJB Deploy operation + * * @return String */ protected String getOptions() { // Set the options StringBuffer options = new StringBuffer(); + if (dbVendor != null) { options.append(" -dbvendor ").append(dbVendor); } if (dbName != null) { options.append(" -dbname \"").append(dbName).append("\""); } - + if (dbSchema != null) { options.append(" -dbschema \"").append(dbSchema).append("\""); } - + if (codegen) { options.append(" -codegen"); } - + if (quiet) { options.append(" -quiet"); } - + if (novalidate) { options.append(" -novalidate"); } - + if (nowarn) { options.append(" -nowarn"); } - + if (noinform) { options.append(" -noinform"); } - + if (trace) { options.append(" -trace"); } - + if (use35MappingRules) { options.append(" -35"); } - + if (rmicOptions != null) { options.append(" -rmic \"").append(rmicOptions).append("\""); } - + return options.toString(); - } // end getOptions - + }// end getOptions + + /** * Helper method invoked by execute() for each websphere jar to be built. * Encapsulates the logic of constructing a java task for calling * websphere.ejbdeploy and executing it. + * * @param sourceJar java.io.File representing the source (EJB1.1) jarfile. * @param destJar java.io.File representing the destination, websphere - * jarfile. + * jarfile. */ private void buildWebsphereJar(File sourceJar, File destJar) { try { @@ -547,14 +582,15 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { // Why do my ""'s get stripped away??? log("EJB Deploy Options: " + args, Project.MSG_VERBOSE); - - Java javaTask = (Java)getTask().getProject().createTask("java"); + + Java javaTask = (Java) getTask().getProject().createTask("java"); // Set the JvmArgs javaTask.createJvmarg().setValue("-Xms64m"); javaTask.createJvmarg().setValue("-Xmx128m"); // Set the Environment variable Environment.Variable var = new Environment.Variable(); + var.setKey("websphere.lib.dir"); var.setValue(getTask().getProject().getProperty("websphere.home") + "/lib"); javaTask.addSysproperty(var); @@ -567,9 +603,11 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { javaTask.setClassname("com.ibm.etools.ejbdeploy.EJBDeploy"); Commandline.Argument arguments = javaTask.createArg(); + arguments.setLine(args); Path classpath = wasClasspath; + if (classpath == null) { classpath = getCombinedClasspath(); } @@ -577,8 +615,7 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { if (classpath != null) { javaTask.setClasspath(classpath); javaTask.setFork(true); - } - else { + } else { javaTask.setFork(true); } @@ -587,25 +624,26 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { javaTask.execute(); } - } - catch (Exception e) { + } catch (Exception e) { // Have to catch this because of the semantics of calling main() String msg = "Exception while calling ejbdeploy. Details: " + e.toString(); + throw new BuildException(msg, e); } } - + + /** - * Method used to encapsulate the writing of the JAR file. Iterates over the - * filenames/java.io.Files in the Hashtable stored on the instance variable - * ejbFiles. + * Method used to encapsulate the writing of the JAR file. Iterates over + * the filenames/java.io.Files in the Hashtable stored on the instance + * variable ejbFiles. */ protected void writeJar(String baseName, File jarFile, Hashtable files, String publicId) - throws BuildException - { + throws BuildException { if (ejbdeploy) { // create the -generic.jar, if required File genericJarFile = super.getVendorOutputJarFile(baseName); + super.writeJar(baseName, genericJarFile, files, publicId); // create the output .jar, if required @@ -617,238 +655,212 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { Project.MSG_VERBOSE); genericJarFile.delete(); } - } - else { + } else { // create the "undeployed" output .jar, if required super.writeJar(baseName, jarFile, files, publicId); } - /* - // need to create a generic jar first. - File genericJarFile = super.getVendorOutputJarFile(baseName); - super.writeJar(baseName, genericJarFile, files, publicId); - - if (alwaysRebuild || isRebuildRequired(genericJarFile, jarFile)) { - buildWebsphereJar(genericJarFile, jarFile); - } - if (!keepGeneric) { - log("deleting generic jar " + genericJarFile.toString(), - Project.MSG_VERBOSE); - genericJarFile.delete(); - } - */ } - + + /** * Called to validate that the tool parameters have been configured. - * */ public void validateConfigured() throws BuildException { super.validateConfigured(); } - - + + /** - * Helper method to check to see if a websphere EBJ1.1 jar needs to be rebuilt using - * ejbdeploy. Called from writeJar it sees if the "Bean" classes are the only thing that needs - * to be updated and either updates the Jar with the Bean classfile or returns true, - * saying that the whole websphere jar needs to be regened with ejbdeploy. This allows faster - * build times for working developers. - *

- * The way websphere ejbdeploy works is it creates wrappers for the publicly defined methods as - * they are exposed in the remote interface. If the actual bean changes without changing the - * the method signatures then only the bean classfile needs to be updated and the rest of the - * websphere jar file can remain the same. If the Interfaces, ie. the method signatures change - * or if the xml deployment dicriptors changed, the whole jar needs to be rebuilt with ejbdeploy. - * This is not strictly true for the xml files. If the JNDI name changes then the jar doesnt - * have to be rebuild, but if the resources references change then it does. At this point the - * websphere jar gets rebuilt if the xml files change at all. + * Helper method to check to see if a websphere EBJ1.1 jar needs to be + * rebuilt using ejbdeploy. Called from writeJar it sees if the "Bean" + * classes are the only thing that needs to be updated and either updates + * the Jar with the Bean classfile or returns true, saying that the whole + * websphere jar needs to be regened with ejbdeploy. This allows faster + * build times for working developers.

+ * + * The way websphere ejbdeploy works is it creates wrappers for the + * publicly defined methods as they are exposed in the remote interface. + * If the actual bean changes without changing the the method signatures + * then only the bean classfile needs to be updated and the rest of the + * websphere jar file can remain the same. If the Interfaces, ie. the + * method signatures change or if the xml deployment dicriptors changed, + * the whole jar needs to be rebuilt with ejbdeploy. This is not strictly + * true for the xml files. If the JNDI name changes then the jar doesnt + * have to be rebuild, but if the resources references change then it + * does. At this point the websphere jar gets rebuilt if the xml files + * change at all. * * @param genericJarFile java.io.File The generic jar file. - * @param websphereJarFile java.io.File The websphere jar file to check to see if it needs to be rebuilt. + * @param websphereJarFile java.io.File The websphere jar file to check to + * see if it needs to be rebuilt. */ - protected boolean isRebuildRequired(File genericJarFile, File websphereJarFile) - { + protected boolean isRebuildRequired(File genericJarFile, File websphereJarFile) { boolean rebuild = false; - + JarFile genericJar = null; JarFile wasJar = null; File newwasJarFile = null; JarOutputStream newJarStream = null; - - try - { - log("Checking if websphere Jar needs to be rebuilt for jar " + websphereJarFile.getName(), - Project.MSG_VERBOSE); - // Only go forward if the generic and the websphere file both exist - if (genericJarFile.exists() && genericJarFile.isFile() - && websphereJarFile.exists() && websphereJarFile.isFile()) - { - //open jar files - genericJar = new JarFile(genericJarFile); - wasJar = new JarFile(websphereJarFile); - - Hashtable genericEntries = new Hashtable(); - Hashtable wasEntries = new Hashtable(); - Hashtable replaceEntries = new Hashtable(); - - //get the list of generic jar entries - for (Enumeration e = genericJar.entries(); e.hasMoreElements();) - { - JarEntry je = (JarEntry)e.nextElement(); - genericEntries.put(je.getName().replace('\\', '/'), je); - } - //get the list of websphere jar entries - for (Enumeration e = wasJar.entries() ; e.hasMoreElements();) - { - JarEntry je = (JarEntry)e.nextElement(); - wasEntries.put(je.getName(), je); - } - - //Cycle Through generic and make sure its in websphere - ClassLoader genericLoader = getClassLoaderFromJar(genericJarFile); - for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) - { - String filepath = (String)e.nextElement(); - if (wasEntries.containsKey(filepath)) // File name/path match - { - // Check files see if same - JarEntry genericEntry = (JarEntry)genericEntries.get(filepath); - JarEntry wasEntry = (JarEntry)wasEntries.get(filepath); - if ((genericEntry.getCrc() != wasEntry.getCrc()) || // Crc's Match - (genericEntry.getSize() != wasEntry.getSize()) ) // Size Match - { - if (genericEntry.getName().endsWith(".class")) - { - //File are different see if its an object or an interface - String classname = genericEntry.getName().replace(File.separatorChar,'.'); - classname = classname.substring(0,classname.lastIndexOf(".class")); - Class genclass = genericLoader.loadClass(classname); - if (genclass.isInterface()) - { - //Interface changed rebuild jar. - log("Interface " + genclass.getName() + " has changed",Project.MSG_VERBOSE); - rebuild = true; - break; - } - else - { - //Object class Changed update it. - replaceEntries.put(filepath, genericEntry); - } - } - else - { - // is it the manifest. If so ignore it - if (!genericEntry.getName().equals("META-INF/MANIFEST.MF")) { - //File other then class changed rebuild - log("Non class file " + genericEntry.getName() + " has changed",Project.MSG_VERBOSE); - rebuild = true; - } - break; - } - } - } - else // a file doesnt exist rebuild - { - log("File " + filepath + " not present in websphere jar",Project.MSG_VERBOSE); - rebuild = true; - break; - } - } - - if (!rebuild) - { - log("No rebuild needed - updating jar",Project.MSG_VERBOSE); - newwasJarFile = new File(websphereJarFile.getAbsolutePath() + ".temp"); - if (newwasJarFile.exists()) { - newwasJarFile.delete(); + + try { + log("Checking if websphere Jar needs to be rebuilt for jar " + websphereJarFile.getName(), + Project.MSG_VERBOSE); + // Only go forward if the generic and the websphere file both exist + if (genericJarFile.exists() && genericJarFile.isFile() + && websphereJarFile.exists() && websphereJarFile.isFile()) { + //open jar files + genericJar = new JarFile(genericJarFile); + wasJar = new JarFile(websphereJarFile); + + Hashtable genericEntries = new Hashtable(); + Hashtable wasEntries = new Hashtable(); + Hashtable replaceEntries = new Hashtable(); + + //get the list of generic jar entries + for (Enumeration e = genericJar.entries(); e.hasMoreElements();) { + JarEntry je = (JarEntry) e.nextElement(); + + genericEntries.put(je.getName().replace('\\', '/'), je); + } + //get the list of websphere jar entries + for (Enumeration e = wasJar.entries(); e.hasMoreElements();) { + JarEntry je = (JarEntry) e.nextElement(); + + wasEntries.put(je.getName(), je); + } + + //Cycle Through generic and make sure its in websphere + ClassLoader genericLoader = getClassLoaderFromJar(genericJarFile); + + for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) { + String filepath = (String) e.nextElement(); + + if (wasEntries.containsKey(filepath)) { + // File name/path match + // Check files see if same + JarEntry genericEntry = (JarEntry) genericEntries.get(filepath); + JarEntry wasEntry = (JarEntry) wasEntries.get(filepath); + + if ((genericEntry.getCrc() != wasEntry.getCrc()) || + (genericEntry.getSize() != wasEntry.getSize())) { + + if (genericEntry.getName().endsWith(".class")) { + //File are different see if its an object or an interface + String classname = genericEntry.getName().replace(File.separatorChar, '.'); + + classname = classname.substring(0, classname.lastIndexOf(".class")); + + Class genclass = genericLoader.loadClass(classname); + + if (genclass.isInterface()) { + //Interface changed rebuild jar. + log("Interface " + genclass.getName() + " has changed", Project.MSG_VERBOSE); + rebuild = true; + break; + } else { + //Object class Changed update it. + replaceEntries.put(filepath, genericEntry); } - - newJarStream = new JarOutputStream(new FileOutputStream(newwasJarFile)); - newJarStream.setLevel(0); - - //Copy files from old websphere jar - for (Enumeration e = wasEntries.elements() ; e.hasMoreElements();) - { - byte[] buffer = new byte[1024]; - int bytesRead; - InputStream is; - JarEntry je = (JarEntry)e.nextElement(); - if (je.getCompressedSize() == -1 || - je.getCompressedSize() == je.getSize()) { - newJarStream.setLevel(0); - } - else { - newJarStream.setLevel(9); - } - - // Update with changed Bean class - if (replaceEntries.containsKey(je.getName())) - { - log("Updating Bean class from generic Jar " + je.getName(), - Project.MSG_VERBOSE); - // Use the entry from the generic jar - je = (JarEntry)replaceEntries.get(je.getName()); - is = genericJar.getInputStream(je); - } - else //use fle from original websphere jar - { - is = wasJar.getInputStream(je); - } - newJarStream.putNextEntry(new JarEntry(je.getName())); - - while ((bytesRead = is.read(buffer)) != -1) - { - newJarStream.write(buffer,0,bytesRead); - } - is.close(); - } - } - else - { - log("websphere Jar rebuild needed due to changed interface or XML",Project.MSG_VERBOSE); + } else { + // is it the manifest. If so ignore it + if (!genericEntry.getName().equals("META-INF/MANIFEST.MF")) { + //File other then class changed rebuild + log("Non class file " + genericEntry.getName() + " has changed", Project.MSG_VERBOSE); + rebuild = true; + } + break; } - } - else - { + } + } else {// a file doesnt exist rebuild + + log("File " + filepath + " not present in websphere jar", Project.MSG_VERBOSE); rebuild = true; + break; } + } + + if (!rebuild) { + log("No rebuild needed - updating jar", Project.MSG_VERBOSE); + newwasJarFile = new File(websphereJarFile.getAbsolutePath() + ".temp"); + if (newwasJarFile.exists()) { + newwasJarFile.delete(); + } + + newJarStream = new JarOutputStream(new FileOutputStream(newwasJarFile)); + newJarStream.setLevel(0); + + //Copy files from old websphere jar + for (Enumeration e = wasEntries.elements(); e.hasMoreElements();) { + byte[] buffer = new byte[1024]; + int bytesRead; + InputStream is; + JarEntry je = (JarEntry) e.nextElement(); + + if (je.getCompressedSize() == -1 || + je.getCompressedSize() == je.getSize()) { + newJarStream.setLevel(0); + } else { + newJarStream.setLevel(9); + } + + // Update with changed Bean class + if (replaceEntries.containsKey(je.getName())) { + log("Updating Bean class from generic Jar " + je.getName(), + Project.MSG_VERBOSE); + // Use the entry from the generic jar + je = (JarEntry) replaceEntries.get(je.getName()); + is = genericJar.getInputStream(je); + } else {//use fle from original websphere jar + + is = wasJar.getInputStream(je); + } + newJarStream.putNextEntry(new JarEntry(je.getName())); + + while ((bytesRead = is.read(buffer)) != -1) { + newJarStream.write(buffer, 0, bytesRead); + } + is.close(); + } + } else { + log("websphere Jar rebuild needed due to changed interface or XML", Project.MSG_VERBOSE); + } + } else { + rebuild = true; } - catch(ClassNotFoundException cnfe) - { - String cnfmsg = "ClassNotFoundException while processing ejb-jar file" - + ". Details: " - + cnfe.getMessage(); - throw new BuildException(cnfmsg, cnfe); - } - catch(IOException ioe) { + } catch (ClassNotFoundException cnfe) { + String cnfmsg = "ClassNotFoundException while processing ejb-jar file" + + ". Details: " + + cnfe.getMessage(); + + throw new BuildException(cnfmsg, cnfe); + } catch (IOException ioe) { String msg = "IOException while processing ejb-jar file " - + ". Details: " - + ioe.getMessage(); + + ". Details: " + + ioe.getMessage(); + throw new BuildException(msg, ioe); - } - finally { + } finally { // need to close files and perhaps rename output if (genericJar != null) { try { genericJar.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} } - + if (wasJar != null) { try { wasJar.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} } - + if (newJarStream != null) { try { newJarStream.close(); + } catch (IOException closeException) { } - catch (IOException closeException) {} - + websphereJarFile.delete(); newwasJarFile.renameTo(websphereJarFile); if (!websphereJarFile.exists()) { @@ -856,26 +868,29 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } } } - + return rebuild; } - + + /** - * Helper method invoked by isRebuildRequired to get a ClassLoader for - * a Jar File passed to it. + * Helper method invoked by isRebuildRequired to get a ClassLoader for a + * Jar File passed to it. * * @param classjar java.io.File representing jar file to get classes from. */ - protected ClassLoader getClassLoaderFromJar(File classjar) throws IOException - { + protected ClassLoader getClassLoaderFromJar(File classjar) throws IOException { Path lookupPath = new Path(getTask().getProject()); + lookupPath.setLocation(classjar); - + Path classpath = getCombinedClasspath(); + if (classpath != null) { lookupPath.append(classpath); } - + return new AntClassLoader(getTask().getProject(), lookupPath); } } + diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java index d42b8be4c..9b125616e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java @@ -166,7 +166,7 @@ public class Translate extends MatchingTask { /** * Sets locale specific language of resource bundle */ - public void setBundleLanguage(String bundleLanguage ) { + public void setBundleLanguage(String bundleLanguage) { this.bundleLanguage = bundleLanguage; } @@ -424,9 +424,9 @@ public class Translate extends MatchingTask { InputStreamReader isr = new InputStreamReader(ins, bundleEncoding); in = new BufferedReader(isr); String line = null; - while((line = in.readLine()) != null) { + while ((line = in.readLine()) != null) { //So long as the line isn't empty and isn't a comment... - if(line.trim().length() > 1 && + if (line.trim().length() > 1 && ('#' != line.charAt(0) || '!' != line.charAt(0))) { //Legal Key-Value separators are :, = and white space. int sepIndex = line.indexOf('='); @@ -463,7 +463,7 @@ public class Translate extends MatchingTask { } } } - if(in != null) { + if (in != null) { in.close(); } } catch (IOException ioe) { @@ -517,15 +517,13 @@ public class Translate extends MatchingTask { log("Processing " + srcFiles[j], Project.MSG_DEBUG); FileOutputStream fos = new FileOutputStream(dest); - BufferedWriter out = new BufferedWriter( - new OutputStreamWriter(fos, - destEncoding)); + BufferedWriter out + = new BufferedWriter(new OutputStreamWriter(fos, destEncoding)); FileInputStream fis = new FileInputStream(srcFiles[j]); - BufferedReader in = new BufferedReader( - new InputStreamReader(fis, - srcEncoding)); + BufferedReader in + = new BufferedReader(new InputStreamReader(fis, srcEncoding)); String line; - while((line = in.readLine()) != null) { + while ((line = in.readLine()) != null) { int startIndex = -1; int endIndex = -1; outer: while (true) { @@ -572,10 +570,10 @@ outer: while (true) { out.write(line); out.newLine(); } - if(in != null) { + if (in != null) { in.close(); } - if(out != null) { + if (out != null) { out.close(); } } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntTool.java index 530f8b572..174dd84cc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntTool.java @@ -87,15 +87,15 @@ public class VAJAntTool { VAJBuildInfo result = null; try { Project project = - VAJLocalUtil.getWorkspace().loadedProjectNamed( projectName ); - if ( project.testToolRepositoryData(TOOL_DATA_KEY) ) { + VAJLocalUtil.getWorkspace().loadedProjectNamed(projectName); + if (project.testToolRepositoryData(TOOL_DATA_KEY)) { ToolData td = project.getToolRepositoryData(TOOL_DATA_KEY); - String data = (String)td.getData(); - result = VAJBuildInfo.parse( data ); + String data = (String) td.getData(); + result = VAJBuildInfo.parse(data); } else { result = new VAJBuildInfo(); } - result.setVAJProjectName( projectName ); + result.setVAJProjectName(projectName); } catch (Throwable t) { throw new BuildException("BuildInfo for Project " + projectName + " could not be loaded" + t); @@ -114,17 +114,17 @@ public class VAJAntTool { public static void main(java.lang.String[] args) { try { VAJBuildInfo info; - if ( args.length >= 2 && args[1] instanceof String ) { - String projectName = (String)args[1]; - info = loadBuildData( projectName ); + if (args.length >= 2 && args[1] instanceof String) { + String projectName = (String) args[1]; + info = loadBuildData(projectName); } else { info = new VAJBuildInfo(); } - VAJAntToolGUI mainFrame = new VAJAntToolGUI( info ); + VAJAntToolGUI mainFrame = new VAJAntToolGUI(info); mainFrame.show(); - } catch ( Throwable t ) { + } catch (Throwable t) { // if all error handling fails, output at least // something on the console t.printStackTrace(); @@ -140,9 +140,9 @@ public class VAJAntTool { public static void saveBuildData(VAJBuildInfo info) { String data = info.asDataString(); try { - ToolData td = new ToolData( TOOL_DATA_KEY, data ); + ToolData td = new ToolData(TOOL_DATA_KEY, data); VAJLocalUtil.getWorkspace().loadedProjectNamed( - info.getVAJProjectName() ).setToolRepositoryData( td ); + info.getVAJProjectName()).setToolRepositoryData(td); } catch (Throwable t) { throw new BuildException("BuildInfo for Project " + info.getVAJProjectName() + " could not be saved", t); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntToolGUI.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntToolGUI.java index 45f4b2588..53c08c738 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntToolGUI.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJAntToolGUI.java @@ -211,23 +211,24 @@ public class VAJAntToolGUI extends Frame { getMessageTextArea().append(lineSeparator + "BUILD SUCCESSFUL"); } else { - logException( error ); + logException(error); } - getMessageTextArea().append(lineSeparator + "Total time: " + DateUtils.formatElapsedTime(System.currentTimeMillis() - startTime)); + getMessageTextArea().append(lineSeparator + "Total time: " + + DateUtils.formatElapsedTime(System.currentTimeMillis() - startTime)); } /** * Outputs an exception. */ - public void logException( Throwable error ) { + public void logException(Throwable error) { getMessageTextArea().append(lineSeparator + "BUILD FAILED" + lineSeparator); if (error instanceof BuildException) { getMessageTextArea().append(error.toString()); - Throwable nested = ((BuildException)error).getException(); + Throwable nested = ((BuildException) error).getException(); if (nested != null) { nested.printStackTrace(System.err); } @@ -318,7 +319,7 @@ public class VAJAntToolGUI extends Frame { getFileDialog().setDirectory(getBuildFileTextField().getText().substring(0, getBuildFileTextField().getText().lastIndexOf('\\') + 1)); getFileDialog().setFile("*.xml"); getFileDialog().show(); - if (!getFileDialog().getFile().equals("") ) { + if (!getFileDialog().getFile().equals("")) { getBuildFileTextField().setText(getFileDialog().getDirectory() + getFileDialog().getFile()); } } @@ -525,7 +526,7 @@ public class VAJAntToolGUI extends Frame { getBuildInfo().executeProject(logger); } catch (Throwable exc) { - logger.logException( exc ); + logger.logException(exc); } return; } @@ -535,7 +536,7 @@ public class VAJAntToolGUI extends Frame { private void fillList() { getTargetList().removeAll(); Vector targets = getBuildInfo().getProjectTargets(); - for (int i = 0;i < targets.size(); i++) { + for (int i = 0; i < targets.size(); i++) { getTargetList().add(targets.elementAt(i).toString()); } getTargetList().select(iBuildInfo.getProjectTargets().indexOf(iBuildInfo.getTarget())); @@ -1348,7 +1349,7 @@ public class VAJAntToolGUI extends Frame { } catch (Throwable exc) { // This Exception occurs when you try to write into a versioned project - handleException( exc ); + handleException(exc); } return; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJBuildInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJBuildInfo.java index 16c704385..59271967e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJBuildInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJBuildInfo.java @@ -107,7 +107,7 @@ class VAJBuildInfo implements Runnable { * Can only be constructed as wrapper around a real listener * @param listener the real listener */ - public InterruptedChecker( BuildListener listener) { + public InterruptedChecker(BuildListener listener) { super(); wrappedListener = listener; } @@ -118,7 +118,7 @@ class VAJBuildInfo implements Runnable { * the execution. */ protected void checkInterrupted() { - if ( buildThread.isInterrupted() ) { + if (buildThread.isInterrupted()) { throw new BuildInterruptedException(); } } @@ -128,7 +128,7 @@ class VAJBuildInfo implements Runnable { * will still be thrown if an error occured during the build. */ public void buildFinished(BuildEvent event) { - wrappedListener.buildFinished( event ); + wrappedListener.buildFinished(event); checkInterrupted(); } @@ -136,7 +136,7 @@ class VAJBuildInfo implements Runnable { * Fired before any targets are started. */ public void buildStarted(BuildEvent event) { - wrappedListener.buildStarted( event ); + wrappedListener.buildStarted(event); checkInterrupted(); } @@ -144,7 +144,7 @@ class VAJBuildInfo implements Runnable { * Fired whenever a message is logged. */ public void messageLogged(BuildEvent event) { - wrappedListener.messageLogged( event ); + wrappedListener.messageLogged(event); checkInterrupted(); } @@ -153,7 +153,7 @@ class VAJBuildInfo implements Runnable { * still be thrown if an error occured during the build. */ public void targetFinished(BuildEvent event) { - wrappedListener.targetFinished( event ); + wrappedListener.targetFinished(event); checkInterrupted(); } @@ -161,7 +161,7 @@ class VAJBuildInfo implements Runnable { * Fired when a target is started. */ public void targetStarted(BuildEvent event) { - wrappedListener.targetStarted( event ); + wrappedListener.targetStarted(event); checkInterrupted(); } @@ -170,7 +170,7 @@ class VAJBuildInfo implements Runnable { * be throw if an error occured during the build. */ public void taskFinished(BuildEvent event) { - wrappedListener.taskFinished( event ); + wrappedListener.taskFinished(event); checkInterrupted(); } @@ -178,7 +178,7 @@ class VAJBuildInfo implements Runnable { * Fired when a task is started. */ public void taskStarted(BuildEvent event) { - wrappedListener.taskStarted( event ); + wrappedListener.taskStarted(event); checkInterrupted(); } } @@ -230,8 +230,8 @@ class VAJBuildInfo implements Runnable { public String asDataString() { String result = getOutputMessageLevel() + "|" + getBuildFileName() + "|" + getTarget(); - for ( Enumeration e = getProjectTargets().elements(); - e.hasMoreElements(); ) { + for (Enumeration e = getProjectTargets().elements(); + e.hasMoreElements();) { result = result + "|" + e.nextElement(); } @@ -244,8 +244,8 @@ class VAJBuildInfo implements Runnable { */ private static int findTargetPosition(Vector names, String name) { int res = names.size(); - for (int i=0; i 0) { - logFiles(files, fileType ); + logFiles(files, fileType); summaryLog.append(files.size()); summaryLog.append(" " + fileType.toLowerCase() + " file"); summaryLog.append(files.size() > 1 ? "s, " : ", "); @@ -463,9 +463,9 @@ abstract class VAJLocalUtil implements VAJUtil{ * @param type java.lang.String file type */ private void logFiles(Vector fileNames, String fileType) { - log( fileType + " files found for import:", MSG_VERBOSE); - for ( Enumeration e = fileNames.elements(); e.hasMoreElements(); ) { - log( " " + e.nextElement(), MSG_VERBOSE ); + log(fileType + " files found for import:", MSG_VERBOSE); + for (Enumeration e = fileNames.elements(); e.hasMoreElements();) { + log(" " + e.nextElement(), MSG_VERBOSE); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJRemoteUtil.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJRemoteUtil.java index 4be586365..2ed2f0dc9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJRemoteUtil.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJRemoteUtil.java @@ -82,7 +82,7 @@ class VAJRemoteUtil implements VAJUtil{ // VAJ remote tool server String remoteServer; - public VAJRemoteUtil( Task caller, String remote ) { + public VAJRemoteUtil(Task caller, String remote) { this.caller = caller; this.remoteServer = remote; } @@ -93,16 +93,16 @@ class VAJRemoteUtil implements VAJUtil{ public void exportPackages(File destDir, String[] includePatterns, String[] excludePatterns, boolean exportClasses, boolean exportDebugInfo, boolean exportResources, - boolean exportSources, boolean useDefaultExcludes, boolean overwrite ) { + boolean exportSources, boolean useDefaultExcludes, boolean overwrite) { try { String request = "http://" + remoteServer + "/servlet/vajexport?" + VAJExportServlet.WITH_DEBUG_INFO + "=" + exportDebugInfo + "&" + VAJExportServlet.OVERWRITE_PARAM + "=" + overwrite + "&" - + assembleImportExportParams( destDir, + + assembleImportExportParams(destDir, includePatterns, excludePatterns, exportClasses, exportResources, - exportSources, useDefaultExcludes ); - sendRequest( request); + exportSources, useDefaultExcludes); + sendRequest(request); } catch (Exception ex) { throw new BuildException(ex); } @@ -120,11 +120,11 @@ class VAJRemoteUtil implements VAJUtil{ String request = "http://" + remoteServer + "/servlet/vajimport?" + VAJImportServlet.PROJECT_NAME_PARAM + "=" + importProject + "&" - + assembleImportExportParams( srcDir, + + assembleImportExportParams(srcDir, includePatterns, excludePatterns, importClasses, importResources, - importSources, useDefaultExcludes ); - sendRequest( request); + importSources, useDefaultExcludes); + sendRequest(request); } catch (Exception ex) { throw new BuildException(ex); } @@ -148,14 +148,14 @@ class VAJRemoteUtil implements VAJUtil{ + VAJToolsServlet.SOURCES_PARAM + "=" + includeSources + "&" + VAJToolsServlet.DEFAULT_EXCLUDES_PARAM + "=" + useDefaultExcludes; - if ( includePatterns != null ) { - for ( int i = 0; i < includePatterns.length; i++ ){ - result= result + "&" + VAJExportServlet.INCLUDE_PARAM + "=" + if (includePatterns != null) { + for (int i = 0; i < includePatterns.length; i++){ + result = result + "&" + VAJExportServlet.INCLUDE_PARAM + "=" + includePatterns[i].replace(' ', '+').replace('\\', '/'); } } - if ( excludePatterns != null ) { - for ( int i = 0; i < excludePatterns.length; i++ ){ + if (excludePatterns != null) { + for (int i = 0; i < excludePatterns.length; i++){ result = result + "&" + VAJExportServlet.EXCLUDE_PARAM + "=" + excludePatterns[i].replace(' ', '+').replace('\\', '/'); } @@ -167,12 +167,12 @@ class VAJRemoteUtil implements VAJUtil{ /** * Load specified projects. */ - public void loadProjects( Vector projectDescriptions) { + public void loadProjects(Vector projectDescriptions) { try { String request = "http://" + remoteServer + "/servlet/vajload?"; String delimiter = ""; - for ( Enumeration e = projectDescriptions.elements(); e.hasMoreElements(); ){ - VAJProjectDescription pd = (VAJProjectDescription)e.nextElement(); + for (Enumeration e = projectDescriptions.elements(); e.hasMoreElements();) { + VAJProjectDescription pd = (VAJProjectDescription) e.nextElement(); request = request + delimiter + VAJLoadServlet.PROJECT_NAME_PARAM + "=" + pd.getName().replace(' ', '+') @@ -181,7 +181,7 @@ class VAJRemoteUtil implements VAJUtil{ //the first param needs no delimiter, but all other delimiter = "&"; } - sendRequest( request); + sendRequest(request); } catch (Exception ex) { throw new BuildException(ex); } @@ -191,7 +191,7 @@ class VAJRemoteUtil implements VAJUtil{ * logs a message. */ public void log(String msg, int level) { - caller.log( msg, level ); + caller.log(msg, level); } /** @@ -203,7 +203,7 @@ class VAJRemoteUtil implements VAJUtil{ log("Request: " + request, MSG_DEBUG); //must be HTTP connection - URL requestUrl = new URL( request ); + URL requestUrl = new URL(request); HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); @@ -218,33 +218,33 @@ class VAJRemoteUtil implements VAJUtil{ } if (is == null) { log("Can't get " + request, MSG_ERR); - throw new BuildException("Couldn't execute " + request ); + throw new BuildException("Couldn't execute " + request); } // log the response - BufferedReader br = new BufferedReader( new InputStreamReader( is ) ); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); - while ( line != null ) { + while (line != null) { int level = MSG_ERR; try { // the first char of each line contains the log level - level = Integer.parseInt( line.substring(0,1) ); - if ( level == MSG_ERR ) { + level = Integer.parseInt(line.substring(0, 1)); + if (level == MSG_ERR) { requestFailed = true; } - } catch ( Exception e ) { - log( "Response line doesn't contain log level!", MSG_ERR ); + } catch (Exception e) { + log("Response line doesn't contain log level!", MSG_ERR); } - log( line.substring(2), level ); + log(line.substring(2), level); line = br.readLine(); } } catch (IOException ex) { log("Error sending tool request to VAJ" + ex, MSG_ERR); - throw new BuildException("Couldn't execute " + request ); + throw new BuildException("Couldn't execute " + request); } - if ( requestFailed ) { - throw new BuildException( "VAJ tool request failed" ); + if (requestFailed) { + throw new BuildException("VAJ tool request failed"); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJTask.java index 90408b18a..779a66a48 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJTask.java @@ -69,7 +69,7 @@ public class VAJTask extends Task { */ class VAJLocalToolUtil extends VAJLocalUtil { public void log(String msg, int level) { - VAJTask.this.log( msg, level ); + VAJTask.this.log(msg, level); } } @@ -84,11 +84,11 @@ public class VAJTask extends Task { * returns the VAJUtil implementation */ protected VAJUtil getUtil() { - if ( util == null ) { - if ( remoteServer == null ) { + if (util == null) { + if (remoteServer == null) { util = new VAJLocalToolUtil(); } else { - util = new VAJRemoteUtil( this, remoteServer ); + util = new VAJRemoteUtil(this, remoteServer); } } return util; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJToolsServlet.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJToolsServlet.java index f274b1912..5ea64774e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJToolsServlet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJToolsServlet.java @@ -81,22 +81,22 @@ public abstract class VAJToolsServlet extends HttpServlet { class VAJLocalServletUtil extends VAJLocalUtil { public void log(String msg, int level) { try { - if ( msg != null ) { + if (msg != null) { msg = msg.replace('\r', ' '); int i = 0; - while ( i < msg.length() ) { + while (i < msg.length()) { int nlPos = msg.indexOf('\n', i); - if ( nlPos == -1 ) { + if (nlPos == -1) { nlPos = msg.length(); } - response.getWriter().println( Integer.toString(level) - + " " + msg.substring( i, nlPos )); + response.getWriter().println(Integer.toString(level) + + " " + msg.substring(i, nlPos)); i = nlPos + 1; } } - } catch( IOException e ) { - throw new BuildException( "logging failed. msg was: " - + e.getMessage() ); + } catch (IOException e) { + throw new BuildException("logging failed. msg was: " + + e.getMessage()); } } } @@ -141,22 +141,21 @@ public abstract class VAJToolsServlet extends HttpServlet { request = req; initRequest(); executeRequest(); - } catch( BuildException e ) { + } catch (BuildException e) { util.log("Error occured: " + e.getMessage(), VAJUtil.MSG_ERR); - } catch( Exception e ) { + } catch (Exception e) { try { - if ( ! (e instanceof BuildException) ) { + if (!(e instanceof BuildException)) { String trace = StringUtils.getStackTrace(e); util.log("Program error in " + this.getClass().getName() + ":\n" + trace, VAJUtil.MSG_ERR); } - } catch( Throwable t ) { + } catch (Throwable t) { t.printStackTrace(); } finally { - if ( ! (e instanceof BuildException) ) - { - throw new ServletException( e.getMessage() ); - } + if (!(e instanceof BuildException)) { + throw new ServletException(e.getMessage()); + } } } } @@ -166,7 +165,7 @@ public abstract class VAJToolsServlet extends HttpServlet { */ protected void initRequest() throws IOException { response.setContentType("text/ascii"); - if ( util == null ) { + if (util == null) { util = new VAJLocalServletUtil(); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJWorkspaceScanner.java b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJWorkspaceScanner.java index 4eaf7c64d..717bd836a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJWorkspaceScanner.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ide/VAJWorkspaceScanner.java @@ -113,8 +113,8 @@ class VAJWorkspaceScanner extends DirectoryScanner { } for (int i = 0; i < DEFAULTEXCLUDES.length; i++) { newExcludes[i + excludesLength] = DEFAULTEXCLUDES[i]. - replace( '/', File.separatorChar ). - replace( '\\', File.separatorChar ); + replace('/', File.separatorChar). + replace('\\', File.separatorChar); } excludes = newExcludes; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java index a50a50c7d..4b57fe1b7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java @@ -103,7 +103,7 @@ public abstract class AbstractHotDeploymentTool implements HotDeploymentTool * @return A Path object representing the classpath to be used. */ public Path createClasspath() { - if(classpath == null) + if (classpath == null) classpath = new Path(task.getProject()); return classpath.createPath(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java index d058d9e8b..514828d17 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java @@ -109,7 +109,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool * @return true if the "action" attribute is valid, false if not. */ protected boolean isActionValid() { - return(getTask().getAction().equals(VALID_ACTIONS[0])); + return (getTask().getAction().equals(VALID_ACTIONS[0])); } /** @@ -118,7 +118,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool */ public void setTask(ServerDeploy task) { super.setTask(task); - java = (Java)task.getProject().createTask("java"); + java = (Java) task.getProject().createTask("java"); } /** @@ -143,7 +143,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool public void validateAttributes() throws BuildException { super.validateAttributes(); - if(className == null) + if (className == null) throw new BuildException("The classname attribute must be set"); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java index eb4cce5fc..ba4423203 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java @@ -98,7 +98,7 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool impleme */ public void deploy() { - Java java = (Java)getTask().getProject().createTask("java"); + Java java = (Java) getTask().getProject().createTask("java"); java.setFork(true); java.setFailonerror(true); java.setClasspath(getClasspath()); @@ -123,20 +123,26 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool impleme String action = getTask().getAction(); // check that the password has been set - if((getPassword() == null)) + if ((getPassword() == null)) throw new BuildException("The password attribute must be set."); // check for missing application on deploy & update - if((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) && application == null) - throw new BuildException("The application attribute must be set if action = " + action); + if ((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) + && application == null) + throw new BuildException("The application attribute must be set " + + "if action = " + action); // check for missing source on deploy & update - if((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) && getTask().getSource() == null) - throw new BuildException("The source attribute must be set if action = " + action); + if ((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) + && getTask().getSource() == null) + throw new BuildException("The source attribute must be set if " + + "action = " + action); // check for missing application on delete & undeploy - if((action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) && application == null) - throw new BuildException("The application attribute must be set if action = " + action); + if ((action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) + && application == null) + throw new BuildException("The application attribute must be set if " + + "action = " + action); } /** @@ -148,11 +154,11 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool impleme String action = getTask().getAction(); String args = null; - if(action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) + if (action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) args = buildDeployArgs(); - else if(action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) + else if (action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) args = buildUndeployArgs(); - else if(action.equals(ACTION_LIST)) + else if (action.equals(ACTION_LIST)) args = buildListArgs(); return args; @@ -168,8 +174,8 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool impleme String action = getTask().getAction(); - for(int i = 0; i < VALID_ACTIONS.length; i++) { - if(action.equals(VALID_ACTIONS[i])) { + for (int i = 0; i < VALID_ACTIONS.length; i++) { + if (action.equals(VALID_ACTIONS[i])) { valid = true; break; } @@ -213,9 +219,10 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool impleme .append(getTask().getSource()) .toString(); - if(component != null) + if (component != null) { args = "-component " + component + " " + args; - + } + return args; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java index b40ee6557..17d20b399 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java @@ -166,9 +166,9 @@ public class JJTree extends Task { // load command line with optional attributes Enumeration iter = optionalAttrs.keys(); while (iter.hasMoreElements()) { - String name = (String)iter.nextElement(); + String name = (String) iter.nextElement(); Object value = optionalAttrs.get(name); - cmdl.createArgument().setValue("-"+name+":"+value.toString()); + cmdl.createArgument().setValue("-" + name + ":" + value.toString()); } if (target == null || !target.isFile()) { @@ -179,18 +179,20 @@ public class JJTree extends Task { if (outputDirectory == null) { outputDirectory = new File(target.getParent()); } - if (!outputDirectory.isDirectory() ) { - throw new BuildException("'outputdirectory' " + outputDirectory + " is not a directory."); + if (!outputDirectory.isDirectory()) { + throw new BuildException("'outputdirectory' " + outputDirectory + + " is not a directory."); } // convert backslashes to slashes, otherwise jjtree will put this as // comments and this seems to confuse javacc - cmdl.createArgument().setValue( - "-OUTPUT_DIRECTORY:"+outputDirectory.getAbsolutePath().replace('\\', '/')); + cmdl.createArgument().setValue("-OUTPUT_DIRECTORY:" + + outputDirectory.getAbsolutePath().replace('\\', '/')); String targetName = target.getName(); final File javaFile = new File(outputDirectory, targetName.substring(0, targetName.indexOf(".jjt")) + ".jj"); - if (javaFile.exists() && target.lastModified() < javaFile.lastModified()) { + if (javaFile.exists() + && target.lastModified() < javaFile.lastModified()) { project.log("Target is already built - skipping (" + target + ")"); return; } @@ -198,12 +200,12 @@ public class JJTree extends Task { final Path classpath = cmdl.createClasspath(project); final File javaccJar = JavaCC.getArchiveFile(javaccHome); - classpath.createPathElement().setPath( javaccJar.getAbsolutePath() ); + classpath.createPathElement().setPath(javaccJar.getAbsolutePath()); classpath.addJavaRuntime(); final Commandline.Argument arg = cmdl.createVmArgument(); arg.setValue("-mx140M"); - arg.setValue("-Dinstall.root="+javaccHome.getAbsolutePath()); + arg.setValue("-Dinstall.root=" + javaccHome.getAbsolutePath()); final Execute process = new Execute(new LogStreamHandler(this, diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java index ae7dfdf9a..29dee70c4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java @@ -211,9 +211,9 @@ public class JavaCC extends Task { // load command line with optional attributes Enumeration iter = optionalAttrs.keys(); while (iter.hasMoreElements()) { - String name = (String)iter.nextElement(); + String name = (String) iter.nextElement(); Object value = optionalAttrs.get(name); - cmdl.createArgument().setValue("-"+name+":"+value.toString()); + cmdl.createArgument().setValue("-" + name + ":" + value.toString()); } // check the target is a file @@ -228,8 +228,8 @@ public class JavaCC extends Task { else if (!outputDirectory.isDirectory()) { throw new BuildException("Outputdir not a directory."); } - cmdl.createArgument().setValue( - "-OUTPUT_DIRECTORY:"+outputDirectory.getAbsolutePath()); + cmdl.createArgument().setValue("-OUTPUT_DIRECTORY:" + + outputDirectory.getAbsolutePath()); // determine if the generated java file is up-to-date final File javaFile = getOutputJavaFile(outputDirectory, target); @@ -241,12 +241,12 @@ public class JavaCC extends Task { final Path classpath = cmdl.createClasspath(project); final File javaccJar = JavaCC.getArchiveFile(javaccHome); - classpath.createPathElement().setPath( javaccJar.getAbsolutePath() ); + classpath.createPathElement().setPath(javaccJar.getAbsolutePath()); classpath.addJavaRuntime(); final Commandline.Argument arg = cmdl.createVmArgument(); arg.setValue("-mx140M"); - arg.setValue("-Dinstall.root="+javaccHome.getAbsolutePath()); + arg.setValue("-Dinstall.root=" + javaccHome.getAbsolutePath()); Execute.runCommand(this, cmdl.getCommandline()); } @@ -265,12 +265,12 @@ public class JavaCC extends Task { } // javacc prior to 2.0 File f = new File(home, "JavaCC.zip"); - if ( f.exists() ){ + if (f.exists()){ return f; } // javacc install 2.0+ f = new File(home, "bin/lib/JavaCC.zip"); - if ( f.exists() ){ + if (f.exists()){ return f; } throw new BuildException("Could not find a path to JavaCC.zip from '" + home + "'."); @@ -287,8 +287,8 @@ public class JavaCC extends Task { // Extract file's base-name int startBasename = path.lastIndexOf(File.separator); - if ( startBasename != -1 ) { - path = path.substring(startBasename+1); + if (startBasename != -1) { + path = path.substring(startBasename + 1); } // Replace the file's extension with '.java' diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java index 1f51db671..38e3f8fc4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java @@ -216,7 +216,7 @@ public class JDependTask extends Task { * @return create a new JVM argument so that any argument can be passed to the JVM. * @see #setFork(boolean) */ - public Commandline.Argument createJvmarg(CommandlineJava commandline ) { + public Commandline.Argument createJvmarg(CommandlineJava commandline) { return commandline.createVmArgument(); } @@ -235,7 +235,7 @@ public class JDependTask extends Task { public static class FormatAttribute extends EnumeratedAttribute { - private String [] formats = new String[]{"xml","text"}; + private String [] formats = new String[]{"xml", "text"}; public String[] getValues() { @@ -257,14 +257,14 @@ public class JDependTask extends Task { CommandlineJava commandline = new CommandlineJava(); - if("text".equals(format)) { + if ("text".equals(format)) { commandline.setClassname("jdepend.textui.JDepend"); } else - if("xml".equals(format)) { + if ("xml".equals(format)) { commandline.setClassname("jdepend.xmlui.JDepend"); } - if(_jvm!=null) { + if (_jvm != null) { commandline.setVm(_jvm); } @@ -275,11 +275,11 @@ public class JDependTask extends Task { // execute the test and get the return code int exitValue = JDependTask.ERRORS; boolean wasKilled = false; - if (! getFork()) { + if (!getFork()) { exitValue = executeInVM(commandline); } else { ExecuteWatchdog watchdog = createWatchdog(); - exitValue = executeAsForked(commandline,watchdog); + exitValue = executeAsForked(commandline, watchdog); // null watchdog means no timeout, you'd better not check with null if (watchdog != null) { //info will be used in later version do nothing for now @@ -287,8 +287,8 @@ public class JDependTask extends Task { } } - // if there is an error/failure and that it should halt, stop everything otherwise - // just log a statement + // if there is an error/failure and that it should halt, stop + // everything otherwise just log a statement boolean errorOccurred = exitValue == JDependTask.ERRORS; if (errorOccurred) { @@ -314,7 +314,7 @@ public class JDependTask extends Task { public int executeInVM(CommandlineJava commandline) throws BuildException { jdepend.textui.JDepend jdepend; - if("xml".equals(format)) { + if ("xml".equals(format)) { jdepend = new jdepend.xmlui.JDepend(); } else { jdepend = new jdepend.textui.JDepend(); @@ -326,7 +326,8 @@ public class JDependTask extends Task { fw = new FileWriter(getOutputFile().getPath()); } catch (IOException e) { - String msg = "JDepend Failed when creating the output file: " + e.getMessage(); + String msg = "JDepend Failed when creating the output file: " + + e.getMessage(); log(msg); throw new BuildException(msg); } @@ -334,13 +335,15 @@ public class JDependTask extends Task { log("Output to be stored in " + getOutputFile().getPath()); } - PathTokenizer sourcesPath = new PathTokenizer(getSourcespath().toString()); + PathTokenizer sourcesPath + = new PathTokenizer(getSourcespath().toString()); while (sourcesPath.hasMoreTokens()) { File f = new File(sourcesPath.nextToken()); // not necessary as JDepend would fail, but why loose some time? - if (! f.exists() || !f.isDirectory()) { - String msg = "\""+ f.getPath() + "\" does not represent a valid directory. JDepend would fail."; + if (!f.exists() || !f.isDirectory()) { + String msg = "\"" + f.getPath() + "\" does not represent a valid" + + " directory. JDepend would fail."; log(msg); throw new BuildException(msg); } @@ -348,7 +351,8 @@ public class JDependTask extends Task { jdepend.addDirectory(f.getPath()); } catch (IOException e) { - String msg = "JDepend Failed when adding a source directory: " + e.getMessage(); + String msg = "JDepend Failed when adding a source directory: " + + e.getMessage(); log(msg); throw new BuildException(msg); } @@ -367,7 +371,8 @@ public class JDependTask extends Task { * the test could probably hang forever. */ // JL: comment extracted from JUnitTask (and slightly modified) - public int executeAsForked(CommandlineJava commandline,ExecuteWatchdog watchdog) throws BuildException { + public int executeAsForked(CommandlineJava commandline, + ExecuteWatchdog watchdog) throws BuildException { // if not set, auto-create the ClassPath from the project createClasspath(); @@ -379,20 +384,23 @@ public class JDependTask extends Task { } if (getOutputFile() != null) { - // having a space between the file and its path causes commandline to add quotes " - // around the argument thus making JDepend not taking it into account. Thus we split it in two + // having a space between the file and its path causes commandline + // to add quotes around the argument thus making JDepend not taking + // it into account. Thus we split it in two commandline.createArgument().setValue("-file"); commandline.createArgument().setValue(_outputFile.getPath()); // we have to find a cleaner way to put this output } - PathTokenizer sourcesPath = new PathTokenizer(getSourcespath().toString()); + PathTokenizer sourcesPath + = new PathTokenizer(getSourcespath().toString()); while (sourcesPath.hasMoreTokens()) { File f = new File(sourcesPath.nextToken()); // not necessary as JDepend would fail, but why loose some time? - if (! f.exists() || !f.isDirectory()) { - throw new BuildException("\""+ f.getPath() + "\" does not represent a valid directory. JDepend would fail."); + if (!f.exists() || !f.isDirectory()) { + throw new BuildException("\"" + f.getPath() + "\" does not " + + "represent a valid directory. JDepend would fail."); } commandline.createArgument().setValue(f.getPath()); } @@ -407,7 +415,7 @@ public class JDependTask extends Task { if (getOutputFile() != null) { log("Output to be stored in " + getOutputFile().getPath()); } - log("Executing: "+commandline.toString(), Project.MSG_VERBOSE); + log("Executing: " + commandline.toString(), Project.MSG_VERBOSE); try { return execute.execute(); } catch (IOException e) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java index 12645587b..f2bc54a3b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java @@ -65,7 +65,7 @@ import java.io.DataInputStream; * strings from a class file. * @author Patrick C. Beard. */ -class ConstantPool extends Object{ +class ConstantPool { final static byte UTF8 = 1, UNUSED = 2, INTEGER = 3, FLOAT = 4, LONG = 5, DOUBLE = 6, @@ -76,84 +76,82 @@ class ConstantPool extends Object{ Object[] values; - ConstantPool( DataInput data ) throws IOException { + ConstantPool(DataInput data) throws IOException { super(); - int count = data .readUnsignedShort(); + int count = data.readUnsignedShort(); types = new byte [ count ]; values = new Object [ count ]; // read in all constant pool entries. - for ( int i = 1; i < count; i++ ) { - byte type = data .readByte(); + for (int i = 1; i < count; i++) { + byte type = data.readByte(); types[i] = type; switch (type) { case UTF8 : - values[i] = data .readUTF(); + values[i] = data.readUTF(); break; case UNUSED : break; case INTEGER : - values[i] = new Integer( data .readInt() ); + values[i] = new Integer(data.readInt()); break; case FLOAT : - values[i] = new Float( data .readFloat() ); + values[i] = new Float(data.readFloat()); break; case LONG : - values[i] = new Long( data .readLong() ); + values[i] = new Long(data.readLong()); ++i; break; case DOUBLE : - values[i] = new Double( data .readDouble() ); + values[i] = new Double(data.readDouble()); ++i; break; case CLASS : case STRING : - values[i] = new Integer( data .readUnsignedShort() ); + values[i] = new Integer(data.readUnsignedShort()); break; case FIELDREF : case METHODREF : case INTERFACEMETHODREF : case NAMEANDTYPE : - values[i] = new Integer( data .readInt() ); + values[i] = new Integer(data.readInt()); break; } } } - - } + /** * Provides a quick and dirty way to determine the true name of a class * given just an InputStream. Reads in just enough to perform this * minimal task only. */ -public class ClassNameReader extends Object{ +public class ClassNameReader extends Object { - public static - String getClassName( InputStream input ) throws IOException { - DataInputStream data = new DataInputStream( input ); + public static String getClassName(InputStream input) throws IOException { + DataInputStream data = new DataInputStream(input); // verify this is a valid class file. - int cookie = data .readInt(); - if ( cookie != 0xCAFEBABE ) { + int cookie = data.readInt(); + if (cookie != 0xCAFEBABE) { return null; } - int version = data .readInt(); + int version = data.readInt(); // read the constant pool. - ConstantPool constants = new ConstantPool( data ); - Object[] values = constants .values; + ConstantPool constants = new ConstantPool(data); + Object[] values = constants.values; // read access flags and class index. - int accessFlags = data .readUnsignedShort(); - int classIndex = data .readUnsignedShort(); + int accessFlags = data.readUnsignedShort(); + int classIndex = data.readUnsignedShort(); Integer stringIndex = (Integer) values[classIndex]; - String className = (String) values[stringIndex .intValue()]; + String className = (String) values[stringIndex.intValue()]; return className; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java index c47e66539..f88e07b2c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java @@ -91,7 +91,7 @@ public class JlinkTask extends MatchingTask { /** * The output file for this run of jlink. Usually a jar or zip file. */ - public void setOutfile( File outfile ) { + public void setOutfile(File outfile) { this.outfile = outfile; } @@ -100,21 +100,21 @@ public class JlinkTask extends MatchingTask { * be merged into the output. */ public Path createMergefiles() { - if ( this .mergefiles == null ) { - this .mergefiles = new Path(getProject()); + if (this.mergefiles == null) { + this.mergefiles = new Path(getProject()); } - return this .mergefiles.createPath(); + return this.mergefiles.createPath(); } /** * Sets the files to be merged into the output. */ - public void setMergefiles( Path mergefiles ) { - if ( this .mergefiles == null ) { - this .mergefiles = mergefiles; + public void setMergefiles(Path mergefiles) { + if (this.mergefiles == null) { + this.mergefiles = mergefiles; } else { - this .mergefiles .append( mergefiles ); + this.mergefiles .append(mergefiles); } } @@ -123,29 +123,29 @@ public class JlinkTask extends MatchingTask { * be added to the output. */ public Path createAddfiles() { - if ( this .addfiles == null ) { - this .addfiles = new Path(getProject()); + if (this.addfiles == null) { + this.addfiles = new Path(getProject()); } - return this .addfiles .createPath(); + return this.addfiles.createPath(); } /** * Sets the files to be added into the output. */ - public void setAddfiles( Path addfiles ) { - if ( this .addfiles == null ) { - this .addfiles = addfiles; + public void setAddfiles(Path addfiles) { + if (this.addfiles == null) { + this.addfiles = addfiles; } else { - this .addfiles .append( addfiles ); + this.addfiles.append(addfiles); } } /** * Defines whether or not the output should be compacted. */ - public void setCompress( boolean compress ) { - this .compress = compress; + public void setCompress(boolean compress) { + this.compress = compress; } /** @@ -153,29 +153,31 @@ public class JlinkTask extends MatchingTask { */ public void execute() throws BuildException { //Be sure everything has been set. - if ( outfile == null ) { - throw new BuildException( "outfile attribute is required! Please set." ); + if (outfile == null) { + throw new BuildException("outfile attribute is required! " + + "Please set."); } if (!haveAddFiles() && !haveMergeFiles()) { - throw new BuildException( "addfiles or mergefiles required! Please set." ); + throw new BuildException("addfiles or mergefiles required! " + + "Please set."); } - log( "linking: " + outfile.getPath() ); - log( "compression: " + compress, Project.MSG_VERBOSE ); + log("linking: " + outfile.getPath()); + log("compression: " + compress, Project.MSG_VERBOSE); jlink linker = new jlink(); - linker .setOutfile( outfile.getPath() ); - linker .setCompression( compress ); - if (haveMergeFiles()){ - log( "merge files: " + mergefiles .toString(), Project .MSG_VERBOSE ); - linker .addMergeFiles( mergefiles .list() ); + linker.setOutfile(outfile.getPath()); + linker.setCompression(compress); + if (haveMergeFiles()) { + log("merge files: " + mergefiles.toString(), Project.MSG_VERBOSE ); + linker.addMergeFiles( mergefiles.list() ); } - if (haveAddFiles()){ - log( "add files: " + addfiles .toString(), Project .MSG_VERBOSE ); - linker .addAddFiles( addfiles .list() ); + if (haveAddFiles()) { + log("add files: " + addfiles.toString(), Project .MSG_VERBOSE); + linker.addAddFiles(addfiles.list()); } try { - linker .link(); - } catch( Exception ex ) { - throw new BuildException( ex, location ); + linker.link(); + } catch(Exception ex) { + throw new BuildException(ex, location); } } @@ -205,7 +207,7 @@ public class JlinkTask extends MatchingTask { private boolean compress = false; - private String ps = System .getProperty( "path.separator" ); + private String ps = System.getProperty("path.separator"); }