Browse Source

Various coding standard fixes

git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@272418 13f79535-47bb-0310-9956-ffa450edef68
master
Conor MacNeill 23 years ago
parent
commit
c6c232893c
100 changed files with 2376 additions and 2285 deletions
  1. +15
    -15
      src/main/org/apache/tools/ant/taskdefs/Delete.java
  2. +14
    -14
      src/main/org/apache/tools/ant/taskdefs/DependSet.java
  3. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/Ear.java
  4. +3
    -3
      src/main/org/apache/tools/ant/taskdefs/Exec.java
  5. +16
    -16
      src/main/org/apache/tools/ant/taskdefs/ExecTask.java
  6. +57
    -51
      src/main/org/apache/tools/ant/taskdefs/Execute.java
  7. +10
    -10
      src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java
  8. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/Exit.java
  9. +6
    -6
      src/main/org/apache/tools/ant/taskdefs/Expand.java
  10. +18
    -21
      src/main/org/apache/tools/ant/taskdefs/FixCRLF.java
  11. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/GUnzip.java
  12. +40
    -40
      src/main/org/apache/tools/ant/taskdefs/GenerateKey.java
  13. +70
    -69
      src/main/org/apache/tools/ant/taskdefs/Get.java
  14. +9
    -9
      src/main/org/apache/tools/ant/taskdefs/Jar.java
  15. +9
    -9
      src/main/org/apache/tools/ant/taskdefs/Java.java
  16. +6
    -7
      src/main/org/apache/tools/ant/taskdefs/Javac.java
  17. +46
    -45
      src/main/org/apache/tools/ant/taskdefs/Javadoc.java
  18. +4
    -4
      src/main/org/apache/tools/ant/taskdefs/Jikes.java
  19. +3
    -2
      src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java
  20. +20
    -21
      src/main/org/apache/tools/ant/taskdefs/KeySubst.java
  21. +5
    -4
      src/main/org/apache/tools/ant/taskdefs/LoadFile.java
  22. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java
  23. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/MatchingTask.java
  24. +5
    -5
      src/main/org/apache/tools/ant/taskdefs/Move.java
  25. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/Pack.java
  26. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java
  27. +8
    -8
      src/main/org/apache/tools/ant/taskdefs/Property.java
  28. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java
  29. +62
    -49
      src/main/org/apache/tools/ant/taskdefs/Recorder.java
  30. +62
    -55
      src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java
  31. +8
    -8
      src/main/org/apache/tools/ant/taskdefs/Replace.java
  32. +9
    -8
      src/main/org/apache/tools/ant/taskdefs/Rmic.java
  33. +25
    -24
      src/main/org/apache/tools/ant/taskdefs/SQLExec.java
  34. +2
    -3
      src/main/org/apache/tools/ant/taskdefs/SendEmail.java
  35. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/Sequential.java
  36. +29
    -28
      src/main/org/apache/tools/ant/taskdefs/SignJar.java
  37. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/Sleep.java
  38. +4
    -4
      src/main/org/apache/tools/ant/taskdefs/StreamPumper.java
  39. +9
    -9
      src/main/org/apache/tools/ant/taskdefs/Tar.java
  40. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java
  41. +5
    -5
      src/main/org/apache/tools/ant/taskdefs/Touch.java
  42. +8
    -8
      src/main/org/apache/tools/ant/taskdefs/Tstamp.java
  43. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/Unpack.java
  44. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/Untar.java
  45. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/UpToDate.java
  46. +14
    -14
      src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java
  47. +29
    -29
      src/main/org/apache/tools/ant/taskdefs/Zip.java
  48. +10
    -10
      src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java
  49. +3
    -1
      src/main/org/apache/tools/ant/taskdefs/condition/ConditionBase.java
  50. +5
    -5
      src/main/org/apache/tools/ant/taskdefs/condition/FilesMatch.java
  51. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/condition/Os.java
  52. +13
    -21
      src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java
  53. +48
    -72
      src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java
  54. +149
    -145
      src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java
  55. +37
    -32
      src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java
  56. +46
    -19
      src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java
  57. +16
    -17
      src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java
  58. +10
    -10
      src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java
  59. +16
    -23
      src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java
  60. +31
    -29
      src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java
  61. +206
    -243
      src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java
  62. +50
    -37
      src/main/org/apache/tools/ant/taskdefs/email/Mailer.java
  63. +50
    -49
      src/main/org/apache/tools/ant/taskdefs/email/Message.java
  64. +62
    -73
      src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java
  65. +50
    -59
      src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java
  66. +16
    -20
      src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java
  67. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/Cab.java
  68. +13
    -14
      src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java
  69. +262
    -192
      src/main/org/apache/tools/ant/taskdefs/optional/IContract.java
  70. +4
    -3
      src/main/org/apache/tools/ant/taskdefs/optional/Javah.java
  71. +3
    -3
      src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java
  72. +263
    -220
      src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java
  73. +12
    -15
      src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java
  74. +9
    -9
      src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java
  75. +78
    -100
      src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java
  76. +5
    -5
      src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java
  77. +6
    -6
      src/main/org/apache/tools/ant/taskdefs/optional/Script.java
  78. +32
    -27
      src/main/org/apache/tools/ant/taskdefs/optional/StyleBook.java
  79. +50
    -41
      src/main/org/apache/tools/ant/taskdefs/optional/Test.java
  80. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java
  81. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java
  82. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java
  83. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java
  84. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java
  85. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java
  86. +10
    -10
      src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java
  87. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java
  88. +36
    -32
      src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java
  89. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java
  90. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java
  91. +13
    -12
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java
  92. +3
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java
  93. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java
  94. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java
  95. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java
  96. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java
  97. +13
    -13
      src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java
  98. +4
    -4
      src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java
  99. +24
    -24
      src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java
  100. +46
    -43
      src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java

+ 15
- 15
src/main/org/apache/tools/ant/taskdefs/Delete.java View File

@@ -145,7 +145,7 @@ public class Delete extends MatchingTask {
* @param failonerror true or false * @param failonerror true or false
*/ */
public void setFailOnError(boolean failonerror) { public void setFailOnError(boolean failonerror) {
this.failonerror=failonerror;
this.failonerror = failonerror;
} }




@@ -291,9 +291,9 @@ public class Delete extends MatchingTask {
log("Deleting: " + file.getAbsolutePath()); log("Deleting: " + file.getAbsolutePath());


if (!file.delete()) { if (!file.delete()) {
String message="Unable to delete file "
String message = "Unable to delete file "
+ file.getAbsolutePath(); + file.getAbsolutePath();
if(failonerror) {
if (failonerror) {
throw new BuildException(message); throw new BuildException(message);
} else { } else {
log(message, quiet ? Project.MSG_VERBOSE log(message, quiet ? Project.MSG_VERBOSE
@@ -325,7 +325,7 @@ public class Delete extends MatchingTask {
} }


// delete the files in the filesets // delete the files in the filesets
for (int i=0; i<filesets.size(); i++) {
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i); FileSet fs = (FileSet) filesets.elementAt(i);
try { try {
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
@@ -379,9 +379,9 @@ public class Delete extends MatchingTask {
} else { } else {
log("Deleting " + f.getAbsolutePath(), verbosity); log("Deleting " + f.getAbsolutePath(), verbosity);
if (!f.delete()) { if (!f.delete()) {
String message="Unable to delete file "
String message = "Unable to delete file "
+ f.getAbsolutePath(); + f.getAbsolutePath();
if(failonerror) {
if (failonerror) {
throw new BuildException(message); throw new BuildException(message);
} else { } else {
log(message, log(message,
@@ -392,9 +392,9 @@ public class Delete extends MatchingTask {
} }
log("Deleting directory " + d.getAbsolutePath(), verbosity); log("Deleting directory " + d.getAbsolutePath(), verbosity);
if (!d.delete()) { if (!d.delete()) {
String message="Unable to delete directory "
String message = "Unable to delete directory "
+ dir.getAbsolutePath(); + dir.getAbsolutePath();
if(failonerror) {
if (failonerror) {
throw new BuildException(message); throw new BuildException(message);
} else { } else {
log(message, log(message,
@@ -414,13 +414,13 @@ public class Delete extends MatchingTask {
if (files.length > 0) { if (files.length > 0) {
log("Deleting " + files.length + " files from " log("Deleting " + files.length + " files from "
+ d.getAbsolutePath()); + d.getAbsolutePath());
for (int j=0; j<files.length; j++) {
for (int j = 0; j < files.length; j++) {
File f = new File(d, files[j]); File f = new File(d, files[j]);
log("Deleting " + f.getAbsolutePath(), verbosity); log("Deleting " + f.getAbsolutePath(), verbosity);
if (!f.delete()) { if (!f.delete()) {
String message="Unable to delete file "
String message = "Unable to delete file "
+ f.getAbsolutePath(); + f.getAbsolutePath();
if(failonerror) {
if (failonerror) {
throw new BuildException(message); throw new BuildException(message);
} else { } else {
log(message, log(message,
@@ -432,15 +432,15 @@ public class Delete extends MatchingTask {


if (dirs.length > 0 && includeEmpty) { if (dirs.length > 0 && includeEmpty) {
int dirCount = 0; 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]); File dir = new File(d, dirs[j]);
String[] dirFiles = dir.list(); String[] dirFiles = dir.list();
if (dirFiles == null || dirFiles.length == 0) { if (dirFiles == null || dirFiles.length == 0) {
log("Deleting " + dir.getAbsolutePath(), verbosity); log("Deleting " + dir.getAbsolutePath(), verbosity);
if (!dir.delete()) { if (!dir.delete()) {
String message="Unable to delete directory "
String message = "Unable to delete directory "
+ dir.getAbsolutePath(); + dir.getAbsolutePath();
if(failonerror) {
if (failonerror) {
throw new BuildException(message); throw new BuildException(message);
} else { } else {
log(message, log(message,
@@ -454,7 +454,7 @@ public class Delete extends MatchingTask {


if (dirCount > 0) { if (dirCount > 0) {
log("Deleted " + dirCount + " director" + log("Deleted " + dirCount + " director" +
(dirCount==1 ? "y" : "ies") +
(dirCount == 1 ? "y" : "ies") +
" from " + d.getAbsolutePath()); " from " + d.getAbsolutePath());
} }
} }


+ 14
- 14
src/main/org/apache/tools/ant/taskdefs/DependSet.java View File

@@ -159,12 +159,12 @@ public class DependSet extends MatchingTask {


public void execute() throws BuildException { 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 <srcfileset> or <srcfilelist>" throw new BuildException("At least one <srcfileset> or <srcfilelist>"
+ " element must be set"); + " element must be set");
} }


if ( (targetFileSets.size() == 0) && (targetFileLists.size() == 0) ) {
if ((targetFileSets.size() == 0) && (targetFileLists.size() == 0)) {
throw new BuildException("At least one <targetfileset> or" throw new BuildException("At least one <targetfileset> or"
+ " <targetfilelist> element must be set"); + " <targetfilelist> element must be set");
} }
@@ -198,7 +198,7 @@ public class DependSet extends MatchingTask {
allTargets.addElement(dest); allTargets.addElement(dest);


if (dest.lastModified() > now) { if (dest.lastModified() > now) {
log("Warning: "+targetFiles[i]+" modified in the future.",
log("Warning: " + targetFiles[i] + " modified in the future.",
Project.MSG_WARN); Project.MSG_WARN);
} }


@@ -224,7 +224,7 @@ public class DependSet extends MatchingTask {
File dest = new File(targetFL.getDir(project), targetFiles[i]); File dest = new File(targetFL.getDir(project), targetFiles[i]);
if (!dest.exists()) { if (!dest.exists()) {
log(targetFiles[i]+ " does not exist.", Project.MSG_VERBOSE);
log(targetFiles[i] + " does not exist.", Project.MSG_VERBOSE);
upToDate = false; upToDate = false;
continue; continue;
} }
@@ -232,7 +232,7 @@ public class DependSet extends MatchingTask {
allTargets.addElement(dest); allTargets.addElement(dest);
} }
if (dest.lastModified() > now) { if (dest.lastModified() > now) {
log("Warning: "+targetFiles[i]+" modified in the future.",
log("Warning: " + targetFiles[i] + " modified in the future.",
Project.MSG_WARN); Project.MSG_WARN);
} }


@@ -261,16 +261,16 @@ public class DependSet extends MatchingTask {
FileList sourceFL = (FileList) enumSourceLists.nextElement(); FileList sourceFL = (FileList) enumSourceLists.nextElement();
String[] sourceFiles = sourceFL.getFiles(project); 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]); File src = new File(sourceFL.getDir(project), sourceFiles[i]);


if (src.lastModified() > now) { 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()) { if (!src.exists()) {
log(sourceFiles[i]+ " does not exist.",
log(sourceFiles[i] + " does not exist.",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
upToDate = false; upToDate = false;
break; break;
@@ -296,12 +296,12 @@ public class DependSet extends MatchingTask {
DirectoryScanner sourceDS = sourceFS.getDirectoryScanner(project); DirectoryScanner sourceDS = sourceFS.getDirectoryScanner(project);
String[] sourceFiles = sourceDS.getIncludedFiles(); 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]); File src = new File(sourceFS.getDir(project), sourceFiles[i]);


if (src.lastModified() > now) { 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) { if (src.lastModified() > oldestTargetTime) {
@@ -315,8 +315,8 @@ public class DependSet extends MatchingTask {


if (!upToDate) { if (!upToDate) {
log("Deleting all target files. ", Project.MSG_VERBOSE); 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(), log("Deleting file " + fileToRemove.getAbsolutePath(),
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
fileToRemove.delete(); fileToRemove.delete();


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/Ear.java View File

@@ -140,7 +140,7 @@ public class Ear extends Jar {
if (deploymentDescriptor == null if (deploymentDescriptor == null
|| !deploymentDescriptor.equals(file) || !deploymentDescriptor.equals(file)
|| descriptorAdded) { || descriptorAdded) {
log("Warning: selected "+archiveType
log("Warning: selected " + archiveType
+ " files include a META-INF/application.xml which will" + " files include a META-INF/application.xml which will"
+ " be ignored (please use appxml attribute to " + " be ignored (please use appxml attribute to "
+ archiveType + " task)", Project.MSG_WARN); + archiveType + " task)", Project.MSG_WARN);


+ 3
- 3
src/main/org/apache/tools/ant/taskdefs/Exec.java View File

@@ -148,8 +148,8 @@ public class Exec extends Task {
// exec command on system runtime // exec command on system runtime
Process proc = Runtime.getRuntime().exec(command); 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); log("Output redirected to " + out, Project.MSG_VERBOSE);
} }


@@ -176,7 +176,7 @@ public class Exec extends Task {
err = proc.exitValue(); err = proc.exitValue();
if (err != 0) { if (err != 0) {
if (failOnError) { if (failOnError) {
throw new BuildException("Exec returned: "+err, location);
throw new BuildException("Exec returned: " + err, location);
} else { } else {
log("Result: " + err, Project.MSG_ERR); log("Result: " + err, Project.MSG_ERR);
} }


+ 16
- 16
src/main/org/apache/tools/ant/taskdefs/ExecTask.java View File

@@ -96,7 +96,7 @@ public class ExecTask extends Task {
private ByteArrayOutputStream baos = null; private ByteArrayOutputStream baos = null;
private String outputprop; private String outputprop;
private String resultProperty; private String resultProperty;
private boolean failIfExecFails=true;
private boolean failIfExecFails = true;
private boolean append = false; private boolean append = false;


/** /**
@@ -207,7 +207,7 @@ public class ExecTask extends Task {
* @since Ant 1.5 * @since Ant 1.5
*/ */
public void setResultProperty(String resultProperty) { 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 * passed in value if appropriate
*/ */
protected void maybeSetResultPropertyValue(int result) { 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 * @since Ant 1.5
*/ */
public void setFailIfExecutionFails(boolean flag) { public void setFailIfExecutionFails(boolean flag) {
failIfExecFails=flag;
failIfExecFails = flag;
} }
/** /**
@@ -312,8 +312,8 @@ public class ExecTask extends Task {
exe.setVMLauncher(vmLauncher); exe.setVMLauncher(vmLauncher);
String[] environment = env.getVariables(); String[] environment = env.getVariables();
if (environment != null) { if (environment != null) {
for (int i=0; i<environment.length; i++) {
log("Setting environment variable: "+environment[i],
for (int i = 0; i < environment.length; i++) {
log("Setting environment variable: " + environment[i],
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
} }
@@ -331,13 +331,13 @@ public class ExecTask extends Task {


err = exe.execute(); err = exe.execute();
//test for and handle a forced process death //test for and handle a forced process death
if(exe.killedProcess()) {
log("Timeout: killed the sub-process",Project.MSG_WARN);
if (exe.killedProcess()) {
log("Timeout: killed the sub-process", Project.MSG_WARN);
} }
maybeSetResultPropertyValue(err); maybeSetResultPropertyValue(err);
if (err != 0) { if (err != 0) {
if (failOnError) { if (failOnError) {
throw new BuildException(taskType + " returned: "+err,
throw new BuildException(taskType + " returned: " + err,
location); location);
} else { } else {
log("Result: " + err, Project.MSG_ERR); log("Result: " + err, Project.MSG_ERR);
@@ -368,10 +368,10 @@ public class ExecTask extends Task {
runExecute(exe); runExecute(exe);
} catch (IOException e) { } catch (IOException e) {
if (failIfExecFails) { if (failIfExecFails) {
throw new BuildException("Execute failed: "+e.toString(), e,
throw new BuildException("Execute failed: " + e.toString(), e,
location); location);
} else { } else {
log("Execute failed: "+e.toString(), Project.MSG_ERR);
log("Execute failed: " + e.toString(), Project.MSG_ERR);
} }
} finally { } finally {
// close the output file if required // close the output file if required
@@ -383,16 +383,16 @@ public class ExecTask extends Task {
* Create the StreamHandler to use with our Execute instance. * Create the StreamHandler to use with our Execute instance.
*/ */
protected ExecuteStreamHandler createHandler() throws BuildException { protected ExecuteStreamHandler createHandler() throws BuildException {
if(out!=null) {
if (out != null) {
try { try {
fos = new FileOutputStream(out.getAbsolutePath(), append); fos = new FileOutputStream(out.getAbsolutePath(), append);
log("Output redirected to " + out, Project.MSG_VERBOSE); log("Output redirected to " + out, Project.MSG_VERBOSE);
return new PumpStreamHandler(fos); return new PumpStreamHandler(fos);
} catch (FileNotFoundException fne) { } catch (FileNotFoundException fne) {
throw new BuildException("Cannot write to "+out, fne,
throw new BuildException("Cannot write to " + out, fne,
location); location);
} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("Cannot write to "+out, ioe,
throw new BuildException("Cannot write to " + out, ioe,
location); location);
} }
} else if (outputprop != null) { } else if (outputprop != null) {


+ 57
- 51
src/main/org/apache/tools/ant/taskdefs/Execute.java View File

@@ -114,23 +114,23 @@ public class Execute {
try { try {
vmLauncher = new Java13CommandLauncher(); vmLauncher = new Java13CommandLauncher();
} }
catch ( NoSuchMethodException exc ) {
// Ignore and keep try
catch (NoSuchMethodException exc) {
// Ignore and keep trying
} }


if ( Os.isFamily("mac") ) {
if (Os.isFamily("mac")) {
// Mac // Mac
shellLauncher = new MacCommandLauncher(new CommandLauncher()); shellLauncher = new MacCommandLauncher(new CommandLauncher());
} }
else if ( Os.isFamily("os/2") ) {
else if (Os.isFamily("os/2")) {
// OS/2 - use same mechanism as Windows 2000 // OS/2 - use same mechanism as Windows 2000
shellLauncher = new WinNTCommandLauncher(new CommandLauncher()); shellLauncher = new WinNTCommandLauncher(new CommandLauncher());
} }
else if ( Os.isFamily("windows") ) {
else if (Os.isFamily("windows")) {
// Windows. Need to determine which JDK we're running in // Windows. Need to determine which JDK we're running in


CommandLauncher baseLauncher; CommandLauncher baseLauncher;
if ( System.getProperty("java.version").startsWith("1.1") ) {
if (System.getProperty("java.version").startsWith("1.1")) {
// JDK 1.1 // JDK 1.1
baseLauncher = new Java11CommandLauncher(); baseLauncher = new Java11CommandLauncher();
} }
@@ -139,7 +139,7 @@ public class Execute {
baseLauncher = new CommandLauncher(); baseLauncher = new CommandLauncher();
} }


if ( !Os.isFamily("win9x") ) {
if (!Os.isFamily("win9x")) {
// Windows XP/2000/NT // Windows XP/2000/NT
shellLauncher = new WinNTCommandLauncher(baseLauncher); shellLauncher = new WinNTCommandLauncher(baseLauncher);
} }
@@ -148,10 +148,10 @@ public class Execute {
shellLauncher = new ScriptCommandLauncher("bin/antRun.bat", baseLauncher); shellLauncher = new ScriptCommandLauncher("bin/antRun.bat", baseLauncher);
} }
} }
else if ( Os.isFamily("netware") ) {
else if (Os.isFamily("netware")) {
// NetWare. Need to determine which JDK we're running in // NetWare. Need to determine which JDK we're running in
CommandLauncher baseLauncher; CommandLauncher baseLauncher;
if ( System.getProperty("java.version").startsWith("1.1") ) {
if (System.getProperty("java.version").startsWith("1.1")) {
// JDK 1.1 // JDK 1.1
baseLauncher = new Java11CommandLauncher(); baseLauncher = new Java11CommandLauncher();
} }
@@ -184,7 +184,7 @@ public class Execute {
// Make sure we do not recurse forever // Make sure we do not recurse forever
exe.setNewenvironment(true); exe.setNewenvironment(true);
int retval = exe.execute(); int retval = exe.execute();
if ( retval != 0 ) {
if (retval != 0) {
// Just try to use what we got // Just try to use what we got
} }


@@ -224,15 +224,15 @@ public class Execute {
} }


private static String[] getProcEnvCommand() { private static String[] getProcEnvCommand() {
if ( Os.isFamily("os/2") ) {
if (Os.isFamily("os/2")) {
// OS/2 - use same mechanism as Windows 2000 // OS/2 - use same mechanism as Windows 2000
// Not sure // Not sure
String[] cmd = {"cmd", "/c", "set" }; String[] cmd = {"cmd", "/c", "set" };
return cmd; return cmd;
} }
else if ( Os.isFamily("windows") ) {
else if (Os.isFamily("windows")) {
// Determine if we're running under XP/2000/NT or 98/95 // Determine if we're running under XP/2000/NT or 98/95
if ( !Os.isFamily("win9x") ) {
if (!Os.isFamily("win9x")) {
// Windows XP/2000/NT // Windows XP/2000/NT
String[] cmd = {"cmd", "/c", "set" }; String[] cmd = {"cmd", "/c", "set" };
return cmd; return cmd;
@@ -243,13 +243,13 @@ public class Execute {
return cmd; return cmd;
} }
} }
else if ( Os.isFamily("unix") ) {
else if (Os.isFamily("unix")) {
// Generic UNIX // Generic UNIX
// Alternatively one could use: /bin/sh -c env // Alternatively one could use: /bin/sh -c env
String[] cmd = {"/usr/bin/env"}; String[] cmd = {"/usr/bin/env"};
return cmd; return cmd;
} }
else if ( Os.isFamily("netware") ) {
else if (Os.isFamily("netware")) {
String[] cmd = {"env"}; String[] cmd = {"env"};
return cmd; return cmd;
} }
@@ -478,7 +478,7 @@ public class Execute {
* @since 1.5 * @since 1.5
*/ */
public boolean killedProcess() { public boolean killedProcess() {
return watchdog!=null && watchdog.killedProcess();
return watchdog != null && watchdog.killedProcess();
} }


/** /**
@@ -490,10 +490,10 @@ public class Execute {
for (int i = 0; i < env.length; i++) { for (int i = 0; i < env.length; i++) {
int pos = env[i].indexOf('='); int pos = env[i].indexOf('=');
// Get key including "=" // Get key including "="
String key = env[i].substring(0, pos+1);
String key = env[i].substring(0, pos + 1);
int size = osEnv.size(); int size = osEnv.size();
for (int j = 0; j < size; j++) { for (int j = 0; j < size; j++) {
if (((String)osEnv.elementAt(j)).startsWith(key)) {
if (((String) osEnv.elementAt(j)).startsWith(key)) {
osEnv.removeElementAt(j); osEnv.removeElementAt(j);
break; break;
} }
@@ -524,12 +524,14 @@ public class Execute {
exe.setAntRun(task.getProject()); exe.setAntRun(task.getProject());
exe.setCommandline(cmdline); exe.setCommandline(cmdline);
int retval = exe.execute(); int retval = exe.execute();
if ( retval != 0 ) {
throw new BuildException(cmdline[0] + " failed with return code " + retval, task.getLocation());
if (retval != 0) {
throw new BuildException(cmdline[0]
+ " failed with return code " + retval, task.getLocation());
} }
} }
catch (java.io.IOException exc) { catch (java.io.IOException exc) {
throw new BuildException("Could not launch " + cmdline[0] + ": " + exc, task.getLocation());
throw new BuildException("Could not launch " + cmdline[0] + ": "
+ exc, task.getLocation());
} }
} }


@@ -548,8 +550,8 @@ public class Execute {
* @param env The environment for the new process. If null, * @param env The environment for the new process. If null,
* the environment of the current proccess is used. * the environment of the current proccess is used.
*/ */
public Process exec(Project project, String[] cmd, String[] env) throws IOException
{
public Process exec(Project project, String[] cmd, String[] env)
throws IOException {
if (project != null) { if (project != null) {
project.log("Execute:CommandLauncher: " + project.log("Execute:CommandLauncher: " +
Commandline.toString(cmd), Project.MSG_DEBUG); Commandline.toString(cmd), Project.MSG_DEBUG);
@@ -568,12 +570,13 @@ public class Execute {
* @param workingDir The directory to start the command in. If null, * @param workingDir The directory to start the command in. If null,
* the current directory is used * the current directory is used
*/ */
public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
{
if ( workingDir == null ) {
public Process exec(Project project, String[] cmd, String[] env,
File workingDir) throws IOException {
if (workingDir == null) {
return exec(project, cmd, env); return exec(project, cmd, env);
} }
throw new IOException("Cannot execute a process in different directory under this JVM");
throw new IOException("Cannot execute a process in different "
+ "directory under this JVM");
} }
} }


@@ -582,17 +585,17 @@ public class Execute {
* in Runtime.exec(). Can only launch commands in the current working * in Runtime.exec(). Can only launch commands in the current working
* directory * directory
*/ */
private static class Java11CommandLauncher extends CommandLauncher
{
private static class Java11CommandLauncher extends CommandLauncher {
/** /**
* Launches the given command in a new process. Needs to quote * Launches the given command in a new process. Needs to quote
* arguments * arguments
*/ */
public Process exec(Project project, String[] cmd, String[] env) throws IOException
{
// Need to quote arguments with spaces, and to escape quote characters
public Process exec(Project project, String[] cmd, String[] env)
throws IOException {
// Need to quote arguments with spaces, and to escape
// quote characters
String[] newcmd = new String[cmd.length]; String[] newcmd = new String[cmd.length];
for ( int i = 0; i < cmd.length; i++ ) {
for (int i = 0; i < cmd.length; i++) {
newcmd[i] = Commandline.quoteArgument(cmd[i]); newcmd[i] = Commandline.quoteArgument(cmd[i]);
} }
if (project != null) { if (project != null) {
@@ -611,8 +614,10 @@ public class Execute {
{ {
public Java13CommandLauncher() throws NoSuchMethodException public Java13CommandLauncher() throws NoSuchMethodException
{ {
// Locate method Runtime.exec(String[] cmdarray, String[] envp, File dir)
_execWithCWD = Runtime.class.getMethod("exec", new Class[] {String[].class, String[].class, File.class});
// Locate method Runtime.exec(String[] cmdarray,
// String[] envp, File dir)
_execWithCWD = Runtime.class.getMethod("exec",
new Class[] {String[].class, String[].class, File.class});
} }


/** /**
@@ -628,15 +633,16 @@ public class Execute {
Commandline.toString(cmd), Project.MSG_DEBUG); Commandline.toString(cmd), Project.MSG_DEBUG);
} }
Object[] arguments = { cmd, env, workingDir }; Object[] arguments = { cmd, env, workingDir };
return (Process)_execWithCWD.invoke(Runtime.getRuntime(), arguments);
return (Process) _execWithCWD.invoke(Runtime.getRuntime(),
arguments);
} }
catch (InvocationTargetException exc) { catch (InvocationTargetException exc) {
Throwable realexc = exc.getTargetException(); Throwable realexc = exc.getTargetException();
if ( realexc instanceof ThreadDeath ) {
throw (ThreadDeath)realexc;
if (realexc instanceof ThreadDeath) {
throw (ThreadDeath) realexc;
} }
else if ( realexc instanceof IOException ) {
throw (IOException)realexc;
else if (realexc instanceof IOException) {
throw (IOException) realexc;
} }
else { else {
throw new BuildException("Unable to execute command", realexc); throw new BuildException("Unable to execute command", realexc);
@@ -694,8 +700,8 @@ public class Execute {
public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
{ {
File commandDir = workingDir; File commandDir = workingDir;
if ( workingDir == null ) {
if ( project != null ) {
if (workingDir == null) {
if (project != null) {
commandDir = project.getBaseDir(); commandDir = project.getBaseDir();
} else { } else {
return exec(project, cmd, env); return exec(project, cmd, env);
@@ -735,7 +741,7 @@ public class Execute {
*/ */
public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
{ {
if ( workingDir == null ) {
if (workingDir == null) {
return exec(project, cmd, env); return exec(project, cmd, env);
} }


@@ -767,8 +773,8 @@ public class Execute {
*/ */
public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
{ {
if ( project == null ) {
if ( workingDir == null ) {
if (project == null) {
if (workingDir == null) {
return exec(project, cmd, env); return exec(project, cmd, env);
} }
throw new IOException("Cannot locate antRun script: No project provided"); throw new IOException("Cannot locate antRun script: No project provided");
@@ -776,14 +782,14 @@ public class Execute {


// Locate the auxiliary script // Locate the auxiliary script
String antHome = project.getProperty("ant.home"); String antHome = project.getProperty("ant.home");
if ( antHome == null ) {
if (antHome == null) {
throw new IOException("Cannot locate antRun script: Property 'ant.home' not found"); throw new IOException("Cannot locate antRun script: Property 'ant.home' not found");
} }
String antRun = project.resolveFile(antHome + File.separator + _script).toString(); String antRun = project.resolveFile(antHome + File.separator + _script).toString();


// Build the command // Build the command
File commandDir = workingDir; File commandDir = workingDir;
if ( workingDir == null && project != null ) {
if (workingDir == null && project != null) {
commandDir = project.getBaseDir(); commandDir = project.getBaseDir();
} }


@@ -816,8 +822,8 @@ public class Execute {
*/ */
public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException
{ {
if ( project == null ) {
if ( workingDir == null ) {
if (project == null) {
if (workingDir == null) {
return exec(project, cmd, env); return exec(project, cmd, env);
} }
throw new IOException("Cannot locate antRun script: No project provided"); throw new IOException("Cannot locate antRun script: No project provided");
@@ -825,14 +831,14 @@ public class Execute {


// Locate the auxiliary script // Locate the auxiliary script
String antHome = project.getProperty("ant.home"); String antHome = project.getProperty("ant.home");
if ( antHome == null ) {
if (antHome == null) {
throw new IOException("Cannot locate antRun script: Property 'ant.home' not found"); throw new IOException("Cannot locate antRun script: Property 'ant.home' not found");
} }
String antRun = project.resolveFile(antHome + File.separator + _script).toString(); String antRun = project.resolveFile(antHome + File.separator + _script).toString();


// Build the command // Build the command
File commandDir = workingDir; File commandDir = workingDir;
if ( workingDir == null && project != null ) {
if (workingDir == null && project != null) {
commandDir = project.getBaseDir(); commandDir = project.getBaseDir();
} }




+ 10
- 10
src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java View File

@@ -208,14 +208,14 @@ public class ExecuteOn extends ExecTask {


Vector fileNames = new Vector(); Vector fileNames = new Vector();
Vector baseDirs = new Vector(); Vector baseDirs = new Vector();
for (int i=0; i<filesets.size(); i++) {
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i); FileSet fs = (FileSet) filesets.elementAt(i);
File base = fs.getDir(project); File base = fs.getDir(project);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);


if (!"dir".equals(type)) { if (!"dir".equals(type)) {
String[] s = getFiles(base, ds); String[] s = getFiles(base, ds);
for (int j=0; j<s.length; j++) {
for (int j = 0; j < s.length; j++) {
fileNames.addElement(s[j]); fileNames.addElement(s[j]);
baseDirs.addElement(base); baseDirs.addElement(base);
} }
@@ -223,7 +223,7 @@ public class ExecuteOn extends ExecTask {


if (!"file".equals(type)) { if (!"file".equals(type)) {
String[] s = getDirs(base, ds);; String[] s = getDirs(base, ds);;
for (int j=0; j<s.length; j++) {
for (int j = 0; j < s.length; j++) {
fileNames.addElement(s[j]); fileNames.addElement(s[j]);
baseDirs.addElement(base); baseDirs.addElement(base);
} }
@@ -238,7 +238,7 @@ public class ExecuteOn extends ExecTask {
if (!parallel) { if (!parallel) {
String[] s = new String[fileNames.size()]; String[] s = new String[fileNames.size()];
fileNames.copyInto(s); fileNames.copyInto(s);
for (int j=0; j<s.length; j++) {
for (int j = 0; j < s.length; j++) {
String[] command = getCommandline(s[j], base); String[] command = getCommandline(s[j], base);
log("Executing " + Commandline.toString(command), log("Executing " + Commandline.toString(command),
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
@@ -280,10 +280,10 @@ public class ExecuteOn extends ExecTask {
Vector targets = new Vector(); Vector targets = new Vector();
if (targetFilePos != null) { if (targetFilePos != null) {
Hashtable addedFiles = new Hashtable(); Hashtable addedFiles = new Hashtable();
for (int i=0; i<srcFiles.length; i++) {
for (int i = 0; i < srcFiles.length; i++) {
String[] subTargets = mapper.mapFileName(srcFiles[i]); String[] subTargets = mapper.mapFileName(srcFiles[i]);
if (subTargets != null) { if (subTargets != null) {
for (int j=0; j<subTargets.length; j++) {
for (int j = 0; j < subTargets.length; j++) {
String name = null; String name = null;
if (!relative) { if (!relative) {
name = name =
@@ -303,7 +303,7 @@ public class ExecuteOn extends ExecTask {
targets.copyInto(targetFiles); targets.copyInto(targetFiles);
String[] orig = cmdl.getCommandline(); String[] orig = cmdl.getCommandline();
String[] result = new String[orig.length+srcFiles.length+targetFiles.length];
String[] result = new String[orig.length + srcFiles.length + targetFiles.length];


int srcIndex = orig.length; int srcIndex = orig.length;
if (srcFilePos != null) { if (srcFilePos != null) {
@@ -366,12 +366,12 @@ public class ExecuteOn extends ExecTask {
} }


// fill in source file names // fill in source file names
for (int i=0; i < srcFiles.length; i++) {
for (int i = 0; i < srcFiles.length; i++) {
if (!relative) { if (!relative) {
result[srcIndex+i] =
result[srcIndex + i] =
(new File(baseDirs[i], srcFiles[i])).getAbsolutePath(); (new File(baseDirs[i], srcFiles[i])).getAbsolutePath();
} else { } else {
result[srcIndex+i] = srcFiles[i];
result[srcIndex + i] = srcFiles[i];
} }
} }
return result; return result;


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/Exit.java View File

@@ -98,8 +98,8 @@ public class Exit extends Task {
* Set a multiline message. * Set a multiline message.
*/ */
public void addText(String msg) { public void addText(String msg) {
if(message==null) {
message="";
if (message == null) {
message = "";
} }
message += project.replaceProperties(msg); message += project.replaceProperties(msg);
} }


+ 6
- 6
src/main/org/apache/tools/ant/taskdefs/Expand.java View File

@@ -127,7 +127,7 @@ public class Expand extends MatchingTask {
} }
} }
if (filesets.size() > 0) { if (filesets.size() > 0) {
for (int j=0; j < filesets.size(); j++) {
for (int j = 0; j < filesets.size(); j++) {
FileSet fs = (FileSet) filesets.elementAt(j); FileSet fs = (FileSet) filesets.elementAt(j);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
File fromDir = fs.getDir(project); File fromDir = fs.getDir(project);
@@ -158,7 +158,7 @@ public class Expand extends MatchingTask {
ze.isDirectory()); ze.isDirectory());
} }


log("expand complete", Project.MSG_VERBOSE );
log("expand complete", Project.MSG_VERBOSE);
} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("Error while expanding " + srcF.getPath(), throw new BuildException("Error while expanding " + srcF.getPath(),
ioe); ioe);
@@ -221,10 +221,10 @@ public class Expand extends MatchingTask {
return; return;
} }


log("expanding " + entryName + " to "+ f,
log("expanding " + entryName + " to " + f,
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
// create intermediary directories - sometimes zip don't add them // create intermediary directories - sometimes zip don't add them
File dirF= fileUtils.getParentFile(f);
File dirF = fileUtils.getParentFile(f);
dirF.mkdirs(); dirF.mkdirs();


if (isDirectory) { if (isDirectory) {
@@ -253,7 +253,7 @@ public class Expand extends MatchingTask {
} }


fileUtils.setFileLastModified(f, entryDate.getTime()); fileUtils.setFileLastModified(f, entryDate.getTime());
} catch( FileNotFoundException ex ) {
} catch (FileNotFoundException ex) {
log("Unable to expand to file " + f.getPath(), Project.MSG_WARN); 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. * @param d Path to the directory.
*/ */
public void setDest(File d) { public void setDest(File d) {
this.dest=d;
this.dest = d;
} }


/** /**


+ 18
- 21
src/main/org/apache/tools/ant/taskdefs/FixCRLF.java View File

@@ -297,7 +297,7 @@ public class FixCRLF extends MatchingTask {
* @param tlength specify the length of tab in spaces, * @param tlength specify the length of tab in spaces,
*/ */
public void setTablength(int tlength) throws BuildException { 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", throw new BuildException("tablength must be between 2 and 80",
location); location);
} }
@@ -366,9 +366,9 @@ public class FixCRLF extends MatchingTask {
// log options used // log options used
log("options:" + log("options:" +
" eol=" + " 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 + " tablength=" + tablength +
" encoding=" + (encoding == null ? "default" : encoding), " encoding=" + (encoding == null ? "default" : encoding),
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
@@ -418,7 +418,7 @@ public class FixCRLF extends MatchingTask {
int endComment; int endComment;


try { try {
line = (OneLiner.BufferLine)lines.nextElement();
line = (OneLiner.BufferLine) lines.nextElement();
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
throw new BuildException(e); throw new BuildException(e);
} }
@@ -449,14 +449,13 @@ public class FixCRLF extends MatchingTask {
break; break;


case IN_MULTI_COMMENT: 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 { else {
endComment = linelen; endComment = linelen;
} }
@@ -604,7 +603,7 @@ public class FixCRLF extends MatchingTask {
lines.close(); lines.close();
} }
} catch (IOException io) { } catch (IOException io) {
log("Error closing "+srcFile, Project.MSG_ERR);
log("Error closing " + srcFile, Project.MSG_ERR);
} // end of catch } // end of catch


if (tmpFile != null) { if (tmpFile != null) {
@@ -767,14 +766,12 @@ public class FixCRLF extends MatchingTask {
nextStop += tablength; nextStop += tablength;
} }


for ( ; nextStop - placediff <= linestring.length()
; nextStop += tablength)
{
for (; nextStop - placediff <= linestring.length()
; nextStop += tablength) {
for (tabCol = nextStop; for (tabCol = nextStop;
--tabCol - placediff >= place --tabCol - placediff >= place
&& linestring.charAt(tabCol - placediff) == ' ' && linestring.charAt(tabCol - placediff) == ' '
;)
{
;) {
; // Loop for the side-effects ; // Loop for the side-effects
} }
// tabCol is column index of the last non-space character // tabCol is column index of the last non-space character
@@ -863,7 +860,7 @@ public class FixCRLF extends MatchingTask {
reader.mark(2); reader.mark(2);
switch ((ch = reader.read())) { switch ((ch = reader.read())) {
case '\r': case '\r':
if ((char)(ch = reader.read()) == '\n') {
if ((char) (ch = reader.read()) == '\n') {
eolcount += 2; eolcount += 2;
eolStr.append("\r\n"); eolStr.append("\r\n");
} }
@@ -935,7 +932,7 @@ public class FixCRLF extends MatchingTask {
public Object nextElement() public Object nextElement()
throws NoSuchElementException throws NoSuchElementException
{ {
if (! hasMoreElements()) {
if (!hasMoreElements()) {
throw new NoSuchElementException("OneLiner"); throw new NoSuchElementException("OneLiner");
} }
BufferLine tmpLine = BufferLine tmpLine =


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/GUnzip.java View File

@@ -84,7 +84,7 @@ public class GUnzip extends Unpack {


protected void extract() { protected void extract() {
if (source.lastModified() > dest.lastModified()) { if (source.lastModified() > dest.lastModified()) {
log("Expanding "+ source.getAbsolutePath() + " to "
log("Expanding " + source.getAbsolutePath() + " to "
+ dest.getAbsolutePath()); + dest.getAbsolutePath());


FileOutputStream out = null; FileOutputStream out = null;


+ 40
- 40
src/main/org/apache/tools/ant/taskdefs/GenerateKey.java View File

@@ -111,25 +111,25 @@ public class GenerateKey extends Task {
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
boolean firstPass = true; boolean firstPass = true;


for( int i = 0; i < size; i++ ) {
if( !firstPass ) {
for (int i = 0; i < size; i++) {
if (!firstPass) {
sb.append(" ,"); sb.append(" ,");
} }
firstPass = false; 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(); return sb.toString();
} }


public String encode( final String string ) {
public String encode(final String string) {
int end = string.indexOf(','); int end = string.indexOf(',');


if( -1 == end ) {
if (-1 == end) {
return string; return string;
} }
@@ -137,15 +137,15 @@ public class GenerateKey extends Task {
int start = 0; 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; start = end + 1;
end = string.indexOf( ',', start );
end = string.indexOf(',', start);
} }


sb.append( string.substring( start ) );
sb.append(string.substring(start));
return sb.toString(); return sb.toString();
} }
@@ -173,24 +173,24 @@ public class GenerateKey extends Task {
protected boolean verbose; protected boolean verbose;


public DistinguishedName createDname() throws BuildException { 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(); expandedDname = new DistinguishedName();
return expandedDname; return expandedDname;
} }
public void setDname(final String dname) { 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; this.dname = dname;
} }
@@ -224,18 +224,18 @@ public class GenerateKey extends Task {
} }


public void setKeysize(final String keysize) throws BuildException { 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 { 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 { public void execute() throws BuildException {
if (Project.getJavaVersion().equals(Project.JAVA_1_1)) { 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) { if (null == alias) {
throw new BuildException( "alias attribute must be set" );
throw new BuildException("alias attribute must be set");
} }


if (null == storepass) { if (null == storepass) {
throw new BuildException( "storepass attribute must be set" );
throw new BuildException("storepass attribute must be set");
} }


if (null == dname && null == expandedDname) { if (null == dname && null == expandedDname) {
throw new BuildException( "dname must be set" );
throw new BuildException("dname must be set");
} }


final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
@@ -337,13 +337,13 @@ public class GenerateKey extends Task {
sb.append("\" "); sb.append("\" ");
} }


log("Generating Key for " + alias );
log("Generating Key for " + alias);
final ExecTask cmd = (ExecTask) project.createTask("exec"); final ExecTask cmd = (ExecTask) project.createTask("exec");
cmd.setExecutable("keytool"); cmd.setExecutable("keytool");
Commandline.Argument arg=cmd.createArg();
Commandline.Argument arg = cmd.createArg();
arg.setLine(sb.toString()); arg.setLine(sb.toString());
cmd.setFailonerror(true); cmd.setFailonerror(true);
cmd.setTaskName( getTaskName() );
cmd.setTaskName(getTaskName());
cmd.execute(); cmd.execute();
} }
} }


+ 70
- 69
src/main/org/apache/tools/ant/taskdefs/Get.java View File

@@ -119,24 +119,24 @@ public class Get extends Task {
log("Getting: " + source); log("Getting: " + source);


//set the timestamp to the file date. //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 //set up the URL connection
URLConnection connection=source.openConnection();
URLConnection connection = source.openConnection();
//modify the headers //modify the headers
//NB: things like user authentication could go in here too. //NB: things like user authentication could go in here too.
if(useTimestamp && hasTimestamp) {
if (useTimestamp && hasTimestamp) {
connection.setIfModifiedSince(timestamp); connection.setIfModifiedSince(timestamp);
} }
// prepare Java 1.1 style credentials // prepare Java 1.1 style credentials
@@ -162,10 +162,11 @@ public class Get extends Task {
//connect to the remote site (may take some time) //connect to the remote site (may take some time)
connection.connect(); connection.connect();
//next test for a 304 result (HTTP only) //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 //not modified so no file download. just return
//instead and trace out something so the user //instead and trace out something so the user
//doesn't think that the download happened when it //doesn't think that the download happened when it
@@ -174,8 +175,8 @@ public class Get extends Task {
return; return;
} }
// test for 401 result (HTTP only) // 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"); log("Not authorized - check " + dest + " for details");
return; return;
} }
@@ -190,21 +191,21 @@ public class Get extends Task {


FileOutputStream fos = new FileOutputStream(dest); 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 { try {
is = connection.getInputStream(); is = connection.getInputStream();
break; 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; return;
} }
throw new BuildException( "Can't get " + source + " to " + dest,
throw new BuildException("Can't get " + source + " to " + dest,
location); location);
} }


@@ -217,7 +218,7 @@ public class Get extends Task {
System.out.print("."); System.out.print(".");
} }
} }
if(verbose) {
if (verbose) {
System.out.println(); System.out.println();
} }
fos.close(); fos.close();
@@ -226,23 +227,23 @@ public class Get extends Task {
//if (and only if) the use file time option is set, then //if (and only if) the use file time option is set, then
//the saved file now has its timestamp set to that of the //the saved file now has its timestamp set to that of the
//downloaded file //downloaded file
if(useTimestamp) {
long remoteTimestamp=connection.getLastModified();
if (useTimestamp) {
long remoteTimestamp = connection.getLastModified();
if (verbose) { 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" ? " - using current time instead"
: "")); : ""));
} }
if(remoteTimestamp!=0) {
if (remoteTimestamp != 0) {
FileUtils.newFileUtils() FileUtils.newFileUtils()
.setFileLastModified(dest, remoteTimestamp); .setFileLastModified(dest, remoteTimestamp);
} }
} }
} catch (IOException ioe) { } catch (IOException ioe) {
log("Error getting " + source + " to " + dest );
if(ignoreErrors) {
log("Error getting " + source + " to " + dest);
if (ignoreErrors) {
return; return;
} }
throw new BuildException(ioe, location); throw new BuildException(ioe, location);
@@ -352,67 +353,67 @@ public class Get extends Task {
'4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63 '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 bits24;
int bits6; int bits6;


char [ ] out char [ ] out
= new char [ ( ( octetString.length - 1 ) / 3 + 1 ) * 4 ];
= new char[((octetString.length - 1) / 3 + 1) * 4];


int outIndex = 0; int outIndex = 0;
int i = 0;
int i = 0;


while ( ( i + 3 ) <= octetString.length ) {
while ((i + 3) <= octetString.length) {
// store the octets // 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 // 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 // padding
out [ outIndex++ ] = '=';
out[outIndex++] = '=';
} }
else if ( octetString.length - i == 1 )
else if (octetString.length - i == 1)
{ {
// store the octets // 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 // padding
out [ outIndex++ ] = '=';
out [ outIndex++ ] = '=';
out[outIndex++] = '=';
out[outIndex++] = '=';
} }


return new String ( out );
return new String(out);
} }
} }
} }

+ 9
- 9
src/main/org/apache/tools/ant/taskdefs/Jar.java View File

@@ -214,7 +214,7 @@ public class Jar extends Zip {


public void setFilesetmanifest(FilesetManifestConfig config) { public void setFilesetmanifest(FilesetManifestConfig config) {
String filesetManifestConfig = config.getValue(); String filesetManifestConfig = config.getValue();
mergeManifests = ! "skip".equals(filesetManifestConfig);
mergeManifests = !("skip".equals(filesetManifestConfig));
mergeManifestsMain = "merge".equals(filesetManifestConfig); mergeManifestsMain = "merge".equals(filesetManifestConfig);
} }


@@ -239,28 +239,28 @@ public class Jar extends Zip {
manifest = getManifest(manifestFile); manifest = getManifest(manifestFile);
finalManifest.merge(filesetManifest); finalManifest.merge(filesetManifest);
finalManifest.merge(configuredManifest); finalManifest.merge(configuredManifest);
finalManifest.merge(manifest, ! mergeManifestsMain);
finalManifest.merge(manifest, !mergeManifestsMain);
} }
else if (configuredManifest != null) { else if (configuredManifest != null) {
// configuredManifest is the final merge // configuredManifest is the final merge
finalManifest.merge(filesetManifest); finalManifest.merge(filesetManifest);
finalManifest.merge(configuredManifest, finalManifest.merge(configuredManifest,
! mergeManifestsMain);
!mergeManifestsMain);
} }
else if (filesetManifest != null) { else if (filesetManifest != null) {
// filesetManifest is the final (and only) merge // filesetManifest is the final (and only) merge
finalManifest.merge(filesetManifest, ! mergeManifestsMain);
finalManifest.merge(filesetManifest, !mergeManifestsMain);
} }
} else { } else {
// manifest is the final merge // manifest is the final merge
finalManifest.merge(filesetManifest); finalManifest.merge(filesetManifest);
finalManifest.merge(configuredManifest); finalManifest.merge(configuredManifest);
finalManifest.merge(manifest, ! mergeManifestsMain);
finalManifest.merge(manifest, !mergeManifestsMain);
} }


for (Enumeration e = finalManifest.getWarnings(); for (Enumeration e = finalManifest.getWarnings();
e.hasMoreElements(); ) {
log("Manifest warning: " + (String)e.nextElement(),
e.hasMoreElements();) {
log("Manifest warning: " + (String) e.nextElement(),
Project.MSG_WARN); Project.MSG_WARN);
} }


@@ -325,7 +325,7 @@ public class Jar extends Zip {
// since it will be read into a hashtable by the classloader. // since it will be read into a hashtable by the classloader.
Enumeration enum = addedDirs.keys(); Enumeration enum = addedDirs.keys();
while (enum.hasMoreElements()) { 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 // try to be smart, not to be fooled by a weird directory name
// @fixme do we need to check for directories starting by ./ ? // @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 // looks like nothing from META-INF should be added
// and the check is not case insensitive. // and the check is not case insensitive.
// see sun.misc.JarIndex // see sun.misc.JarIndex
if ( dir.startsWith("META-INF") ){
if (dir.startsWith("META-INF")) {
continue; continue;
} }
// name newline // name newline


+ 9
- 9
src/main/org/apache/tools/ant/taskdefs/Java.java View File

@@ -106,7 +106,7 @@ public class Java extends Task {
try { try {
if ((err = executeJava()) != 0) { if ((err = executeJava()) != 0) {
if (failOnError) { if (failOnError) {
throw new BuildException("Java returned: "+err, location);
throw new BuildException("Java returned: " + err, location);
} else { } else {
log("Java Result: " + err, Project.MSG_ERR); log("Java Result: " + err, Project.MSG_ERR);
} }
@@ -207,7 +207,7 @@ public class Java extends Task {
* set the jar name... * set the jar name...
*/ */
public void setJar(File jarfile) throws BuildException { public void setJar(File jarfile) throws BuildException {
if ( cmdl.getClassname() != null ){
if (cmdl.getClassname() != null){
throw new BuildException("Cannot use 'jar' and 'classname' " throw new BuildException("Cannot use 'jar' and 'classname' "
+ "attributes in same command."); + "attributes in same command.");
} }
@@ -218,7 +218,7 @@ public class Java extends Task {
* Set the class name. * Set the class name.
*/ */
public void setClassname(String s) throws BuildException { public void setClassname(String s) throws BuildException {
if ( cmdl.getJar() != null ){
if (cmdl.getJar() != null){
throw new BuildException("Cannot use 'jar' and 'classname' " throw new BuildException("Cannot use 'jar' and 'classname' "
+ "attributes in same command"); + "attributes in same command");
} }
@@ -431,7 +431,7 @@ public class Java extends Task {
dir = project.getBaseDir(); dir = project.getBaseDir();
} else if (!dir.exists() || !dir.isDirectory()) { } else if (!dir.exists() || !dir.isDirectory()) {
throw new BuildException(dir.getAbsolutePath() throw new BuildException(dir.getAbsolutePath()
+" is not a valid directory",
+ " is not a valid directory",
location); location);
} }
@@ -439,8 +439,8 @@ public class Java extends Task {
String[] environment = env.getVariables(); String[] environment = env.getVariables();
if (environment != null) { if (environment != null) {
for (int i=0; i<environment.length; i++) {
log("Setting environment variable: "+environment[i],
for (int i = 0; i < environment.length; i++) {
log("Setting environment variable: " + environment[i],
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
} }
@@ -450,8 +450,8 @@ public class Java extends Task {
exe.setCommandline(command); exe.setCommandline(command);
try { try {
int rc = exe.execute(); int rc = exe.execute();
if(exe.killedProcess()) {
log("Timeout: killed the sub-process",Project.MSG_WARN);
if (exe.killedProcess()) {
log("Timeout: killed the sub-process", Project.MSG_WARN);
} }
return rc; return rc;
} catch (IOException e) { } catch (IOException e) {
@@ -473,7 +473,7 @@ public class Java extends Task {
protected void run(String classname, Vector args) throws BuildException { protected void run(String classname, Vector args) throws BuildException {
CommandlineJava cmdj = new CommandlineJava(); CommandlineJava cmdj = new CommandlineJava();
cmdj.setClassname(classname); cmdj.setClassname(classname);
for (int i=0; i<args.size(); i++) {
for (int i = 0; i < args.size(); i++) {
cmdj.createArgument().setValue((String) args.elementAt(i)); cmdj.createArgument().setValue((String) args.elementAt(i));
} }
run(cmdj); run(cmdj);


+ 6
- 7
src/main/org/apache/tools/ant/taskdefs/Javac.java View File

@@ -518,7 +518,7 @@ public class Javac extends MatchingTask {
/** /**
* Include ant's own classpath in this task's classpath? * Include ant's own classpath in this task's classpath?
*/ */
public void setIncludeantruntime( boolean include ) {
public void setIncludeantruntime(boolean include) {
includeAntRuntime = include; includeAntRuntime = include;
} }


@@ -534,7 +534,7 @@ public class Javac extends MatchingTask {
* Sets whether or not to include the java runtime libraries to this * Sets whether or not to include the java runtime libraries to this
* task's classpath. * task's classpath.
*/ */
public void setIncludejavaruntime( boolean include ) {
public void setIncludejavaruntime(boolean include) {
includeJavaRuntime = include; includeJavaRuntime = include;
} }


@@ -615,12 +615,11 @@ public class Javac extends MatchingTask {
public String[] getCurrentCompilerArgs() { public String[] getCurrentCompilerArgs() {
Vector args = new Vector(); Vector args = new Vector();
for (Enumeration enum = implementationSpecificArgs.elements(); for (Enumeration enum = implementationSpecificArgs.elements();
enum.hasMoreElements();
) {
enum.hasMoreElements();) {
ImplementationSpecificArgument arg = ImplementationSpecificArgument arg =
((ImplementationSpecificArgument) enum.nextElement()); ((ImplementationSpecificArgument) enum.nextElement());
String[] curr = arg.getParts(); String[] curr = arg.getParts();
for (int i=0; i<curr.length; i++) {
for (int i = 0; i < curr.length; i++) {
args.addElement(curr[i]); args.addElement(curr[i]);
} }
} }
@@ -639,7 +638,7 @@ public class Javac extends MatchingTask {
// scan source directories and dest directory to build up // scan source directories and dest directory to build up
// compile lists // compile lists
String[] list = src.list(); String[] list = src.list();
for (int i=0; i<list.length; i++) {
for (int i = 0; i < list.length; i++) {
File srcDir = project.resolveFile(list[i]); File srcDir = project.resolveFile(list[i]);
if (!srcDir.exists()) { if (!srcDir.exists()) {
throw new BuildException("srcdir \"" throw new BuildException("srcdir \""
@@ -792,7 +791,7 @@ public class Javac extends MatchingTask {
+ (destDir != null ? " to " + destDir : "")); + (destDir != null ? " to " + destDir : ""));


if (listFiles) { if (listFiles) {
for (int i=0 ; i < compileList.length ; i++)
for (int i = 0 ; i < compileList.length ; i++)
{ {
String filename = compileList[i].getAbsolutePath(); String filename = compileList[i].getAbsolutePath();
log(filename) ; log(filename) ;


+ 46
- 45
src/main/org/apache/tools/ant/taskdefs/Javadoc.java View File

@@ -306,9 +306,9 @@ public class Javadoc extends Task {
} }


public void setMaxmemory(String max){ public void setMaxmemory(String max){
if(javadoc1){
if (javadoc1) {
cmd.createArgument().setValue("-J-mx" + max); cmd.createArgument().setValue("-J-mx" + max);
} else{
} else {
cmd.createArgument().setValue("-J-Xmx" + max); cmd.createArgument().setValue("-J-Xmx" + max);
} }
} }
@@ -704,17 +704,17 @@ public class Javadoc extends Task {
*/ */
public class TagArgument { public class TagArgument {
/** Name of the tag. */ /** Name of the tag. */
private String name=null;
private String name = null;
/** Description of the tag to place in the JavaDocs. */ /** Description of the tag to place in the JavaDocs. */
private String description=null;
private String description = null;
/** Whether or not the tag is enabled. */ /** Whether or not the tag is enabled. */
private boolean enabled=true;
private boolean enabled = true;
/** /**
* Scope string of the tag. This will form the middle * Scope string of the tag. This will form the middle
* argument of the -tag parameter when the tag is enabled * argument of the -tag parameter when the tag is enabled
* (with an X prepended for and is parsed from human-readable form. * (with an X prepended for and is parsed from human-readable form.
*/ */
private String scope="a";
private String scope = "a";
/** Sole constructor. */ /** Sole constructor. */
public TagArgument () { public TagArgument () {
@@ -727,7 +727,7 @@ public class Javadoc extends Task {
* Must not be <code>null</code> or empty. * Must not be <code>null</code> or empty.
*/ */
public void setName (String name) { public void setName (String name) {
this.name=name;
this.name = name;
} }
/** /**
@@ -738,7 +738,7 @@ public class Javadoc extends Task {
* Must not be <code>null</code> or empty. * Must not be <code>null</code> or empty.
*/ */
public void setDescription (String description) { public void setDescription (String description) {
this.description=description;
this.description = description;
} }


/** /**
@@ -758,12 +758,12 @@ public class Javadoc extends Task {
* specified. * specified.
*/ */
public void setScope (String verboseScope) throws BuildException { 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 // Go through the tokens one at a time, updating the
// elements array and issuing warnings where appropriate. // elements array and issuing warnings where appropriate.
@@ -775,15 +775,15 @@ public class Javadoc extends Task {
getProject().log ("Repeated tag scope element: all", getProject().log ("Repeated tag scope element: all",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
gotAll=true;
gotAll = true;
} }
else { else {
int i; int i;
for (i=0; i < SCOPE_ELEMENTS.length; i++) {
for (i = 0; i < SCOPE_ELEMENTS.length; i++) {
if (next.equals (SCOPE_ELEMENTS[i])) if (next.equals (SCOPE_ELEMENTS[i]))
break; break;
} }
if (i==SCOPE_ELEMENTS.length) {
if (i == SCOPE_ELEMENTS.length) {
throw new BuildException ("Unrecognised scope element: " throw new BuildException ("Unrecognised scope element: "
+ next); + next);
} }
@@ -792,8 +792,8 @@ public class Javadoc extends Task {
getProject().log ("Repeated tag scope element: " getProject().log ("Repeated tag scope element: "
+ next, Project.MSG_VERBOSE); + next, Project.MSG_VERBOSE);
} }
elements[i]=true;
gotNotAll=true;
elements[i] = true;
gotNotAll = true;
} }
} }
} }
@@ -807,16 +807,16 @@ public class Javadoc extends Task {
+ "parameter."); + "parameter.");
} }
if (gotAll) { if (gotAll) {
this.scope="a";
this.scope = "a";
} }
else { else {
StringBuffer buff = new StringBuffer (elements.length); 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]) { if (elements[i]) {
buff.append (SCOPE_ELEMENTS[i].charAt(0)); 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. * @param enabled Whether or not this tag is enabled.
*/ */
public void setEnabled (boolean enabled) { public void setEnabled (boolean enabled) {
this.enabled=enabled;
this.enabled = enabled;
} }
/** /**
@@ -836,15 +836,16 @@ public class Javadoc extends Task {
* is <code>null</code> or empty. * is <code>null</code> or empty.
*/ */
public String getParameter () throws BuildException { public String getParameter () throws BuildException {
if (name==null || name.equals ("")) {
if (name == null || name.equals("")) {
throw new BuildException ("No name specified for custom tag."); throw new BuildException ("No name specified for custom tag.");
} }
if (description==null || description.equals ("")){
if (description == null || description.equals("")){
throw new BuildException 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() { public String getPackages() {
StringBuffer p = new StringBuffer(); StringBuffer p = new StringBuffer();
for (int i = 0; i < packages.size(); i++) { 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(); return p.toString();
} }
@@ -936,7 +937,7 @@ public class Javadoc extends Task {


log("Generating Javadoc", Project.MSG_INFO); log("Generating Javadoc", Project.MSG_INFO);


Commandline toExecute = (Commandline)cmd.clone();
Commandline toExecute = (Commandline) cmd.clone();
toExecute.setExecutable(JavaEnvUtils.getJdkExecutable("javadoc")); toExecute.setExecutable(JavaEnvUtils.getJdkExecutable("javadoc"));


// ------------------------------------------------ general javadoc arguments // ------------------------------------------------ general javadoc arguments
@@ -1011,7 +1012,7 @@ public class Javadoc extends Task {
} }
for (Enumeration e = doclet.getParams(); for (Enumeration e = doclet.getParams();
e.hasMoreElements();) { e.hasMoreElements();) {
DocletParam param = (DocletParam)e.nextElement();
DocletParam param = (DocletParam) e.nextElement();
if (param.getName() == null) { if (param.getName() == null) {
throw new BuildException("Doclet parameters must " throw new BuildException("Doclet parameters must "
+ "have a name"); + "have a name");
@@ -1032,8 +1033,8 @@ public class Javadoc extends Task {


// add the links arguments // add the links arguments
if (links.size() != 0) { 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) { if (la.getHref() == null) {
throw new BuildException("Links must provide the URL " throw new BuildException("Links must provide the URL "
@@ -1100,8 +1101,8 @@ public class Javadoc extends Task {


// add the group arguments // add the group arguments
if (groups.size() != 0) { 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 title = ga.getTitle();
String packages = ga.getPackages(); String packages = ga.getPackages();
if (title == null || packages == null) { if (title == null || packages == null) {
@@ -1117,7 +1118,7 @@ public class Javadoc extends Task {
// JavaDoc 1.4 parameters // JavaDoc 1.4 parameters
if (javadoc4) { if (javadoc4) {
for (Enumeration e = tags.elements(); e.hasMoreElements(); ) {
for (Enumeration e = tags.elements(); e.hasMoreElements();) {
Object element = e.nextElement(); Object element = e.nextElement();
if (element instanceof TagArgument) { if (element instanceof TagArgument) {
TagArgument ta = (TagArgument) element; TagArgument ta = (TagArgument) element;
@@ -1244,7 +1245,7 @@ public class Javadoc extends Task {
exe.setCommandline(toExecute.getCommandline()); exe.setCommandline(toExecute.getCommandline());
int ret = exe.execute(); int ret = exe.execute();
if (ret != 0 && failOnError) { if (ret != 0 && failOnError) {
throw new BuildException("Javadoc returned "+ret, location);
throw new BuildException("Javadoc returned " + ret, location);
} }
} catch (IOException e) { } catch (IOException e) {
throw new BuildException("Javadoc failed: " + e, e, location); throw new BuildException("Javadoc failed: " + e, e, location);
@@ -1273,7 +1274,7 @@ public class Javadoc extends Task {
Vector packages, Vector excludePackages) { Vector packages, Vector excludePackages) {
log("Source path = " + sourcePath.toString(), Project.MSG_VERBOSE); log("Source path = " + sourcePath.toString(), Project.MSG_VERBOSE);
StringBuffer msg = new StringBuffer("Packages = "); StringBuffer msg = new StringBuffer("Packages = ");
for (int i=0; i<packages.size(); i++) {
for (int i = 0; i < packages.size(); i++) {
if (i > 0) { if (i > 0) {
msg.append(","); msg.append(",");
} }
@@ -1283,7 +1284,7 @@ public class Javadoc extends Task {


msg.setLength(0); msg.setLength(0);
msg.append("Exclude Packages = "); msg.append("Exclude Packages = ");
for (int i=0; i<excludePackages.size(); i++) {
for (int i = 0; i < excludePackages.size(); i++) {
if (i > 0) { if (i > 0) {
msg.append(","); msg.append(",");
} }
@@ -1303,8 +1304,8 @@ public class Javadoc extends Task {


Enumeration e = packages.elements(); Enumeration e = packages.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
String pkg = (String)e.nextElement();
pkg = pkg.replace('.','/');
String pkg = (String) e.nextElement();
pkg = pkg.replace('.', '/');
if (pkg.endsWith("*")) { if (pkg.endsWith("*")) {
pkg += "*"; pkg += "*";
} }
@@ -1314,8 +1315,8 @@ public class Javadoc extends Task {


e = excludePackages.elements(); e = excludePackages.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
String pkg = (String)e.nextElement();
pkg = pkg.replace('.','/');
String pkg = (String) e.nextElement();
pkg = pkg.replace('.', '/');
if (pkg.endsWith("*")) { if (pkg.endsWith("*")) {
pkg += "*"; pkg += "*";
} }
@@ -1332,14 +1333,14 @@ public class Javadoc extends Task {
packageListWriter = new PrintWriter(new FileWriter(tmpList)); packageListWriter = new PrintWriter(new FileWriter(tmpList));
} }


for (int j=0; j<list.length; j++) {
for (int j = 0; j < list.length; j++) {
File source = project.resolveFile(list[j]); File source = project.resolveFile(list[j]);
fs.setDir(source); fs.setDir(source);


DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
String[] packageDirs = ds.getIncludedDirectories(); String[] packageDirs = ds.getIncludedDirectories();


for (int i=0; i<packageDirs.length; i++) {
for (int i = 0; i < packageDirs.length; i++) {
File pd = new File(source, packageDirs[i]); File pd = new File(source, packageDirs[i]);
String[] files = pd.list(new FilenameFilter () { String[] files = pd.list(new FilenameFilter () {
public boolean accept(File dir1, String name) { public boolean accept(File dir1, String name) {
@@ -1352,7 +1353,7 @@ public class Javadoc extends Task {


if (files.length > 0) { if (files.length > 0) {
String pkgDir = String pkgDir =
packageDirs[i].replace('/','.').replace('\\','.');
packageDirs[i].replace('/', '.').replace('\\', '.');
if (!addedPackages.contains(pkgDir)) { if (!addedPackages.contains(pkgDir)) {
if (useExternalFile) { if (useExternalFile) {
packageListWriter.println(pkgDir); packageListWriter.println(pkgDir);


+ 4
- 4
src/main/org/apache/tools/ant/taskdefs/Jikes.java View File

@@ -84,7 +84,7 @@ public class Jikes {
* @param jop - Parser to send jike's output to * @param jop - Parser to send jike's output to
* @param command - name of jikes executeable * @param command - name of jikes executeable
*/ */
protected Jikes(JikesOutputParser jop,String command, Project project) {
protected Jikes(JikesOutputParser jop, String command, Project project) {
super(); super();


System.err.println("As of Ant 1.2 released in October 2000, the Jikes class"); 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) { && args.length > 250) {
PrintWriter out = null; PrintWriter out = null;
try { 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)); out = new PrintWriter(new FileWriter(tmpFile));
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
out.println(args[i]); out.println(args[i]);
@@ -132,9 +132,9 @@ public class Jikes {
} }
} }
} else { } else {
commandArray = new String[args.length+1];
commandArray = new String[args.length + 1];
commandArray[0] = command; 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 // We assume, that everything jikes writes goes to


+ 3
- 2
src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java View File

@@ -77,7 +77,8 @@ import java.io.InputStreamReader;
public class JikesOutputParser implements ExecuteStreamHandler { public class JikesOutputParser implements ExecuteStreamHandler {
protected Task task; protected Task task;
protected boolean errorFlag = false; // no errors so far protected boolean errorFlag = false; // no errors so far
protected int errors,warnings;
protected int errors;
protected int warnings;
protected boolean error = false; protected boolean error = false;
protected boolean emacsMode; protected boolean emacsMode;
@@ -182,7 +183,7 @@ public class JikesOutputParser implements ExecuteStreamHandler {


private void setError(boolean err) { private void setError(boolean err) {
error = err; error = err;
if(error) {
if (error) {
errorFlag = true; errorFlag = true;
} }
} }


+ 20
- 21
src/main/org/apache/tools/ant/taskdefs/KeySubst.java View File

@@ -88,7 +88,7 @@ public class KeySubst extends Task {
public void execute() throws BuildException { public void execute() throws BuildException {
log("!! KeySubst is deprecated. Use Filter + Copy instead. !!"); log("!! KeySubst is deprecated. Use Filter + Copy instead. !!");
log("Performing Substitions"); log("Performing Substitions");
if ( source == null || dest == null ) {
if (source == null || dest == null) {
log("Source and destinations must not be null"); log("Source and destinations must not be null");
return; return;
} }
@@ -103,11 +103,11 @@ public class KeySubst extends Task {
String newline = null; String newline = null;
line = br.readLine(); line = br.readLine();
while (line != null) { while (line != null) {
if ( line.length() == 0 ) {
if (line.length() == 0) {
bw.newLine(); bw.newLine();
} else { } else {
newline = KeySubst.replace ( line, replacements );
bw.write ( newline );
newline = KeySubst.replace(line, replacements);
bw.write(newline);
bw.newLine(); bw.newLine();
} }
line = br.readLine(); line = br.readLine();
@@ -173,7 +173,7 @@ public class KeySubst extends Task {
String name = itok.nextToken(); String name = itok.nextToken();
String value = 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) 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(); e.printStackTrace();
} }
} }
@@ -198,23 +197,23 @@ public class KeySubst extends Task {
@return the string with the replacements in it. @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 throws BuildException
{ {
StringBuffer finalString=new StringBuffer();
int index=0;
StringBuffer finalString = new StringBuffer();
int index = 0;
int i = 0; int i = 0;
String key = null; String key = null;
while ((index = origString.indexOf("${", i)) > -1) { while ((index = origString.indexOf("${", i)) > -1) {
key = origString.substring(index + 2, origString.indexOf("}", key = origString.substring(index + 2, origString.indexOf("}",
index+3));
index + 3));
finalString.append (origString.substring(i, index)); finalString.append (origString.substring(i, index));
if ( keys.containsKey ( key ) ) {
if (keys.containsKey(key)) {
finalString.append (keys.get(key)); finalString.append (keys.get(key));
} else { } else {
finalString.append ( "${" );
finalString.append ( key );
finalString.append ( "}" );
finalString.append ("${");
finalString.append (key);
finalString.append ("}");
} }
i = index + 3 + key.length(); i = index + 3 + key.length();
} }


+ 5
- 4
src/main/org/apache/tools/ant/taskdefs/LoadFile.java View File

@@ -166,12 +166,13 @@ public final class LoadFile extends Task {
FileInputStream fis = null; FileInputStream fis = null;
BufferedInputStream bis = null; BufferedInputStream bis = null;
Reader instream = null; Reader instream = null;
log("loading "+srcFile+" into property "+property,Project.MSG_VERBOSE);
log("loading " + srcFile + " into property " + property,
Project.MSG_VERBOSE);
try { try {
final long len = srcFile.length(); 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 //discard most of really big files
final int size=(int) len;
final int size = (int) len;
//open up the file //open up the file
fis = new FileInputStream(srcFile); fis = new FileInputStream(srcFile);
bis = new BufferedInputStream(fis); bis = new BufferedInputStream(fis);
@@ -195,7 +196,7 @@ public final class LoadFile extends Task {
project.setNewProperty(property, text); project.setNewProperty(property, text);
log("loaded " + text.length() + " characters", log("loaded " + text.length() + " characters",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
log(property+" := "+text,Project.MSG_DEBUG);
log(property + " := " + text, Project.MSG_DEBUG);
} }


} catch (final IOException ioe) { } catch (final IOException ioe) {


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/LogOutputStream.java View File

@@ -99,7 +99,7 @@ public class LogOutputStream extends OutputStream {
* @param cc data to log (byte). * @param cc data to log (byte).
*/ */
public void write(int cc) throws IOException { public void write(int cc) throws IOException {
final byte c = (byte)cc;
final byte c = (byte) cc;
if ((c == '\n') || (c == '\r')) { if ((c == '\n') || (c == '\r')) {
if (!skip) { if (!skip) {
processBuffer(); processBuffer();


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/MatchingTask.java View File

@@ -152,7 +152,7 @@ public abstract class MatchingTask extends Task {
while (tok.hasMoreTokens()) { while (tok.hasMoreTokens()) {
String pattern = tok.nextToken().trim(); String pattern = tok.nextToken().trim();
if (pattern.length() > 0) { 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, ", ", StringTokenizer tok = new StringTokenizer(ignoreString, ", ",
false); false);
while (tok.hasMoreTokens()) { while (tok.hasMoreTokens()) {
createExclude().setName("**/"+tok.nextToken().trim()+"/**");
createExclude().setName("**/" + tok.nextToken().trim() + "/**");
} }
} }
} }


+ 5
- 5
src/main/org/apache/tools/ant/taskdefs/Move.java View File

@@ -120,14 +120,14 @@ public class Move extends Copy {
} }
if (fileCopyMap.size() > 0) { // files to move if (fileCopyMap.size() > 0) { // files to move
log("Moving " + fileCopyMap.size() + " files to " + log("Moving " + fileCopyMap.size() + " files to " +
destDir.getAbsolutePath() );
destDir.getAbsolutePath());


Enumeration e = fileCopyMap.keys(); Enumeration e = fileCopyMap.keys();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
String fromFile = (String) e.nextElement(); String fromFile = (String) e.nextElement();
String toFile = (String) fileCopyMap.get(fromFile); String toFile = (String) fileCopyMap.get(fromFile);


if( fromFile.equals( toFile ) ) {
if (fromFile.equals(toFile)) {
log("Skipping self-move of " + fromFile, verbosity); log("Skipping self-move of " + fromFile, verbosity);
continue; continue;
} }
@@ -164,7 +164,7 @@ public class Move extends Copy {
getFilterSets().elements(); getFilterSets().elements();
filterEnum.hasMoreElements();) { filterEnum.hasMoreElements();) {
executionFilters executionFilters
.addFilterSet((FilterSet)filterEnum
.addFilterSet((FilterSet) filterEnum
.nextElement()); .nextElement());
} }
getFileUtils().copyFile(f, d, executionFilters, getFileUtils().copyFile(f, d, executionFilters,
@@ -194,7 +194,7 @@ public class Move extends Copy {
Enumeration e = dirCopyMap.elements(); Enumeration e = dirCopyMap.elements();
int count = 0; int count = 0;
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
File d = new File((String)e.nextElement());
File d = new File((String) e.nextElement());
if (!d.exists()) { if (!d.exists()) {
if (!d.mkdirs()) { if (!d.mkdirs()) {
log("Unable to create directory " log("Unable to create directory "
@@ -214,7 +214,7 @@ public class Move extends Copy {
if (filesets.size() > 0) { if (filesets.size() > 0) {
Enumeration e = filesets.elements(); Enumeration e = filesets.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
FileSet fs = (FileSet)e.nextElement();
FileSet fs = (FileSet) e.nextElement();
File dir = fs.getDir(project); File dir = fs.getDir(project);


if (okToDelete(dir)) { if (okToDelete(dir)) {


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/Pack.java View File

@@ -107,10 +107,10 @@ public abstract class Pack extends Task {
public void execute() throws BuildException { public void execute() throws BuildException {
validate(); validate();


if(zipFile.lastModified() < source.lastModified()){
if (zipFile.lastModified() < source.lastModified()) {
log("Building: " + zipFile.getAbsolutePath()); log("Building: " + zipFile.getAbsolutePath());
pack(); pack();
}else{
} else {
log("Nothing to do: " + zipFile.getAbsolutePath() + log("Nothing to do: " + zipFile.getAbsolutePath() +
" is up to date."); " is up to date.");
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java View File

@@ -127,7 +127,7 @@ class ProcessDestroyer
*/ */
public void run() public void run()
{ {
synchronized(processes)
synchronized (processes)
{ {
Enumeration e = processes.elements(); Enumeration e = processes.elements();
while (e.hasMoreElements()) while (e.hasMoreElements())


+ 8
- 8
src/main/org/apache/tools/ant/taskdefs/Property.java View File

@@ -255,7 +255,7 @@ public class Property extends Task {
log("Unable to find property file: " + file.getAbsolutePath(), log("Unable to find property file: " + file.getAbsolutePath(),
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
} catch(IOException ex) {
} catch (IOException ex) {
throw new BuildException(ex, location); 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(); Properties props = new Properties();
if (!prefix.endsWith(".")) { if (!prefix.endsWith(".")) {
prefix += "."; prefix += ".";
} }
log("Loading Environment " + prefix, Project.MSG_VERBOSE); log("Loading Environment " + prefix, Project.MSG_VERBOSE);
Vector osEnv = Execute.getProcEnvironment(); 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('='); int pos = entry.indexOf('=');
if (pos == -1) { if (pos == -1) {
log("Ignoring: " + entry, Project.MSG_WARN); log("Ignoring: " + entry, Project.MSG_WARN);
@@ -335,7 +335,7 @@ public class Property extends Task {
} }


protected void addProperty(String n, String v) { protected void addProperty(String n, String v) {
if( userProperty ) {
if (userProperty) {
if (project.getUserProperty(n) == null) { if (project.getUserProperty(n) == null) {
project.setUserProperty(n, v); project.setUserProperty(n, v);
} else { } else {
@@ -348,7 +348,7 @@ public class Property extends Task {


private void resolveAllProperties(Properties props) throws BuildException { private void resolveAllProperties(Properties props) throws BuildException {
for (Enumeration e = props.keys(); e.hasMoreElements();) { for (Enumeration e = props.keys(); e.hasMoreElements();) {
String name = (String)e.nextElement();
String name = (String) e.nextElement();
String value = props.getProperty(name); String value = props.getProperty(name);


boolean resolved = false; boolean resolved = false;
@@ -364,9 +364,9 @@ public class Property extends Task {
Enumeration i = fragments.elements(); Enumeration i = fragments.elements();
Enumeration j = propertyRefs.elements(); Enumeration j = propertyRefs.elements();
while (i.hasMoreElements()) { while (i.hasMoreElements()) {
String fragment = (String)i.nextElement();
String fragment = (String) i.nextElement();
if (fragment == null) { if (fragment == null) {
String propertyName = (String)j.nextElement();
String propertyName = (String) j.nextElement();
if (propertyName.equals(name)) { if (propertyName.equals(name)) {
throw new BuildException("Property " + name throw new BuildException("Property " + name
+ " was circularly " + " was circularly "


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/PumpStreamHandler.java View File

@@ -110,10 +110,10 @@ public class PumpStreamHandler implements ExecuteStreamHandler {
public void stop() { public void stop() {
try { try {
inputThread.join(); inputThread.join();
} catch(InterruptedException e) {}
} catch (InterruptedException e) {}
try { try {
errorThread.join(); errorThread.join();
} catch(InterruptedException e) {}
} catch (InterruptedException e) {}
try { try {
err.flush(); err.flush();
} catch (IOException e) {} } catch (IOException e) {}


+ 62
- 49
src/main/org/apache/tools/ant/taskdefs/Recorder.java View File

@@ -51,7 +51,6 @@
* information on the Apache Software Foundation, please see * information on the Apache Software Foundation, please see
* <http://www.apache.org/>. * <http://www.apache.org/>.
*/ */

package org.apache.tools.ant.taskdefs; package org.apache.tools.ant.taskdefs;


import org.apache.tools.ant.BuildException; 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.Project;
import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.EnumeratedAttribute;



import org.apache.tools.ant.Task; import org.apache.tools.ant.Task;


import java.io.PrintStream; import java.io.PrintStream;
@@ -69,11 +67,12 @@ import java.io.IOException;
import java.util.Hashtable; 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 &lt;recorder&gt;
* 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 &lt;recorder&gt; task is called,
* and addes them to the build listener process.
*
* @author <a href="mailto:jayglanville@home.com">J D Glanville</a> * @author <a href="mailto:jayglanville@home.com">J D Glanville</a>
* @see RecorderEntry
* @version 0.5 * @version 0.5
* @since Ant 1.4 * @since Ant 1.4
* @ant.task name="record" category="utility" * @ant.task name="record" category="utility"
@@ -85,19 +84,18 @@ public class Recorder extends Task {


/** The name of the file to record to. */ /** The name of the file to record to. */
private String filename = null; 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; 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; private Boolean start = null;
/** The level to log at. A level of -1 means not initialized yet. */ /** The level to log at. A level of -1 means not initialized yet. */
private int loglevel = -1; private int loglevel = -1;
/**
* Strip task banners if true.
*/
/** Strip task banners if true. */
private boolean emacsMode = false; private boolean emacsMode = false;
/** The list of recorder entries. */ /** The list of recorder entries. */
private static Hashtable recorderEntries = new Hashtable(); private static Hashtable recorderEntries = new Hashtable();
@@ -109,52 +107,59 @@ public class Recorder extends Task {
// ACCESSOR METHODS // 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. * @param fname File name of logfile.
*/ */
public void setName( String fname ) {
public void setName(String fname) {
filename = fname; filename = fname;
} }



/** /**
* Sets the action for the associated recorder entry. * Sets the action for the associated recorder entry.
*
* @param action The action for the entry to take: start or stop. * @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; start = Boolean.TRUE;
} else { } else {
start = Boolean.FALSE; 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); this.append = new Boolean(append);
} }



public void setEmacsMode(boolean emacsMode) { public void setEmacsMode(boolean emacsMode) {
this.emacsMode = emacsMode; this.emacsMode = emacsMode;
} }



/** /**
* Sets the level to which this recorder entry should log to. * Sets the level to which this recorder entry should log to.
*
* @see VerbosityLevelChoices * @see VerbosityLevelChoices
*/ */
public void setLoglevel( VerbosityLevelChoices level ){
public void setLoglevel(VerbosityLevelChoices level) {
//I hate cascading if/elseif clauses !!! //I hate cascading if/elseif clauses !!!
String lev = level.getValue(); String lev = level.getValue();
if ( lev.equalsIgnoreCase("error") ) {

if (lev.equalsIgnoreCase("error")) {
loglevel = Project.MSG_ERR; loglevel = Project.MSG_ERR;
} else if ( lev.equalsIgnoreCase("warn") ){
} else if (lev.equalsIgnoreCase("warn")) {
loglevel = Project.MSG_WARN; loglevel = Project.MSG_WARN;
} else if ( lev.equalsIgnoreCase("info") ){
} else if (lev.equalsIgnoreCase("info")) {
loglevel = Project.MSG_INFO; loglevel = Project.MSG_INFO;
} else if ( lev.equalsIgnoreCase("verbose") ){
} else if (lev.equalsIgnoreCase("verbose")) {
loglevel = Project.MSG_VERBOSE; loglevel = Project.MSG_VERBOSE;
} else if ( lev.equalsIgnoreCase("debug") ){
} else if (lev.equalsIgnoreCase("debug")) {
loglevel = Project.MSG_DEBUG; loglevel = Project.MSG_DEBUG;
} }
} }
@@ -162,23 +167,21 @@ public class Recorder extends Task {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// CORE / MAIN BODY // CORE / MAIN BODY


/**
* The main execution.
*/
/** The main execution. */
public void execute() throws BuildException { 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 // get the recorder entry
RecorderEntry recorder = getRecorder( filename, getProject() );
RecorderEntry recorder = getRecorder(filename, getProject());
// set the values on the recorder // 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 { public static class ActionChoices extends EnumeratedAttribute {
private final static String[] values = {"start", "stop"}; private final static String[] values = {"start", "stop"};


public String[] getValues() { public String[] getValues() {
return values; return values;
} }
} }



/** /**
* A list of possible values for the <code>setLoglevel()</code> method. * A list of possible values for the <code>setLoglevel()</code> method.
* Possible values include: error, warn, info, verbose, debug. * Possible values include: error, warn, info, verbose, debug.
*/ */
public static class VerbosityLevelChoices extends EnumeratedAttribute { public static class VerbosityLevelChoices extends EnumeratedAttribute {
private final static String[] values = { "error", "warn", "info",
private final static String[] values = {"error", "warn", "info",
"verbose", "debug"}; "verbose", "debug"};


public String[] getValues() { public String[] getValues() {
return values; 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); Object o = recorderEntries.get(name);
RecorderEntry entry; RecorderEntry entry;
if ( o == null ) {

if (o == null) {
// create a recorder entry // create a recorder entry
try { try {
entry = new RecorderEntry( name );
entry = new RecorderEntry(name);

PrintStream out = null; PrintStream out = null;
if ( append == null ) {

if (append == null) {
out = new PrintStream( out = new PrintStream(
new FileOutputStream(name)); new FileOutputStream(name));
} else { } else {
@@ -229,9 +241,9 @@ public class Recorder extends Task {
} }
entry.setErrorPrintStream(out); entry.setErrorPrintStream(out);
entry.setOutputPrintStream(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); proj.addBuildListener(entry);
recorderEntries.put(name, entry); recorderEntries.put(name, entry);
@@ -242,3 +254,4 @@ public class Recorder extends Task {
} }


} }


+ 62
- 55
src/main/org/apache/tools/ant/taskdefs/RecorderEntry.java View File

@@ -51,7 +51,6 @@
* information on the Apache Software Foundation, please see * information on the Apache Software Foundation, please see
* <http://www.apache.org/>. * <http://www.apache.org/>.
*/ */

package org.apache.tools.ant.taskdefs; package org.apache.tools.ant.taskdefs;


import org.apache.tools.ant.BuildLogger; import org.apache.tools.ant.BuildLogger;
@@ -62,42 +61,30 @@ import org.apache.tools.ant.util.StringUtils;


import java.io.PrintStream; 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 <a href="mailto:jayglanville@home.com">J D Glanville</a> * @author <a href="mailto:jayglanville@home.com">J D Glanville</a>
* @version 0.5 * @version 0.5
* @since Ant 1.4 * @since Ant 1.4
*/ */
public class RecorderEntry implements BuildLogger {
public class RecorderEntry implements BuildLogger {


////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// ATTRIBUTES // 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; 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; private boolean record = true;
/**
* The current verbosity level to record at.
*/
/** The current verbosity level to record at. */
private int loglevel = Project.MSG_INFO; private int loglevel = Project.MSG_INFO;
/**
* The output PrintStream to record to.
*/
/** The output PrintStream to record to. */
private PrintStream out = null; private PrintStream out = null;
/**
* The start time of the last know target.
*/
/** The start time of the last know target. */
private long targetStartTime = 0l; private long targetStartTime = 0l;
/**
* Strip task banners if true.
*/
/** Strip task banners if true. */
private boolean emacsMode = false; private boolean emacsMode = false;


////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@@ -105,9 +92,8 @@ public class RecorderEntry implements BuildLogger {


/** /**
* @param name The name of this recorder (used as the filename). * @param name The name of this recorder (used as the filename).
*
*/ */
protected RecorderEntry( String name ) {
protected RecorderEntry(String name) {
filename = name; filename = name;
} }


@@ -121,108 +107,129 @@ public class RecorderEntry implements BuildLogger {
return filename; return filename;
} }



/** /**
* Turns off or on this recorder. * Turns off or on this recorder.
*
* @param state true for on, false for off, null for no change. * @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(); record = state.booleanValue();
} }
} }



public void buildStarted(BuildEvent event) { public void buildStarted(BuildEvent event) {
log( "> BUILD STARTED", Project.MSG_DEBUG );
log("> BUILD STARTED", Project.MSG_DEBUG);
} }



public void buildFinished(BuildEvent event) { public void buildFinished(BuildEvent event) {
log( "< BUILD FINISHED", Project.MSG_DEBUG );
log("< BUILD FINISHED", Project.MSG_DEBUG);


Throwable error = event.getException(); Throwable error = event.getException();

if (error == null) { if (error == null) {
out.println(StringUtils.LINE_SEP + "BUILD SUCCESSFUL"); out.println(StringUtils.LINE_SEP + "BUILD SUCCESSFUL");
} else { } else {
out.println(StringUtils.LINE_SEP + "BUILD FAILED"
+ StringUtils.LINE_SEP);
out.println(StringUtils.LINE_SEP + "BUILD FAILED"
+ StringUtils.LINE_SEP);
error.printStackTrace(out); error.printStackTrace(out);
} }
out.flush(); out.flush();
out.close(); out.close();
} }



public void targetStarted(BuildEvent event) { 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(); targetStartTime = System.currentTimeMillis();
} }



public void targetFinished(BuildEvent event) { 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); String time = formatTime(System.currentTimeMillis() - targetStartTime);
log( event.getTarget() + ": duration " + time, Project.MSG_VERBOSE );

log(event.getTarget() + ": duration " + time, Project.MSG_VERBOSE);
out.flush(); out.flush();
} }



public void taskStarted(BuildEvent event) { 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) { public void taskFinished(BuildEvent event) {
log( "<<< TASK FINISHED -- " + event.getTask(), Project.MSG_DEBUG );
log("<<< TASK FINISHED -- " + event.getTask(), Project.MSG_DEBUG);
out.flush(); out.flush();
} }



public void messageLogged(BuildEvent event) { public void messageLogged(BuildEvent event) {
log( "--- MESSAGE LOGGED", Project.MSG_DEBUG );
log("--- MESSAGE LOGGED", Project.MSG_DEBUG);


StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
if ( event.getTask() != null ) {

if (event.getTask() != null) {
String name = event.getTask().getTaskName(); String name = event.getTask().getTaskName();
if (!emacsMode) { if (!emacsMode) {
String label = "[" + name + "] "; String label = "[" + name + "] ";
int size = DefaultLogger.LEFT_COLUMN_SIZE - label.length(); int size = DefaultLogger.LEFT_COLUMN_SIZE - label.length();

for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
buf.append(" "); buf.append(" ");
} // for
}// for
buf.append(label); 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. * The thing that actually sends the information to the output.
*
* @param mesg The message to log. * @param mesg The message to log.
* @param level The verbosity level of the message. * @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); out.println(mesg);
} }
} }



public void setMessageOutputLevel(int level) { 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; loglevel = level;
} }
} }



public void setOutputPrintStream(PrintStream output) { public void setOutputPrintStream(PrintStream output) {
out = output; out = output;
} }



public void setEmacsMode(boolean emacsMode) { public void setEmacsMode(boolean emacsMode) {
this.emacsMode = emacsMode; this.emacsMode = emacsMode;
} }



public void setErrorPrintStream(PrintStream err) { public void setErrorPrintStream(PrintStream err) {
out = err; out = err;
} }



private static String formatTime(long millis) { private static String formatTime(long millis) {
long seconds = millis / 1000; long seconds = millis / 1000;
long minutes = seconds / 60; long minutes = seconds / 60;
@@ -230,14 +237,14 @@ public class RecorderEntry implements BuildLogger {


if (minutes > 0) { if (minutes > 0) {
return Long.toString(minutes) + " minute" 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" return Long.toString(seconds) + " second"
+ (seconds%60 == 1 ? "" : "s");
+ (seconds % 60 == 1 ? "" : "s");
} }


} }
} }


+ 8
- 8
src/main/org/apache/tools/ant/taskdefs/Replace.java View File

@@ -228,7 +228,7 @@ public class Replace extends MatchingTask {
if (replaceFilterFile != null) { if (replaceFilterFile != null) {
Properties props = getProperties(replaceFilterFile); Properties props = getProperties(replaceFilterFile);
Enumeration enum = props.keys(); Enumeration enum = props.keys();
while(enum.hasMoreElements()){
while (enum.hasMoreElements()){
String token = enum.nextElement().toString(); String token = enum.nextElement().toString();
Replacefilter replaceFilter = createReplacefilter(); Replacefilter replaceFilter = createReplacefilter();
replaceFilter.setToken(token); replaceFilter.setToken(token);
@@ -254,8 +254,8 @@ public class Replace extends MatchingTask {
DirectoryScanner ds = super.getDirectoryScanner(dir); DirectoryScanner ds = super.getDirectoryScanner(dir);
String[] srcs = ds.getIncludedFiles(); String[] srcs = ds.getIncludedFiles();
for(int i=0; i<srcs.length; i++) {
File file = new File(dir,srcs[i]);
for (int i = 0; i < srcs.length; i++) {
File file = new File(dir, srcs[i]);
processFile(file); processFile(file);
} }
} }
@@ -294,7 +294,7 @@ public class Replace extends MatchingTask {
throw new BuildException(message, location); throw new BuildException(message, location);
} }
if (token != null && "".equals(token.getText())) { if (token != null && "".equals(token.getText())) {
String message ="The token attribute must not be an empty string.";
String message = "The token attribute must not be an empty string.";
throw new BuildException(message, location); throw new BuildException(message, location);
} }
} }
@@ -367,14 +367,14 @@ public class Replace extends MatchingTask {
// when multibyte characters exist in the source file // when multibyte characters exist in the source file
// but then again, it might be smaller than needed on // but then again, it might be smaller than needed on
// platforms like Windows where length can't be trusted // platforms like Windows where length can't be trusted
int fileLengthInBytes = (int)(src.length());
int fileLengthInBytes = (int) src.length();
StringBuffer tmpBuf = new StringBuffer(fileLengthInBytes); StringBuffer tmpBuf = new StringBuffer(fileLengthInBytes);
int readChar = 0; int readChar = 0;
int totread = 0; int totread = 0;
while (true) { while (true) {
readChar = br.read(); readChar = br.read();
if (readChar < 0) { break; } if (readChar < 0) { break; }
tmpBuf.append((char)readChar);
tmpBuf.append((char) readChar);
totread++; totread++;
} }


@@ -406,7 +406,7 @@ public class Replace extends MatchingTask {


boolean changes = !newString.equals(buf); boolean changes = !newString.equals(buf);
if (changes) { if (changes) {
bw.write(newString,0,newString.length());
bw.write(newString, 0, newString.length());
bw.flush(); bw.flush();
} }


@@ -571,7 +571,7 @@ public class Replace extends MatchingTask {


// search again // search again
start = found + str1.length(); start = found + str1.length();
found = str.indexOf(str1,start);
found = str.indexOf(str1, start);
++replaceCount; ++replaceCount;
} }




+ 9
- 8
src/main/org/apache/tools/ant/taskdefs/Rmic.java View File

@@ -301,7 +301,7 @@ public class Rmic extends MatchingTask {
/** /**
* Include ant's own classpath in this task's classpath? * Include ant's own classpath in this task's classpath?
*/ */
public void setIncludeantruntime( boolean include ) {
public void setIncludeantruntime(boolean include) {
includeAntRuntime = include; includeAntRuntime = include;
} }


@@ -317,7 +317,7 @@ public class Rmic extends MatchingTask {
* Sets whether or not to include the java runtime libraries to this * Sets whether or not to include the java runtime libraries to this
* task's classpath. * task's classpath.
*/ */
public void setIncludejavaruntime( boolean include ) {
public void setIncludejavaruntime(boolean include) {
includeJavaRuntime = include; includeJavaRuntime = include;
} }


@@ -379,7 +379,7 @@ public class Rmic extends MatchingTask {
RmicAdapter adapter = RmicAdapterFactory.getRmic(compiler, this); RmicAdapter adapter = RmicAdapterFactory.getRmic(compiler, this);
// now we need to populate the compiler adapter // now we need to populate the compiler adapter
adapter.setRmic( this );
adapter.setRmic(this);


Path classpath = adapter.getClasspath(); Path classpath = adapter.getClasspath();
loader = new AntClassLoader(project, classpath); loader = new AntClassLoader(project, classpath);
@@ -403,7 +403,7 @@ public class Rmic extends MatchingTask {
int fileCount = compileList.size(); int fileCount = compileList.size();
if (fileCount > 0) { if (fileCount > 0) {
log("RMI Compiling " + fileCount + log("RMI Compiling " + fileCount +
" class"+ (fileCount > 1 ? "es" : "")+" to " + baseDir,
" class" + (fileCount > 1 ? "es" : "") + " to " + baseDir,
Project.MSG_INFO); Project.MSG_INFO);
// finally, lets execute the compiler!! // finally, lets execute the compiler!!
@@ -453,7 +453,7 @@ public class Rmic extends MatchingTask {
String[] generatedFiles = String[] generatedFiles =
adapter.getMapper().mapFileName(classFileName); adapter.getMapper().mapFileName(classFileName);


for (int i=0; i<generatedFiles.length; i++) {
for (int i = 0; i < generatedFiles.length; i++) {
if (!generatedFiles[i].endsWith(".class")) { if (!generatedFiles[i].endsWith(".class")) {
// don't know how to handle that - a IDL file doesn't // don't know how to handle that - a IDL file doesn't
// have a corresponding Java source for example. // have a corresponding Java source for example.
@@ -461,7 +461,7 @@ public class Rmic extends MatchingTask {
} }
String sourceFileName = String sourceFileName =
generatedFiles[i].substring(0, classFileName.length()-6)
generatedFiles[i].substring(0, classFileName.length() - 6)
+ ".java"; + ".java";


File oldFile = new File(baseDir, sourceFileName); File oldFile = new File(baseDir, sourceFileName);
@@ -570,7 +570,8 @@ public class Rmic extends MatchingTask {
/** /**
* Classloader for the user-specified classpath. * Classloader for the user-specified classpath.
*/ */
public ClassLoader getLoader() {return loader;}

public ClassLoader getLoader() {
return loader;
}
} }



+ 25
- 24
src/main/org/apache/tools/ant/taskdefs/SQLExec.java View File

@@ -142,7 +142,7 @@ public class SQLExec extends Task {
/** /**
* Autocommit flag. Default value is false * Autocommit flag. Default value is false
*/ */
private boolean autocommit=false;
private boolean autocommit = false;
/** /**
* SQL statement * SQL statement
@@ -426,7 +426,7 @@ public class SQLExec extends Task {
sqlCommand = sqlCommand.trim(); sqlCommand = sqlCommand.trim();


try { try {
if (srcFile == null && sqlCommand.length()==0
if (srcFile == null && sqlCommand.length() == 0
&& filesets.isEmpty()) { && filesets.isEmpty()) {
if (transactions.size() == 0) { if (transactions.size() == 0) {
throw new BuildException("Source file or fileset, " throw new BuildException("Source file or fileset, "
@@ -466,13 +466,13 @@ public class SQLExec extends Task {
// in most cases. // in most cases.
synchronized (loaderMap){ synchronized (loaderMap){
if (caching){ if (caching){
loader = (AntClassLoader)loaderMap.get(driver);
loader = (AntClassLoader) loaderMap.get(driver);
} }
if (loader == null){ if (loader == null){
log( "Loading " + driver
+ " using AntClassLoader with classpath "
+ classpath,
Project.MSG_VERBOSE );
log("Loading " + driver
+ " using AntClassLoader with classpath "
+ classpath,
Project.MSG_VERBOSE);
loader = new AntClassLoader(project, classpath); loader = new AntClassLoader(project, classpath);
if (caching){ if (caching){
loaderMap.put(driver, loader); loaderMap.put(driver, loader);
@@ -491,22 +491,22 @@ public class SQLExec extends Task {
dc = Class.forName(driver); dc = Class.forName(driver);
} }
driverInstance = (Driver) dc.newInstance(); driverInstance = (Driver) dc.newInstance();
}catch(ClassNotFoundException e){
} catch (ClassNotFoundException e){
throw new BuildException("Class Not Found: JDBC driver " throw new BuildException("Class Not Found: JDBC driver "
+ driver + " could not be loaded", + driver + " could not be loaded",
location); location);
}catch(IllegalAccessException e){
} catch (IllegalAccessException e){
throw new BuildException("Illegal Access: JDBC driver " throw new BuildException("Illegal Access: JDBC driver "
+ driver + " could not be loaded", + driver + " could not be loaded",
location); location);
}catch(InstantiationException e) {
} catch (InstantiationException e) {
throw new BuildException("Instantiation Exception: JDBC driver " throw new BuildException("Instantiation Exception: JDBC driver "
+ driver + " could not be loaded", + driver + " could not be loaded",
location); location);
} }


// deal with the filesets // 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); FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
File srcDir = fs.getDir(project); File srcDir = fs.getDir(project);
@@ -514,7 +514,7 @@ public class SQLExec extends Task {
String[] srcFiles = ds.getIncludedFiles(); String[] srcFiles = ds.getIncludedFiles();
// Make a transaction for each file // Make a transaction for each file
for ( int j=0 ; j<srcFiles.length ; j++ ) {
for (int j = 0 ; j < srcFiles.length ; j++) {
Transaction t = createTransaction(); Transaction t = createTransaction();
t.setSrc(new File(srcDir, srcFiles[j])); t.setSrc(new File(srcDir, srcFiles[j]));
} }
@@ -525,8 +525,8 @@ public class SQLExec extends Task {
t.setSrc(srcFile); t.setSrc(srcFile);
t.addText(sqlCommand); t.addText(sqlCommand);


try{
log("connecting to " + url, Project.MSG_VERBOSE );
try {
log("connecting to " + url, Project.MSG_VERBOSE);
Properties info = new Properties(); Properties info = new Properties();
info.put("user", userId); info.put("user", userId);
info.put("password", password); info.put("password", password);
@@ -534,7 +534,7 @@ public class SQLExec extends Task {
if (conn == null) { if (conn == null) {
// Driver doesn't understand the URL // Driver doesn't understand the URL
throw new SQLException("No suitable Driver for "+url);
throw new SQLException("No suitable Driver for " + url);
} }
if (!isValidRdbms(conn)) { if (!isValidRdbms(conn)) {
@@ -574,14 +574,14 @@ public class SQLExec extends Task {
out.close(); out.close();
} }
} }
} catch(IOException e){
} catch (IOException e){
if (!autocommit && conn != null && onError.equals("abort")) { if (!autocommit && conn != null && onError.equals("abort")) {
try { try {
conn.rollback(); conn.rollback();
} catch (SQLException ex) {} } catch (SQLException ex) {}
} }
throw new BuildException(e, location); throw new BuildException(e, location);
} catch(SQLException e){
} catch (SQLException e){
if (!autocommit && conn != null && onError.equals("abort")) { if (!autocommit && conn != null && onError.equals("abort")) {
try { try {
conn.rollback(); conn.rollback();
@@ -616,7 +616,7 @@ public class SQLExec extends Task {
BufferedReader in = new BufferedReader(reader); BufferedReader in = new BufferedReader(reader);
while ((line=in.readLine()) != null){
while ((line = in.readLine()) != null){
line = line.trim(); line = line.trim();
line = project.replaceProperties(line); line = project.replaceProperties(line);
if (line.startsWith("//")) { if (line.startsWith("//")) {
@@ -656,7 +656,7 @@ public class SQLExec extends Task {
} }
// Catch any statements not followed by ; // Catch any statements not followed by ;
if(!sql.equals("")){
if (!sql.equals("")){
execSQL(sql, out); execSQL(sql, out);
} }
} }
@@ -677,7 +677,8 @@ public class SQLExec extends Task {
log("RDBMS = " + theVendor, Project.MSG_VERBOSE); log("RDBMS = " + theVendor, Project.MSG_VERBOSE);
if (theVendor == null || theVendor.indexOf(rdbms) < 0) { if (theVendor == null || theVendor.indexOf(rdbms) < 0) {
log("Not the required RDBMS: "+rdbms, Project.MSG_VERBOSE);
log("Not the required RDBMS: " + rdbms,
Project.MSG_VERBOSE);
return false; return false;
} }
} }
@@ -692,7 +693,7 @@ public class SQLExec extends Task {
!(theVersion.startsWith(version) || !(theVersion.startsWith(version) ||
theVersion.indexOf(" " + version) >= 0)) { theVersion.indexOf(" " + version) >= 0)) {
log("Not the required version: \"" log("Not the required version: \""
+ version +"\"", Project.MSG_VERBOSE);
+ version + "\"", Project.MSG_VERBOSE);
return false; return false;
} }
} }
@@ -718,7 +719,7 @@ public class SQLExec extends Task {
try { try {
totalSql++; totalSql++;
if (!statement.execute(sql)) { if (!statement.execute(sql)) {
log(statement.getUpdateCount()+" rows affected",
log(statement.getUpdateCount() + " rows affected",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
else { else {
@@ -728,9 +729,9 @@ public class SQLExec extends Task {
} }
SQLWarning warning = conn.getWarnings(); SQLWarning warning = conn.getWarnings();
while(warning!=null){
while (warning != null){
log(warning + " sql warning", Project.MSG_VERBOSE); log(warning + " sql warning", Project.MSG_VERBOSE);
warning=warning.getNextWarning();
warning = warning.getNextWarning();
} }
conn.clearWarnings(); conn.clearWarnings();
goodSql++; goodSql++;


+ 2
- 3
src/main/org/apache/tools/ant/taskdefs/SendEmail.java View File

@@ -118,8 +118,7 @@ public class SendEmail extends EmailTask
* *
* @deprecated Use {@link #setMailport(int)} instead. * @deprecated Use {@link #setMailport(int)} instead.
*/ */
public void setMailport( Integer value )
{
setMailport( value.intValue() );
public void setMailport(Integer value) {
setMailport(value.intValue());
} }
} }

+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/Sequential.java View File

@@ -90,7 +90,7 @@ public class Sequential extends Task
*/ */
public void execute() throws BuildException { public void execute() throws BuildException {
for (Enumeration e = nestedTasks.elements(); e.hasMoreElements();) { for (Enumeration e = nestedTasks.elements(); e.hasMoreElements();) {
Task nestedTask = (Task)e.nextElement();
Task nestedTask = (Task) e.nextElement();
nestedTask.perform(); nestedTask.perform();
} }
} }


+ 29
- 28
src/main/org/apache/tools/ant/taskdefs/SignJar.java View File

@@ -172,20 +172,19 @@ public class SignJar extends Task {
throw new BuildException("jar must be set through jar attribute " throw new BuildException("jar must be set through jar attribute "
+ "or nested filesets"); + "or nested filesets");
} }
if( null != jar ) {
if (null != jar) {
doOneJar(jar, signedjar); doOneJar(jar, signedjar);
return; return;
} else { } else {
//Assume null != filesets //Assume null != filesets


// deal with the filesets // 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); FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
String[] jarFiles = ds.getIncludedFiles(); String[] jarFiles = ds.getIncludedFiles();
for(int j=0; j<jarFiles.length; j++) {
doOneJar( new File( fs.getDir(project), jarFiles[j] ),
null);
for (int j = 0; j < jarFiles.length; j++) {
doOneJar(new File(fs.getDir(project), jarFiles[j]), null);
} }
} }
} }
@@ -206,7 +205,7 @@ public class SignJar extends Task {
throw new BuildException("storepass attribute must be set"); throw new BuildException("storepass attribute must be set");
} }


if(isUpToDate(jarSource, jarTarget)) {
if (isUpToDate(jarSource, jarTarget)) {
return; return;
} }


@@ -215,7 +214,7 @@ public class SignJar extends Task {


if (null != keystore) { if (null != keystore) {
cmd.createArg().setValue("-keystore"); cmd.createArg().setValue("-keystore");
cmd.createArg().setValue( keystore.toString() );
cmd.createArg().setValue(keystore.toString());
} }


if (null != storepass) { if (null != storepass) {
@@ -235,12 +234,12 @@ public class SignJar extends Task {


if (null != sigfile) { if (null != sigfile) {
cmd.createArg().setValue("-sigfile"); cmd.createArg().setValue("-sigfile");
cmd.createArg().setValue( sigfile.toString() );
cmd.createArg().setValue(sigfile.toString());
} }


if (null != jarTarget) { if (null != jarTarget) {
cmd.createArg().setValue("-signedjar"); cmd.createArg().setValue("-signedjar");
cmd.createArg().setValue( jarTarget.toString() );
cmd.createArg().setValue(jarTarget.toString());
} }


if (verbose) { if (verbose) {
@@ -255,37 +254,37 @@ public class SignJar extends Task {
cmd.createArg().setValue("-sectionsonly"); cmd.createArg().setValue("-sectionsonly");
} }


cmd.createArg().setValue( jarSource.toString() );
cmd.createArg().setValue(jarSource.toString());


cmd.createArg().setValue(alias); cmd.createArg().setValue(alias);


log("Signing Jar : " + jarSource.getAbsolutePath()); log("Signing Jar : " + jarSource.getAbsolutePath());
cmd.setFailonerror(true); cmd.setFailonerror(true);
cmd.setTaskName( getTaskName() );
cmd.setTaskName(getTaskName());
cmd.execute(); cmd.execute();
} }


protected boolean isUpToDate(File jarFile, File signedjarFile) { protected boolean isUpToDate(File jarFile, File signedjarFile) {
if( null == jarFile ) {
if (null == jarFile) {
return false; return false;
} }


if( null != signedjarFile ) {
if (null != signedjarFile) {


if(!jarFile.exists()) {
if (!jarFile.exists()) {
return false; return false;
} }
if(!signedjarFile.exists()) {
if (!signedjarFile.exists()) {
return false; return false;
} }
if(jarFile.equals(signedjarFile)) {
if (jarFile.equals(signedjarFile)) {
return false; return false;
} }
if(signedjarFile.lastModified() > jarFile.lastModified()) {
if (signedjarFile.lastModified() > jarFile.lastModified()) {
return true; return true;
} }
} else { } else {
if( lazy ) {
if (lazy) {
return isSigned(jarFile); return isSigned(jarFile);
} }
} }
@@ -297,33 +296,35 @@ public class SignJar extends Task {
final String SIG_START = "META-INF/"; final String SIG_START = "META-INF/";
final String SIG_END = ".SF"; final String SIG_END = ".SF";


if( !file.exists() ) {
if (!file.exists()) {
return false; return false;
} }
ZipFile jarFile = null; ZipFile jarFile = null;
try { try {
jarFile = new ZipFile(file); jarFile = new ZipFile(file);
if(null == alias) {
if (null == alias) {
Enumeration entries = jarFile.entries(); 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 true;
} }
} }
return false; return false;
} else { } else {
return jarFile.getEntry(SIG_START+alias.toUpperCase()+
return jarFile.getEntry(SIG_START + alias.toUpperCase() +
SIG_END) != null; SIG_END) != null;
} }
} catch(IOException e) {
} catch (IOException e) {
return false; return false;
} finally { } finally {
if(jarFile != null) {
try {jarFile.close();} catch(IOException e) {}
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
}
} }
} }
} }

} }



+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/Sleep.java View File

@@ -197,8 +197,8 @@ public class Sleep extends Task {
throws BuildException { throws BuildException {
try { try {
validate(); validate();
long sleepTime=getSleepTime();
log("sleeping for "+sleepTime+" milliseconds",
long sleepTime = getSleepTime();
log("sleeping for " + sleepTime + " milliseconds",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
doSleep(sleepTime); doSleep(sleepTime);
} }


+ 4
- 4
src/main/org/apache/tools/ant/taskdefs/StreamPumper.java View File

@@ -93,7 +93,7 @@ public class StreamPumper implements Runnable {
* Terminates as soon as the input stream is closed or an error occurs. * Terminates as soon as the input stream is closed or an error occurs.
*/ */
public void run() { public void run() {
synchronized(this) {
synchronized (this) {
// Just in case this object is reused in the future // Just in case this object is reused in the future
finished = false; finished = false;
} }
@@ -108,9 +108,9 @@ public class StreamPumper implements Runnable {
Thread.sleep(SLEEP); Thread.sleep(SLEEP);
} catch (InterruptedException e) {} } catch (InterruptedException e) {}
} }
} catch(IOException e) {
} catch (IOException e) {
} finally { } finally {
synchronized(this) {
synchronized (this) {
finished = true; finished = true;
notify(); notify();
} }
@@ -132,7 +132,7 @@ public class StreamPumper implements Runnable {
public synchronized void waitFor() public synchronized void waitFor()
throws InterruptedException throws InterruptedException
{ {
while(!isFinished()) {
while (!isFinished()) {
wait(); wait();
} }
} }


+ 9
- 9
src/main/org/apache/tools/ant/taskdefs/Tar.java View File

@@ -231,7 +231,7 @@ public class Tar extends MatchingTask {
// fileset // fileset
boolean upToDate = true; boolean upToDate = true;
for (Enumeration e = filesets.elements(); e.hasMoreElements();) { for (Enumeration e = filesets.elements(); e.hasMoreElements();) {
TarFileSet fs = (TarFileSet)e.nextElement();
TarFileSet fs = (TarFileSet) e.nextElement();
String[] files = fs.getFiles(project); String[] files = fs.getFiles(project);


if (!archiveIsUpToDate(files)) { if (!archiveIsUpToDate(files)) {
@@ -248,12 +248,12 @@ public class Tar extends MatchingTask {
} }


if (upToDate) { 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; return;
} }


log("Building tar: "+ tarFile.getAbsolutePath(), Project.MSG_INFO);
log("Building tar: " + tarFile.getAbsolutePath(), Project.MSG_INFO);


TarOutputStream tOut = null; TarOutputStream tOut = null;
try { try {
@@ -274,7 +274,7 @@ public class Tar extends MatchingTask {
longWarningGiven = false; longWarningGiven = false;
for (Enumeration e = filesets.elements(); for (Enumeration e = filesets.elements();
e.hasMoreElements();) { e.hasMoreElements();) {
TarFileSet fs = (TarFileSet)e.nextElement();
TarFileSet fs = (TarFileSet) e.nextElement();
String[] files = fs.getFiles(project); String[] files = fs.getFiles(project);
if (files.length > 1 && fs.getFullpath().length() > 0) { if (files.length > 1 && fs.getFullpath().length() > 0) {
throw new BuildException("fullpath attribute may only " throw new BuildException("fullpath attribute may only "
@@ -284,7 +284,7 @@ public class Tar extends MatchingTask {
} }
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
File f = new File(fs.getDir(project), files[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); tarFile(f, tOut, name, fs);
} }
} }
@@ -344,10 +344,10 @@ public class Tar extends MatchingTask {
try { try {
if (vPath.length() >= TarConstants.NAMELEN) { if (vPath.length() >= TarConstants.NAMELEN) {
if (longFileMode.isOmitMode()) { if (longFileMode.isOmitMode()) {
log("Omitting: "+ vPath, Project.MSG_INFO);
log("Omitting: " + vPath, Project.MSG_INFO);
return; return;
} else if (longFileMode.isWarnMode()) { } else if (longFileMode.isWarnMode()) {
log("Entry: "+ vPath + " longer than " +
log("Entry: " + vPath + " longer than " +
TarConstants.NAMELEN + " characters.", TarConstants.NAMELEN + " characters.",
Project.MSG_WARN); Project.MSG_WARN);
if (!longWarningGiven) { if (!longWarningGiven) {
@@ -358,7 +358,7 @@ public class Tar extends MatchingTask {
} }
} else if (longFileMode.isFailMode()) { } else if (longFileMode.isFailMode()) {
throw new BuildException( throw new BuildException(
"Entry: "+ vPath + " longer than " +
"Entry: " + vPath + " longer than " +
TarConstants.NAMELEN + "characters.", location); TarConstants.NAMELEN + "characters.", location);
} }
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/TaskOutputStream.java View File

@@ -103,7 +103,7 @@ public class TaskOutputStream extends OutputStream {
*/ */


public void write(int c) throws IOException { public void write(int c) throws IOException {
char cc = (char)c;
char cc = (char) c;
if (cc == '\r' || cc == '\n') { if (cc == '\r' || cc == '\n') {
// line feed // line feed
if (line.length() > 0) { if (line.length() > 0) {


+ 5
- 5
src/main/org/apache/tools/ant/taskdefs/Touch.java View File

@@ -179,11 +179,11 @@ public class Touch extends Task {
protected void touch() throws BuildException { protected void touch() throws BuildException {
if (file != null) { if (file != null) {
if (!file.exists()) { if (!file.exists()) {
log("Creating "+file, Project.MSG_INFO);
log("Creating " + file, Project.MSG_INFO);
try { try {
fileUtils.createNewFile(file); fileUtils.createNewFile(file);
} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("Could not create "+file, ioe,
throw new BuildException("Could not create " + file, ioe,
location); location);
} }
} }
@@ -206,7 +206,7 @@ public class Touch extends Task {
} }


// deal with the filesets // 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); FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);
File fromDir = fs.getDir(project); File fromDir = fs.getDir(project);
@@ -214,11 +214,11 @@ public class Touch extends Task {
String[] srcFiles = ds.getIncludedFiles(); String[] srcFiles = ds.getIncludedFiles();
String[] srcDirs = ds.getIncludedDirectories(); 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])); 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])); touch(new File(fromDir, srcDirs[j]));
} }
} }


+ 8
- 8
src/main/org/apache/tools/ant/taskdefs/Tstamp.java View File

@@ -111,9 +111,9 @@ public class Tstamp extends Task {
project.setNewProperty(prefix + "TODAY", today.format(d)); project.setNewProperty(prefix + "TODAY", today.format(d));


Enumeration i = customFormats.elements(); 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) { } catch (Exception e) {
@@ -138,7 +138,7 @@ public class Tstamp extends Task {
private String variant; private String variant;
private int offset = 0; private int offset = 0;
private int field = Calendar.DATE; private int field = Calendar.DATE;
private String prefix="";
private String prefix = "";


public CustomFormat(String prefix) public CustomFormat(String prefix)
{ {
@@ -157,7 +157,7 @@ public class Tstamp extends Task {


public void setLocale(String locale) public void setLocale(String locale)
{ {
StringTokenizer st = new StringTokenizer( locale, " \t\n\r\f,");
StringTokenizer st = new StringTokenizer(locale, " \t\n\r\f,");
try { try {
language = st.nextToken(); language = st.nextToken();
if (st.hasMoreElements()) { if (st.hasMoreElements()) {
@@ -165,7 +165,7 @@ public class Tstamp extends Task {
if (st.hasMoreElements()) { if (st.hasMoreElements()) {
variant = st.nextToken(); variant = st.nextToken();
if (st.hasMoreElements()) { if (st.hasMoreElements()) {
throw new BuildException( "bad locale format",
throw new BuildException("bad locale format",
getLocation()); getLocation());
} }
} }
@@ -175,8 +175,8 @@ public class Tstamp extends Task {
} }
} }
catch (NoSuchElementException e) { catch (NoSuchElementException e) {
throw new BuildException( "bad locale format", e,
getLocation());
throw new BuildException("bad locale format", e,
getLocation());
} }
} }




+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/Unpack.java View File

@@ -132,9 +132,9 @@ public abstract class Unpack extends Task {
int len = sourceName.length(); int len = sourceName.length();
if (defaultExtension != null if (defaultExtension != null
&& len > defaultExtension.length() && len > defaultExtension.length()
&& defaultExtension.equalsIgnoreCase(sourceName.substring(len-defaultExtension.length()))) {
&& defaultExtension.equalsIgnoreCase(sourceName.substring(len - defaultExtension.length()))) {
dest = new File(dest, sourceName.substring(0, dest = new File(dest, sourceName.substring(0,
len-defaultExtension.length()));
len - defaultExtension.length()));
} else { } else {
dest = new File(dest, sourceName); dest = new File(dest, sourceName);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/Untar.java View File

@@ -88,7 +88,7 @@ public class Untar extends Expand {
extractFile(fileUtils, srcF, dir, tis, extractFile(fileUtils, srcF, dir, tis,
te.getName(), te.getModTime(), te.isDirectory()); te.getName(), te.getModTime(), te.isDirectory());
} }
log("expand complete", Project.MSG_VERBOSE );
log("expand complete", Project.MSG_VERBOSE);


} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("Error while expanding " + srcF.getPath(), throw new BuildException("Error while expanding " + srcF.getPath(),


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/UpToDate.java View File

@@ -116,7 +116,7 @@ public class UpToDate extends Task implements Condition {
* Returns the value, or "true" if a specific value wasn't provided. * Returns the value, or "true" if a specific value wasn't provided.
*/ */
private String getValue() { private String getValue() {
return ( _value != null ) ? _value : "true";
return (_value != null) ? _value : "true";
} }


/** /**


+ 14
- 14
src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java View File

@@ -193,7 +193,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
// check if liaison wants to log errors using us as logger // check if liaison wants to log errors using us as logger
if (liaison instanceof XSLTLoggerAware) { if (liaison instanceof XSLTLoggerAware) {
((XSLTLoggerAware)liaison).setLogger(this);
((XSLTLoggerAware) liaison).setLogger(this);
} }
log("Using " + liaison.getClass().toString(), Project.MSG_VERBOSE); log("Using " + liaison.getClass().toString(), Project.MSG_VERBOSE);
@@ -224,7 +224,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
*/ */
//-- make sure Source directory exists... //-- make sure Source directory exists...
if (destDir == null ) {
if (destDir == null) {
String msg = "destdir attributes must be set!"; String msg = "destdir attributes must be set!";
throw new BuildException(msg); throw new BuildException(msg);
} }
@@ -234,7 +234,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
// Process all the files marked for styling // Process all the files marked for styling
list = scanner.getIncludedFiles(); list = scanner.getIncludedFiles();
for (int i = 0; i < list.length; ++i) { for (int i = 0; i < list.length; ++i) {
process( baseDir, list[i], destDir, stylesheet );
process(baseDir, list[i], destDir, stylesheet);
} }
if (performDirectoryScan) { if (performDirectoryScan) {
// Process all the directories marked for styling // 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){ for (int j = 0; j < dirs.length; ++j){
list = new File(baseDir, dirs[j]).list(); list = new File(baseDir, dirs[j]).list();
for (int i = 0; i < list.length; ++i) { 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 { private void resolveProcessor(String proc) throws Exception {
if (proc.equals("trax")) { if (proc.equals("trax")) {
final Class clazz = loadClass(TRAX_LIAISON_CLASS); final Class clazz = loadClass(TRAX_LIAISON_CLASS);
liaison = (XSLTLiaison)clazz.newInstance();
liaison = (XSLTLiaison) clazz.newInstance();
} else if (proc.equals("xslp")) { } else if (proc.equals("xslp")) {
log("DEPRECATED - xslp processor is deprecated. Use trax or " log("DEPRECATED - xslp processor is deprecated. Use trax or "
+ "xalan instead."); + "xalan instead.");
@@ -367,7 +367,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
liaison = (XSLTLiaison) clazz.newInstance(); liaison = (XSLTLiaison) clazz.newInstance();
} else if (proc.equals("xalan")) { } else if (proc.equals("xalan")) {
final Class clazz = loadClass(XALAN_LIASON_CLASS); final Class clazz = loadClass(XALAN_LIASON_CLASS);
liaison = (XSLTLiaison)clazz.newInstance();
liaison = (XSLTLiaison) clazz.newInstance();
} else { } else {
liaison = (XSLTLiaison) loadClass(proc).newInstance(); liaison = (XSLTLiaison) loadClass(proc).newInstance();
} }
@@ -448,7 +448,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
if (force || if (force ||
inFile.lastModified() > outFile.lastModified() || inFile.lastModified() > outFile.lastModified() ||
styleSheetLastModified > outFile.lastModified()) { styleSheetLastModified > outFile.lastModified()) {
ensureDirectoryFor( outFile );
ensureDirectoryFor(outFile);
log("Processing " + inFile + " to " + outFile); log("Processing " + inFile + " to " + outFile);
configureLiaison(stylesheet); configureLiaison(stylesheet);
@@ -489,7 +489,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
if (force || if (force ||
inFile.lastModified() > outFile.lastModified() || inFile.lastModified() > outFile.lastModified() ||
styleSheetLastModified > outFile.lastModified()) { styleSheetLastModified > outFile.lastModified()) {
ensureDirectoryFor( outFile );
ensureDirectoryFor(outFile);
log("Processing " + inFile + " to " + outFile, log("Processing " + inFile + " to " + outFile,
Project.MSG_INFO); Project.MSG_INFO);
configureLiaison(stylesheet); configureLiaison(stylesheet);
@@ -516,7 +516,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
if (!directory.exists()) { if (!directory.exists()) {
if (!directory.mkdirs()) { if (!directory.mkdirs()) {
throw new BuildException("Unable to create directory: " throw new BuildException("Unable to create directory: "
+ directory.getAbsolutePath() );
+ directory.getAbsolutePath());
} }
} }
} }
@@ -647,11 +647,11 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger {
stylesheetLoaded = true; stylesheetLoaded = true;
try { 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 // if liaison is a TraxLiason, use XMLCatalog as the entity
// resolver // resolver


+ 29
- 29
src/main/org/apache/tools/ant/taskdefs/Zip.java View File

@@ -265,9 +265,9 @@ public class Zip extends MatchingTask {
public void execute() throws BuildException { public void execute() throws BuildException {
if (baseDir == null && filesets.size() == 0 if (baseDir == null && filesets.size() == 0
&& groupfilesets.size() == 0 && "zip".equals(archiveType)) { && 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) { if (zipFile == null) {
@@ -304,14 +304,14 @@ public class Zip extends MatchingTask {
} }


// Add the files found in groupfileset to fileset // Add the files found in groupfileset to fileset
for (int i=0; i<groupfilesets.size(); i++) {
for (int i = 0; i < groupfilesets.size(); i++) {


log("Processing groupfileset ", Project.MSG_VERBOSE); log("Processing groupfileset ", Project.MSG_VERBOSE);
FileSet fs = (FileSet) groupfilesets.elementAt(i); FileSet fs = (FileSet) groupfilesets.elementAt(i);
FileScanner scanner = fs.getDirectoryScanner(project); FileScanner scanner = fs.getDirectoryScanner(project);
String[] files = scanner.getIncludedFiles(); String[] files = scanner.getIncludedFiles();
File basedir = scanner.getBasedir(); File basedir = scanner.getBasedir();
for (int j=0; j<files.length; j++) {
for (int j = 0; j < files.length; j++) {


log("Adding file " + files[j] + " to fileset", log("Adding file " + files[j] + " to fileset",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
@@ -327,7 +327,7 @@ public class Zip extends MatchingTask {
if (baseDir != null) { if (baseDir != null) {
dss.addElement(getDirectoryScanner(baseDir)); dss.addElement(getDirectoryScanner(baseDir));
} }
for (int i=0; i<filesets.size(); i++) {
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i); FileSet fs = (FileSet) filesets.elementAt(i);
dss.addElement (fs.getDirectoryScanner(project)); dss.addElement (fs.getDirectoryScanner(project));
} }
@@ -345,7 +345,7 @@ public class Zip extends MatchingTask {
String action = doUpdate ? "Updating " : "Building "; String action = doUpdate ? "Updating " : "Building ";
log(action + archiveType +": "+ zipFile.getAbsolutePath());
log(action + archiveType + ": " + zipFile.getAbsolutePath());


ZipOutputStream zOut = ZipOutputStream zOut =
new ZipOutputStream(new FileOutputStream(zipFile)); new ZipOutputStream(new FileOutputStream(zipFile));
@@ -369,10 +369,10 @@ public class Zip extends MatchingTask {
ZipFileSet oldFiles = new ZipFileSet(); ZipFileSet oldFiles = new ZipFileSet();
oldFiles.setSrc(renamedFile); oldFiles.setSrc(renamedFile);


for (int i=0; i < addedFiles.size(); i++)
for (int i = 0; i < addedFiles.size(); i++)
{ {
PatternSet.NameEntry ne = oldFiles.createExclude(); PatternSet.NameEntry ne = oldFiles.createExclude();
ne.setName((String)addedFiles.elementAt(i));
ne.setName((String) addedFiles.elementAt(i));
} }
Vector tmp = new Vector(1); Vector tmp = new Vector(1);
tmp.addElement(oldFiles); tmp.addElement(oldFiles);
@@ -395,7 +395,7 @@ public class Zip extends MatchingTask {
if (zOut != null) { if (zOut != null) {
zOut.close(); zOut.close();
} }
} catch(IOException ex) {
} catch (IOException ex) {
// If we're in this finally clause because of an // If we're in this finally clause because of an
// exception, we don't really care if there's an // exception, we don't really care if there's an
// exception when closing the stream. E.g. if it // exception when closing the stream. E.g. if it
@@ -422,8 +422,8 @@ public class Zip extends MatchingTask {


if (doUpdate) { if (doUpdate) {
if (!renamedFile.renameTo(zipFile)) { if (!renamedFile.renameTo(zipFile)) {
msg+=" (and I couldn't rename the temporary file "+
renamedFile.getName()+" back)";
msg += " (and I couldn't rename the temporary file " +
renamedFile.getName() + " back)";
} }
} }


@@ -469,7 +469,7 @@ public class Zip extends MatchingTask {
if ("".equals(dirs[i])) { if ("".equals(dirs[i])) {
continue; continue;
} }
String name = dirs[i].replace(File.separatorChar,'/');
String name = dirs[i].replace(File.separatorChar, '/');
if (!name.endsWith("/")) { if (!name.endsWith("/")) {
name += "/"; name += "/";
} }
@@ -494,9 +494,9 @@ public class Zip extends MatchingTask {
else else
{ {
// Add this file with the specified prefix. // Add this file with the specified prefix.
String name = files[i].replace(File.separatorChar,'/');
String name = files[i].replace(File.separatorChar, '/');
addParentDirs(thisBaseDir, name, zOut, prefix); addParentDirs(thisBaseDir, name, zOut, prefix);
zipFile(f, zOut, prefix+name);
zipFile(f, zOut, prefix + name);
} }
} }
} }
@@ -531,8 +531,8 @@ public class Zip extends MatchingTask {
zipFile(in, zOut, fullpath, entry.getTime(), zipSrc); zipFile(in, zOut, fullpath, entry.getTime(), zipSrc);
} else { } else {
addParentDirs(null, vPath, zOut, prefix); addParentDirs(null, vPath, zOut, prefix);
if (! entry.isDirectory()) {
zipFile(in, zOut, prefix+vPath, entry.getTime(),
if (!entry.isDirectory()) {
zipFile(in, zOut, prefix + vPath, entry.getTime(),
zipSrc); zipSrc);
} }
} }
@@ -564,7 +564,7 @@ public class Zip extends MatchingTask {
// In this case using java.util.zip will not work // In this case using java.util.zip will not work
// because it does not permit a zero-entry archive. // because it does not permit a zero-entry archive.
// Must create it manually. // Must create it manually.
log("Note: creating empty "+archiveType+" archive " + zipFile,
log("Note: creating empty " + archiveType + " archive " + zipFile,
Project.MSG_INFO); Project.MSG_INFO);
OutputStream os = null; OutputStream os = null;
try { try {
@@ -609,12 +609,12 @@ public class Zip extends MatchingTask {
File[] files = grabFiles(scanners, fileNames); File[] files = grabFiles(scanners, fileNames);
if (files.length == 0) { if (files.length == 0) {
if (emptyBehavior.equals("skip")) { if (emptyBehavior.equals("skip")) {
log("Warning: skipping "+archiveType+" archive " + zipFile +
log("Warning: skipping " + archiveType + " archive " + zipFile +
" because no files were included.", Project.MSG_WARN); " because no files were included.", Project.MSG_WARN);
return true; return true;
} else if (emptyBehavior.equals("fail")) { } else if (emptyBehavior.equals("fail")) {
throw new BuildException("Cannot create "+archiveType
+" archive " + zipFile +
throw new BuildException("Cannot create " + archiveType
+ " archive " + zipFile +
": no files were included.", location); ": no files were included.", location);
} else { } else {
// Create. // Create.
@@ -635,7 +635,7 @@ public class Zip extends MatchingTask {
SourceFileScanner sfs = new SourceFileScanner(this); SourceFileScanner sfs = new SourceFileScanner(this);
MergingMapper mm = new MergingMapper(); MergingMapper mm = new MergingMapper();
mm.setTo(zipFile.getAbsolutePath()); mm.setTo(zipFile.getAbsolutePath());
for (int i=0; i<scanners.length; i++) {
for (int i = 0; i < scanners.length; i++) {
if (sfs.restrict(fileNames[i], scanners[i].getBasedir(), null, if (sfs.restrict(fileNames[i], scanners[i].getBasedir(), null,
mm).length > 0) { mm).length > 0) {
return false; return false;
@@ -665,7 +665,7 @@ public class Zip extends MatchingTask {


protected static String[][] grabFileNames(FileScanner[] scanners) { protected static String[][] grabFileNames(FileScanner[] scanners) {
String[][] result = new String[scanners.length][]; String[][] result = new String[scanners.length][];
for (int i=0; i<scanners.length; i++) {
for (int i = 0; i < scanners.length; i++) {
String[] files = scanners[i].getIncludedFiles(); String[] files = scanners[i].getIncludedFiles();
String[] dirs = scanners[i].getIncludedDirectories(); String[] dirs = scanners[i].getIncludedDirectories();
result[i] = new String[files.length + dirs.length]; result[i] = new String[files.length + dirs.length];
@@ -815,13 +815,13 @@ public class Zip extends MatchingTask {
protected void addParentDirs(File baseDir, String entry, protected void addParentDirs(File baseDir, String entry,
ZipOutputStream zOut, String prefix) ZipOutputStream zOut, String prefix)
throws IOException { throws IOException {
if( !doFilesonly ) {
if (!doFilesonly) {
Stack directories = new Stack(); Stack directories = new Stack();
int slashPos = entry.length(); int slashPos = entry.length();


while ((slashPos = entry.lastIndexOf('/', slashPos-1)) != -1) {
String dir = entry.substring(0, slashPos+1);
if (addedDirs.get(prefix+dir) != null) {
while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) {
String dir = entry.substring(0, slashPos + 1);
if (addedDirs.get(prefix + dir) != null) {
break; break;
} }
directories.push(dir); directories.push(dir);
@@ -835,7 +835,7 @@ public class Zip extends MatchingTask {
} else { } else {
f = new File(dir); f = new File(dir);
} }
zipDir(f, zOut, prefix+dir);
zipDir(f, zOut, prefix + dir);
} }
} }
} }
@@ -848,7 +848,7 @@ public class Zip extends MatchingTask {
protected void addFiles(Vector filesets, ZipOutputStream zOut) protected void addFiles(Vector filesets, ZipOutputStream zOut)
throws IOException { throws IOException {
// Add each fileset in the Vector. // Add each fileset in the Vector.
for (int i = 0; i<filesets.size(); i++) {
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i); FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(project); DirectoryScanner ds = fs.getDirectoryScanner(project);




+ 10
- 10
src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java View File

@@ -94,11 +94,11 @@ public class CompilerAdapterFactory {
*/ */
public static CompilerAdapter getCompiler(String compilerType, Task task) public static CompilerAdapter getCompiler(String compilerType, Task task)
throws BuildException { throws BuildException {
boolean isClassicCompilerSupported=true;
boolean isClassicCompilerSupported = true;
//as new versions of java come out, add them to this test //as new versions of java come out, add them to this test
if(Project.getJavaVersion()==Project.JAVA_1_4) {
isClassicCompilerSupported=false;
}
if (Project.getJavaVersion() == Project.JAVA_1_4) {
isClassicCompilerSupported = false;
}


if (compilerType.equalsIgnoreCase("jikes")) { if (compilerType.equalsIgnoreCase("jikes")) {
return new Jikes(); return new Jikes();
@@ -109,12 +109,12 @@ public class CompilerAdapterFactory {
if (compilerType.equalsIgnoreCase("classic") || if (compilerType.equalsIgnoreCase("classic") ||
compilerType.equalsIgnoreCase("javac1.1") || compilerType.equalsIgnoreCase("javac1.1") ||
compilerType.equalsIgnoreCase("javac1.2")) { compilerType.equalsIgnoreCase("javac1.2")) {
if(isClassicCompilerSupported) {
if (isClassicCompilerSupported) {
return new Javac12(); return new Javac12();
} }
else { else {
throw new BuildException("This version of java does " throw new BuildException("This version of java does "
+"not support the classic compiler");
+ "not support the classic compiler");
} }


} }
@@ -124,18 +124,18 @@ public class CompilerAdapterFactory {
compilerType.equalsIgnoreCase("javac1.3") || compilerType.equalsIgnoreCase("javac1.3") ||
compilerType.equalsIgnoreCase("javac1.4")) { compilerType.equalsIgnoreCase("javac1.4")) {
// does the modern compiler exist? // does the modern compiler exist?
if(doesModernCompilerExist()) {
if (doesModernCompilerExist()) {
return new Javac13(); return new Javac13();
} else { } else {
if(isClassicCompilerSupported) {
if (isClassicCompilerSupported) {
task.log("Modern compiler not found - looking for " task.log("Modern compiler not found - looking for "
+ "classic compiler", Project.MSG_WARN); + "classic compiler", Project.MSG_WARN);
return new Javac12(); return new Javac12();
} }
else { else {
throw new BuildException("Unable to find a javac compiler;\n" throw new BuildException("Unable to find a javac compiler;\n"
+"com.sun.tools.javac.Main is not on the classpath.\n"
+"Perhaps JAVA_HOME does not point to the JDK");
+ "com.sun.tools.javac.Main is not on the classpath.\n"
+ "Perhaps JAVA_HOME does not point to the JDK");
} }
} }


+ 3
- 1
src/main/org/apache/tools/ant/taskdefs/condition/ConditionBase.java View File

@@ -81,7 +81,9 @@ public abstract class ConditionBase extends ProjectComponent {
* *
* @since 1.1 * @since 1.1
*/ */
protected int countConditions() {return conditions.size();}
protected int countConditions() {
return conditions.size();
}


/** /**
* Iterate through all conditions. * Iterate through all conditions.


+ 5
- 5
src/main/org/apache/tools/ant/taskdefs/condition/FilesMatch.java View File

@@ -114,12 +114,12 @@ public class FilesMatch implements Condition {
} }


//#now match the files //#now match the files
boolean matches=false;
boolean matches = false;
try { try {
matches=fu.contentEquals(file1, file2);
} catch(IOException ioe) {
throw new BuildException("when comparing files: "+ioe.getMessage(),
ioe);
matches = fu.contentEquals(file1, file2);
} catch (IOException ioe) {
throw new BuildException("when comparing files: "
+ ioe.getMessage(), ioe);
} }
return matches; return matches;
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/condition/Os.java View File

@@ -220,7 +220,7 @@ public class Os implements Condition {
isFamily = isFamily("windows") && isFamily = isFamily("windows") &&
!(osName.indexOf("nt") >= 0 || !(osName.indexOf("nt") >= 0 ||
osName.indexOf("2000") >= 0 || osName.indexOf("2000") >= 0 ||
osName.indexOf("xp") >= 0 );
osName.indexOf("xp") >= 0);
} else { } else {
throw new BuildException( throw new BuildException(
"Don\'t know how to detect os family \"" "Don\'t know how to detect os family \""


+ 13
- 21
src/main/org/apache/tools/ant/taskdefs/cvslib/CVSEntry.java View File

@@ -63,52 +63,44 @@ import java.util.Date;
* @author <a href="mailto:peter@apache.org">Peter Donald</a> * @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class CVSEntry
{
class CVSEntry {
private Date m_date; private Date m_date;
private final String m_author; private final String m_author;
private final String m_comment; private final String m_comment;
private final Vector m_files = new Vector(); 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_date = date;
m_author = author; m_author = author;
m_comment = comment; 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; return m_date;
} }


String getAuthor()
{
String getAuthor() {
return m_author; return m_author;
} }


String getComment()
{
String getComment() {
return m_comment; return m_comment;
} }


Vector getFiles()
{
Vector getFiles() {
return m_files; 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();
} }
} }

+ 48
- 72
src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java View File

@@ -66,8 +66,7 @@ import java.util.Properties;
* @author <a href="mailto:peter@apache.org">Peter Donald</a> * @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class ChangeLogParser
{
class ChangeLogParser {
//private static final int GET_ENTRY = 0; //private static final int GET_ENTRY = 0;
private static final int GET_FILE = 1; private static final int GET_FILE = 1;
private static final int GET_DATE = 2; private static final int GET_DATE = 2;
@@ -76,7 +75,8 @@ class ChangeLogParser
private static final int GET_PREVIOUS_REV = 5; private static final int GET_PREVIOUS_REV = 5;


/** input format for dates read in from cvs log */ /** 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 //The following is data used while processing stdout of CVS command
private String m_file; private String m_file;
@@ -98,8 +98,7 @@ class ChangeLogParser
* *
* @param userList the userlist * @param userList the userlist
*/ */
public ChangeLogParser( Properties userList )
{
public ChangeLogParser(Properties userList) {
m_userList = userList; m_userList = userList;
} }


@@ -108,8 +107,7 @@ class ChangeLogParser
* *
* @return a list of rcs entrys as an array * @return a list of rcs entrys as an array
*/ */
CVSEntry[] getEntrySetAsArray()
{
CVSEntry[] getEntrySetAsArray() {
final CVSEntry[] array = new CVSEntry[ m_entries.size() ]; final CVSEntry[] array = new CVSEntry[ m_entries.size() ];
Enumeration enum = m_entries.elements(); Enumeration enum = m_entries.elements();
int i = 0; int i = 0;
@@ -123,27 +121,25 @@ class ChangeLogParser
* Receive notification about the process writing * Receive notification about the process writing
* to standard output. * to standard output.
*/ */
public void stdout( final String line )
{
switch( m_status )
{
public void stdout(final String line) {
switch(m_status) {
case GET_FILE: case GET_FILE:
processFile( line );
processFile(line);
break; break;
case GET_REVISION: case GET_REVISION:
processRevision( line );
processRevision(line);
break; break;


case GET_DATE: case GET_DATE:
processDate( line );
processDate(line);
break; break;


case GET_COMMENT: case GET_COMMENT:
processComment( line );
processComment(line);
break; break;


case GET_PREVIOUS_REV: case GET_PREVIOUS_REV:
processGetPreviousRevision( line );
processGetPreviousRevision(line);
break; break;
} }
} }
@@ -153,22 +149,19 @@ class ChangeLogParser
* *
* @param line the line * @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 //We have ended changelog for that particular file
//so we can save it //so we can save it
final int end = m_comment.length() - lineSeparator.length(); //was -1 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(); saveEntry();
m_status = GET_FILE; m_status = GET_FILE;
} }
else if( line.startsWith( "------" ) )
{
else if (line.startsWith("------")) {
final int end = m_comment.length() - lineSeparator.length(); //was -1 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; m_status = GET_PREVIOUS_REV;
} }
else else
@@ -182,11 +175,9 @@ class ChangeLogParser
* *
* @param line the line * @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; m_status = GET_REVISION;
} }
} }
@@ -196,15 +187,12 @@ class ChangeLogParser
* *
* @param line the line * @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; m_status = GET_DATE;
} }
else if( line.startsWith( "======" ) )
{
else if (line.startsWith("======")) {
//There was no revisions in this changelog //There was no revisions in this changelog
//entry so lets move unto next file //entry so lets move unto next file
m_status = GET_FILE; m_status = GET_FILE;
@@ -216,17 +204,14 @@ class ChangeLogParser
* *
* @param line the line * @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; m_status = GET_COMMENT;
@@ -242,13 +227,12 @@ class ChangeLogParser
* *
* @param line the line * @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(); saveEntry();


@@ -259,21 +243,17 @@ class ChangeLogParser
/** /**
* Utility method that saves the current entry. * Utility method that saves the current entry.
*/ */
private void saveEntry()
{
private void saveEntry() {
final String entryKey = m_date + m_author + m_comment; final String entryKey = m_date + m_author + m_comment;
CVSEntry entry; 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 * @param date the string holding dat
* @return the date object or null if unknown date format * @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 ); //final String message = REZ.getString( "changelog.bat-date.error", date );
//getContext().error( message ); //getContext().error( message );
return null; return null;


+ 149
- 145
src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogTask.java View File

@@ -104,9 +104,7 @@ import org.apache.tools.ant.types.FileSet;
* @since Ant 1.5 * @since Ant 1.5
* @ant.task name="changelog" * @ant.task name="changelog"
*/ */
public class ChangeLogTask
extends Task
{
public class ChangeLogTask extends Task {
/** User list */ /** User list */
private File m_usersFile; private File m_usersFile;


@@ -119,14 +117,10 @@ public class ChangeLogTask
/** Output file */ /** Output file */
private File m_destfile; 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; 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; private Date m_stop;


/** /**
@@ -136,287 +130,297 @@ public class ChangeLogTask
*/ */
private final Vector m_filesets = new Vector(); private final Vector m_filesets = new Vector();



/** /**
* Set the base dir for cvs. * 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; m_dir = dir;
} }



/** /**
* Set the output file for the log. * 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; m_destfile = destfile;
} }



/** /**
* Set a lookup list of user names & addresses * 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; m_usersFile = usersFile;
} }



/** /**
* Add a user to list changelog knows about. * Add a user to list changelog knows about.
* *
* @param user the user * @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. * Set the date at which the changelog should start.
* *
* @param start 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; m_start = start;
} }



/** /**
* Set the date at which the changelog should stop. * Set the date at which the changelog should stop.
* *
* @param stop 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; m_stop = stop;
} }



/** /**
* Set the numbers of days worth of log entries to process. * 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. * 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. * @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 * 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 { try {


validate(); validate();


final Properties userList = new Properties(); 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(); user.validate();
userList.put( user.getUserID(), user.getDisplayname() );
userList.put(user.getUserID(), user.getDisplayname());
} }
final Commandline command = new Commandline(); 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 = final SimpleDateFormat outputDate =
new SimpleDateFormat( "yyyy-MM-dd" );
new SimpleDateFormat("yyyy-MM-dd");
// We want something of the form: -d ">=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 // Check if list of files to check has been specified
if( !m_filesets.isEmpty() ) {
if (!m_filesets.isEmpty()) {
final Enumeration e = m_filesets.elements(); 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(); 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 = 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 { try {
final int resultCode = exe.execute(); 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(); 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[] entrySet = parser.getEntrySetAsArray();
final CVSEntry[] filteredEntrySet = filterEntrySet( entrySet );
writeChangeLog( filteredEntrySet );
final CVSEntry[] filteredEntrySet = filterEntrySet(entrySet);

writeChangeLog(filteredEntrySet);


} finally { } finally {
m_dir = savedDir; m_dir = savedDir;
} }
} }



/** /**
* Validate the parameters specified for task. * Validate the parameters specified for task.
* *
* @throws BuildException if fails validation checks * @throws BuildException if fails validation checks
*/ */
private void validate() private void validate()
throws BuildException
{
if( null == m_dir )
{
throws BuildException {
if (null == m_dir) {
m_dir = getProject().getBaseDir(); m_dir = getProject().getBaseDir();
} }
if( null == m_destfile )
{
if (null == m_destfile) {
final String message = "Destfile must be set."; 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 * @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 * @param entrySet the entry set to filter
* @return the filtered entry set * @return the filtered entry set
*/ */
private CVSEntry[] filterEntrySet( final CVSEntry[] entrySet )
{
private CVSEntry[] filterEntrySet(final CVSEntry[] entrySet) {
final Vector results = new Vector(); 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(); 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 //Skip dates that are too early
continue; continue;
} }
if( null != m_stop && m_stop.before( date ) )
{
if (null != m_stop && m_stop.before(date)) {
//Skip dates that are too late //Skip dates that are too late
continue; 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; return resultArray;
} }



/** /**
* Print changelog to file specified in task. * 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; FileOutputStream output = null;
try
{
output = new FileOutputStream( m_destfile );

try {
output = new FileOutputStream(m_destfile);

final PrintWriter writer = final PrintWriter writer =
new PrintWriter( new OutputStreamWriter( output, "UTF-8" ) );
new PrintWriter(new OutputStreamWriter(output, "UTF-8"));


final ChangeLogWriter serializer = new ChangeLogWriter(); 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(); output.close();
}
catch( final IOException ioe )
{
} catch (final IOException ioe) {
} }
} }
} }
} }
} }


+ 37
- 32
src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriter.java View File

@@ -63,60 +63,65 @@ import java.util.Enumeration;
* @author <a href="mailto:peter@apache.org">Peter Donald</a> * @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class ChangeLogWriter
{
class ChangeLogWriter {
/** output format for dates writtn to xml file */ /** 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 */ /** 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. * 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( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
output.println( "<changelog>" );
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
output.println("<changelog>");
for (int i = 0; i < entries.length; i++) {
final CVSEntry entry = entries[i];

printEntry(output, entry);
} }
output.println( "</changelog>" );
output.println("</changelog>");
output.flush(); output.flush();
output.close(); output.close();
} }



/** /**
* Print out an individual entry in changelog. * Print out an individual entry in changelog.
* *
* @param entry the entry to print * @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<entry>" );
output.println( "\t\t<date>" + c_outputDate.format( entry.getDate() ) + "</date>" );
output.println( "\t\t<time>" + c_outputTime.format( entry.getDate() ) + "</time>" );
output.println( "\t\t<author><![CDATA[" + entry.getAuthor() + "]]></author>" );
private void printEntry(final PrintWriter output, final CVSEntry entry) {
output.println("\t<entry>");
output.println("\t\t<date>" + c_outputDate.format(entry.getDate()) + "</date>");
output.println("\t\t<time>" + c_outputTime.format(entry.getDate()) + "</time>");
output.println("\t\t<author><![CDATA[" + entry.getAuthor() + "]]></author>");


final Enumeration enumeration = entry.getFiles().elements(); final Enumeration enumeration = entry.getFiles().elements();
while( enumeration.hasMoreElements() )
{
final RCSFile file = (RCSFile)enumeration.nextElement();
output.println( "\t\t<file>" );
output.println( "\t\t\t<name>" + file.getName() + "</name>" );
output.println( "\t\t\t<revision>" + file.getRevision() + "</revision>" );

while (enumeration.hasMoreElements()) {
final RCSFile file = (RCSFile) enumeration.nextElement();

output.println("\t\t<file>");
output.println("\t\t\t<name>" + file.getName() + "</name>");
output.println("\t\t\t<revision>" + file.getRevision() + "</revision>");


final String previousRevision = file.getPreviousRevision(); final String previousRevision = file.getPreviousRevision();
if( previousRevision != null )
{
output.println( "\t\t\t<prevrevision>" + previousRevision + "</prevrevision>" );
if (previousRevision != null) {
output.println("\t\t\t<prevrevision>" + previousRevision + "</prevrevision>");
} }


output.println( "\t\t</file>" );
output.println("\t\t</file>");
} }
output.println( "\t\t<msg><![CDATA[" + entry.getComment() + "]]></msg>" );
output.println( "\t</entry>" );
output.println("\t\t<msg><![CDATA[" + entry.getComment() + "]]></msg>");
output.println("\t</entry>");
} }
} }


+ 46
- 19
src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java View File

@@ -62,44 +62,71 @@ import org.apache.tools.ant.BuildException;
* @author <a href="mailto:jeff.martin@synamic.co.uk">Jeff Martin</a> * @author <a href="mailto:jeff.martin@synamic.co.uk">Jeff Martin</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class CvsUser
{
public class CvsUser {
/** The user's Id */
private String m_userID; private String m_userID;
/** The user's full name */
private String m_displayName; 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; 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; m_userID = userID;
} }


String getUserID()
{

/**
* Get the user's id.
*
* @return The userID value
*/
String getUserID() {
return m_userID; return m_userID;
} }


String getDisplayname()
{

/**
* Get the user's full name
*
* @return the usre's full name
*/
String getDisplayname() {
return m_displayName; 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."; 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 = final String message =
"Displayname attribute must be set for userID " + m_userID; "Displayname attribute must be set for userID " + m_userID;
throw new BuildException( message );

throw new BuildException(message);
} }
} }
} }


+ 16
- 17
src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java View File

@@ -60,41 +60,40 @@ package org.apache.tools.ant.taskdefs.cvslib;
* @author <a href="mailto:jeff.martin@synamic.co.uk">Jeff Martin</a> * @author <a href="mailto:jeff.martin@synamic.co.uk">Jeff Martin</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class RCSFile
{
class RCSFile {
private String m_name; private String m_name;
private String m_revision; private String m_revision;
private String m_previousRevision; 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_name = name;
m_revision = revision; m_revision = revision;
if( !revision.equals( previousRevision ) )
{
if (!revision.equals(previousRevision)) {
m_previousRevision = previousRevision; m_previousRevision = previousRevision;
} }
} }


String getName()
{
String getName() {
return m_name; return m_name;
} }


String getRevision()
{
String getRevision() {
return m_revision; return m_revision;
} }


String getPreviousRevision()
{
String getPreviousRevision() {
return m_previousRevision; return m_previousRevision;
} }
} }


+ 10
- 10
src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java View File

@@ -51,7 +51,6 @@
* information on the Apache Software Foundation, please see * information on the Apache Software Foundation, please see
* <http://www.apache.org/>. * <http://www.apache.org/>.
*/ */

package org.apache.tools.ant.taskdefs.cvslib; package org.apache.tools.ant.taskdefs.cvslib;


import org.apache.tools.ant.taskdefs.LogOutputStream; import org.apache.tools.ant.taskdefs.LogOutputStream;
@@ -62,28 +61,29 @@ import org.apache.tools.ant.taskdefs.LogOutputStream;
* @author <a href="mailto:peter@apache.org">Peter Donald</a> * @author <a href="mailto:peter@apache.org">Peter Donald</a>
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class RedirectingOutputStream
extends LogOutputStream
{
class RedirectingOutputStream
extends LogOutputStream {
private final ChangeLogParser m_parser; private final ChangeLogParser m_parser;



/** /**
* Creates a new instance of this class. * 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; m_parser = parser;
} }



/** /**
* Logs a line to the log system of ant. * Logs a line to the log system of ant.
* *
* @param line the line to log. * @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);
} }
} }


+ 16
- 23
src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java View File

@@ -65,40 +65,33 @@ import org.apache.tools.ant.BuildException;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
class RedirectingStreamHandler 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; return null;
} }
} }




public void stop()
{
public void stop() {
super.stop(); super.stop();
try
{
try {
getErr().close(); getErr().close();
getOut().close(); getOut().close();
}
catch( final IOException e )
{
} catch (final IOException e) {
// plain impossible // plain impossible
throw new BuildException( e );
throw new BuildException(e);
} }
} }
} }


+ 31
- 29
src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java View File

@@ -59,75 +59,77 @@ package org.apache.tools.ant.taskdefs.email;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @since Ant 1.5
*/ */
public class EmailAddress
{
public class EmailAddress {
private String name; private String name;
private String address; 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 * Creates a new email address based on the given string
*
* @param address the email address * @param address the email address
*/ */
public EmailAddress( String address )
{
public EmailAddress(String address) {
this.address = address; this.address = address;
} }


/**

/**
* Sets the personal / display name of the address * Sets the personal / display name of the address
*
* @param name the display name * @param name the display name
*/ */
public void setName( String name )
{
public void setName(String name) {
this.name = name; this.name = name;
} }


/**

/**
* Sets the email address * Sets the email address
*
* @param address the actual email address * @param address the actual email address
*/ */
public void setAddress( String address )
{
public void setAddress(String address) {
this.address = address; this.address = address;
} }


/**

/**
* Constructs a string "name &lt;address&gt;" or "address" * Constructs a string "name &lt;address&gt;" or "address"
*
* @return a string representation of the address * @return a string representation of the address
*/ */
public String toString()
{
if( name == null )
{
public String toString() {
if (name == null) {
return address; return address;
}
else
{
} else {
return name + " <" + address + ">"; return name + " <" + address + ">";
} }
} }


/**

/**
* Returns the address * Returns the address
*
* @return the address part * @return the address part
*/ */
public String getAddress()
{
public String getAddress() {
return address; return address;
} }


/**

/**
* Returns the display name * Returns the display name
*
* @return the display name part * @return the display name part
*/ */
public String getName()
{
public String getName() {
return name; return name;
} }
} }


+ 206
- 243
src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java View File

@@ -67,8 +67,8 @@ import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet; 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 <a href="mailto:umagesh@apache.org">Magesh Umasankar</a> * @author <a href="mailto:umagesh@apache.org">Magesh Umasankar</a>
* @author glenn_twiggs@bmc.com * @author glenn_twiggs@bmc.com
@@ -77,480 +77,443 @@ import org.apache.tools.ant.types.FileSet;
* @author paulo.gaspar@krankikom.de Paulo Gaspar * @author paulo.gaspar@krankikom.de Paulo Gaspar
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @since Ant 1.5
*
* @ant.task name="mail" category="network" * @ant.task name="mail" category="network"
*/ */
public class EmailTask 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"; 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"; 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"; 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"; 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 * @return a list of valid entries
*/ */
public String[] getValues()
{
public String[] getValues() {
return new String[] return new String[]
{AUTO, MIME, UU, PLAIN};
{AUTO, MIME, UU, PLAIN};
} }
} }



private String encoding = AUTO; private String encoding = AUTO;
/**
* host running SMTP
*/
/** host running SMTP */
private String host = "localhost"; private String host = "localhost";
private int port = 25; private int port = 25;
/**
* subject field
*/
/** subject field */
private String subject = null; private String subject = null;
/**
* any text
*/
/** any text */
private Message message = null; private Message message = null;
/** failure flag */ /** failure flag */
private boolean failOnError = true; private boolean failOnError = true;
private boolean includeFileNames = false; private boolean includeFileNames = false;
private String messageMimeType = null; private String messageMimeType = null;


/**
* sender
*/
/** sender */
private EmailAddress from = null; private EmailAddress from = null;
/**
* TO recipients
*/
/** TO recipients */
private Vector toList = new Vector(); private Vector toList = new Vector();
/**
* CC (Carbon Copy) recipients
*/
/** CC (Carbon Copy) recipients */
private Vector ccList = new Vector(); private Vector ccList = new Vector();
/**
* BCC (Blind Carbon Copy) recipients
*/
/** BCC (Blind Carbon Copy) recipients */
private Vector bccList = new Vector(); private Vector bccList = new Vector();


/**
* file list
*/
/** file list */
private Vector files = new Vector(); private Vector files = new Vector();
private Vector filesets = new Vector(); private Vector filesets = new Vector();


/**

/**
* Allows the build writer to choose the preferred encoding method * Allows the build writer to choose the preferred encoding method
*
* @param encoding The encoding (one of AUTO,MIME,UU,PLAIN) * @param encoding The encoding (one of AUTO,MIME,UU,PLAIN)
*/ */
public void setEncoding( Encoding encoding )
{
public void setEncoding(Encoding encoding) {
this.encoding = encoding.getValue(); this.encoding = encoding.getValue();
} }


/**

/**
* Sets the mail server port * Sets the mail server port
*
* @param port The port to use * @param port The port to use
*/ */
public void setMailport( int port )
{
public void setMailport(int port) {
this.port = port; this.port = port;
} }


/**

/**
* Sets the host * Sets the host
*
* @param host The host to connect to * @param host The host to connect to
*/ */
public void setMailhost( String host )
{
public void setMailhost(String host) {
this.host = host; this.host = host;
} }


/**

/**
* Sets the subject line of the email * Sets the subject line of the email
* *
* @param subject Subject of this email. * @param subject Subject of this email.
*/ */
public void setSubject( String subject )
{
public void setSubject(String subject) {
this.subject = subject; this.subject = subject;
} }


/**

/**
* Shorthand method to set the message * Shorthand method to set the message
*
* @param message Message body of this email. * @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 * Shorthand method to set the message from a file
*
* @param file The file from which to take the message * @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 * @param type The new MessageMimeType value
*/ */
public void setMessageMimeType( String type )
{
public void setMessageMimeType(String type) {
this.messageMimeType = type; this.messageMimeType = type;
} }


/**

/**
* Add a message elemnt * Add a message elemnt
*
* @param message The message object * @param message The message object
* @throws BuildException if a message has already been added * @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; this.message = message;
} }


/**

/**
* Adds a from address element * Adds a from address element
*
* @param address The address to send from * @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; this.from = address;
} }


/**

/**
* Shorthand to set the from address element * Shorthand to set the from address element
* *
* @param address The address to send mail from * @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 * Adds a to address element
*
* @param address An email address * @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 * Adds "to" address elements
* *
* @param list Comma separated list of addresses * @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 * Adds "cc" address element
*
* @param address The email address * @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 * Adds "cc" address elements
* *
* @param list Comma separated list of addresses * @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 * Adds "bcc" address elements
*
* @param address The email address * @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 * Adds "bcc" address elements
* *
* @param list comma separated list of addresses * @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 * Indicates whether BuildExceptions should be passed back to the core
* *
* @param failOnError The new FailOnError value * @param failOnError The new FailOnError value
*/ */
public void setFailOnError( boolean failOnError )
{
public void setFailOnError(boolean failOnError) {
this.failOnError = failOnError; this.failOnError = failOnError;
} }


/**

/**
* Adds a list of files to be attached * Adds a list of files to be attached
* *
* @param filenames Comma separated list of files * @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). * Adds a set of files (nested fileset attribute).
*
* @param fs The fileset * @param fs The fileset
*/ */
public void addFileset( FileSet fs )
{
filesets.addElement( fs );
public void addFileset(FileSet fs) {
filesets.addElement(fs);
} }


/**

/**
* Sets Includefilenames attribute * 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; this.includeFileNames = includeFileNames;
} }


/**

/**
* Identifies whether file names should be included * Identifies whether file names should be included
*
* @return Identifies whether file names should be included * @return Identifies whether file names should be included
*/ */
public boolean getIncludeFileNames()
{
public boolean getIncludeFileNames() {
return includeFileNames; return includeFileNames;
} }


/**
* Sends an email
*/
public void execute()
{

/** Sends an email */
public void execute() {
Message savedMessage = message; Message savedMessage = message;
Vector savedFiles = (Vector) files.clone(); Vector savedFiles = (Vector) files.clone();
try
{
try {
Mailer mailer = null; Mailer mailer = null;


// prepare for the auto select mechanism // prepare for the auto select mechanism
boolean autoFound = false; boolean autoFound = false;


// try MIME format // 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(); .newInstance();
autoFound = true; 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 // 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(); .newInstance();
autoFound = true; 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 // try plain format
if( encoding.equals( PLAIN )
|| ( encoding.equals( AUTO ) && !autoFound ) )
{
if (encoding.equals(PLAIN)
|| (encoding.equals(AUTO) && !autoFound)) {
mailer = new PlainMailer(); mailer = new PlainMailer();
autoFound = true; autoFound = true;
log( "Using plain mail", Project.MSG_VERBOSE );
log("Using plain mail", Project.MSG_VERBOSE);
} }


// a valid mailer must be present by now // 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 // a valid message is required
if( message == null )
{
if (message == null) {
message = new Message(); message = new Message();
} }


// an address to send from is required // 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 // 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) // 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 // identify which files should be attached
Enumeration e = filesets.elements(); 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(); String[] includedFiles = ds.getIncludedFiles();
File baseDir = ds.getBasedir(); 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 // 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 // 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 // send the email
mailer.send(); mailer.send();


// let the user know what happened // let the user know what happened
int count = files.size(); 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; throw e;
} }
} finally { } finally {


+ 50
- 37
src/main/org/apache/tools/ant/taskdefs/email/Mailer.java View File

@@ -63,8 +63,7 @@ import org.apache.tools.ant.Task;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @since Ant 1.5
*/ */
abstract class Mailer
{
abstract class Mailer {
protected String host = null; protected String host = null;
protected int port = -1; protected int port = -1;
protected Message message; protected Message message;
@@ -77,109 +76,123 @@ abstract class Mailer
protected Task task; protected Task task;
protected boolean includeFileNames = false; protected boolean includeFileNames = false;


/**

/**
* Sets the mail server * Sets the mail server
*
* @param host * @param host
*/ */
public void setHost( String host )
{
public void setHost(String host) {
this.host = host; this.host = host;
} }


/**

/**
* Sets the smtp port * Sets the smtp port
*
* @param port * @param port
*/ */
public void setPort( int port )
{
public void setPort(int port) {
this.port = port; this.port = port;
} }


/**

/**
* Sets the message * Sets the message
*
* @param m * @param m
*/ */
public void setMessage( Message m )
{
public void setMessage(Message m) {
this.message = m; this.message = m;
} }


/**

/**
* Sets the address to send from * Sets the address to send from
*
* @param from * @param from
*/ */
public void setFrom( EmailAddress from )
{
public void setFrom(EmailAddress from) {
this.from = from; this.from = from;
} }


/**

/**
* Set the to addresses * Set the to addresses
*
* @param list * @param list
*/ */
public void setToList( Vector list )
{
public void setToList(Vector list) {
this.toList = list; this.toList = list;
} }


/**

/**
* Sets the cc addresses * Sets the cc addresses
*
* @param list * @param list
*/ */
public void setCcList( Vector list )
{
public void setCcList(Vector list) {
this.ccList = list; this.ccList = list;
} }


/**

/**
* Sets the bcc addresses * Sets the bcc addresses
*
* @param list * @param list
*/ */
public void setBccList( Vector list )
{
public void setBccList(Vector list) {
this.bccList = list; this.bccList = list;
} }


/**

/**
* Sets the files to attach * Sets the files to attach
*
* @param files * @param files
*/ */
public void setFiles( Vector files )
{
public void setFiles(Vector files) {
this.files = files; this.files = files;
} }


/**

/**
* Sets the subject * Sets the subject
*
* @param subject * @param subject
*/ */
public void setSubject( String subject )
{
public void setSubject(String subject) {
this.subject = subject; this.subject = subject;
} }


/**

/**
* Sets the owning task * Sets the owning task
*
* @param task * @param task
*/ */
public void setTask( Task task )
{
public void setTask(Task task) {
this.task = task; this.task = task;
} }


/**

/**
* Indicates whether filenames should be listed in the body * Indicates whether filenames should be listed in the body
*
* @param b * @param b
*/ */
public void setIncludeFileNames( boolean b )
{
public void setIncludeFileNames(boolean b) {
this.includeFileNames = b; this.includeFileNames = b;
} }


/**

/**
* This method should send the email * This method should send the email
*
* @throws BuildException * @throws BuildException
*/ */
public abstract void send() public abstract void send()
throws BuildException;
throws BuildException;
} }


+ 50
- 49
src/main/org/apache/tools/ant/taskdefs/email/Message.java View File

@@ -65,113 +65,114 @@ import java.io.PrintStream;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @since Ant 1.5
*/ */
public class Message
{
public class Message {
private File messageSource = null; private File messageSource = null;
private StringBuffer buffer = new StringBuffer(); private StringBuffer buffer = new StringBuffer();
private String mimeType = "text/plain"; private String mimeType = "text/plain";
private boolean specified = false; 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 * Creates a new message based on the given string
*
* @param text the message * @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. * Creates a new message using the contents of the given file.
*
* @param file the source of the message * @param file the source of the message
*/ */
public Message( File file )
{
public Message(File file) {
messageSource = file; messageSource = file;
} }


/**

/**
* Adds a textual part of the message * Adds a textual part of the message
*
* @param text some text to add * @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 * Sets the source file of the message
*
* @param src the source of the message * @param src the source of the message
*/ */
public void setSrc( File src )
{
public void setSrc(File src) {
this.messageSource = src; this.messageSource = src;
} }


/**

/**
* Sets the content type for the message * Sets the content type for the message
*
* @param mimeType a mime type e.g. "text/plain" * @param mimeType a mime type e.g. "text/plain"
*/ */
public void setMimeType( String mimeType )
{
public void setMimeType(String mimeType) {
this.mimeType = mimeType; this.mimeType = mimeType;
specified = true; specified = true;
} }


/**

/**
* Returns the content type * Returns the content type
*
* @return the mime type * @return the mime type
*/ */
public String getMimeType()
{
public String getMimeType() {
return mimeType; return mimeType;
} }


/**

/**
* Prints the message onto an output stream * Prints the message onto an output stream
*
* @param out The print stream to write to * @param out The print stream to write to
* @throws IOException if an error occurs * @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 // 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; String line = null;


while( ( line = in.readLine() ) != null )
{
out.println( line );
while ((line = in.readLine()) != null) {
out.println(line);
} }
}
finally {
} finally {
freader.close(); freader.close();
} }
}
else
{
out.println( buffer );
} else {
out.println(buffer);
} }
} }


/**

/**
* Returns true iff the mimeType has been set. * Returns true iff the mimeType has been set.
*
* @return false if the default value is in use * @return false if the default value is in use
*/ */
public boolean isMimeTypeSpecified()
{
public boolean isMimeTypeSpecified() {
return specified; return specified;
} }
} }


+ 62
- 73
src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java View File

@@ -80,112 +80,101 @@ import org.apache.tools.ant.BuildException;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @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(); 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 // Aside, the JDK is clearly unaware of the scottish
// 'session', which //involves excessive quantities of // 'session', which //involves excessive quantities of
// alcohol :-) // alcohol :-)
Session sesh = Session.getDefaultInstance( props, null );
Session sesh = Session.getDefaultInstance(props, null);


//create the message //create the message
MimeMessage msg = new MimeMessage( sesh );
MimeMessage msg = new MimeMessage(sesh);
MimeMultipart attachments = new MimeMultipart(); MimeMultipart attachments = new MimeMultipart();


//set the sender //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(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream( baos );
message.print( out );
PrintStream out = new PrintStream(baos);

message.print(out);
out.close(); out.close();


MimeBodyPart textbody = new MimeBodyPart(); 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(); Enumeration e = files.elements();
while( e.hasMoreElements() )
{
File file = (File)e.nextElement();
while (e.hasMoreElements()) {
File file = (File) e.nextElement();


MimeBodyPart body; MimeBodyPart body;

body = new MimeBodyPart(); 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; return addrs;
} }
} }


+ 50
- 59
src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java View File

@@ -68,112 +68,103 @@ import org.apache.tools.mail.MailMessage;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @since Ant 1.5
*/ */
class PlainMailer
extends Mailer
{
/**
class PlainMailer extends Mailer {
/**
* Sends the email using the apache MailMessage class. * Sends the email using the apache MailMessage class.
*
* @see org.apache.tools.mail.MailMessage * @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; Enumeration e;


e = toList.elements(); e = toList.elements();
while( e.hasMoreElements() )
{
mailMessage.to( e.nextElement().toString() );
while (e.hasMoreElements()) {
mailMessage.to(e.nextElement().toString());
} }


e = ccList.elements(); e = ccList.elements();
while( e.hasMoreElements() )
{
mailMessage.cc( e.nextElement().toString() );
while (e.hasMoreElements()) {
mailMessage.cc(e.nextElement().toString());
} }


e = bccList.elements(); 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(); PrintStream out = mailMessage.getPrintStream();


message.print( out );
message.print(out);


e = files.elements(); 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(); 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 * Attaches a file to this email
*
* @param file The file to attache * @param file The file to attache
* @param out The message stream to add to * @param out The message stream to add to
* @throws IOException if errors occur * @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(); out.println();

String filename = file.getName(); String filename = file.getName();
int filenamelength = filename.length(); 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(); out.println();
} }


int length; 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(); finstr.close();
} }
} }
} }


+ 16
- 20
src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java View File

@@ -67,30 +67,26 @@ import sun.misc.UUEncoder;
* @author roxspring@yahoo.com Rob Oxspring * @author roxspring@yahoo.com Rob Oxspring
* @since Ant 1.5 * @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(); finstr.close();
} }
} }
} }


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/Cab.java View File

@@ -320,12 +320,12 @@ public class Cab extends MatchingTask {
outLog.close(); outLog.close();
errPump.waitFor(); errPump.waitFor();
errLog.close(); errLog.close();
} catch(InterruptedException ie) {
} catch (InterruptedException ie) {
log("Thread interrupted: " + ie); log("Thread interrupted: " + ie);
} }


// Informative summary message in case of errors // Informative summary message in case of errors
if(result != 0) {
if (result != 0) {
log("Error executing listcab; error code: " + result); log("Error executing listcab; error code: " + result);
} }
} catch (IOException ex) { } catch (IOException ex) {


+ 13
- 14
src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java View File

@@ -211,12 +211,12 @@ public class EchoProperties extends Task {
while (enum.hasMoreElements()) { while (enum.hasMoreElements()) {
String name = (String) enum.nextElement(); String name = (String) enum.nextElement();
String value = (String) allProps.get(name); String value = (String) allProps.get(name);
if (prefix == null || name.indexOf(prefix) == 0 ) {
if (prefix == null || name.indexOf(prefix) == 0) {
props.put(name, value); props.put(name, value);
} }
} }
try { try {
jdkSaveProperties( props, os, "Ant properties" );
jdkSaveProperties(props, os, "Ant properties");
} finally { } finally {
os.close(); os.close();
} }
@@ -237,32 +237,31 @@ public class EchoProperties extends Task {
*@exception IOException on an I/O error during a write. Only thrown *@exception IOException on an I/O error during a write. Only thrown
* for JDK 1.2+. * 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 { try {
java.lang.reflect.Method m = props.getClass().getMethod( 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) { } catch (java.lang.reflect.InvocationTargetException ite) {
Throwable t = ite.getTargetException(); Throwable t = ite.getTargetException();
if (t instanceof IOException) { if (t instanceof IOException) {
throw (IOException)t;
throw (IOException) t;
} }
if (t instanceof RuntimeException) { if (t instanceof RuntimeException) {
throw (RuntimeException)t;
throw (RuntimeException) t;
} }
// not an expected exception. Resort to JDK 1.0 to execute // not an expected exception. Resort to JDK 1.0 to execute
// this method // this method
jdk10SaveProperties( props, os, header );
jdk10SaveProperties(props, os, header);
} catch (ThreadDeath td) { } catch (ThreadDeath td) {
// don't trap thread death errors. // don't trap thread death errors.
throw td; throw td;
} catch (Throwable ex) { } catch (Throwable ex) {
// this 'store' method is not available, so resort to the JDK 1.0 // this 'store' method is not available, so resort to the JDK 1.0
// compatible method. // 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 os record the properties to this output stream
*@param header prepend this header to the property output *@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);
} }
} }



+ 262
- 192
src/main/org/apache/tools/ant/taskdefs/optional/IContract.java View File

@@ -55,9 +55,6 @@ package org.apache.tools.ant.taskdefs.optional;









import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -89,7 +86,7 @@ import org.apache.tools.ant.types.Reference;
* <p/> * <p/>
* Thanks to Rainer Schmitz for enhancements and comments. * Thanks to Rainer Schmitz for enhancements and comments.
* *
* @author <a href="mailto:aslak.hellesoy@bekk.no">Aslak Hellesøy</a>
* @author <a href="mailto:aslak.hellesoy@bekk.no">Aslak Helles�a>
* *
* <p/> * <p/>
* <table border="1" cellpadding="2" cellspacing="0"> * <table border="1" cellpadding="2" cellspacing="0">
@@ -233,7 +230,7 @@ public class IContract extends MatchingTask {
"You should probably modify icontrol.properties' classRoot to where comiled (uninstrumented) classes go."; "You should probably modify icontrol.properties' classRoot to where comiled (uninstrumented) classes go.";


/** \ on windows, / on linux/unix */ /** \ 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 */ /** compiler to use for instrumenation */
private String icCompiler = "javac"; 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 */ /** temporary file with file names of all java files to be instrumented */
private File targets = null; 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; private boolean dirty = false;


/** set to true if the iContract jar is missing */ /** set to true if the iContract jar is missing */
@@ -297,166 +297,182 @@ public class IContract extends MatchingTask {
private boolean instrumentall = false; 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; private boolean updateIcontrol = false;


/**
* Regular compilation class root
*/
/** Regular compilation class root */
private File classDir = null; private File classDir = null;



/** /**
* Sets the source directory * Sets the source directory
* *
* @param srcDir the source directory * @param srcDir the source directory
*/ */
public void setSrcdir( File srcDir ) {
public void setSrcdir(File srcDir) {
this.srcDir = srcDir; this.srcDir = srcDir;
} }



/** /**
* Sets the class directory (uninstrumented classes) * Sets the class directory (uninstrumented classes)
* *
* @param srcDir the source directory * @param srcDir the source directory
*/ */
public void setClassdir( File classDir ) {
public void setClassdir(File classDir) {
this.classDir = classDir; this.classDir = classDir;
} }



/** /**
* Sets the instrumentation directory * Sets the instrumentation directory
* *
* @param instrumentDir the source directory * @param instrumentDir the source directory
*/ */
public void setInstrumentdir( File instrumentDir ) {
public void setInstrumentdir(File instrumentDir) {
this.instrumentDir = instrumentDir; this.instrumentDir = instrumentDir;
if ( this.buildDir == null ) {
setBuilddir( instrumentDir );
if (this.buildDir == null) {
setBuilddir(instrumentDir);
} }
} }



/** /**
* Sets the build directory for instrumented classes * Sets the build directory for instrumented classes
* *
* @param buildDir the build directory * @param buildDir the build directory
*/ */
public void setBuilddir( File buildDir ) {
public void setBuilddir(File buildDir) {
this.buildDir = buildDir; this.buildDir = buildDir;
} }



/** /**
* Sets the build directory for repository classes * Sets the build directory for repository classes
* *
* @param repositoryDir the source directory * @param repositoryDir the source directory
*/ */
public void setRepositorydir( File repositoryDir ) {
public void setRepositorydir(File repositoryDir) {
this.repositoryDir = repositoryDir; this.repositoryDir = repositoryDir;
if( this.repBuildDir == null ) {
setRepbuilddir( repositoryDir );
if (this.repBuildDir == null) {
setRepbuilddir(repositoryDir);
} }
} }



/** /**
* Sets the build directory for instrumented classes * Sets the build directory for instrumented classes
* *
* @param buildDir the build directory * @param buildDir the build directory
*/ */
public void setRepbuilddir( File repBuildDir ) {
public void setRepbuilddir(File repBuildDir) {
this.repBuildDir = repBuildDir; this.repBuildDir = repBuildDir;
} }



/** /**
* Turns on/off precondition instrumentation * Turns on/off precondition instrumentation
* *
* @param pre true turns it on * @param pre true turns it on
*/ */
public void setPre( boolean pre ) {
public void setPre(boolean pre) {
this.pre = pre; this.pre = pre;
preModified = true; preModified = true;
} }



/** /**
* Turns on/off postcondition instrumentation * Turns on/off postcondition instrumentation
* *
* @param post true turns it on * @param post true turns it on
*/ */
public void setPost( boolean post ) {
public void setPost(boolean post) {
this.post = post; this.post = post;
postModified = true; postModified = true;
} }



/** /**
* Turns on/off invariant instrumentation * Turns on/off invariant instrumentation
* *
* @param invariant true turns it on * @param invariant true turns it on
*/ */
public void setInvariant( boolean invariant ) {
public void setInvariant(boolean invariant) {
this.invariant = invariant; this.invariant = invariant;
invariantModified = true; invariantModified = true;
} }



/** /**
* Sets the Throwable (Exception) to be thrown on assertion violation * Sets the Throwable (Exception) to be thrown on assertion violation
* *
* @param clazz the fully qualified Throwable class name * @param clazz the fully qualified Throwable class name
*/ */
public void setFailthrowable( String clazz ) {
public void setFailthrowable(String clazz) {
this.failThrowable = clazz; this.failThrowable = clazz;
} }



/** /**
* Sets the verbosity level of iContract. Any combination of * 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 * @param verbosity verbosity level
*/ */
public void setVerbosity( String verbosity ) {
public void setVerbosity(String verbosity) {
this.verbosity = verbosity; this.verbosity = verbosity;
} }



/** /**
* Tells iContract to be quiet. * Tells iContract to be quiet.
* *
* @param quiet true if iContract should be quiet. * @param quiet true if iContract should be quiet.
*/ */
public void setQuiet( boolean quiet ) {
public void setQuiet(boolean quiet) {
this.quiet = 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 * @param targets the targets file name
*/ */
public void setTargets( File targets ) {
public void setTargets(File targets) {
this.targets = targets; this.targets = targets;
} }



/** /**
* Sets the control file to pass to iContract. * Sets the control file to pass to iContract.
* *
* @param controlFile the control file * @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; this.controlFile = controlFile;
} }



/** /**
* Sets the classpath to be used for invocation of iContract. * Sets the classpath to be used for invocation of iContract.
* *
* @param path the classpath * @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 * Creates a nested classpath element
* *
@@ -464,29 +480,33 @@ public class IContract extends MatchingTask {
*/ */
public Path createClasspath() { public Path createClasspath() {
if (classpath == null) { if (classpath == null) {
classpath = new Path( getProject() );
classpath = new Path(getProject());
} }
return classpath; return classpath;
} }



/** /**
* Adds a reference to a classpath defined elsewhere. * Adds a reference to a classpath defined elsewhere.
* *
* @param reference referenced classpath * @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 * 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; this.updateIcontrol = updateIcontrol;
} }



/** /**
* Executes the task * Executes the task
* *
@@ -495,39 +515,41 @@ public class IContract extends MatchingTask {
public void execute() throws BuildException { public void execute() throws BuildException {
preconditions(); preconditions();
scan(); scan();
if( dirty ) {
if (dirty) {


// turn off assertions if we're using controlfile, unless they are not explicitly set. // turn off assertions if we're using controlfile, unless they are not explicitly set.
boolean useControlFile = (controlFile != null) && controlFile.exists(); boolean useControlFile = (controlFile != null) && controlFile.exists();
if( useControlFile && !preModified ) {

if (useControlFile && !preModified) {
pre = false; pre = false;
} }
if( useControlFile && !postModified ) {
if (useControlFile && !postModified) {
post = false; post = false;
} }
if( useControlFile && !invariantModified ) {
if (useControlFile && !invariantModified) {
invariant = false; invariant = false;
} }
// issue warning if pre,post or invariant is used together with controlfile // 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 // 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!) // 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 // 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 // don't exist, but for some reason I don't know, it will complain about the REP files
// afterwards // afterwards
Mkdir mkdir = (Mkdir) project.createTask( "mkdir" );
mkdir.setDir( instrumentDir );
Mkdir mkdir = (Mkdir) project.createTask("mkdir");

mkdir.setDir(instrumentDir);
mkdir.execute(); mkdir.execute();
mkdir.setDir( buildDir );
mkdir.setDir(buildDir);
mkdir.execute(); mkdir.execute();
mkdir.setDir( repositoryDir );
mkdir.setDir(repositoryDir);
mkdir.execute(); mkdir.execute();


// Set the classpath that is needed for regular Javac compilation // 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) // Might need to add the core classes if we're not using Sun's Javac (like Jikes)
String compiler = project.getProperty("build.compiler"); 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 // Create the classpath required to compile the sourcefiles BEFORE instrumentation
Path beforeInstrumentationClasspath = ((Path) baseClasspath.clone()); 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 // Create the classpath required to compile the sourcefiles AFTER instrumentation
Path afterInstrumentationClasspath = ((Path) baseClasspath.clone()); 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 // Create the classpath required to automatically compile the repository files
Path repositoryClasspath = ((Path) baseClasspath.clone()); 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 // Create the classpath required for iContract itself
Path iContractClasspath = ((Path) baseClasspath.clone()); 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 // 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 // Build the arguments to iContract
StringBuffer args = new StringBuffer(); 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() ); //System.out.println( "JAVA -classpath " + iContractClasspath + " com.reliablesystems.iContract.Tool " + args.toString() );


// update iControlProperties if it's set. // update iControlProperties if it's set.
if( updateIcontrol ) {
if (updateIcontrol) {
Properties iControlProps = new Properties(); 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! // do it!
int result = iContract.executeJava(); 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." ); //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 { private void preconditions() throws BuildException {
if (srcDir == null) { if (srcDir == null) {
throw new BuildException( "srcdir attribute must be set!", location );
throw new BuildException("srcdir attribute must be set!", location);
} }
if (!srcDir.exists()) { 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) { if (instrumentDir == null) {
throw new BuildException( "instrumentdir attribute must be set!", location );
throw new BuildException("instrumentdir attribute must be set!", location);
} }
if (repositoryDir == null) { 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) { 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.
* <br/>
* 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. <br/>
* Also creates a temporary file with a list of the source files, that
* will be deleted upon exit.
*/ */
private void scan() throws BuildException { private void scan() throws BuildException {
long now = (new Date()).getTime(); long now = (new Date()).getTime();


DirectoryScanner ds = null; DirectoryScanner ds = null;


ds = getDirectoryScanner( srcDir );
ds = getDirectoryScanner(srcDir);

String[] files = ds.getIncludedFiles(); String[] files = ds.getIncludedFiles();


FileOutputStream targetOutputStream = null; FileOutputStream targetOutputStream = null;
PrintStream targetPrinter = null; PrintStream targetPrinter = null;
boolean writeTargets = false; boolean writeTargets = false;

try { 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; 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; 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]); File srcFile = new File(srcDir, files[i]);

if (files[i].endsWith(".java")) { if (files[i].endsWith(".java")) {
// print the target, while we're at here. (Only if generatetarget=true). // 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) { if (srcFile.lastModified() > now) {
log("Warning: file modified in the future: " + 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.flush();
targetPrinter.close(); 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 // also, check controlFile timestamp
long controlFileTime = -1; long controlFileTime = -1;

try { try {
if( controlFile != null ) {
if( controlFile.exists() && buildDir.exists() ) {
if (controlFile != null) {
if (controlFile.exists() && buildDir.exists()) {
controlFileTime = controlFile.lastModified(); controlFileTime = controlFile.lastModified();
ds = getDirectoryScanner( buildDir );
ds = getDirectoryScanner(buildDir);
files = ds.getIncludedFiles(); 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; dirty = true;
instrumentall = 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() { private final String directiveString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
boolean comma = false; boolean comma = false;


boolean useControlFile = (controlFile != null) && controlFile.exists(); 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; comma = true;
} }
if( pre ) {
if( comma ) {
sb.append( "," );
if (pre) {
if (comma) {
sb.append(",");
} }
sb.append( "pre" );
sb.append("pre");
comma = true; comma = true;
} }
if( post ) {
if( comma ) {
sb.append( "," );
if (post) {
if (comma) {
sb.append(",");
} }
sb.append( "post" );
sb.append("post");
comma = true; 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(); 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 { 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) { 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; 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 class ClasspathHelper extends DefaultCompilerAdapter {
private final String compiler; private final String compiler;
public ClasspathHelper( String compiler ) {


public ClasspathHelper(String compiler) {
super(); super();
this.compiler = compiler; this.compiler = compiler;
} }


// make it public // make it public
public void modify( Path path ) {
public void modify(Path path) {
// depending on what compiler to use, set the includeJavaRuntime flag // depending on what compiler to use, set the includeJavaRuntime flag
if( "jikes".equals( compiler ) ) {
if ("jikes".equals(compiler)) {
icCompiler = compiler; icCompiler = compiler;
includeJavaRuntime = true; includeJavaRuntime = true;
path.append( getCompileClasspath() );
path.append(getCompileClasspath());
} }
} }


// dummy implementation. Never called // dummy implementation. Never called
public void setJavac( Javac javac ) {}
public boolean execute() { return true; }
public void setJavac(Javac javac) {
}


public boolean execute() {
return true;
}
} }
} }


+ 4
- 3
src/main/org/apache/tools/ant/taskdefs/optional/Javah.java View File

@@ -136,7 +136,7 @@ public class Javah extends Task {


public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
log("ClassArgument.name="+name);
log("ClassArgument.name=" + name);
} }


public String getName() { public String getName() {
@@ -318,7 +318,8 @@ public class Javah extends Task {
// dynamically. However, javah has a different interface and this // dynamically. However, javah has a different interface and this
// makes it harder, so here's a simple alternative. // 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(); main.run();
} }
//catch (ClassNotFoundException ex) { //catch (ClassNotFoundException ex) {
@@ -411,7 +412,7 @@ public class Javah extends Task {


Enumeration enum = classes.elements(); Enumeration enum = classes.elements();
while (enum.hasMoreElements()) { while (enum.hasMoreElements()) {
ClassArgument arg = (ClassArgument)enum.nextElement();
ClassArgument arg = (ClassArgument) enum.nextElement();
String aClass = arg.getName(); String aClass = arg.getName();
cmd.createArgument().setValue(aClass); cmd.createArgument().setValue(aClass);
niceClassList.append(" " + aClass + lSep); niceClassList.append(" " + aClass + lSep);


+ 3
- 3
src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java View File

@@ -189,7 +189,7 @@ public class Native2Ascii extends MatchingTask {
if (count == 0) { if (count == 0) {
return; return;
} }
String message = "Converting "+ count + " file"
String message = "Converting " + count + " file"
+ (count != 1 ? "s" : "") + " from "; + (count != 1 ? "s" : "") + " from ";
log(message + srcDir + " to " + destDir); log(message + srcDir + " to " + destDir);
for (int i = 0; i < files.length; i++){ for (int i = 0; i < files.length; i++){
@@ -237,7 +237,7 @@ public class Native2Ascii extends MatchingTask {
if (parentName != null){ if (parentName != null){
File parentFile = new File(parentName); File parentFile = new File(parentName);
if ((! parentFile.exists()) && ( ! parentFile.mkdirs())){
if ((!parentFile.exists()) && (!parentFile.mkdirs())){
throw new BuildException("cannot create parent directory " throw new BuildException("cannot create parent directory "
+ parentName); + parentName);
} }
@@ -246,7 +246,7 @@ public class Native2Ascii extends MatchingTask {
log("converting " + srcName, Project.MSG_VERBOSE); log("converting " + srcName, Project.MSG_VERBOSE);
sun.tools.native2ascii.Main n2a sun.tools.native2ascii.Main n2a
= new sun.tools.native2ascii.Main(); = new sun.tools.native2ascii.Main();
if(! n2a.convert(cmd.getArguments())){
if (!n2a.convert(cmd.getArguments())){
throw new BuildException("conversion failed"); throw new BuildException("conversion failed");
} }
} }


+ 263
- 220
src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java View File

@@ -124,14 +124,13 @@ import org.apache.tools.ant.types.EnumeratedAttribute;
* *
* @author dIon Gillard <a href="mailto:dion@multitask.com.au">dion@multitask.com.au</a> * @author dIon Gillard <a href="mailto:dion@multitask.com.au">dion@multitask.com.au</a>
*/ */

public class NetRexxC extends MatchingTask { public class NetRexxC extends MatchingTask {


// variables to hold arguments // variables to hold arguments
private boolean binary; private boolean binary;
private String classpath; private String classpath;
private boolean comments; 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 compile = true;
private boolean console; private boolean console;
private boolean crossref; private boolean crossref;
@@ -146,7 +145,7 @@ public class NetRexxC extends MatchingTask {
private boolean replace; private boolean replace;
private boolean savelog; private boolean savelog;
private File srcDir; 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 strictargs;
private boolean strictassign; private boolean strictassign;
private boolean strictcase; private boolean strictcase;
@@ -165,17 +164,18 @@ public class NetRexxC extends MatchingTask {
private boolean suppressDeprecation = false; private boolean suppressDeprecation = false;


// constants for the messages to suppress by flags and their corresponding properties // 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 // other implementation variables
private Vector compileList = new Vector(); private Vector compileList = new Vector();
private Hashtable filecopyList = new Hashtable(); private Hashtable filecopyList = new Hashtable();
private String oldClasspath = System.getProperty("java.class.path"); private String oldClasspath = System.getProperty("java.class.path");



/** /**
* Set whether literals are treated as binary, rather than NetRexx types * Set whether literals are treated as binary, rather than NetRexx types
*/ */
@@ -183,78 +183,83 @@ public class NetRexxC extends MatchingTask {
this.binary = binary; this.binary = binary;
} }


/**
* Set the classpath used for NetRexx compilation
*/

/** Set the classpath used for NetRexx compilation */
public void setClasspath(String classpath) { public void setClasspath(String classpath) {
this.classpath = classpath; this.classpath = classpath;
} }



/** /**
* Set whether comments are passed through to the generated java source. * 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) { public void setComments(boolean comments) {
this.comments = 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 * The default value is false
*/ */
public void setCompact(boolean compact) { public void setCompact(boolean compact) {
this.compact = compact; this.compact = compact;
} }



/** /**
* Set whether the NetRexx compiler should compile the generated java code * 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) { public void setCompile(boolean compile) {
this.compile = compile; this.compile = compile;
if (!this.compile && !this.keep) { 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. * The default value is true.
*/ */
public void setConsole(boolean console) { public void setConsole(boolean console) {
this.console = console; this.console = console;
} }


/**
* Whether variable cross references are generated
*/

/** Whether variable cross references are generated */
public void setCrossref(boolean crossref) { public void setCrossref(boolean crossref) {
this.crossref = crossref; this.crossref = crossref;
} }



/** /**
* Set whether decimal arithmetic should be used for the netrexx code. * 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) { public void setDecimal(boolean decimal) {
this.decimal = 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) { public void setDestDir(File destDirName) {
destDir = destDirName; destDir = destDirName;
} }



/** /**
* Whether diagnostic information about the compile is generated * Whether diagnostic information about the compile is generated
*/ */
@@ -262,27 +267,30 @@ public class NetRexxC extends MatchingTask {
this.diag = diag; 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. * The default value is false.
*/ */
public void setExplicit(boolean explicit) { public void setExplicit(boolean explicit) {
this.explicit = 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) { public void setFormat(boolean format) {
this.format = 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) { public void setJava(boolean java) {
this.java = 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, <b>not</b> .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,
* <b>not</b> .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) { public void setKeep(boolean keep) {
this.keep = 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) { public void setLogo(boolean logo) {
this.logo = logo; this.logo = logo;
} }



/** /**
* Whether the generated .java file should be replaced when compiling * 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) { public void setReplace(boolean replace) {
this.replace = replace; this.replace = replace;
} }



/** /**
* Sets whether the compiler messages will be written to NetRexxC.log as * 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) { public void setSavelog(boolean savelog) {
this.savelog = 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) { public void setSourcedir(boolean sourcedir) {
this.sourcedir = 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) { public void setSrcDir(File srcDirName) {
srcDir = srcDirName; srcDir = srcDirName;
} }



/** /**
* Tells the NetRexx compiler that method calls always need parentheses, * Tells the NetRexx compiler that method calls always need parentheses,
* even if no arguments are needed, e.g. <code>aStringVar.getBytes</code> * even if no arguments are needed, e.g. <code>aStringVar.getBytes</code>
* vs. <code>aStringVar.getBytes()</code>
* Valid true values are "on" or "true". Anything else sets the flag to false.
* The default value is false.
* vs. <code>aStringVar.getBytes()</code> Valid true values are "on" or
* "true". Anything else sets the flag to false. The default value is
* false.
*/ */
public void setStrictargs(boolean strictargs) { public void setStrictargs(boolean strictargs) {
this.strictargs = strictargs; this.strictargs = strictargs;
} }



/** /**
* Tells the NetRexx compile that assignments must match exactly on type * Tells the NetRexx compile that assignments must match exactly on type
*/ */
@@ -360,6 +370,7 @@ public class NetRexxC extends MatchingTask {
this.strictassign = strictassign; this.strictassign = strictassign;
} }



/** /**
* Specifies whether the NetRexx compiler should be case sensitive or not * Specifies whether the NetRexx compiler should be case sensitive or not
*/ */
@@ -367,21 +378,22 @@ public class NetRexxC extends MatchingTask {
this.strictcase = strictcase; this.strictcase = strictcase;
} }



/** /**
* Sets whether classes need to be imported explicitly using an
* <code>import</code> 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 <code>import</code>
* 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) { public void setStrictimport(boolean strictimport) {
this.strictimport = strictimport; this.strictimport = strictimport;
} }



/** /**
* Sets whether local properties need to be qualified explicitly using <code>this</code>
* 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
* <code>this</code> Valid true values are "on" or "true". Anything else
* sets the flag to false. The default value is false.
*/ */
public void setStrictprops(boolean strictprops) { public void setStrictprops(boolean strictprops) {
this.strictprops = 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) { public void setStrictsignal(boolean strictsignal) {
this.strictsignal = strictsignal; this.strictsignal = strictsignal;
} }



/** /**
* Sets whether debug symbols should be generated into the class file * 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) { public void setSymbols(boolean symbols) {
this.symbols = symbols; this.symbols = symbols;
} }



/** /**
* Asks the NetRexx compiler to print compilation times to the console * 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) { public void setTime(boolean time) {
this.time = time; this.time = time;
} }



public void setTrace(TraceAttr trace) { public void setTrace(TraceAttr trace) {
this.trace = trace.getValue(); 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) { public void setTrace(String trace) {
TraceAttr t = new TraceAttr(); TraceAttr t = new TraceAttr();

t.setValue(trace); t.setValue(trace);
setTrace(t); 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) { public void setUtf8(boolean utf8) {
this.utf8 = utf8; this.utf8 = utf8;
} }



/** /**
* Whether lots of warnings and error messages should be generated * Whether lots of warnings and error messages should be generated
*/ */
public void setVerbose(VerboseAttr verbose) { public void setVerbose(VerboseAttr verbose) {
this.verbose = verbose.getValue(); this.verbose = verbose.getValue();
} }


/** /**
* Whether lots of warnings and error messages should be generated * Whether lots of warnings and error messages should be generated
*/ */
public void setVerbose(String verbose) { public void setVerbose(String verbose) {
VerboseAttr v = new VerboseAttr(); VerboseAttr v = new VerboseAttr();

v.setValue(verbose); v.setValue(verbose);
setVerbose(v); 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. * The warning is logged as verbose message, though.
*/ */
public void setSuppressMethodArgumentNotUsed(boolean suppressMethodArgumentNotUsed) { public void setSuppressMethodArgumentNotUsed(boolean suppressMethodArgumentNotUsed) {
this.suppressMethodArgumentNotUsed = suppressMethodArgumentNotUsed; this.suppressMethodArgumentNotUsed = suppressMethodArgumentNotUsed;
} }



/** /**
* Whether the task should suppress the "Private property is defined but * 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) { public void setSuppressPrivatePropertyNotUsed(boolean suppressPrivatePropertyNotUsed) {
this.suppressPrivatePropertyNotUsed = 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) { public void setSuppressVariableNotUsed(boolean suppressVariableNotUsed) {
this.suppressVariableNotUsed = 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) { public void setSuppressExceptionNotSignalled(boolean suppressExceptionNotSignalled) {
this.suppressExceptionNotSignalled = 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) { public void setSuppressDeprecation(boolean suppressDeprecation) {
this.suppressDeprecation = 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). // Sorry for the formatting, but that way it's easier to keep in sync with the private properties (line by line).
public void init() { public void init() {
String p; 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 // 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 // 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 // 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); 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); 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 { public void execute() throws BuildException {


// first off, make sure that we've got a srcdir and destdir // 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!"); throw new BuildException("srcDir and destDir attributes must be set!");
} }


@@ -632,15 +660,16 @@ public class NetRexxC extends MatchingTask {
// compile the source files // compile the source files
if (compileList.size() > 0) { if (compileList.size() > 0) {
log("Compiling " + compileList.size() + " source file" log("Compiling " + compileList.size() + " source file"
+ (compileList.size() == 1 ? "" : "s")
+ " to " + destDir);
+ (compileList.size() == 1 ? "" : "s")
+ " to " + destDir);
doNetRexxCompile(); 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) { private void scanDir(File srcDir, File destDir, String[] files) {
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
@@ -654,7 +683,7 @@ public class NetRexxC extends MatchingTask {
if (filename.toLowerCase().endsWith(".nrx")) { if (filename.toLowerCase().endsWith(".nrx")) {
File classFile = File classFile =
new File(destDir, new File(destDir,
filename.substring(0, filename.lastIndexOf('.')) + ".class");
filename.substring(0, filename.lastIndexOf('.')) + ".class");


if (!compile || srcFile.lastModified() > classFile.lastModified()) { if (!compile || srcFile.lastModified() > classFile.lastModified()) {
filecopyList.put(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); 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() { private void copyFilesToDestination() {
if (filecopyList.size() > 0) { if (filecopyList.size() > 0) {
log("Copying " + filecopyList.size() + " file" log("Copying " + filecopyList.size() + " file"
+ (filecopyList.size() == 1 ? "" : "s")
+ " to " + destDir.getAbsolutePath());
+ (filecopyList.size() == 1 ? "" : "s")
+ " to " + destDir.getAbsolutePath());

Enumeration enum = filecopyList.keys(); Enumeration enum = filecopyList.keys();

while (enum.hasMoreElements()) { 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 { try {
project.copyFile(fromFile, toFile); project.copyFile(fromFile, toFile);
} catch (IOException ioe) { } catch (IOException ioe) {
String msg = "Failed to copy " + fromFile + " to " + toFile String msg = "Failed to copy " + fromFile + " to " + toFile
+ " due to " + ioe.getMessage();
+ " due to " + ioe.getMessage();

throw new BuildException(msg, ioe); 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 { private void doNetRexxCompile() throws BuildException {
log("Using NetRexx compiler", Project.MSG_VERBOSE); log("Using NetRexx compiler", Project.MSG_VERBOSE);

String classpath = getCompileClasspath(); String classpath = getCompileClasspath();
StringBuffer compileOptions = new StringBuffer(); StringBuffer compileOptions = new StringBuffer();
StringBuffer fileList = new StringBuffer(); StringBuffer fileList = new StringBuffer();
@@ -706,17 +738,19 @@ public class NetRexxC extends MatchingTask {
String[] fileListArray = new String[compileList.size()]; String[] fileListArray = new String[compileList.size()];
Enumeration e = compileList.elements(); Enumeration e = compileList.elements();
int j = 0; int j = 0;

while (e.hasMoreElements()) { while (e.hasMoreElements()) {
fileListArray[j] = (String)e.nextElement();
fileListArray[j] = (String) e.nextElement();
j++; j++;
} }
// create a single array of arguments for the compiler // create a single array of arguments for the compiler
String compileArgs[] = new String[compileOptionsArray.length + fileListArray.length]; String compileArgs[] = new String[compileOptionsArray.length + fileListArray.length];

for (int i = 0; i < compileOptionsArray.length; i++) { for (int i = 0; i < compileOptionsArray.length; i++) {
compileArgs[i] = compileOptionsArray[i]; compileArgs[i] = compileOptionsArray[i];
} }
for (int i = 0; i < fileListArray.length; 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 // 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 // since the NetRexx compiler has no option for the classpath
String currentClassPath = System.getProperty("java.class.path"); String currentClassPath = System.getProperty("java.class.path");
Properties currentProperties = System.getProperties(); Properties currentProperties = System.getProperties();

currentProperties.put("java.class.path", classpath); currentProperties.put("java.class.path", classpath);


try { try {
StringWriter out = new StringWriter(); 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; 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; 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 // 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); 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); 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); 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); 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); 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); 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); log(l, Project.MSG_WARN);
} else { } 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."); throw new BuildException("Compile failed, messages should have been provided.");
} }
} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("Unexpected IOException while playing with Strings", throw new BuildException("Unexpected IOException while playing with Strings",
ioe);
ioe);
} finally { } finally {
// need to reset java.class.path property // need to reset java.class.path property
// since the NetRexx compiler has no option for the classpath // 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() { private String getCompileClasspath() {
StringBuffer classpath = new StringBuffer(); StringBuffer classpath = new StringBuffer();


@@ -814,11 +850,11 @@ public class NetRexxC extends MatchingTask {
return classpath.toString(); return classpath.toString();
} }


/**
* This
*/

/** This */
private String[] getCompileOptionsAsArray() { private String[] getCompileOptionsAsArray() {
Vector options = new Vector(); Vector options = new Vector();

options.addElement(binary ? "-binary" : "-nobinary"); options.addElement(binary ? "-binary" : "-nobinary");
options.addElement(comments ? "-comments" : "-nocomments"); options.addElement(comments ? "-comments" : "-nocomments");
options.addElement(compile ? "-compile" : "-nocompile"); options.addElement(compile ? "-compile" : "-nocompile");
@@ -827,7 +863,7 @@ public class NetRexxC extends MatchingTask {
options.addElement(crossref ? "-crossref" : "-nocrossref"); options.addElement(crossref ? "-crossref" : "-nocrossref");
options.addElement(decimal ? "-decimal" : "-nodecimal"); options.addElement(decimal ? "-decimal" : "-nodecimal");
options.addElement(diag ? "-diag" : "-nodiag"); options.addElement(diag ? "-diag" : "-nodiag");
options.addElement(explicit ? "-explicit": "-noexplicit");
options.addElement(explicit ? "-explicit" : "-noexplicit");
options.addElement(format ? "-format" : "-noformat"); options.addElement(format ? "-format" : "-noformat");
options.addElement(keep ? "-keep" : "-nokeep"); options.addElement(keep ? "-keep" : "-nokeep");
options.addElement(logo ? "-logo" : "-nologo"); options.addElement(logo ? "-logo" : "-nologo");
@@ -836,7 +872,7 @@ public class NetRexxC extends MatchingTask {
options.addElement(sourcedir ? "-sourcedir" : "-nosourcedir"); options.addElement(sourcedir ? "-sourcedir" : "-nosourcedir");
options.addElement(strictargs ? "-strictargs" : "-nostrictargs"); options.addElement(strictargs ? "-strictargs" : "-nostrictargs");
options.addElement(strictassign ? "-strictassign" : "-nostrictassign"); options.addElement(strictassign ? "-strictassign" : "-nostrictassign");
options.addElement(strictcase ? "-strictcase": "-nostrictcase");
options.addElement(strictcase ? "-strictcase" : "-nostrictcase");
options.addElement(strictimport ? "-strictimport" : "-nostrictimport"); options.addElement(strictimport ? "-strictimport" : "-nostrictimport");
options.addElement(strictprops ? "-strictprops" : "-nostrictprops"); options.addElement(strictprops ? "-strictprops" : "-nostrictprops");
options.addElement(strictsignal ? "-strictsignal" : "-nostrictsignal"); options.addElement(strictsignal ? "-strictsignal" : "-nostrictsignal");
@@ -845,24 +881,28 @@ public class NetRexxC extends MatchingTask {
options.addElement("-" + trace); options.addElement("-" + trace);
options.addElement(utf8 ? "-utf8" : "-noutf8"); options.addElement(utf8 ? "-utf8" : "-noutf8");
options.addElement("-" + verbose); options.addElement("-" + verbose);

String[] results = new String[options.size()]; String[] results = new String[options.size()];

options.copyInto(results); options.copyInto(results);
return 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. * annoying.
*
* @param target - target classpath * @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, StringTokenizer tok = new StringTokenizer(source,
System.getProperty("path.separator"), false);
System.getProperty("path.separator"), false);

while (tok.hasMoreTokens()) { while (tok.hasMoreTokens()) {
File f = project.resolveFile(tok.nextToken()); File f = project.resolveFile(tok.nextToken());


@@ -870,24 +910,27 @@ public class NetRexxC extends MatchingTask {
target.append(File.pathSeparator); target.append(File.pathSeparator);
target.append(f.getAbsolutePath()); target.append(f.getAbsolutePath());
} else { } else {
log("Dropping from classpath: "+
log("Dropping from classpath: " +
f.getAbsolutePath(), Project.MSG_VERBOSE); f.getAbsolutePath(), Project.MSG_VERBOSE);
} }
} }


} }



public static class TraceAttr extends EnumeratedAttribute { public static class TraceAttr extends EnumeratedAttribute {
public String[] getValues() { public String[] getValues() {
return new String[] {"trace", "trace1", "trace2", "notrace"};
return new String[]{"trace", "trace1", "trace2", "notrace"};
} }
} }



public static class VerboseAttr extends EnumeratedAttribute { public static class VerboseAttr extends EnumeratedAttribute {
public String[] getValues() { 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"};
} }
} }
} }


+ 12
- 15
src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java View File

@@ -197,9 +197,9 @@ public class PropertyFile extends Task


private void executeOperation() throws BuildException 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); entry.executeOn(properties);
} }
} }
@@ -212,7 +212,8 @@ public class PropertyFile extends Task
{ {
if (propertyfile.exists()) if (propertyfile.exists())
{ {
log("Updating property file: "+propertyfile.getAbsolutePath());
log("Updating property file: "
+ propertyfile.getAbsolutePath());
FileInputStream fis = null; FileInputStream fis = null;
try { try {
fis = new FileInputStream(propertyfile); fis = new FileInputStream(propertyfile);
@@ -226,8 +227,8 @@ public class PropertyFile extends Task
} }
else else
{ {
log("Creating new property file: "+
propertyfile.getAbsolutePath());
log("Creating new property file: "
+ propertyfile.getAbsolutePath());
FileOutputStream out = null; FileOutputStream out = null;
try { try {
out = new FileOutputStream(propertyfile.getAbsolutePath()); 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()); throw new BuildException(ioe.toString());
} }
} }
@@ -275,8 +274,7 @@ public class PropertyFile extends Task
Properties.class.getMethod("store", Properties.class.getMethod("store",
new Class[] { new Class[] {
OutputStream.class, OutputStream.class,
String.class}
);
String.class});
m.invoke(properties, new Object[] {bos, comment}); m.invoke(properties, new Object[] {bos, comment});


} catch (NoSuchMethodException nsme) { } catch (NoSuchMethodException nsme) {
@@ -287,9 +285,7 @@ public class PropertyFile extends Task
} catch (IllegalAccessException iae) { } catch (IllegalAccessException iae) {
// impossible // impossible
throw new BuildException(iae, location); throw new BuildException(iae, location);
}
catch (IOException ioe)
{
} catch (IOException ioe) {
throw new BuildException(ioe, location); throw new BuildException(ioe, location);
} }
finally { finally {
@@ -369,7 +365,7 @@ public class PropertyFile extends Task
checkParameters(); checkParameters();


// type may be null because it wasn't set // type may be null because it wasn't set
String oldValue = (String)props.get(key);
String oldValue = (String) props.get(key);
try { try {
if (type == Type.INTEGER_TYPE) if (type == Type.INTEGER_TYPE)
{ {
@@ -385,7 +381,8 @@ public class PropertyFile extends Task
} }
else else
{ {
throw new BuildException("Unknown operation type: "+type+"");
throw new BuildException("Unknown operation type: "
+ type);
} }
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
// Default to string type // Default to string type


+ 9
- 9
src/main/org/apache/tools/ant/taskdefs/optional/RenameExtensions.java View File

@@ -129,24 +129,24 @@ public class RenameExtensions extends MatchingTask {


// first off, make sure that we've got a from and to extension // first off, make sure that we've got a from and to extension
if (fromExtension == null || toExtension == null || srcDir == null) { 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.", log("DEPRECATED - The renameext task is deprecated. Use move instead.",
Project.MSG_WARN); Project.MSG_WARN);
log("Replace this with:", Project.MSG_INFO); log("Replace this with:", Project.MSG_INFO);
log("<move todir=\""+srcDir+"\" overwrite=\""+replace+"\">",
log("<move todir=\"" + srcDir + "\" overwrite=\"" + replace + "\">",
Project.MSG_INFO); Project.MSG_INFO);
log(" <fileset dir=\""+srcDir+"\" />", Project.MSG_INFO);
log(" <fileset dir=\"" + srcDir + "\" />", Project.MSG_INFO);
log(" <mapper type=\"glob\"", Project.MSG_INFO); log(" <mapper type=\"glob\"", Project.MSG_INFO);
log(" from=\"*"+fromExtension+"\"", Project.MSG_INFO);
log(" to=\"*"+toExtension+"\" />", Project.MSG_INFO);
log(" from=\"*" + fromExtension + "\"", Project.MSG_INFO);
log(" to=\"*" + toExtension + "\" />", Project.MSG_INFO);
log("</move>", Project.MSG_INFO); log("</move>", Project.MSG_INFO);
log("using the same patterns on <fileset> as you\'ve used here", log("using the same patterns on <fileset> as you\'ve used here",
Project.MSG_INFO); Project.MSG_INFO);


Move move = (Move)project.createTask("move");
Move move = (Move) project.createTask("move");
move.setOwningTarget(target); move.setOwningTarget(target);
move.setTaskName(getTaskName()); move.setTaskName(getTaskName());
move.setLocation(getLocation()); move.setLocation(getLocation());
@@ -158,8 +158,8 @@ public class RenameExtensions extends MatchingTask {


Mapper me = move.createMapper(); Mapper me = move.createMapper();
me.setType(globType); me.setType(globType);
me.setFrom("*"+fromExtension);
me.setTo("*"+toExtension);
me.setFrom("*" + fromExtension);
me.setTo("*" + toExtension);


move.execute(); move.execute();
} }


+ 78
- 100
src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java View File

@@ -1,7 +1,7 @@
/* /*
* The Apache Software License, Version 1.1 * 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. * reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
@@ -73,7 +73,7 @@ import java.io.PrintWriter;


import java.util.Vector; import java.util.Vector;


/***
/**
* <pre> * <pre>
* Task to do regular expression string replacements in a text * Task to do regular expression string replacements in a text
* file. The input file(s) must be able to be properly processed by * file. The input file(s) must be able to be properly processed by
@@ -85,7 +85,6 @@ import java.util.Vector;
* is <code>org.apache.tools.ant.util.regexp.JakartaOroRegexp</code> and * is <code>org.apache.tools.ant.util.regexp.JakartaOroRegexp</code> and
* requires the Jakarta Oro Package). * requires the Jakarta Oro Package).
* *
* <pre>
* For jdk &lt;= 1.3, there are two available implementations: * For jdk &lt;= 1.3, there are two available implementations:
* org.apache.tools.ant.util.regexp.JakartaOroRegexp (the default) * org.apache.tools.ant.util.regexp.JakartaOroRegexp (the default)
* Requires the jakarta-oro package * Requires the jakarta-oro package
@@ -96,7 +95,6 @@ import java.util.Vector;
* For jdk &gt;= 1.4 an additional implementation is available: * For jdk &gt;= 1.4 an additional implementation is available:
* org.apache.tools.ant.util.regexp.Jdk14RegexpRegexp * org.apache.tools.ant.util.regexp.Jdk14RegexpRegexp
* Requires the jdk 1.4 built in regular expression package. * Requires the jdk 1.4 built in regular expression package.
* </pre>
* *
* Usage: * Usage:
* *
@@ -146,23 +144,20 @@ import java.util.Vector;
* *
* @author <a href="mailto:mattinger@mindless.com">Matthew Inger</a> * @author <a href="mailto:mattinger@mindless.com">Matthew Inger</a>
*/ */
public class ReplaceRegExp extends Task
{
public class ReplaceRegExp extends Task {


private File file; private File file;
private String flags; private String flags;
private boolean byline; 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 RegularExpression regex;
private Substitution subs; private Substitution subs;


private FileUtils fileUtils = FileUtils.newFileUtils(); private FileUtils fileUtils = FileUtils.newFileUtils();


/***
* Default Constructor
*/
public ReplaceRegExp()
{

/** Default Constructor */
public ReplaceRegExp() {
super(); super();
this.file = null; this.file = null;
this.filesets = new Vector(); this.filesets = new Vector();
@@ -173,13 +168,13 @@ public class ReplaceRegExp extends Task
this.subs = null; this.subs = null;
} }


public void setFile(File file)
{
public void setFile(File file) {
this.file = file; this.file = file;
} }


public void setMatch(String match)
{
public void setMatch(String match) {
if (regex != null) { if (regex != null) {
throw new BuildException("Only one regular expression is allowed"); throw new BuildException("Only one regular expression is allowed");
} }
@@ -188,8 +183,8 @@ public class ReplaceRegExp extends Task
regex.setPattern(match); regex.setPattern(match);
} }


public void setReplace(String replace)
{
public void setReplace(String replace) {
if (subs != null) { if (subs != null) {
throw new BuildException("Only one substitution expression is allowed"); throw new BuildException("Only one substitution expression is allowed");
} }
@@ -198,27 +193,28 @@ public class ReplaceRegExp extends Task
subs.setExpression(replace); subs.setExpression(replace);
} }


public void setFlags(String flags)
{
public void setFlags(String flags) {
this.flags = flags; this.flags = flags;
} }


public void setByLine(String byline)
{
public void setByLine(String byline) {
Boolean res = Boolean.valueOf(byline); Boolean res = Boolean.valueOf(byline);

if (res == null) { if (res == null) {
res = Boolean.FALSE; res = Boolean.FALSE;
} }
this.byline = res.booleanValue(); this.byline = res.booleanValue();
} }


public void addFileset(FileSet set)
{
public void addFileset(FileSet set) {
filesets.addElement(set); filesets.addElement(set);
} }


public RegularExpression createRegexp()
{
public RegularExpression createRegexp() {
if (regex != null) { if (regex != null) {
throw new BuildException("Only one regular expression is allowed."); throw new BuildException("Only one regular expression is allowed.");
} }
@@ -227,8 +223,8 @@ public class ReplaceRegExp extends Task
return regex; return regex;
} }


public Substitution createSubstitution()
{
public Substitution createSubstitution() {
if (subs != null) { if (subs != null) {
throw new BuildException("Only one substitution expression is allowed"); throw new BuildException("Only one substitution expression is allowed");
} }
@@ -236,38 +232,33 @@ public class ReplaceRegExp extends Task
subs = new Substitution(); subs = new Substitution();
return subs; return subs;
} }


protected String doReplace(RegularExpression r, protected String doReplace(RegularExpression r,
Substitution s, Substitution s,
String input, String input,
int options)
{
int options) {
String res = input; String res = input;
Regexp regexp = r.getRegexp(project); Regexp regexp = r.getRegexp(project);


if (regexp.matches(input, options))
{
if (regexp.matches(input, options)) {
res = regexp.substitute(input, s.getExpression(project), options); res = regexp.substitute(input, s.getExpression(project), options);
} }


return res; return res;
} }


/***
* Perform the replace on the entire file
*/

/** Perform the replace on the entire file */
protected void doReplace(File f, int options) protected void doReplace(File f, int options)
throws IOException
{
throws IOException {
File parentDir = new File(new File(f.getAbsolutePath()).getParent()); File parentDir = new File(new File(f.getAbsolutePath()).getParent());
File temp = fileUtils.createTempFile("replace", ".txt", parentDir); File temp = fileUtils.createTempFile("replace", ".txt", parentDir);


FileReader r = null; FileReader r = null;
FileWriter w = null; FileWriter w = null;


try
{
try {
r = new FileReader(f); r = new FileReader(f);
w = new FileWriter(temp); w = new FileWriter(temp);


@@ -277,45 +268,43 @@ public class ReplaceRegExp extends Task


boolean changes = false; 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" : "") + (byline ? " by line" : "") +
(flags.length() > 0 ? " with flags: '" + flags + "'" : "") + (flags.length() > 0 ? " with flags: '" + flags + "'" : "") +
".", ".",
Project.MSG_WARN); Project.MSG_WARN);


if (byline)
{
if (byline) {
LineNumberReader lnr = new LineNumberReader(br); LineNumberReader lnr = new LineNumberReader(br);
String line = null; String line = null;
while ((line = lnr.readLine()) != null)
{

while ((line = lnr.readLine()) != null) {
String res = doReplace(regex, subs, line, options); String res = doReplace(regex, subs, line, options);
if (! res.equals(line)) {

if (!res.equals(line)) {
changes = true; changes = true;
} }


pw.println(res); pw.println(res);
} }
pw.flush(); pw.flush();
}
else
{
int flen = (int)(f.length());
} else {
int flen = (int) f.length();
char tmpBuf[] = new char[flen]; char tmpBuf[] = new char[flen];
int numread = 0; int numread = 0;
int totread = 0; int totread = 0;
while (numread != -1 && totread < flen)
{
while (numread != -1 && totread < flen) {
numread = br.read(tmpBuf, totread, flen); numread = br.read(tmpBuf, totread, flen);
totread += numread; totread += numread;
} }


String buf = new String(tmpBuf); String buf = new String(tmpBuf);
String res = doReplace(regex, subs, buf, options); String res = doReplace(regex, subs, buf, options);
if (! res.equals(buf)) {

if (!res.equals(buf)) {
changes = true; changes = true;
} }


@@ -328,33 +317,34 @@ public class ReplaceRegExp extends Task
w.close(); w.close();
w = null; w = null;


if (changes)
{
if (changes) {
f.delete(); f.delete();
temp.renameTo(f); temp.renameTo(f);
}
else
{
} else {
temp.delete(); temp.delete();
} }
}
finally
{
try { if (r != null) {
} finally {
try {
if (r != null) {
r.close(); r.close();
} }
catch (Exception e) { };
}
} catch (Exception e) {
}
;


try { if (w != null) {
try {
if (w != null) {
r.close(); r.close();
} }
catch (Exception e) { };
}
} catch (Exception e) {
}
;
} }
} }



public void execute() public void execute()
throws BuildException
{
throws BuildException {
if (regex == null) { if (regex == null) {
throw new BuildException("No expression to match."); 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."); throw new BuildException("You cannot supply the 'file' attribute and filesets at the same time.");
} }



int options = 0; int options = 0;
if (flags.indexOf('g') != -1) { if (flags.indexOf('g') != -1) {
options |= Regexp.REPLACE_ALL; options |= Regexp.REPLACE_ALL;
} }
@@ -385,48 +374,37 @@ public class ReplaceRegExp extends Task
options |= Regexp.MATCH_SINGLELINE; options |= Regexp.MATCH_SINGLELINE;
} }


if (file != null && file.exists())
{
try
{
if (file != null && file.exists()) {
try {
doReplace(file, options); doReplace(file, options);
}
catch (IOException e)
{
} catch (IOException e) {
log("An error occurred processing file: '" + file.getAbsolutePath() + "': " + e.toString(), log("An error occurred processing file: '" + file.getAbsolutePath() + "': " + e.toString(),
Project.MSG_ERR); Project.MSG_ERR);
} }
}
else if (file != null)
{
} else if (file != null) {
log("The following file is missing: '" + file.getAbsolutePath() + "'", log("The following file is missing: '" + file.getAbsolutePath() + "'",
Project.MSG_ERR); Project.MSG_ERR);
} }


int sz = filesets.size(); int sz = filesets.size();
for (int i=0;i<sz;i++)
{
FileSet fs = (FileSet)(filesets.elementAt(i));
for (int i = 0; i < sz; i++) {
FileSet fs = (FileSet) (filesets.elementAt(i));
DirectoryScanner ds = fs.getDirectoryScanner(getProject()); DirectoryScanner ds = fs.getDirectoryScanner(getProject());
String files[] = ds.getIncludedFiles(); String files[] = ds.getIncludedFiles();
for (int j=0;j<files.length;j++)
{
for (int j = 0; j < files.length; j++) {
File f = new File(files[j]); File f = new File(files[j]);
if (f.exists())
{
try
{

if (f.exists()) {
try {
doReplace(f, options); doReplace(f, options);
}
catch (Exception e)
{
} catch (Exception e) {
log("An error occurred processing file: '" + f.getAbsolutePath() + "': " + e.toString(), log("An error occurred processing file: '" + f.getAbsolutePath() + "': " + e.toString(),
Project.MSG_ERR); Project.MSG_ERR);
} }
}
else
{
} else {
log("The following file is missing: '" + file.getAbsolutePath() + "'", log("The following file is missing: '" + file.getAbsolutePath() + "'",
Project.MSG_ERR); Project.MSG_ERR);
} }


+ 5
- 5
src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java View File

@@ -151,17 +151,17 @@ public class Rpm extends Task {
try { try {
outputstream = new PrintStream(new BufferedOutputStream(new FileOutputStream(output))); outputstream = new PrintStream(new BufferedOutputStream(new FileOutputStream(output)));
} catch (IOException e) { } catch (IOException e) {
throw new BuildException(e,location);
throw new BuildException(e, location);
} }
} }
else { else {
outputstream = new LogOutputStream(this,Project.MSG_INFO);
outputstream = new LogOutputStream(this, Project.MSG_INFO);
} }
if (error != null) { if (error != null) {
try { try {
errorstream = new PrintStream(new BufferedOutputStream(new FileOutputStream(error))); errorstream = new PrintStream(new BufferedOutputStream(new FileOutputStream(error)));
} catch (IOException e) { } catch (IOException e) {
throw new BuildException(e,location);
throw new BuildException(e, location);
} }
} }
else { else {
@@ -207,8 +207,8 @@ public class Rpm extends Task {
} }


public void setSpecFile(String sf) { public void setSpecFile(String sf) {
if ( (sf == null) || (sf.trim().equals(""))) {
throw new BuildException("You must specify a spec file",location);
if ((sf == null) || (sf.trim().equals(""))) {
throw new BuildException("You must specify a spec file", location);
} }
this.specFile = sf; this.specFile = sf;
} }


+ 6
- 6
src/main/org/apache/tools/ant/taskdefs/optional/Script.java View File

@@ -78,13 +78,13 @@ public class Script extends Task {
* Add a list of named objects to the list to be exported to the script * Add a list of named objects to the list to be exported to the script
*/ */
private void addBeans(Hashtable dictionary) { private void addBeans(Hashtable dictionary) {
for (Enumeration e=dictionary.keys(); e.hasMoreElements(); ) {
String key = (String)e.nextElement();
for (Enumeration e = dictionary.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();


boolean isValid = key.length()>0 &&
boolean isValid = key.length() > 0 &&
Character.isJavaIdentifierStart(key.charAt(0)); Character.isJavaIdentifierStart(key.charAt(0));


for (int i=1; isValid && i<key.length(); i++) {
for (int i = 1; isValid && i < key.length(); i++) {
isValid = Character.isJavaIdentifierPart(key.charAt(i)); isValid = Character.isJavaIdentifierPart(key.charAt(i));
} }


@@ -113,7 +113,7 @@ public class Script extends Task {
BSFManager manager = new BSFManager (); BSFManager manager = new BSFManager ();


for (Enumeration e = beans.keys() ; e.hasMoreElements() ;) { for (Enumeration e = beans.keys() ; e.hasMoreElements() ;) {
String key = (String)e.nextElement();
String key = (String) e.nextElement();
Object value = beans.get(key); Object value = beans.get(key);
manager.declareBean(key, value, value.getClass()); manager.declareBean(key, value, value.getClass());
} }
@@ -154,7 +154,7 @@ public class Script extends Task {
throw new BuildException("file " + fileName + " not found."); throw new BuildException("file " + fileName + " not found.");
} }


int count = (int)file.length();
int count = (int) file.length();
byte data[] = new byte[count]; byte data[] = new byte[count];


try { try {


+ 32
- 27
src/main/org/apache/tools/ant/taskdefs/optional/StyleBook.java View File

@@ -57,65 +57,70 @@ import java.io.File;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;





import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.taskdefs.Java;


/** /**
* Basic task for apache stylebook. * Basic task for apache stylebook.
* *
* @author <a href="mailto:donaldp@apache.org">Peter Donald</a> * @author <a href="mailto:donaldp@apache.org">Peter Donald</a>
* @author <a href="mailto:marcus.boerger@post.rwth-aachen.de">Marcus B&ouml;rger</a>
* @author <a href="mailto:marcus.boerger@post.rwth-aachen.de">Marcus
* B&ouml;rger</a>
*/ */
public class StyleBook 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() { 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; m_book = book;
} }


public void setSkinDirectory( final File skinDirectory ) {

public void setSkinDirectory(final File skinDirectory) {
m_skinDirectory = skinDirectory; m_skinDirectory = skinDirectory;
} }


public void setTargetDirectory( final File targetDirectory ) {

public void setTargetDirectory(final File targetDirectory) {
m_targetDirectory = targetDirectory; m_targetDirectory = targetDirectory;
} }


public void setLoaderConfig( final String loaderConfig ) {

public void setLoaderConfig(final String loaderConfig) {
m_loaderConfig = loaderConfig; m_loaderConfig = loaderConfig;
} }



public void execute() 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(); super.execute();


+ 50
- 41
src/main/org/apache/tools/ant/taskdefs/optional/Test.java View File

@@ -52,70 +52,79 @@
* <http://www.apache.org/>. * <http://www.apache.org/>.
*/ */
package org.apache.tools.ant.taskdefs.optional; 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 <a href="mailto:donaldp@apache.org">Peter Donald</a>
*/
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 <a href="mailto:donaldp@apache.org">Peter Donald</a>
*/
public class Test extends Java {

protected Vector m_tests = new Vector();



protected final static class TestletEntry { protected final static class TestletEntry {


protected String m_testname = ""; protected String m_testname = "";


public void addText( final String testname ) {

public void addText(final String testname) {
m_testname += testname; m_testname += testname;
} }



public String toString() { public String toString() {
return m_testname; return m_testname;
} }
} }



public Test() { public Test() {
setClassname( "org.apache.testlet.engine.TextTestEngine" );
setClassname("org.apache.testlet.engine.TextTestEngine");
} }



public TestletEntry createTestlet() { public TestletEntry createTestlet() {
final TestletEntry entry = new TestletEntry(); final TestletEntry entry = new TestletEntry();
m_tests.addElement( entry );

m_tests.addElement(entry);
return 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(); 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(); super.execute();
}
}
}
}

+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/XslpLiaison.java View File

@@ -89,13 +89,13 @@ public class XslpLiaison implements XSLTLiaison {
XSLReader xslReader = new XSLReader(); XSLReader xslReader = new XSLReader();
// a file:/// + getAbsolutePath() does not work here // a file:/// + getAbsolutePath() does not work here
// it is really the pathname // it is really the pathname
xslSheet = xslReader.read( fileName.getAbsolutePath() );
xslSheet = xslReader.read(fileName.getAbsolutePath());
} }
public void transform(File infile, File outfile) throws Exception { public void transform(File infile, File outfile) throws Exception {
FileOutputStream fos = new FileOutputStream(outfile); FileOutputStream fos = new FileOutputStream(outfile);
// XSLP does not support encoding...we're in hot water. // 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); processor.process(infile.getAbsolutePath(), xslSheet, out);
} }




+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java View File

@@ -143,7 +143,7 @@ public class CCCheckin extends ClearCase {
checkOptions(commandLine); checkOptions(commandLine);


result = run(commandLine); result = run(commandLine);
if ( result != 0 ) {
if (result != 0) {
String msg = "Failed executing: " + commandLine.toString(); String msg = "Failed executing: " + commandLine.toString();
throw new BuildException(msg, location); throw new BuildException(msg, location);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java View File

@@ -155,7 +155,7 @@ public class CCCheckout extends ClearCase {
checkOptions(commandLine); checkOptions(commandLine);


result = run(commandLine); result = run(commandLine);
if ( result != 0 ) {
if (result != 0) {
String msg = "Failed executing: " + commandLine.toString(); String msg = "Failed executing: " + commandLine.toString();
throw new BuildException(msg, location); throw new BuildException(msg, location);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java View File

@@ -113,7 +113,7 @@ public class CCUnCheckout extends ClearCase {
checkOptions(commandLine); checkOptions(commandLine);


result = run(commandLine); result = run(commandLine);
if ( result != 0 ) {
if (result != 0) {
String msg = "Failed executing: " + commandLine.toString(); String msg = "Failed executing: " + commandLine.toString();
throw new BuildException(msg, location); throw new BuildException(msg, location);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java View File

@@ -148,7 +148,7 @@ public class CCUpdate extends ClearCase {
System.out.println(commandLine.toString()); System.out.println(commandLine.toString());


result = run(commandLine); result = run(commandLine);
if ( result != 0 ) {
if (result != 0) {
String msg = "Failed executing: " + commandLine.toString(); String msg = "Failed executing: " + commandLine.toString();
throw new BuildException(msg, location); throw new BuildException(msg, location);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java View File

@@ -97,7 +97,7 @@ public abstract class ClearCase extends Task {
*/ */
protected final String getClearToolCommand() { protected final String getClearToolCommand() {
String toReturn = m_ClearToolDir; String toReturn = m_ClearToolDir;
if ( !toReturn.equals("") && !toReturn.endsWith("/") ) {
if (!toReturn.equals("") && !toReturn.endsWith("/")) {
toReturn += "/"; toReturn += "/";
} }




+ 10
- 10
src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java View File

@@ -88,8 +88,8 @@ public class AntAnalyzer extends AbstractAnalyzer {
Hashtable dependencies = new Hashtable(); Hashtable dependencies = new Hashtable();
Hashtable containers = new Hashtable(); Hashtable containers = new Hashtable();
Hashtable toAnalyze = 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); toAnalyze.put(classname, classname);
} }


@@ -97,8 +97,8 @@ public class AntAnalyzer extends AbstractAnalyzer {
int maxCount = isClosureRequired() ? MAX_LOOPS : 2; int maxCount = isClosureRequired() ? MAX_LOOPS : 2;
while (toAnalyze.size() != 0 && count++ < maxCount) { while (toAnalyze.size() != 0 && count++ < maxCount) {
Hashtable analyzedDeps = new Hashtable(); 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); dependencies.put(classname, classname);
try { try {
File container = getClassContainer(classname); File container = getClassContainer(classname);
@@ -125,7 +125,7 @@ public class AntAnalyzer extends AbstractAnalyzer {
Vector dependencyList = classFile.getClassRefs(); Vector dependencyList = classFile.getClassRefs();
Enumeration depEnum = dependencyList.elements(); Enumeration depEnum = dependencyList.elements();
while (depEnum.hasMoreElements()) { while (depEnum.hasMoreElements()) {
String dependency = (String)depEnum.nextElement();
String dependency = (String) depEnum.nextElement();
analyzedDeps.put(dependency, dependency); analyzedDeps.put(dependency, dependency);
} }
} finally { } finally {
@@ -146,7 +146,7 @@ public class AntAnalyzer extends AbstractAnalyzer {
// now recover all the dependencies collected and add to the list. // now recover all the dependencies collected and add to the list.
Enumeration depsEnum = analyzedDeps.elements(); Enumeration depsEnum = analyzedDeps.elements();
while (depsEnum.hasMoreElements()) { while (depsEnum.hasMoreElements()) {
String className = (String)depsEnum.nextElement();
String className = (String) depsEnum.nextElement();
if (!dependencies.containsKey(className)) { if (!dependencies.containsKey(className)) {
toAnalyze.put(className, className); toAnalyze.put(className, className);
} }
@@ -154,13 +154,13 @@ public class AntAnalyzer extends AbstractAnalyzer {
} }


files.removeAllElements(); 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(); 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());
} }
} }




+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java View File

@@ -114,7 +114,7 @@ public class ClassFile {
int thisClassIndex = classStream.readUnsignedShort(); int thisClassIndex = classStream.readUnsignedShort();
int superClassIndex = classStream.readUnsignedShort(); int superClassIndex = classStream.readUnsignedShort();
ClassCPInfo classInfo ClassCPInfo classInfo
= (ClassCPInfo)constantPool.getEntry(thisClassIndex);
= (ClassCPInfo) constantPool.getEntry(thisClassIndex);
className = classInfo.getClassName(); className = classInfo.getClassName();
} }


@@ -133,7 +133,7 @@ public class ClassFile {


if (entry != null if (entry != null
&& entry.getTag() == ConstantPoolEntry.CONSTANT_CLASS) { && entry.getTag() == ConstantPoolEntry.CONSTANT_CLASS) {
ClassCPInfo classEntry = (ClassCPInfo)entry;
ClassCPInfo classEntry = (ClassCPInfo) entry;


if (!classEntry.getClassName().equals(className)) { if (!classEntry.getClassName().equals(className)) {
classRefs.addElement(ClassFileUtils.convertSlashName(classEntry.getClassName())); classRefs.addElement(ClassFileUtils.convertSlashName(classEntry.getClassName()));


+ 36
- 32
src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java View File

@@ -246,12 +246,12 @@ public class Depend extends MatchingTask {
pw = new PrintWriter(new FileWriter(depFile)); pw = new PrintWriter(new FileWriter(depFile));
Enumeration e = dependencyMap.keys(); Enumeration e = dependencyMap.keys();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
String className = (String)e.nextElement();
String className = (String) e.nextElement();


pw.println(CLASSNAME_PREPEND + className); pw.println(CLASSNAME_PREPEND + className);


Vector dependencyList Vector dependencyList
= (Vector)dependencyMap.get(className);
= (Vector) dependencyMap.get(className);
int size = dependencyList.size(); int size = dependencyList.size();
for (int x = 0; x < size; x++) { for (int x = 0; x < size; x++) {
pw.println(dependencyList.elementAt(x)); pw.println(dependencyList.elementAt(x));
@@ -339,7 +339,7 @@ public class Depend extends MatchingTask {
} }
Enumeration classfileEnum = getClassFiles(destPath).elements(); Enumeration classfileEnum = getClassFiles(destPath).elements();
while (classfileEnum.hasMoreElements()) { while (classfileEnum.hasMoreElements()) {
ClassFileInfo info = (ClassFileInfo)classfileEnum.nextElement();
ClassFileInfo info = (ClassFileInfo) classfileEnum.nextElement();
log("Adding class info for " + info.className, Project.MSG_DEBUG); log("Adding class info for " + info.className, Project.MSG_DEBUG);
classFileInfoMap.put(info.className, info); classFileInfoMap.put(info.className, info);


@@ -352,7 +352,7 @@ public class Depend extends MatchingTask {
&& cacheLastModified > info.absoluteFile.lastModified()) { && cacheLastModified > info.absoluteFile.lastModified()) {
// depFile exists and is newer than the class file // depFile exists and is newer than the class file
// need to get dependency list from the map. // 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 // one of those, add this class into their affected classes list
Enumeration depEnum = dependencyList.elements(); Enumeration depEnum = dependencyList.elements();
while (depEnum.hasMoreElements()) { while (depEnum.hasMoreElements()) {
String dependentClass = (String)depEnum.nextElement();
String dependentClass = (String) depEnum.nextElement();


Hashtable affectedClasses Hashtable affectedClasses
= (Hashtable)affectedClassMap.get(dependentClass);
= (Hashtable) affectedClassMap.get(dependentClass);
if (affectedClasses == null) { if (affectedClasses == null) {
affectedClasses = new Hashtable(); affectedClasses = new Hashtable();
affectedClassMap.put(dependentClass, affectedClasses); affectedClassMap.put(dependentClass, affectedClasses);
@@ -401,13 +401,13 @@ public class Depend extends MatchingTask {
Hashtable classpathFileCache = new Hashtable(); Hashtable classpathFileCache = new Hashtable();
Object nullFileMarker = new Object(); Object nullFileMarker = new Object();
for (Enumeration e = dependencyMap.keys(); e.hasMoreElements();) { 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(); Hashtable dependencies = new Hashtable();
classpathDependencies.put(className, dependencies); classpathDependencies.put(className, dependencies);
Enumeration e2 = dependencyList.elements(); Enumeration e2 = dependencyList.elements();
while (e2.hasMoreElements()) { while (e2.hasMoreElements()) {
String dependency = (String)e2.nextElement();
String dependency = (String) e2.nextElement();
Object classpathFileObject Object classpathFileObject
= classpathFileCache.get(dependency); = classpathFileCache.get(dependency);
if (classpathFileObject == null) { if (classpathFileObject == null) {
@@ -437,7 +437,7 @@ public class Depend extends MatchingTask {
} }
if (classpathFileObject != null && classpathFileObject != nullFileMarker) { if (classpathFileObject != null && classpathFileObject != nullFileMarker) {
// we need to add this jar to the list for this class. // we need to add this jar to the list for this class.
File jarFile = (File)classpathFileObject;
File jarFile = (File) classpathFileObject;
dependencies.put(jarFile, jarFile); dependencies.put(jarFile, jarFile);
} }
} }
@@ -459,10 +459,10 @@ public class Depend extends MatchingTask {
private int deleteAllAffectedFiles() { private int deleteAllAffectedFiles() {
int count = 0; int count = 0;
for (Enumeration e = outOfDateClasses.elements(); e.hasMoreElements();) { for (Enumeration e = outOfDateClasses.elements(); e.hasMoreElements();) {
String className = (String)e.nextElement();
String className = (String) e.nextElement();
count += deleteAffectedFiles(className); count += deleteAffectedFiles(className);
ClassFileInfo classInfo ClassFileInfo classInfo
= (ClassFileInfo)classFileInfoMap.get(className);
= (ClassFileInfo) classFileInfoMap.get(className);
if (classInfo != null && classInfo.absoluteFile.exists()) { if (classInfo != null && classInfo.absoluteFile.exists()) {
classInfo.absoluteFile.delete(); classInfo.absoluteFile.delete();
count++; count++;
@@ -481,14 +481,14 @@ public class Depend extends MatchingTask {
private int deleteAffectedFiles(String className) { private int deleteAffectedFiles(String className) {
int count = 0; int count = 0;


Hashtable affectedClasses = (Hashtable)affectedClassMap.get(className);
Hashtable affectedClasses = (Hashtable) affectedClassMap.get(className);
if (affectedClasses == null) { if (affectedClasses == null) {
return count; return count;
} }
for (Enumeration e = affectedClasses.keys(); e.hasMoreElements();) { for (Enumeration e = affectedClasses.keys(); e.hasMoreElements();) {
String affectedClass = (String)e.nextElement();
String affectedClass = (String) e.nextElement();
ClassFileInfo affectedClassInfo ClassFileInfo affectedClassInfo
= (ClassFileInfo)affectedClasses.get(affectedClass);
= (ClassFileInfo) affectedClasses.get(affectedClass);
if (!affectedClassInfo.absoluteFile.exists()) { if (!affectedClassInfo.absoluteFile.exists()) {
continue; continue;
@@ -526,7 +526,7 @@ public class Depend extends MatchingTask {
log("Top level class = " + topLevelClassName, log("Top level class = " + topLevelClassName,
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
ClassFileInfo topLevelClassInfo ClassFileInfo topLevelClassInfo
= (ClassFileInfo)classFileInfoMap.get(topLevelClassName);
= (ClassFileInfo) classFileInfoMap.get(topLevelClassName);
if (topLevelClassInfo != null && if (topLevelClassInfo != null &&
topLevelClassInfo.absoluteFile.exists()) { topLevelClassInfo.absoluteFile.exists()) {
log("Deleting file " log("Deleting file "
@@ -553,15 +553,15 @@ public class Depend extends MatchingTask {


Enumeration classEnum = affectedClassMap.keys(); Enumeration classEnum = affectedClassMap.keys();
while (classEnum.hasMoreElements()) { while (classEnum.hasMoreElements()) {
String className = (String)classEnum.nextElement();
String className = (String) classEnum.nextElement();
log(" Class " + className + " affects:", Project.MSG_DEBUG); log(" Class " + className + " affects:", Project.MSG_DEBUG);
Hashtable affectedClasses Hashtable affectedClasses
= (Hashtable)affectedClassMap.get(className);
= (Hashtable) affectedClassMap.get(className);
Enumeration affectedClassEnum = affectedClasses.keys(); Enumeration affectedClassEnum = affectedClasses.keys();
while (affectedClassEnum.hasMoreElements()) { while (affectedClassEnum.hasMoreElements()) {
String affectedClass = (String)affectedClassEnum.nextElement();
String affectedClass = (String) affectedClassEnum.nextElement();
ClassFileInfo info ClassFileInfo info
= (ClassFileInfo)affectedClasses.get(affectedClass);
= (ClassFileInfo) affectedClasses.get(affectedClass);
log(" " + affectedClass + " in " log(" " + affectedClass + " in "
+ info.absoluteFile.getPath(), Project.MSG_DEBUG); + info.absoluteFile.getPath(), Project.MSG_DEBUG);
} }
@@ -572,14 +572,14 @@ public class Depend extends MatchingTask {
Enumeration classpathEnum = classpathDependencies.keys(); Enumeration classpathEnum = classpathDependencies.keys();
while (classpathEnum.hasMoreElements()) { while (classpathEnum.hasMoreElements()) {
String className = (String)classpathEnum.nextElement();
String className = (String) classpathEnum.nextElement();
log(" Class " + className + " depends on:", Project.MSG_DEBUG); log(" Class " + className + " depends on:", Project.MSG_DEBUG);
Hashtable dependencies Hashtable dependencies
= (Hashtable)classpathDependencies.get(className);
= (Hashtable) classpathDependencies.get(className);


Enumeration classpathFileEnum = dependencies.elements(); Enumeration classpathFileEnum = dependencies.elements();
while (classpathFileEnum.hasMoreElements()) { while (classpathFileEnum.hasMoreElements()) {
File classpathFile = (File)classpathFileEnum.nextElement();
File classpathFile = (File) classpathFileEnum.nextElement();
log(" " + classpathFile.getPath(), Project.MSG_DEBUG); log(" " + classpathFile.getPath(), Project.MSG_DEBUG);
} }
} }
@@ -589,7 +589,7 @@ public class Depend extends MatchingTask {
private void determineOutOfDateClasses() { private void determineOutOfDateClasses() {
outOfDateClasses = new Hashtable(); outOfDateClasses = new Hashtable();
for (int i = 0; i < srcPathList.length; i++) { 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()) { if (srcDir.exists()) {
DirectoryScanner ds = this.getDirectoryScanner(srcDir); DirectoryScanner ds = this.getDirectoryScanner(srcDir);
String[] files = ds.getIncludedFiles(); String[] files = ds.getIncludedFiles();
@@ -604,18 +604,20 @@ public class Depend extends MatchingTask {


Enumeration classpathDepsEnum = classpathDependencies.keys(); Enumeration classpathDepsEnum = classpathDependencies.keys();
while (classpathDepsEnum.hasMoreElements()) { while (classpathDepsEnum.hasMoreElements()) {
String className = (String)classpathDepsEnum.nextElement();
String className = (String) classpathDepsEnum.nextElement();
if (outOfDateClasses.containsKey(className)) { if (outOfDateClasses.containsKey(className)) {
continue; 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 // if we have no info about the class - it may have been deleted already and we
// are using cached info. // are using cached info.
if (info != null) { 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() if (classpathFile.lastModified()
> info.absoluteFile.lastModified()) { > info.absoluteFile.lastModified()) {
log("Class " + className + log("Class " + className +
@@ -692,10 +694,12 @@ public class Depend extends MatchingTask {
File srcFile = new File(srcDir, files[i]); File srcFile = new File(srcDir, files[i]);
if (files[i].endsWith(".java")) { if (files[i].endsWith(".java")) {
String filePath = srcFile.getPath(); 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); className = ClassFileUtils.convertSlashName(className);
ClassFileInfo info = (ClassFileInfo)classFileInfoMap.get(className);
ClassFileInfo info
= (ClassFileInfo) classFileInfoMap.get(className);
if (info == null) { if (info == null) {
// there was no class file. add this class to the list // there was no class file. add this class to the list
outOfDateClasses.put(className, className); outOfDateClasses.put(className, className);


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java View File

@@ -165,7 +165,7 @@ public class DirectoryIterator implements ClassFileIterator {
try { try {
while (nextElement == null) { while (nextElement == null) {
if (currentEnum.hasMoreElements()) { if (currentEnum.hasMoreElements()) {
File element = (File)currentEnum.nextElement();
File element = (File) currentEnum.nextElement();


if (element.isDirectory()) { if (element.isDirectory()) {


@@ -198,7 +198,7 @@ public class DirectoryIterator implements ClassFileIterator {
if (enumStack.empty()) { if (enumStack.empty()) {
break; break;
} else { } else {
currentEnum = (Enumeration)enumStack.pop();
currentEnum = (Enumeration) enumStack.pop();
} }
} }
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java View File

@@ -112,7 +112,7 @@ public class ClassCPInfo extends ConstantPoolEntry {
* class. * class.
*/ */
public void resolve(ConstantPool constantPool) { public void resolve(ConstantPool constantPool) {
className = ((Utf8CPInfo)constantPool.getEntry(index)).getValue();
className = ((Utf8CPInfo) constantPool.getEntry(index)).getValue();


super.resolve(constantPool); super.resolve(constantPool);
} }


+ 13
- 12
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java View File

@@ -100,7 +100,7 @@ public class ConstantPool {
public void read(DataInputStream classStream) throws IOException { public void read(DataInputStream classStream) throws IOException {
int numEntries = classStream.readUnsignedShort(); int numEntries = classStream.readUnsignedShort();


for (int i = 1; i < numEntries; ) {
for (int i = 1; i < numEntries;) {
ConstantPoolEntry nextEntry ConstantPoolEntry nextEntry
= ConstantPoolEntry.readEntry(classStream); = ConstantPoolEntry.readEntry(classStream);


@@ -139,7 +139,7 @@ public class ConstantPool {
} }


if (entry instanceof Utf8CPInfo) { if (entry instanceof Utf8CPInfo) {
Utf8CPInfo utf8Info = (Utf8CPInfo)entry;
Utf8CPInfo utf8Info = (Utf8CPInfo) entry;


utf8Indexes.put(utf8Info.getValue(), new Integer(index)); utf8Indexes.put(utf8Info.getValue(), new Integer(index));
} }
@@ -153,8 +153,8 @@ public class ConstantPool {
* into the actual data for that entry. * into the actual data for that entry.
*/ */
public void resolve() { 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()) { if (poolInfo != null && !poolInfo.isResolved()) {
poolInfo.resolve(this); poolInfo.resolve(this);
@@ -170,7 +170,7 @@ public class ConstantPool {
* @return the constant pool entry at that index. * @return the constant pool entry at that index.
*/ */
public ConstantPoolEntry getEntry(int 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) { public int getUTF8Entry(String value) {
int index = -1; int index = -1;
Integer indexInteger = (Integer)utf8Indexes.get(value);
Integer indexInteger = (Integer) utf8Indexes.get(value);


if (indexInteger != null) { if (indexInteger != null) {
index = indexInteger.intValue(); index = indexInteger.intValue();
@@ -206,7 +206,7 @@ public class ConstantPool {
Object element = entries.elementAt(i); Object element = entries.elementAt(i);


if (element instanceof ClassCPInfo) { if (element instanceof ClassCPInfo) {
ClassCPInfo classinfo = (ClassCPInfo)element;
ClassCPInfo classinfo = (ClassCPInfo) element;


if (classinfo.getClassName().equals(className)) { if (classinfo.getClassName().equals(className)) {
index = i; index = i;
@@ -232,7 +232,7 @@ public class ConstantPool {
Object element = entries.elementAt(i); Object element = entries.elementAt(i);


if (element instanceof ConstantCPInfo) { if (element instanceof ConstantCPInfo) {
ConstantCPInfo constantEntry = (ConstantCPInfo)element;
ConstantCPInfo constantEntry = (ConstantCPInfo) element;


if (constantEntry.getValue().equals(constantValue)) { if (constantEntry.getValue().equals(constantValue)) {
index = i; index = i;
@@ -262,7 +262,7 @@ public class ConstantPool {
Object element = entries.elementAt(i); Object element = entries.elementAt(i);


if (element instanceof MethodRefCPInfo) { if (element instanceof MethodRefCPInfo) {
MethodRefCPInfo methodRefEntry = (MethodRefCPInfo)element;
MethodRefCPInfo methodRefEntry = (MethodRefCPInfo) element;


if (methodRefEntry.getMethodClassName().equals(methodClassName) if (methodRefEntry.getMethodClassName().equals(methodClassName)
&& methodRefEntry.getMethodName().equals(methodName) && methodRefEntry.getMethodName().equals(methodName)
@@ -297,7 +297,7 @@ public class ConstantPool {


if (element instanceof InterfaceMethodRefCPInfo) { if (element instanceof InterfaceMethodRefCPInfo) {
InterfaceMethodRefCPInfo interfaceMethodRefEntry InterfaceMethodRefCPInfo interfaceMethodRefEntry
= (InterfaceMethodRefCPInfo)element;
= (InterfaceMethodRefCPInfo) element;


if (interfaceMethodRefEntry.getInterfaceMethodClassName().equals(interfaceMethodClassName) if (interfaceMethodRefEntry.getInterfaceMethodClassName().equals(interfaceMethodClassName)
&& interfaceMethodRefEntry.getInterfaceMethodName().equals(interfaceMethodName) && interfaceMethodRefEntry.getInterfaceMethodName().equals(interfaceMethodName)
@@ -329,7 +329,7 @@ public class ConstantPool {
Object element = entries.elementAt(i); Object element = entries.elementAt(i);


if (element instanceof FieldRefCPInfo) { if (element instanceof FieldRefCPInfo) {
FieldRefCPInfo fieldRefEntry = (FieldRefCPInfo)element;
FieldRefCPInfo fieldRefEntry = (FieldRefCPInfo) element;


if (fieldRefEntry.getFieldClassName().equals(fieldClassName) if (fieldRefEntry.getFieldClassName().equals(fieldClassName)
&& fieldRefEntry.getFieldName().equals(fieldName) && fieldRefEntry.getFieldName().equals(fieldName)
@@ -358,7 +358,8 @@ public class ConstantPool {
Object element = entries.elementAt(i); Object element = entries.elementAt(i);


if (element instanceof NameAndTypeCPInfo) { if (element instanceof NameAndTypeCPInfo) {
NameAndTypeCPInfo nameAndTypeEntry = (NameAndTypeCPInfo)element;
NameAndTypeCPInfo nameAndTypeEntry
= (NameAndTypeCPInfo) element;


if (nameAndTypeEntry.getName().equals(name) if (nameAndTypeEntry.getName().equals(name)
&& nameAndTypeEntry.getType().equals(type)) { && nameAndTypeEntry.getType().equals(type)) {


+ 3
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java View File

@@ -99,14 +99,15 @@ public class FieldRefCPInfo extends ConstantPoolEntry {
* and against which this entry is to be resolved. * and against which this entry is to be resolved.
*/ */
public void resolve(ConstantPool constantPool) { public void resolve(ConstantPool constantPool) {
ClassCPInfo fieldClass = (ClassCPInfo)constantPool.getEntry(classIndex);
ClassCPInfo fieldClass
= (ClassCPInfo) constantPool.getEntry(classIndex);


fieldClass.resolve(constantPool); fieldClass.resolve(constantPool);


fieldClassName = fieldClass.getClassName(); fieldClassName = fieldClass.getClassName();


NameAndTypeCPInfo nt NameAndTypeCPInfo nt
= (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex);
= (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex);


nt.resolve(constantPool); nt.resolve(constantPool);




+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java View File

@@ -106,14 +106,14 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry {
*/ */
public void resolve(ConstantPool constantPool) { public void resolve(ConstantPool constantPool) {
ClassCPInfo interfaceMethodClass ClassCPInfo interfaceMethodClass
= (ClassCPInfo)constantPool.getEntry(classIndex);
= (ClassCPInfo) constantPool.getEntry(classIndex);


interfaceMethodClass.resolve(constantPool); interfaceMethodClass.resolve(constantPool);


interfaceMethodClassName = interfaceMethodClass.getClassName(); interfaceMethodClassName = interfaceMethodClass.getClassName();


NameAndTypeCPInfo nt NameAndTypeCPInfo nt
= (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex);
= (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex);


nt.resolve(constantPool); nt.resolve(constantPool);




+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java View File

@@ -122,14 +122,14 @@ public class MethodRefCPInfo extends ConstantPoolEntry {
*/ */
public void resolve(ConstantPool constantPool) { public void resolve(ConstantPool constantPool) {
ClassCPInfo methodClass ClassCPInfo methodClass
= (ClassCPInfo)constantPool.getEntry(classIndex);
= (ClassCPInfo) constantPool.getEntry(classIndex);


methodClass.resolve(constantPool); methodClass.resolve(constantPool);


methodClassName = methodClass.getClassName(); methodClassName = methodClass.getClassName();


NameAndTypeCPInfo nt NameAndTypeCPInfo nt
= (NameAndTypeCPInfo)constantPool.getEntry(nameAndTypeIndex);
= (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex);


nt.resolve(constantPool); nt.resolve(constantPool);




+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java View File

@@ -107,8 +107,8 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry {
* and against which this entry is to be resolved. * and against which this entry is to be resolved.
*/ */
public void resolve(ConstantPool constantPool) { 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); super.resolve(constantPool);
} }


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java View File

@@ -101,7 +101,7 @@ public class StringCPInfo extends ConstantCPInfo {
* and against which this entry is to be resolved. * and against which this entry is to be resolved.
*/ */
public void resolve(ConstantPool constantPool) { public void resolve(ConstantPool constantPool) {
setValue(((Utf8CPInfo)constantPool.getEntry(index)).getValue());
setValue(((Utf8CPInfo) constantPool.getEntry(index)).getValue());
super.resolve(constantPool); super.resolve(constantPool);
} }




+ 13
- 13
src/main/org/apache/tools/ant/taskdefs/optional/dotnet/CSharp.java View File

@@ -241,7 +241,7 @@ public class CSharp
/** /**
* file alignment; 0 means let the compiler decide * 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 * Fix C# reference inclusion. C# is really dumb in how it handles
@@ -1033,7 +1033,7 @@ public class CSharp
includeDefaultReferences = true; includeDefaultReferences = true;
extraOptions = null; extraOptions = null;
fullpaths = true; fullpaths = true;
fileAlign=0;
fileAlign = 0;
} }




@@ -1053,7 +1053,7 @@ public class CSharp
*/ */
protected void validate() protected void validate()
throws BuildException { throws BuildException {
if(outputFile!=null && outputFile.isDirectory()) {
if (outputFile != null && outputFile.isDirectory()) {
throw new BuildException("destFile cannot be a directory"); throw new BuildException("destFile cannot be a directory");
} }
} }
@@ -1068,7 +1068,7 @@ public class CSharp
if (srcDir == null) { if (srcDir == null) {
srcDir = project.resolveFile("."); srcDir = project.resolveFile(".");
} }
log("CSC working from source directory "+srcDir,Project.MSG_VERBOSE);
log("CSC working from source directory " + srcDir, Project.MSG_VERBOSE);
validate(); validate();


NetCommand command = new NetCommand(this, "CSC", csc_exe_name); NetCommand command = new NetCommand(this, "CSC", csc_exe_name);
@@ -1100,36 +1100,36 @@ public class CSharp
command.addArgument(getFileAlignParameter()); command.addArgument(getFileAlignParameter());


long outputTimestamp; long outputTimestamp;
if(outputFile!=null && outputFile.exists()) {
if (outputFile != null && outputFile.exists()) {
outputTimestamp = outputFile.lastModified(); outputTimestamp = outputFile.lastModified();
} else { } else {
outputTimestamp = 0; outputTimestamp = 0;
} }
int filesOutOfDate=0;
int filesOutOfDate = 0;
//get dependencies list. //get dependencies list.
DirectoryScanner scanner = super.getDirectoryScanner(srcDir); DirectoryScanner scanner = super.getDirectoryScanner(srcDir);
String[] dependencies = scanner.getIncludedFiles(); String[] dependencies = scanner.getIncludedFiles();
log("compiling " + dependencies.length + " file" + ((dependencies.length == 1) ? "" : "s")); log("compiling " + dependencies.length + " file" + ((dependencies.length == 1) ? "" : "s"));
String baseDir = scanner.getBasedir().toString(); String baseDir = scanner.getBasedir().toString();
File base=scanner.getBasedir();
File base = scanner.getBasedir();
//add to the command //add to the command
for (int i = 0; i < dependencies.length; i++) { 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()); command.addArgument(targetFile.toString());
if(targetFile.lastModified()>outputTimestamp) {
if (targetFile.lastModified() > outputTimestamp) {
filesOutOfDate++; filesOutOfDate++;
log("Source file "+targetFile.toString()+" is out of date",
log("Source file " + targetFile.toString() + " is out of date",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} else { } else {
log("Source file "+targetFile.toString()+" is up to date",
log("Source file " + targetFile.toString() + " is up to date",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
} }
} }


//now run the command of exe + settings + files //now run the command of exe + settings + files
if(filesOutOfDate>0) {
if (filesOutOfDate > 0) {
command.runCommand(); command.runCommand();
} }
} }


+ 4
- 4
src/main/org/apache/tools/ant/taskdefs/optional/dotnet/NetCommand.java View File

@@ -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) { 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() { protected void prepareExecutor() {
// default directory to the project's base directory // default directory to the project's base directory
if(owner==null) {
if (owner == null) {
throw new RuntimeException("no owner"); throw new RuntimeException("no owner");
} }
if(owner.getProject()==null) {
if (owner.getProject() == null) {
throw new RuntimeException("Owner has no project"); throw new RuntimeException("Owner has no project");
} }
File dir = owner.getProject().getBaseDir(); File dir = owner.getProject().getBaseDir();


+ 24
- 24
src/main/org/apache/tools/ant/taskdefs/optional/dotnet/WsdlToDotnet.java View File

@@ -72,42 +72,42 @@ public class WsdlToDotnet extends Task {
/** /**
* name of output file (required) * name of output file (required)
*/ */
private File destFile=null;
private File destFile = null;
/** /**
* url to retrieve * url to retrieve
*/ */
private String url=null;
private String url = null;
/** /**
* name of source file * name of source file
*/ */
private File srcFile=null;
private File srcFile = null;
/** /**
* language; defaults to C# * language; defaults to C#
*/ */
private String language="CS";
private String language = "CS";
/** /**
* flag set to true to generate server side skeleton * flag set to true to generate server side skeleton
*/ */
private boolean server=false;
private boolean server = false;
/** /**
* namespace * namespace
*/ */
private String namespace=null;
private String namespace = null;
/** /**
* flag to control action on execution trouble * flag to control action on execution trouble
*/ */
private boolean failOnError=true;
private boolean failOnError = true;


/** /**
* any extra command options? * any extra command options?
*/ */
protected String extraOptions=null;
protected String extraOptions = null;
/** /**
* *
@@ -155,27 +155,27 @@ public class WsdlToDotnet extends Task {
*/ */
protected void validate() protected void validate()
throws BuildException { throws BuildException {
if(destFile==null) {
if (destFile == null) {
throw new BuildException("destination file must be specified"); throw new BuildException("destination file must be specified");
} }
if(destFile.isDirectory() ) {
if (destFile.isDirectory()) {
throw new BuildException( throw new BuildException(
"destination file is a directory"); "destination file is a directory");
} }
if(url!=null && srcFile!=null) {
if (url != null && srcFile != null) {
throw new BuildException( throw new BuildException(
"you can not specify both a source file and a URL"); "you can not specify both a source file and a URL");
} }
if(url==null && srcFile==null) {
if (url == null && srcFile == null) {
throw new BuildException( throw new BuildException(
"you must specify either a source file or a URL"); "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( throw new BuildException(
"source file does not exist"); "source file does not exist");
} }
if(srcFile.isDirectory() ) {
if (srcFile.isDirectory()) {
throw new BuildException( throw new BuildException(
"source file is a directory"); "source file is a directory");
} }
@@ -197,12 +197,12 @@ public class WsdlToDotnet extends Task {
command.setTraceCommandLine(true); command.setTraceCommandLine(true);
//fill in args //fill in args
command.addArgument("/nologo"); 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("/server");
} }
command.addArgument("/namespace:",namespace);
command.addArgument("/namespace:", namespace);
command.addArgument(extraOptions); command.addArgument(extraOptions);
//because these args arent added when null, we can //because these args arent added when null, we can
//set both of these and let either of them //set both of these and let either of them
@@ -210,12 +210,12 @@ public class WsdlToDotnet extends Task {
command.addArgument(url); command.addArgument(url);
//rebuild unless the dest file is newer than the source file //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(); command.runCommand();
} }
} }


+ 46
- 43
src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java View File

@@ -202,8 +202,9 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
// Get the filename of vendor specific descriptor // Get the filename of vendor specific descriptor
String fileNameWithMETA = currentText; String fileNameWithMETA = currentText;
//trim the META_INF\ off of the file name //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); File descriptorFile = new File(srcDir, fileName);
ejbFiles.put(fileNameWithMETA, descriptorFile); ejbFiles.put(fileNameWithMETA, descriptorFile);
@@ -214,7 +215,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
borlandDTD == null ? DEFAULT_BAS_DTD_LOCATION : borlandDTD); borlandDTD == null ? DEFAULT_BAS_DTD_LOCATION : borlandDTD);
for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { 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()); handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation());
} }
return handler; return handler;
@@ -226,9 +227,9 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
*/ */
protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { 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()) { 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); ejbFiles.put(META_DIR + BAS_DD, borlandDD);
} }
else { else {
@@ -252,11 +253,11 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
*/ */
private void verifyBorlandJar(File sourceJar) { private void verifyBorlandJar(File sourceJar) {
org.apache.tools.ant.taskdefs.Java javaTask = null; org.apache.tools.ant.taskdefs.Java javaTask = null;
log("verify "+sourceJar,Project.MSG_INFO);
log("verify " + sourceJar, Project.MSG_INFO);
try { try {


String args = verifyArgs; String args = verifyArgs;
args += " "+sourceJar.getPath();
args += " " + sourceJar.getPath();
javaTask = (Java) getTask().getProject().createTask("java"); javaTask = (Java) getTask().getProject().createTask("java");
javaTask.setTaskName("verify"); javaTask.setTaskName("verify");
@@ -270,12 +271,14 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
javaTask.setFork(true); javaTask.setFork(true);
} }
log("Calling "+VERIFY+" for " + sourceJar.toString(), Project.MSG_VERBOSE);
log("Calling " + VERIFY + " for " + sourceJar.toString(),
Project.MSG_VERBOSE);
javaTask.execute(); javaTask.execute();
} }
catch (Exception e) { catch (Exception e) {
//TO DO : delete the file if it is not a valid file. //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); throw new BuildException(msg, e);
} }
} }
@@ -287,13 +290,13 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
*/ */
private void generateClient(File sourceJar) { private void generateClient(File sourceJar) {
getTask().getProject().addTaskDefinition("internal_bas_generateclient", 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; 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 { try {
String args = verifyArgs; String args = verifyArgs;
args += " "+sourceJar.getPath();
args += " " + sourceJar.getPath();
gentask = (BorlandGenerateClient) getTask().getProject().createTask("internal_bas_generateclient"); gentask = (BorlandGenerateClient) getTask().getProject().createTask("internal_bas_generateclient");
gentask.setEjbjar(sourceJar); gentask.setEjbjar(sourceJar);
@@ -307,7 +310,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
} }
catch (Exception e) { catch (Exception e) {
//TO DO : delete the file if it is not a valid file. //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); throw new BuildException(msg, e);
} }
} }
@@ -318,7 +322,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
* @param ithomes : iterator on home class * @param ithomes : iterator on home class
* @param files : file list , updated by the adding generated files * @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; Execute execTask = null;


execTask = new Execute(this); execTask = new Execute(this);
@@ -329,7 +333,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
Commandline commandline = new Commandline(); Commandline commandline = new Commandline();
commandline.setExecutable(JAVA2IIOP); commandline.setExecutable(JAVA2IIOP);
//debug ? //debug ?
if ( java2iiopdebug ) {
if (java2iiopdebug) {
commandline.createArgument().setValue("-VBJdebug"); commandline.createArgument().setValue("-VBJdebug");
} // end of if () } // end of if ()
//set the classpath //set the classpath
@@ -345,23 +349,24 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
//compiling order //compiling order
commandline.createArgument().setValue("-compile"); commandline.createArgument().setValue("-compile");
//add the home class //add the home class
while ( ithomes.hasNext()) {
while (ithomes.hasNext()) {
commandline.createArgument().setValue(ithomes.next().toString()); commandline.createArgument().setValue(ithomes.next().toString());
} // end of while () } // end of while ()


try { 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()); execTask.setCommandline(commandline.getCommandline());
int result = execTask.execute(); 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()); throw new BuildException(msg, getTask().getLocation());
} }
} }
catch (java.io.IOException e) { 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. //build the home classes list.
Vector homes = new Vector(); Vector homes = new Vector();
Iterator it = files.keySet().iterator(); Iterator it = files.keySet().iterator();
while ( it.hasNext()) {
while (it.hasNext()) {
String clazz = (String) it.next(); String clazz = (String) it.next();
if ( clazz.endsWith("Home.class") ) {
if (clazz.endsWith("Home.class")) {
//remove .class extension //remove .class extension
String home = toClass(clazz); String home = toClass(clazz);
homes.add(home); homes.add(home);
log(" Home "+home,Project.MSG_VERBOSE);
log(" Home " + home, Project.MSG_VERBOSE);
} // end of if () } // end of if ()
} // end of while () } // end of while ()
buildBorlandStubs(homes.iterator(),files);
buildBorlandStubs(homes.iterator(), files);


//add the gen files to the collection //add the gen files to the collection
files.putAll(_genfiles); files.putAll(_genfiles);
super.writeJar(baseName, jarFile, files, publicId); super.writeJar(baseName, jarFile, files, publicId);


if ( verify ) {
if (verify) {
verifyBorlandJar(jarFile); verifyBorlandJar(jarFile);
} // end of if () } // end of if ()


if ( generateclient) {
if (generateclient) {
generateClient(jarFile); generateClient(jarFile);
} // end of if () } // end of if ()
} }
@@ -407,8 +412,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
*/ */
private String toClass(String filename) { private String toClass(String filename) {
//remove the .class //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; return classname;
} }


@@ -418,8 +423,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
*/ */
private String toClassFile(String filename) { private String toClassFile(String filename) {
//remove the .class //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; return classfile;
} }


@@ -439,19 +444,19 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
try { try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String javafile; 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 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)); _genfiles.put(key, new File(classfile));
} // end of if () } // end of if ()
} // end of while () } // end of while ()
reader.close(); reader.close();
} }
catch(Exception e) {
catch (Exception e) {
String msg = "Exception while parsing java2iiop output. Details: " + e.toString(); String msg = "Exception while parsing java2iiop output. Details: " + e.toString();
throw new BuildException(msg, e); throw new BuildException(msg, e);
} }
@@ -465,10 +470,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool implements Exe
{ {
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = reader.readLine(); 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 () } // end of if ()
} }
} }

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save