From f979b4444378fb3595d2f00101336b774d1134cf Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Mon, 21 May 2018 17:21:35 +0200 Subject: [PATCH 1/9] Shorten fully-qualified names (cherry-pick 5c6e9ac) --- .../tools/ant/helper/ProjectHelper2.java | 5 +- .../optional/ejb/DescriptorHandler.java | 23 ++++------ .../apache/tools/ant/types/Permissions.java | 46 ++++++++++--------- 3 files changed, 36 insertions(+), 38 deletions(-) diff --git a/src/main/org/apache/tools/ant/helper/ProjectHelper2.java b/src/main/org/apache/tools/ant/helper/ProjectHelper2.java index 34dfde30b..d2014b388 100644 --- a/src/main/org/apache/tools/ant/helper/ProjectHelper2.java +++ b/src/main/org/apache/tools/ant/helper/ProjectHelper2.java @@ -23,6 +23,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; @@ -226,7 +227,7 @@ public class ProjectHelper2 extends ProjectHelper { try { context.setBuildFile((File) null); context.setBuildFile(url); - } catch (java.net.MalformedURLException ex) { + } catch (MalformedURLException ex) { throw new BuildException(ex); } buildFileName = url.toString(); @@ -773,7 +774,7 @@ public class ProjectHelper2 extends ProjectHelper { if (MagicNames.ANT_FILE_TYPE_URL.equals(dupType)) { try { dupFile = new URL(dup); - } catch (java.net.MalformedURLException mue) { + } catch (MalformedURLException mue) { throw new BuildException("failed to parse " + dup + " as URL while looking" + " at a duplicate project" diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java index 9ae0e6707..af1594586 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java @@ -23,6 +23,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.net.MalformedURLException; import java.net.URL; import java.util.Hashtable; @@ -168,7 +169,7 @@ public class DescriptorHandler extends HandlerBase { URL urldtd = new URL(location); urlDTDs.put(publicId, urldtd); } - } catch (java.net.MalformedURLException e) { + } catch (MalformedURLException e) { //ignored } @@ -262,7 +263,6 @@ public class DescriptorHandler extends HandlerBase { inEJBRef = false; } - /** * SAX parser call-back method that is invoked when a new element is entered * into. Used to store the context (attribute name) in the currentAttribute @@ -290,7 +290,6 @@ public class DescriptorHandler extends HandlerBase { } } - /** * SAX parser call-back method that is invoked when an element is exited. * Used to blank out (set to the empty string, not nullify) the name of @@ -338,11 +337,9 @@ public class DescriptorHandler extends HandlerBase { */ public void characters(char[] ch, int start, int length) throws SAXException { - currentText += new String(ch, start, length); } - /** * Called when an endelement is seen. * This may be overridden in derived classes. @@ -357,15 +354,14 @@ public class DescriptorHandler extends HandlerBase { return; } - if (currentElement.equals(HOME_INTERFACE) - || currentElement.equals(REMOTE_INTERFACE) - || currentElement.equals(LOCAL_INTERFACE) - || currentElement.equals(LOCAL_HOME_INTERFACE) - || currentElement.equals(BEAN_CLASS) - || currentElement.equals(PK_CLASS)) { + if (HOME_INTERFACE.equals(currentElement) + || REMOTE_INTERFACE.equals(currentElement) + || LOCAL_INTERFACE.equals(currentElement) + || LOCAL_HOME_INTERFACE.equals(currentElement) + || BEAN_CLASS.equals(currentElement) + || PK_CLASS.equals(currentElement)) { // Get the filename into a String object - File classFile = null; String className = currentText.trim(); // If it's a primitive wrapper then we shouldn't try and put @@ -376,8 +372,7 @@ public class DescriptorHandler extends HandlerBase { // name, create the File object and add it to the Hashtable. className = className.replace('.', File.separatorChar); className += ".class"; - classFile = new File(srcDir, className); - ejbFiles.put(className, classFile); + ejbFiles.put(className, new File(srcDir, className)); } } diff --git a/src/main/org/apache/tools/ant/types/Permissions.java b/src/main/org/apache/tools/ant/types/Permissions.java index d0559c75d..da805afd4 100644 --- a/src/main/org/apache/tools/ant/types/Permissions.java +++ b/src/main/org/apache/tools/ant/types/Permissions.java @@ -19,10 +19,12 @@ package org.apache.tools.ant.types; import java.lang.reflect.Constructor; +import java.net.SocketPermission; import java.security.UnresolvedPermission; import java.util.HashSet; import java.util.LinkedList; import java.util.List; +import java.util.PropertyPermission; import java.util.Set; import java.util.StringTokenizer; @@ -122,27 +124,27 @@ public class Permissions { } } // Add base set of permissions - granted.add(new java.net.SocketPermission("localhost:1024-", "listen")); - granted.add(new java.util.PropertyPermission("java.version", "read")); - granted.add(new java.util.PropertyPermission("java.vendor", "read")); - granted.add(new java.util.PropertyPermission("java.vendor.url", "read")); - granted.add(new java.util.PropertyPermission("java.class.version", "read")); - granted.add(new java.util.PropertyPermission("os.name", "read")); - granted.add(new java.util.PropertyPermission("os.version", "read")); - granted.add(new java.util.PropertyPermission("os.arch", "read")); - granted.add(new java.util.PropertyPermission("file.encoding", "read")); - granted.add(new java.util.PropertyPermission("file.separator", "read")); - granted.add(new java.util.PropertyPermission("path.separator", "read")); - granted.add(new java.util.PropertyPermission("line.separator", "read")); - granted.add(new java.util.PropertyPermission("java.specification.version", "read")); - granted.add(new java.util.PropertyPermission("java.specification.vendor", "read")); - granted.add(new java.util.PropertyPermission("java.specification.name", "read")); - granted.add(new java.util.PropertyPermission("java.vm.specification.version", "read")); - granted.add(new java.util.PropertyPermission("java.vm.specification.vendor", "read")); - granted.add(new java.util.PropertyPermission("java.vm.specification.name", "read")); - granted.add(new java.util.PropertyPermission("java.vm.version", "read")); - granted.add(new java.util.PropertyPermission("java.vm.vendor", "read")); - granted.add(new java.util.PropertyPermission("java.vm.name", "read")); + granted.add(new SocketPermission("localhost:1024-", "listen")); + granted.add(new PropertyPermission("java.version", "read")); + granted.add(new PropertyPermission("java.vendor", "read")); + granted.add(new PropertyPermission("java.vendor.url", "read")); + granted.add(new PropertyPermission("java.class.version", "read")); + granted.add(new PropertyPermission("os.name", "read")); + granted.add(new PropertyPermission("os.version", "read")); + granted.add(new PropertyPermission("os.arch", "read")); + granted.add(new PropertyPermission("file.encoding", "read")); + granted.add(new PropertyPermission("file.separator", "read")); + granted.add(new PropertyPermission("path.separator", "read")); + granted.add(new PropertyPermission("line.separator", "read")); + granted.add(new PropertyPermission("java.specification.version", "read")); + granted.add(new PropertyPermission("java.specification.vendor", "read")); + granted.add(new PropertyPermission("java.specification.name", "read")); + granted.add(new PropertyPermission("java.vm.specification.version", "read")); + granted.add(new PropertyPermission("java.vm.specification.vendor", "read")); + granted.add(new PropertyPermission("java.vm.specification.name", "read")); + granted.add(new PropertyPermission("java.vm.version", "read")); + granted.add(new PropertyPermission("java.vm.vendor", "read")); + granted.add(new PropertyPermission("java.vm.name", "read")); } private java.security.Permission createPermission( @@ -187,7 +189,7 @@ public class Permissions { */ @Override public void checkExit(final int status) { - final java.security.Permission perm = new java.lang.RuntimePermission("exitVM", null); + final java.security.Permission perm = new RuntimePermission("exitVM", null); try { checkPermission(perm); } catch (final SecurityException e) { From 8190d103173fa86b0a715980bf526a26aa4f1fc1 Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Mon, 21 May 2018 21:09:15 +0200 Subject: [PATCH 2/9] Fix javadoc (cf master) --- src/main/org/apache/tools/ant/types/resources/ResourceList.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/org/apache/tools/ant/types/resources/ResourceList.java b/src/main/org/apache/tools/ant/types/resources/ResourceList.java index 79cbbb5cb..01adc532e 100644 --- a/src/main/org/apache/tools/ant/types/resources/ResourceList.java +++ b/src/main/org/apache/tools/ant/types/resources/ResourceList.java @@ -106,7 +106,7 @@ public class ResourceList extends DataType implements ResourceCollection { * this allows the resources contained inside this collection to * be considered relative to a certain base directory. * - * @param basedir the basedir + * @param baseDir the basedir * @since Ant 1.9.12 */ public final void setBasedir(File baseDir) { From 8c38eb4c618fdf496d577962a1fe2f3c91516b9a Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 17:46:29 +0200 Subject: [PATCH 3/9] Use foreach loops (cherry-pick 1c80d50) --- .../org/apache/tools/ant/AntClassLoader.java | 6 +- .../org/apache/tools/ant/Diagnostics.java | 10 +- .../apache/tools/ant/DirectoryScanner.java | 27 +- .../apache/tools/ant/IntrospectionHelper.java | 14 +- src/main/org/apache/tools/ant/Project.java | 71 +- .../org/apache/tools/ant/ProjectHelper.java | 6 +- .../org/apache/tools/ant/PropertyHelper.java | 8 +- .../tools/ant/attribute/BaseIfAttribute.java | 8 +- .../tools/ant/filters/ConcatFilter.java | 10 +- .../apache/tools/ant/filters/HeadFilter.java | 10 +- .../tools/ant/filters/LineContains.java | 10 +- .../tools/ant/filters/LineContainsRegExp.java | 14 +- .../apache/tools/ant/filters/PrefixLines.java | 6 +- .../apache/tools/ant/filters/SortFilter.java | 13 +- .../tools/ant/filters/StripLineBreaks.java | 6 +- .../tools/ant/filters/StripLineComments.java | 6 +- .../apache/tools/ant/filters/SuffixLines.java | 6 +- .../tools/ant/filters/TabsToSpaces.java | 8 +- .../apache/tools/ant/filters/TailFilter.java | 10 +- .../ant/filters/util/JavaClassHelper.java | 3 +- .../tools/ant/helper/DefaultExecutor.java | 4 +- .../helper/IgnoreDependenciesExecutor.java | 6 +- .../org/apache/tools/ant/launch/Launcher.java | 13 +- .../org/apache/tools/ant/launch/Locator.java | 9 +- .../tools/ant/taskdefs/AbstractCvsTask.java | 4 +- .../tools/ant/taskdefs/AntStructure.java | 4 +- .../apache/tools/ant/taskdefs/Checksum.java | 6 +- .../tools/ant/taskdefs/Classloader.java | 5 +- .../org/apache/tools/ant/taskdefs/Copy.java | 44 +- .../apache/tools/ant/taskdefs/CopyPath.java | 6 +- .../apache/tools/ant/taskdefs/Copydir.java | 3 +- .../org/apache/tools/ant/taskdefs/Delete.java | 16 +- .../apache/tools/ant/taskdefs/Deltree.java | 4 +- .../apache/tools/ant/taskdefs/ExecTask.java | 17 +- .../apache/tools/ant/taskdefs/Execute.java | 3 +- .../tools/ant/taskdefs/ExecuteJava.java | 5 +- .../apache/tools/ant/taskdefs/ExecuteOn.java | 21 +- .../org/apache/tools/ant/taskdefs/Expand.java | 19 +- .../apache/tools/ant/taskdefs/FixCRLF.java | 5 +- .../org/apache/tools/ant/taskdefs/Jar.java | 17 +- .../org/apache/tools/ant/taskdefs/Javac.java | 13 +- .../apache/tools/ant/taskdefs/Javadoc.java | 86 +-- .../org/apache/tools/ant/taskdefs/Jikes.java | 4 +- .../apache/tools/ant/taskdefs/MacroDef.java | 3 +- .../org/apache/tools/ant/taskdefs/Move.java | 12 +- .../apache/tools/ant/taskdefs/Parallel.java | 6 +- .../apache/tools/ant/taskdefs/Recorder.java | 21 +- .../apache/tools/ant/taskdefs/Replace.java | 6 +- .../org/apache/tools/ant/taskdefs/SubAnt.java | 4 +- .../org/apache/tools/ant/taskdefs/Sync.java | 13 +- .../org/apache/tools/ant/taskdefs/Touch.java | 4 +- .../org/apache/tools/ant/taskdefs/Untar.java | 19 +- .../tools/ant/taskdefs/XSLTProcess.java | 6 +- .../tools/ant/taskdefs/compilers/Javac12.java | 15 +- .../ant/taskdefs/condition/AntVersion.java | 15 +- .../ant/taskdefs/condition/HasMethod.java | 12 +- .../tools/ant/taskdefs/cvslib/CvsTagDiff.java | 4 +- .../tools/ant/taskdefs/email/MimeMailer.java | 46 +- .../taskdefs/launcher/VmsCommandLauncher.java | 8 +- .../ant/taskdefs/optional/Native2Ascii.java | 6 +- .../ant/taskdefs/optional/TraXLiaison.java | 30 +- .../taskdefs/optional/XMLValidateTask.java | 67 +- .../optional/ejb/IPlanetDeploymentTool.java | 8 +- .../taskdefs/optional/ejb/IPlanetEjbc.java | 14 +- .../optional/extension/ExtensionUtil.java | 5 +- .../optional/extension/LibraryDisplayer.java | 18 +- .../ant/taskdefs/optional/i18n/Translate.java | 15 +- .../ant/taskdefs/optional/image/Image.java | 3 +- .../ant/taskdefs/optional/jlink/jlink.java | 5 +- .../tools/ant/taskdefs/optional/jsp/JspC.java | 4 +- .../taskdefs/optional/junit/BatchTest.java | 4 +- .../optional/junit/FailureRecorder.java | 6 +- .../junit/JUnit4TestMethodAdapter.java | 13 +- .../taskdefs/optional/junit/JUnitTask.java | 34 +- .../optional/junit/JUnitTestRunner.java | 98 ++- .../optional/junit/XMLResultAggregator.java | 10 +- .../native2ascii/KaffeNative2Ascii.java | 6 +- .../tools/ant/taskdefs/optional/net/FTP.java | 78 ++- .../optional/net/FTPTaskMirrorImpl.java | 77 +-- .../taskdefs/optional/sound/SoundTask.java | 7 +- .../ant/taskdefs/optional/ssh/SSHSession.java | 14 +- .../ant/taskdefs/rmic/DefaultRmicAdapter.java | 15 +- .../tools/ant/taskdefs/rmic/KaffeRmic.java | 17 +- .../tools/ant/types/AbstractFileSet.java | 8 +- .../apache/tools/ant/types/Commandline.java | 12 +- .../tools/ant/types/CommandlineJava.java | 4 +- .../apache/tools/ant/types/FilterChain.java | 4 +- .../org/apache/tools/ant/types/FilterSet.java | 5 +- src/main/org/apache/tools/ant/types/Path.java | 40 +- .../apache/tools/ant/types/PatternSet.java | 16 +- .../apache/tools/ant/types/Quantifier.java | 4 +- .../tools/ant/types/RedirectorElement.java | 17 +- .../apache/tools/ant/types/XMLCatalog.java | 7 +- .../types/optional/depend/ClassfileSet.java | 7 +- .../ant/types/resources/BZip2Resource.java | 8 +- .../tools/ant/types/resources/Files.java | 8 +- .../selectors/ContainsRegexpSelector.java | 13 +- .../ant/types/selectors/ContainsSelector.java | 10 +- .../ant/types/selectors/DateSelector.java | 20 +- .../ant/types/selectors/DepthSelector.java | 12 +- .../ant/types/selectors/FilenameSelector.java | 12 +- .../ant/types/selectors/SelectorUtils.java | 4 +- .../ant/types/selectors/SizeSelector.java | 12 +- .../ant/types/selectors/TokenizedPath.java | 14 +- .../ant/types/selectors/TypeSelector.java | 6 +- .../modifiedselector/DigestAlgorithm.java | 6 +- .../tools/ant/util/DOMElementWriter.java | 4 +- .../ant/util/LayoutPreservingProperties.java | 3 +- .../apache/tools/ant/util/ResourceUtils.java | 12 +- .../tools/ant/util/SplitClassLoader.java | 6 +- .../tools/ant/util/StringTokenizer.java | 4 +- .../tools/ant/util/WeakishReference.java | 4 +- .../ant/util/depend/AbstractAnalyzer.java | 4 +- .../org/apache/tools/mail/MailMessage.java | 604 +++++++++--------- src/main/org/apache/tools/tar/TarUtils.java | 3 +- .../tools/zip/Simple8BitZipEncoding.java | 4 +- .../tools/ant/IntrospectionHelperTest.java | 22 +- .../apache/tools/ant/UnknownElementTest.java | 6 +- .../apache/tools/ant/taskdefs/AntTest.java | 12 +- .../apache/tools/ant/taskdefs/FailTest.java | 14 +- .../taskdefs/optional/depend/DependTest.java | 9 +- .../ant/taskdefs/optional/ssh/ScpTest.java | 10 +- .../optional/depend/ClassFileSetTest.java | 20 +- 123 files changed, 1047 insertions(+), 1257 deletions(-) diff --git a/src/main/org/apache/tools/ant/AntClassLoader.java b/src/main/org/apache/tools/ant/AntClassLoader.java index 9f22011e3..1395f3223 100644 --- a/src/main/org/apache/tools/ant/AntClassLoader.java +++ b/src/main/org/apache/tools/ant/AntClassLoader.java @@ -356,11 +356,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo public void setClassPath(final Path classpath) { pathComponents.removeAllElements(); if (classpath != null) { - final Path actualClasspath = classpath.concatSystemClasspath("ignore"); - final String[] pathElements = actualClasspath.list(); - for (int i = 0; i < pathElements.length; ++i) { + for (String pathElement : classpath.concatSystemClasspath("ignore").list()) { try { - addPathElement(pathElements[i]); + addPathElement(pathElement); } catch (final BuildException e) { // ignore path elements which are invalid // relative to the project diff --git a/src/main/org/apache/tools/ant/Diagnostics.java b/src/main/org/apache/tools/ant/Diagnostics.java index 6007e2af3..424a0d2d1 100644 --- a/src/main/org/apache/tools/ant/Diagnostics.java +++ b/src/main/org/apache/tools/ant/Diagnostics.java @@ -422,8 +422,7 @@ public final class Diagnostics { */ private static void doReportAntHomeLibraries(PrintStream out) { out.println(MagicNames.ANT_HOME + ": " + System.getProperty(MagicNames.ANT_HOME)); - File[] libs = listLibraries(); - printLibraries(libs, out); + printLibraries(listLibraries(), out); } /** @@ -435,8 +434,7 @@ public final class Diagnostics { String home = System.getProperty(Launcher.USER_HOMEDIR); out.println("user.home: " + home); File libDir = new File(home, Launcher.USER_LIBDIR); - File[] libs = listJarFiles(libDir); - printLibraries(libs, out); + printLibraries(listJarFiles(libDir), out); } /** @@ -449,8 +447,8 @@ public final class Diagnostics { out.println("No such directory."); return; } - for (int i = 0; i < libs.length; i++) { - out.println(libs[i].getName() + " (" + libs[i].length() + " bytes)"); + for (File lib : libs) { + out.println(lib.getName() + " (" + lib.length() + " bytes)"); } } diff --git a/src/main/org/apache/tools/ant/DirectoryScanner.java b/src/main/org/apache/tools/ant/DirectoryScanner.java index b739ff8ac..a0e7837e4 100644 --- a/src/main/org/apache/tools/ant/DirectoryScanner.java +++ b/src/main/org/apache/tools/ant/DirectoryScanner.java @@ -1215,7 +1215,7 @@ public class DirectoryScanner } private void scandir(final File dir, final TokenizedPath path, final boolean fast, - String[] newfiles, final LinkedList directoryNamesFollowed) { + String[] newFiles, final LinkedList directoryNamesFollowed) { String vpath = path.toString(); if (vpath.length() > 0 && !vpath.endsWith(File.separator)) { vpath += File.separator; @@ -1227,11 +1227,11 @@ public class DirectoryScanner } if (!followSymlinks) { final ArrayList noLinks = new ArrayList(); - for (int i = 0; i < newfiles.length; i++) { + for (final String newFile : newFiles) { try { - if (SYMLINK_UTILS.isSymbolicLink(dir, newfiles[i])) { - final String name = vpath + newfiles[i]; - final File file = new File(dir, newfiles[i]); + if (SYMLINK_UTILS.isSymbolicLink(dir, newFile)) { + final String name = vpath + newFile; + final File file = new File(dir, newFile); if (file.isDirectory()) { dirsExcluded.addElement(name); } else if (file.isFile()) { @@ -1239,25 +1239,25 @@ public class DirectoryScanner } accountForNotFollowedSymlink(name, file); } else { - noLinks.add(newfiles[i]); + noLinks.add(newFile); } } catch (final IOException ioe) { final String msg = "IOException caught while checking " + "for links, couldn't get canonical path!"; // will be caught and redirected to Ant's logging system System.err.println(msg); - noLinks.add(newfiles[i]); + noLinks.add(newFile); } } - newfiles = (noLinks.toArray(new String[noLinks.size()])); + newFiles = (noLinks.toArray(new String[noLinks.size()])); } else { directoryNamesFollowed.addFirst(dir.getName()); } - for (int i = 0; i < newfiles.length; i++) { - final String name = vpath + newfiles[i]; - final TokenizedPath newPath = new TokenizedPath(path, newfiles[i]); - final File file = new File(dir, newfiles[i]); + for (String newFile : newFiles) { + final String name = vpath + newFile; + final TokenizedPath newPath = new TokenizedPath(path, newFile); + final File file = new File(dir, newFile); final String[] children = file.list(); if (children == null || (children.length == 0 && file.isFile())) { if (isIncluded(newPath)) { @@ -1269,8 +1269,7 @@ public class DirectoryScanner } else if (file.isDirectory()) { // dir if (followSymlinks - && causesIllegalSymlinkLoop(newfiles[i], dir, - directoryNamesFollowed)) { + && causesIllegalSymlinkLoop(newFile, dir, directoryNamesFollowed)) { // will be caught and redirected to Ant's logging system System.err.println("skipping symbolic link " + file.getAbsolutePath() diff --git a/src/main/org/apache/tools/ant/IntrospectionHelper.java b/src/main/org/apache/tools/ant/IntrospectionHelper.java index c13f802a4..af7f3125e 100644 --- a/src/main/org/apache/tools/ant/IntrospectionHelper.java +++ b/src/main/org/apache/tools/ant/IntrospectionHelper.java @@ -179,10 +179,8 @@ public final class IntrospectionHelper { */ private IntrospectionHelper(final Class bean) { this.bean = bean; - final Method[] methods = bean.getMethods(); Method addTextMethod = null; - for (int i = 0; i < methods.length; i++) { - final Method m = methods[i]; + for (final Method m : bean.getMethods()) { final String name = m.getName(); final Class returnType = m.getReturnType(); final Class[] args = m.getParameterTypes(); @@ -205,7 +203,7 @@ public final class IntrospectionHelper { } if ("addText".equals(name) && Void.TYPE.equals(returnType) && args.length == 1 && String.class.equals(args[0])) { - addTextMethod = methods[i]; + addTextMethod = m; } else if (name.startsWith("set") && Void.TYPE.equals(returnType) && args.length == 1 && !args[0].isArray()) { final String propName = getPropertyName(name, "set"); @@ -1631,9 +1629,7 @@ public final class IntrospectionHelper { Class matchedClass = null; Method matchedMethod = null; - final int size = methods.size(); - for (int i = 0; i < size; ++i) { - final Method method = methods.get(i); + for (final Method method : methods) { final Class methodClass = method.getParameterTypes()[0]; if (methodClass.isAssignableFrom(paramClass)) { if (matchedClass == null) { @@ -1679,9 +1675,7 @@ public final class IntrospectionHelper { return null; } synchronized (definitions) { - final int size = definitions.size(); - for (int i = 0; i < size; ++i) { - final AntTypeDefinition d = definitions.get(i); + for (final AntTypeDefinition d : definitions) { final Class exposedClass = d.getExposedClass(helper.getProject()); if (exposedClass == null) { continue; diff --git a/src/main/org/apache/tools/ant/Project.java b/src/main/org/apache/tools/ant/Project.java index 5feeb38e9..b8636d945 100644 --- a/src/main/org/apache/tools/ant/Project.java +++ b/src/main/org/apache/tools/ant/Project.java @@ -393,8 +393,8 @@ public class Project implements ResourceFactory { public void addBuildListener(final BuildListener listener) { synchronized (listenersLock) { // If the listeners already has this listener, do nothing - for (int i = 0; i < listeners.length; i++) { - if (listeners[i] == listener) { + for (BuildListener buildListener : listeners) { + if (buildListener == listener) { return; } } @@ -439,8 +439,8 @@ public class Project implements ResourceFactory { public Vector getBuildListeners() { synchronized (listenersLock) { final Vector r = new Vector(listeners.length); - for (int i = 0; i < listeners.length; i++) { - r.add(listeners[i]); + for (BuildListener listener : listeners) { + r.add(listener); } return r; } @@ -1832,13 +1832,13 @@ public class Project implements ResourceFactory { // dependency tree, not just on the Targets that depend on the // build Target. - for (int i = 0; i < roots.length; i++) { - final String st = (state.get(roots[i])); + for (String root : roots) { + final String st = state.get(root); if (st == null) { - tsort(roots[i], targetTable, state, visiting, ret); + tsort(root, targetTable, state, visiting, ret); } else if (st == VISITING) { throw new BuildException("Unexpected node in visiting state: " - + roots[i]); + + root); } } final StringBuffer buf = new StringBuffer("Build sequence for target(s)"); @@ -2093,9 +2093,8 @@ public class Project implements ResourceFactory { */ public void fireBuildStarted() { final BuildEvent event = new BuildEvent(this); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].buildStarted(event); + for (BuildListener currListener : listeners) { + currListener.buildStarted(event); } } @@ -2109,9 +2108,8 @@ public class Project implements ResourceFactory { public void fireBuildFinished(final Throwable exception) { final BuildEvent event = new BuildEvent(this); event.setException(exception); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].buildFinished(event); + for (BuildListener currListener : listeners) { + currListener.buildFinished(event); } // Inform IH to clear the cache IntrospectionHelper.clearCache(); @@ -2125,10 +2123,9 @@ public class Project implements ResourceFactory { */ public void fireSubBuildStarted() { final BuildEvent event = new BuildEvent(this); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - if (currListeners[i] instanceof SubBuildListener) { - ((SubBuildListener) currListeners[i]).subBuildStarted(event); + for (BuildListener currListener : listeners) { + if (currListener instanceof SubBuildListener) { + ((SubBuildListener) currListener).subBuildStarted(event); } } } @@ -2145,10 +2142,9 @@ public class Project implements ResourceFactory { public void fireSubBuildFinished(final Throwable exception) { final BuildEvent event = new BuildEvent(this); event.setException(exception); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - if (currListeners[i] instanceof SubBuildListener) { - ((SubBuildListener) currListeners[i]).subBuildFinished(event); + for (BuildListener currListener : listeners) { + if (currListener instanceof SubBuildListener) { + ((SubBuildListener) currListener).subBuildFinished(event); } } } @@ -2162,9 +2158,8 @@ public class Project implements ResourceFactory { */ protected void fireTargetStarted(final Target target) { final BuildEvent event = new BuildEvent(target); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].targetStarted(event); + for (BuildListener currListener : listeners) { + currListener.targetStarted(event); } } @@ -2182,9 +2177,8 @@ public class Project implements ResourceFactory { protected void fireTargetFinished(final Target target, final Throwable exception) { final BuildEvent event = new BuildEvent(target); event.setException(exception); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].targetFinished(event); + for (BuildListener currListener : listeners) { + currListener.targetFinished(event); } } @@ -2200,9 +2194,8 @@ public class Project implements ResourceFactory { // register this as the current task on the current thread. registerThreadTask(Thread.currentThread(), task); final BuildEvent event = new BuildEvent(task); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].taskStarted(event); + for (BuildListener currListener : listeners) { + currListener.taskStarted(event); } } @@ -2222,9 +2215,8 @@ public class Project implements ResourceFactory { System.err.flush(); final BuildEvent event = new BuildEvent(task); event.setException(exception); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].taskFinished(event); + for (BuildListener currListener : listeners) { + currListener.taskFinished(event); } } @@ -2270,9 +2262,8 @@ public class Project implements ResourceFactory { } try { isLoggingMessage.set(Boolean.TRUE); - final BuildListener[] currListeners = listeners; - for (int i = 0; i < currListeners.length; i++) { - currListeners[i].messageLogged(event); + for (BuildListener currListener : listeners) { + currListener.messageLogged(event); } } finally { isLoggingMessage.set(Boolean.FALSE); @@ -2472,11 +2463,9 @@ public class Project implements ResourceFactory { return; } try { - final Method method = - obj.getClass().getMethod( - "setProject", new Class[] {Project.class}); + final Method method = obj.getClass().getMethod("setProject", Project.class); if (method != null) { - method.invoke(obj, new Object[] {this}); + method.invoke(obj, this); } } catch (final Throwable e) { // ignore this if the object does not have diff --git a/src/main/org/apache/tools/ant/ProjectHelper.java b/src/main/org/apache/tools/ant/ProjectHelper.java index 5bc1cf571..907430a21 100644 --- a/src/main/org/apache/tools/ant/ProjectHelper.java +++ b/src/main/org/apache/tools/ant/ProjectHelper.java @@ -136,9 +136,9 @@ public class ProjectHelper { if (name == null) { throw new NullPointerException(); } - for (int i = 0; i < values.length; i++) { - if (name.equals(values[i].name())) { - return values[i]; + for (OnMissingExtensionPoint value : values) { + if (name.equals(value.name())) { + return value; } } throw new IllegalArgumentException( diff --git a/src/main/org/apache/tools/ant/PropertyHelper.java b/src/main/org/apache/tools/ant/PropertyHelper.java index 7561e735b..c7f385e66 100644 --- a/src/main/org/apache/tools/ant/PropertyHelper.java +++ b/src/main/org/apache/tools/ant/PropertyHelper.java @@ -1144,11 +1144,11 @@ public class PropertyHelper implements GetProperty { final HashSet> result = new HashSet>(); Class c = d.getClass(); while (c != null) { - Class[] ifs = c.getInterfaces(); - for (int i = 0; i < ifs.length; i++) { - if (Delegate.class.isAssignableFrom(ifs[i])) { + for (Class ifc : c.getInterfaces()) { + if (Delegate.class.isAssignableFrom(ifc)) { @SuppressWarnings("unchecked") - final Class delegateInterface = (Class) ifs[i]; + final Class delegateInterface = + (Class) ifc; result.add(delegateInterface); } } diff --git a/src/main/org/apache/tools/ant/attribute/BaseIfAttribute.java b/src/main/org/apache/tools/ant/attribute/BaseIfAttribute.java index c2ec08ab4..3e8b5665d 100644 --- a/src/main/org/apache/tools/ant/attribute/BaseIfAttribute.java +++ b/src/main/org/apache/tools/ant/attribute/BaseIfAttribute.java @@ -19,7 +19,6 @@ package org.apache.tools.ant.attribute; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import org.apache.tools.ant.ProjectComponent; @@ -70,10 +69,9 @@ public abstract class BaseIfAttribute protected Map getParams(UnknownElement el) { Map ret = new HashMap(); RuntimeConfigurable rc = el.getWrapper(); - Map attributes = rc.getAttributeMap(); // This does a copy! - for (Iterator i = attributes.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - String key = (String) entry.getKey(); + Map attributes = rc.getAttributeMap(); // This does a copy! + for (Map.Entry entry : attributes.entrySet()) { + String key = entry.getKey(); String value = (String) entry.getValue(); if (key.startsWith("ant-attribute:param")) { int pos = key.lastIndexOf(':'); diff --git a/src/main/org/apache/tools/ant/filters/ConcatFilter.java b/src/main/org/apache/tools/ant/filters/ConcatFilter.java index 0ac6024b4..817572ff1 100644 --- a/src/main/org/apache/tools/ant/filters/ConcatFilter.java +++ b/src/main/org/apache/tools/ant/filters/ConcatFilter.java @@ -191,13 +191,13 @@ public final class ConcatFilter extends BaseParamFilterReader // get parameters final Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if ("prepend".equals(params[i].getName())) { - setPrepend(new File(params[i].getValue())); + for (Parameter param : params) { + if ("prepend".equals(param.getName())) { + setPrepend(new File(param.getValue())); continue; } - if ("append".equals(params[i].getName())) { - setAppend(new File(params[i].getValue())); + if ("append".equals(param.getName())) { + setAppend(new File(param.getValue())); continue; } } diff --git a/src/main/org/apache/tools/ant/filters/HeadFilter.java b/src/main/org/apache/tools/ant/filters/HeadFilter.java index 522fe57b5..29806b3d5 100644 --- a/src/main/org/apache/tools/ant/filters/HeadFilter.java +++ b/src/main/org/apache/tools/ant/filters/HeadFilter.java @@ -187,13 +187,13 @@ public final class HeadFilter extends BaseParamFilterReader private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (LINES_KEY.equals(params[i].getName())) { - lines = Long.parseLong(params[i].getValue()); + for (Parameter param : params) { + if (LINES_KEY.equals(param.getName())) { + lines = Long.parseLong(param.getValue()); continue; } - if (SKIP_KEY.equals(params[i].getName())) { - skip = Long.parseLong(params[i].getValue()); + if (SKIP_KEY.equals(param.getName())) { + skip = Long.parseLong(param.getValue()); continue; } } diff --git a/src/main/org/apache/tools/ant/filters/LineContains.java b/src/main/org/apache/tools/ant/filters/LineContains.java index c83cae283..d74d4dd91 100644 --- a/src/main/org/apache/tools/ant/filters/LineContains.java +++ b/src/main/org/apache/tools/ant/filters/LineContains.java @@ -204,11 +204,11 @@ public final class LineContains private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (CONTAINS_KEY.equals(params[i].getType())) { - contains.addElement(params[i].getValue()); - } else if (NEGATE_KEY.equals(params[i].getType())) { - setNegate(Project.toBoolean(params[i].getValue())); + for (Parameter param : params) { + if (CONTAINS_KEY.equals(param.getType())) { + contains.addElement(param.getValue()); + } else if (NEGATE_KEY.equals(param.getType())) { + setNegate(Project.toBoolean(param.getValue())); } } } diff --git a/src/main/org/apache/tools/ant/filters/LineContainsRegExp.java b/src/main/org/apache/tools/ant/filters/LineContainsRegExp.java index 5d144c2b3..b18e3625d 100644 --- a/src/main/org/apache/tools/ant/filters/LineContainsRegExp.java +++ b/src/main/org/apache/tools/ant/filters/LineContainsRegExp.java @@ -237,13 +237,13 @@ public final class LineContainsRegExp private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (REGEXP_KEY.equals(params[i].getType())) { - setRegexp(params[i].getValue()); - } else if (NEGATE_KEY.equals(params[i].getType())) { - setNegate(Project.toBoolean(params[i].getValue())); - } else if (CS_KEY.equals(params[i].getType())) { - setCaseSensitive(Project.toBoolean(params[i].getValue())); + for (Parameter param : params) { + if (REGEXP_KEY.equals(param.getType())) { + setRegexp(param.getValue()); + } else if (NEGATE_KEY.equals(param.getType())) { + setNegate(Project.toBoolean(param.getValue())); + } else if (CS_KEY.equals(param.getType())) { + setCaseSensitive(Project.toBoolean(param.getValue())); } } } diff --git a/src/main/org/apache/tools/ant/filters/PrefixLines.java b/src/main/org/apache/tools/ant/filters/PrefixLines.java index 324397e8b..e125aa326 100644 --- a/src/main/org/apache/tools/ant/filters/PrefixLines.java +++ b/src/main/org/apache/tools/ant/filters/PrefixLines.java @@ -153,9 +153,9 @@ public final class PrefixLines private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (PREFIX_KEY.equals(params[i].getName())) { - prefix = params[i].getValue(); + for (Parameter param : params) { + if (PREFIX_KEY.equals(param.getName())) { + prefix = param.getValue(); break; } } diff --git a/src/main/org/apache/tools/ant/filters/SortFilter.java b/src/main/org/apache/tools/ant/filters/SortFilter.java index 056ad6a74..be08acb32 100644 --- a/src/main/org/apache/tools/ant/filters/SortFilter.java +++ b/src/main/org/apache/tools/ant/filters/SortFilter.java @@ -314,19 +314,18 @@ public final class SortFilter extends BaseParamFilterReader // get parameters Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - final String paramName = params[i].getName(); + for (Parameter param : params) { + final String paramName = param.getName(); if (REVERSE_KEY.equals(paramName)) { - setReverse(Boolean.valueOf(params[i].getValue()) - .booleanValue()); + setReverse(Boolean.valueOf(param.getValue()).booleanValue()); continue; } if (COMPARATOR_KEY.equals(paramName)) { try { - String className = (String) params[i].getValue(); + String className = (String) param.getValue(); @SuppressWarnings("unchecked") - final Comparator comparatorInstance = (Comparator) (Class - .forName(className).newInstance()); + final Comparator comparatorInstance + = (Comparator) (Class.forName(className).newInstance()); setComparator(comparatorInstance); continue; } catch (InstantiationException e) { diff --git a/src/main/org/apache/tools/ant/filters/StripLineBreaks.java b/src/main/org/apache/tools/ant/filters/StripLineBreaks.java index 9a97940a8..9ba70dd5b 100644 --- a/src/main/org/apache/tools/ant/filters/StripLineBreaks.java +++ b/src/main/org/apache/tools/ant/filters/StripLineBreaks.java @@ -140,9 +140,9 @@ public final class StripLineBreaks String userDefinedLineBreaks = null; Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (LINE_BREAKS_KEY.equals(params[i].getName())) { - userDefinedLineBreaks = params[i].getValue(); + for (Parameter param : params) { + if (LINE_BREAKS_KEY.equals(param.getName())) { + userDefinedLineBreaks = param.getValue(); break; } } diff --git a/src/main/org/apache/tools/ant/filters/StripLineComments.java b/src/main/org/apache/tools/ant/filters/StripLineComments.java index e3d240bad..0dbb3079c 100644 --- a/src/main/org/apache/tools/ant/filters/StripLineComments.java +++ b/src/main/org/apache/tools/ant/filters/StripLineComments.java @@ -186,9 +186,9 @@ public final class StripLineComments private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (COMMENTS_KEY.equals(params[i].getType())) { - comments.addElement(params[i].getValue()); + for (Parameter param : params) { + if (COMMENTS_KEY.equals(param.getType())) { + comments.addElement(param.getValue()); } } } diff --git a/src/main/org/apache/tools/ant/filters/SuffixLines.java b/src/main/org/apache/tools/ant/filters/SuffixLines.java index 23d9b534b..9c22d2b1b 100644 --- a/src/main/org/apache/tools/ant/filters/SuffixLines.java +++ b/src/main/org/apache/tools/ant/filters/SuffixLines.java @@ -163,9 +163,9 @@ public final class SuffixLines private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (SUFFIX_KEY.equals(params[i].getName())) { - suffix = params[i].getValue(); + for (Parameter param : params) { + if (SUFFIX_KEY.equals(param.getName())) { + suffix = param.getValue(); break; } } diff --git a/src/main/org/apache/tools/ant/filters/TabsToSpaces.java b/src/main/org/apache/tools/ant/filters/TabsToSpaces.java index adaaa7afe..15c7c500d 100644 --- a/src/main/org/apache/tools/ant/filters/TabsToSpaces.java +++ b/src/main/org/apache/tools/ant/filters/TabsToSpaces.java @@ -142,10 +142,10 @@ public final class TabsToSpaces private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (params[i] != null) { - if (TAB_LENGTH_KEY.equals(params[i].getName())) { - tabLength = Integer.parseInt(params[i].getValue()); + for (Parameter param : params) { + if (param != null) { + if (TAB_LENGTH_KEY.equals(param.getName())) { + tabLength = Integer.parseInt(param.getValue()); break; } } diff --git a/src/main/org/apache/tools/ant/filters/TailFilter.java b/src/main/org/apache/tools/ant/filters/TailFilter.java index fcc84d168..0f264969c 100644 --- a/src/main/org/apache/tools/ant/filters/TailFilter.java +++ b/src/main/org/apache/tools/ant/filters/TailFilter.java @@ -187,13 +187,13 @@ public final class TailFilter extends BaseParamFilterReader private void initialize() { Parameter[] params = getParameters(); if (params != null) { - for (int i = 0; i < params.length; i++) { - if (LINES_KEY.equals(params[i].getName())) { - setLines(Long.parseLong(params[i].getValue())); + for (Parameter param : params) { + if (LINES_KEY.equals(param.getName())) { + setLines(Long.parseLong(param.getValue())); continue; } - if (SKIP_KEY.equals(params[i].getName())) { - skip = Long.parseLong(params[i].getValue()); + if (SKIP_KEY.equals(param.getName())) { + skip = Long.parseLong(param.getValue()); continue; } } diff --git a/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java b/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java index b0c67ce2d..4e9752135 100644 --- a/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java +++ b/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java @@ -48,8 +48,7 @@ public final class JavaClassHelper { final ClassParser parser = new ClassParser(bis, ""); final JavaClass javaClass = parser.parse(); final Field[] fields = javaClass.getFields(); - for (int i = 0; i < fields.length; i++) { - final Field field = fields[i]; + for (final Field field : fields) { if (field != null) { final ConstantValue cv = field.getConstantValue(); if (cv != null) { diff --git a/src/main/org/apache/tools/ant/helper/DefaultExecutor.java b/src/main/org/apache/tools/ant/helper/DefaultExecutor.java index cdbc587ce..dbdd36e5a 100644 --- a/src/main/org/apache/tools/ant/helper/DefaultExecutor.java +++ b/src/main/org/apache/tools/ant/helper/DefaultExecutor.java @@ -36,9 +36,9 @@ public class DefaultExecutor implements Executor { public void executeTargets(Project project, String[] targetNames) throws BuildException { BuildException thrownException = null; - for (int i = 0; i < targetNames.length; i++) { + for (String targetName : targetNames) { try { - project.executeTarget(targetNames[i]); + project.executeTarget(targetName); } catch (BuildException ex) { if (project.isKeepGoingMode()) { thrownException = ex; diff --git a/src/main/org/apache/tools/ant/helper/IgnoreDependenciesExecutor.java b/src/main/org/apache/tools/ant/helper/IgnoreDependenciesExecutor.java index da85dba75..be0a28962 100644 --- a/src/main/org/apache/tools/ant/helper/IgnoreDependenciesExecutor.java +++ b/src/main/org/apache/tools/ant/helper/IgnoreDependenciesExecutor.java @@ -42,11 +42,11 @@ public class IgnoreDependenciesExecutor implements Executor { throws BuildException { Hashtable targets = project.getTargets(); BuildException thrownException = null; - for (int i = 0; i < targetNames.length; i++) { + for (String targetName : targetNames) { try { - Target t = targets.get(targetNames[i]); + Target t = targets.get(targetName); if (t == null) { - throw new BuildException("Unknown target " + targetNames[i]); + throw new BuildException("Unknown target " + targetName); } t.performTasks(); } catch (BuildException ex) { diff --git a/src/main/org/apache/tools/ant/launch/Launcher.java b/src/main/org/apache/tools/ant/launch/Launcher.java index 10ca77c69..953792b0d 100644 --- a/src/main/org/apache/tools/ant/launch/Launcher.java +++ b/src/main/org/apache/tools/ant/launch/Launcher.java @@ -148,10 +148,11 @@ public class Launcher { } if (getJars && element.isDirectory()) { // add any jars in the directory - final URL[] dirURLs = Locator.getLocationURLs(element); - for (int j = 0; j < dirURLs.length; ++j) { - if (launchDiag) { System.out.println("adding library JAR: " + dirURLs[j]);} - libPathURLs.add(dirURLs[j]); + for (URL dirURL : Locator.getLocationURLs(element)) { + if (launchDiag) { + System.out.println("adding library JAR: " + dirURL); + } + libPathURLs.add(dirURL); } } @@ -268,9 +269,9 @@ public class Launcher { baseClassPath.setLength(baseClassPath.length() - 1); } - for (int i = 0; i < jars.length; ++i) { + for (URL jar : jars) { baseClassPath.append(File.pathSeparatorChar); - baseClassPath.append(Locator.fromURI(jars[i].toString())); + baseClassPath.append(Locator.fromURI(jar.toString())); } setProperty(JAVA_CLASS_PATH, baseClassPath.toString()); diff --git a/src/main/org/apache/tools/ant/launch/Locator.java b/src/main/org/apache/tools/ant/launch/Locator.java index 4f5aef494..0513e64b2 100644 --- a/src/main/org/apache/tools/ant/launch/Locator.java +++ b/src/main/org/apache/tools/ant/launch/Locator.java @@ -89,10 +89,7 @@ public final class Locator { gAfterEscaping2[DEL] = 'F'; char[] escChs = {' ', '<', '>', '#', '%', '"', '{', '}', '|', '\\', '^', '~', '[', ']', '`'}; - int len = escChs.length; - char ch; - for (int i = 0; i < len; i++) { - ch = escChs[i]; + for (char ch : escChs) { gNeedEscaping[ch] = true; gAfterEscaping1[ch] = gHexChs[ch >> NIBBLE]; gAfterEscaping2[ch] = gHexChs[ch & NIBBLE_MASK]; @@ -498,8 +495,8 @@ public final class Locator { urls = new URL[1]; String path = location.getPath(); String littlePath = path.toLowerCase(Locale.ENGLISH); - for (int i = 0; i < extensions.length; ++i) { - if (littlePath.endsWith(extensions[i])) { + for (String extension : extensions) { + if (littlePath.endsWith(extension)) { urls[0] = fileToURL(location); break; } diff --git a/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java b/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java index 09b9b4a74..59f91c82f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java @@ -438,10 +438,10 @@ public abstract class AbstractCvsTask extends Task { stringBuffer.append(newLine); stringBuffer.append("environment:"); stringBuffer.append(newLine); - for (int z = 0; z < variableArray.length; z++) { + for (String variable : variableArray) { stringBuffer.append(newLine); stringBuffer.append("\t"); - stringBuffer.append(variableArray[z]); + stringBuffer.append(variable); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java index 8554a2a3a..331c1a999 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java +++ b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java @@ -456,8 +456,8 @@ public class AntStructure extends Task { * @return true if all the strings in the array math XML-NMTOKEN */ public static final boolean areNmtokens(final String[] s) { - for (int i = 0; i < s.length; i++) { - if (!isNmtoken(s[i])) { + for (String value : s) { + if (!isNmtoken(value)) { return false; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Checksum.java b/src/main/org/apache/tools/ant/taskdefs/Checksum.java index bd95e9366..ff95dac6c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Checksum.java +++ b/src/main/org/apache/tools/ant/taskdefs/Checksum.java @@ -581,9 +581,9 @@ public class Checksum extends MatchingTask implements Condition { } private String createDigestString(byte[] fileDigest) { - StringBuffer checksumSb = new StringBuffer(); - for (int i = 0; i < fileDigest.length; i++) { - String hexStr = Integer.toHexString(BYTE_MASK & fileDigest[i]); + StringBuilder checksumSb = new StringBuilder(); + for (byte digestByte : fileDigest) { + String hexStr = Integer.toHexString(BYTE_MASK & digestByte); if (hexStr.length() < 2) { checksumSb.append("0"); } diff --git a/src/main/org/apache/tools/ant/taskdefs/Classloader.java b/src/main/org/apache/tools/ant/taskdefs/Classloader.java index 57bbf90bf..a7b96916d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Classloader.java +++ b/src/main/org/apache/tools/ant/taskdefs/Classloader.java @@ -225,9 +225,8 @@ public class Classloader extends Task { } if (existingLoader && classpath != null) { - String[] list = classpath.list(); - for (int i = 0; i < list.length; i++) { - File f = new File(list[i]); + for (String path : classpath.list()) { + File f = new File(path); if (f.exists()) { log("Adding to class loader " + acl + " " + f.getAbsolutePath(), Project.MSG_DEBUG); diff --git a/src/main/org/apache/tools/ant/taskdefs/Copy.java b/src/main/org/apache/tools/ant/taskdefs/Copy.java index fab73796a..5845523a0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Copy.java +++ b/src/main/org/apache/tools/ant/taskdefs/Copy.java @@ -773,28 +773,27 @@ public class Copy extends Task { final FileNameMapper mapper, final Hashtable map) { String[] toCopy = null; if (forceOverwrite) { - final Vector v = new Vector(); - for (int i = 0; i < names.length; i++) { - if (mapper.mapFileName(names[i]) != null) { - v.addElement(names[i]); + final List v = new ArrayList(); + for (String name : names) { + if (mapper.mapFileName(name) != null) { + v.add(name); } } - toCopy = new String[v.size()]; - v.copyInto(toCopy); + toCopy = v.toArray(new String[v.size()]); } else { final SourceFileScanner ds = new SourceFileScanner(this); toCopy = ds.restrict(names, fromDir, toDir, mapper, granularity); } - for (int i = 0; i < toCopy.length; i++) { - final File src = new File(fromDir, toCopy[i]); - final String[] mappedFiles = mapper.mapFileName(toCopy[i]); + for (String name : toCopy) { + final File src = new File(fromDir, name); + final String[] mappedFiles = mapper.mapFileName(name); if (mappedFiles == null || mappedFiles.length == 0) { continue; } if (!enableMultipleMappings) { map.put(src.getAbsolutePath(), - new String[] {new File(toDir, mappedFiles[0]).getAbsolutePath()}); + new String[]{new File(toDir, mappedFiles[0]).getAbsolutePath()}); } else { // reuse the array created by the mapper for (int k = 0; k < mappedFiles.length; k++) { @@ -819,14 +818,13 @@ public class Copy extends Task { final HashMap map = new HashMap(); Resource[] toCopy = null; if (forceOverwrite) { - final Vector v = new Vector(); - for (int i = 0; i < fromResources.length; i++) { - if (mapper.mapFileName(fromResources[i].getName()) != null) { - v.addElement(fromResources[i]); + final List v = new ArrayList(); + for (Resource rc : fromResources) { + if (mapper.mapFileName(rc.getName()) != null) { + v.add(rc); } } - toCopy = new Resource[v.size()]; - v.copyInto(toCopy); + toCopy = v.toArray(new Resource[v.size()]); } else { toCopy = ResourceUtils.selectOutOfDateSources(this, fromResources, mapper, @@ -837,22 +835,21 @@ public class Copy extends Task { }, granularity); } - for (int i = 0; i < toCopy.length; i++) { - final String[] mappedFiles = mapper.mapFileName(toCopy[i].getName()); + for (Resource rc : toCopy) { + final String[] mappedFiles = mapper.mapFileName(rc.getName()); if (mappedFiles == null || mappedFiles.length == 0) { throw new BuildException("Can't copy a resource without a" + " name if the mapper doesn't" + " provide one."); } if (!enableMultipleMappings) { - map.put(toCopy[i], - new String[] {new File(toDir, mappedFiles[0]).getAbsolutePath()}); + map.put(rc, new String[]{new File(toDir, mappedFiles[0]).getAbsolutePath()}); } else { // reuse the array created by the mapper for (int k = 0; k < mappedFiles.length; k++) { mappedFiles[k] = new File(toDir, mappedFiles[k]).getAbsolutePath(); } - map.put(toCopy[i], mappedFiles); + map.put(rc, mappedFiles); } } return map; @@ -870,11 +867,8 @@ public class Copy extends Task { for (final Map.Entry e : fileCopyMap.entrySet()) { final String fromFile = e.getKey(); - final String[] toFiles = e.getValue(); - - for (int i = 0; i < toFiles.length; i++) { - final String toFile = toFiles[i]; + for (final String toFile : e.getValue()) { if (fromFile.equals(toFile)) { log("Skipping self-copy of " + fromFile, verbosity); continue; diff --git a/src/main/org/apache/tools/ant/taskdefs/CopyPath.java b/src/main/org/apache/tools/ant/taskdefs/CopyPath.java index afedf70e5..e5003d1e8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/CopyPath.java +++ b/src/main/org/apache/tools/ant/taskdefs/CopyPath.java @@ -177,17 +177,15 @@ public class CopyPath extends Task { return; } - for (int sources = 0; sources < sourceFiles.length; sources++) { + for (String sourceFileName : sourceFiles) { - String sourceFileName = sourceFiles[sources]; File sourceFile = new File(sourceFileName); String[] toFiles = (String[]) mapper.mapFileName(sourceFileName); if (toFiles == null) { continue; } - for (int i = 0; i < toFiles.length; i++) { - String destFileName = toFiles[i]; + for (String destFileName : toFiles) { File destFile = new File(destDir, destFileName); if (sourceFile.equals(destFile)) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Copydir.java b/src/main/org/apache/tools/ant/taskdefs/Copydir.java index 8b4efc3be..26fc7155c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Copydir.java +++ b/src/main/org/apache/tools/ant/taskdefs/Copydir.java @@ -144,8 +144,7 @@ public class Copydir extends MatchingTask { } private void scanDir(File from, File to, String[] files) { - for (int i = 0; i < files.length; i++) { - String filename = files[i]; + for (String filename : files) { File srcFile = new File(from, filename); File destFile; if (flatten) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Delete.java b/src/main/org/apache/tools/ant/taskdefs/Delete.java index bf266a09c..f887695b1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Delete.java +++ b/src/main/org/apache/tools/ant/taskdefs/Delete.java @@ -627,8 +627,7 @@ public class Delete extends MatchingTask { } final int size = filesets.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) filesets.get(i); + for (FileSet fs : filesets) { if (fs.getProject() == null) { log("Deleting fileset with no project specified;" + " assuming executing project", Project.MSG_VERBOSE); @@ -674,11 +673,9 @@ public class Delete extends MatchingTask { String[] links = new String[n.length]; System.arraycopy(n, 0, links, 0, n.length); Arrays.sort(links, ReverseDirs.REVERSE); - for (int l = 0; l < links.length; l++) { + for (String link : links) { try { - SYMLINK_UTILS - .deleteSymbolicLink(new File(links[l]), - this); + SYMLINK_UTILS.deleteSymbolicLink(new File(link), this); } catch (java.io.IOException ex) { handle(ex); } @@ -772,8 +769,7 @@ public class Delete extends MatchingTask { if (list == null) { list = new String[0]; } - for (int i = 0; i < list.length; i++) { - String s = list[i]; + for (String s : list) { File f = new File(d, s); if (f.isDirectory()) { removeDir(f); @@ -801,8 +797,8 @@ public class Delete extends MatchingTask { if (files.length > 0) { log("Deleting " + files.length + " files from " + d.getAbsolutePath(), quiet ? Project.MSG_VERBOSE : verbosity); - for (int j = 0; j < files.length; j++) { - File f = new File(d, files[j]); + for (String filename : files) { + File f = new File(d, filename); log("Deleting " + f.getAbsolutePath(), quiet ? Project.MSG_VERBOSE : verbosity); if (!delete(f)) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Deltree.java b/src/main/org/apache/tools/ant/taskdefs/Deltree.java index 7290a6307..8657d76c1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Deltree.java +++ b/src/main/org/apache/tools/ant/taskdefs/Deltree.java @@ -90,9 +90,7 @@ public class Deltree extends Task { // if (dir.getCanonicalPath().equals(dir.getAbsolutePath())) { // (costin) It will not work if /home/costin is symlink to // /da0/home/costin ( taz for example ) - String[] list = dir.list(); - for (int i = 0; i < list.length; i++) { - String s = list[i]; + for (String s : dir.list()) { File f = new File(dir, s); if (f.isDirectory()) { removeDir(f); diff --git a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java index b9eb963be..cc3c2bdf8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java @@ -447,9 +447,9 @@ public class ExecTask extends Task { Path p = null; String[] environment = env.getVariables(); if (environment != null) { - for (int i = 0; i < environment.length; i++) { - if (isPath(environment[i])) { - p = new Path(getProject(), getPath(environment[i])); + for (String variable : environment) { + if (isPath(variable)) { + p = new Path(getProject(), getPath(variable)); break; } } @@ -461,10 +461,9 @@ public class ExecTask extends Task { } } if (p != null) { - String[] dirs = p.list(); - for (int i = 0; i < dirs.length; i++) { + for (String pathname : p.list()) { executableFile - = FILE_UTILS.resolveFile(new File(dirs[i]), exec); + = FILE_UTILS.resolveFile(new File(pathname), exec); if (executableFile.exists()) { return executableFile.getAbsolutePath(); } @@ -605,9 +604,9 @@ public class ExecTask extends Task { exe.setVMLauncher(vmLauncher); String[] environment = env.getVariables(); if (environment != null) { - for (int i = 0; i < environment.length; i++) { - log("Setting environment variable: " + environment[i], - Project.MSG_VERBOSE); + for (String variable : environment) { + log("Setting environment variable: " + variable, + Project.MSG_VERBOSE); } } exe.setNewenvironment(newEnvironment); diff --git a/src/main/org/apache/tools/ant/taskdefs/Execute.java b/src/main/org/apache/tools/ant/taskdefs/Execute.java index d9923e8cb..9b4c26867 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Execute.java +++ b/src/main/org/apache/tools/ant/taskdefs/Execute.java @@ -612,8 +612,7 @@ public class Execute { } Map osEnv = new LinkedHashMap(getEnvironmentVariables()); - for (int i = 0; i < env.length; i++) { - String keyValue = env[i]; + for (String keyValue : env) { String key = keyValue.substring(0, keyValue.indexOf('=')); // Find the key in the current environment copy // and remove it. diff --git a/src/main/org/apache/tools/ant/taskdefs/ExecuteJava.java b/src/main/org/apache/tools/ant/taskdefs/ExecuteJava.java index 2f65308d2..08fd8cdfe 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ExecuteJava.java +++ b/src/main/org/apache/tools/ant/taskdefs/ExecuteJava.java @@ -272,9 +272,8 @@ public class ExecuteJava implements Runnable, TimeoutObserver { public int fork(ProjectComponent pc) throws BuildException { CommandlineJava cmdl = new CommandlineJava(); cmdl.setClassname(javaCommand.getExecutable()); - String[] args = javaCommand.getArguments(); - for (int i = 0; i < args.length; i++) { - cmdl.createArgument().setValue(args[i]); + for (String arg : javaCommand.getArguments()) { + cmdl.createArgument().setValue(arg); } if (classpath != null) { cmdl.createClasspath(pc.getProject()).append(classpath); diff --git a/src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java b/src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java index 39cc03aed..44a7977f7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java +++ b/src/main/org/apache/tools/ant/taskdefs/ExecuteOn.java @@ -21,6 +21,7 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; import java.util.HashSet; +import java.util.Set; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -369,19 +370,17 @@ public class ExecuteOn extends ExecTask { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); if (!FileDirBoth.DIR.equals(currentType)) { - String[] s = getFiles(base, ds); - for (int j = 0; j < s.length; j++) { + for (String value : getFiles(base, ds)) { totalFiles++; - fileNames.addElement(s[j]); - baseDirs.addElement(base); + fileNames.add(value); + baseDirs.add(base); } } if (!FileDirBoth.FILE.equals(currentType)) { - String[] s = getDirs(base, ds); - for (int j = 0; j < s.length; j++) { + for (String value : getDirs(base, ds)) { totalDirs++; - fileNames.addElement(s[j]); - baseDirs.addElement(base); + fileNames.add(value); + baseDirs.add(base); } } if (fileNames.size() == 0 && skipEmpty) { @@ -516,9 +515,9 @@ public class ExecuteOn extends ExecTask { final char fileSeparator = File.separatorChar; Vector targets = new Vector(); if (targetFilePos != null) { - HashSet addedFiles = new HashSet(); - for (int i = 0; i < srcFiles.length; i++) { - String[] subTargets = mapper.mapFileName(srcFiles[i]); + Set addedFiles = new HashSet(); + for (String srcFile : srcFiles) { + String[] subTargets = mapper.mapFileName(srcFile); if (subTargets != null) { for (int j = 0; j < subTargets.length; j++) { String name = null; diff --git a/src/main/org/apache/tools/ant/taskdefs/Expand.java b/src/main/org/apache/tools/ant/taskdefs/Expand.java index 3f83b655e..b3897efc6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Expand.java +++ b/src/main/org/apache/tools/ant/taskdefs/Expand.java @@ -279,18 +279,16 @@ public class Expand extends Task { boolean included = false; Set includePatterns = new HashSet(); Set excludePatterns = new HashSet(); - final int size = patternsets.size(); - for (int v = 0; v < size; v++) { - PatternSet p = patternsets.elementAt(v); + for (PatternSet p : patternsets) { String[] incls = p.getIncludePatterns(getProject()); if (incls == null || incls.length == 0) { // no include pattern implicitly means includes="**" - incls = new String[] {"**"}; + incls = new String[]{"**"}; } - for (int w = 0; w < incls.length; w++) { - String pattern = incls[w].replace('/', File.separatorChar) - .replace('\\', File.separatorChar); + for (String incl : incls) { + String pattern = incl.replace('/', File.separatorChar) + .replace('\\', File.separatorChar); if (pattern.endsWith(File.separator)) { pattern += "**"; } @@ -299,10 +297,9 @@ public class Expand extends Task { String[] excls = p.getExcludePatterns(getProject()); if (excls != null) { - for (int w = 0; w < excls.length; w++) { - String pattern = excls[w] - .replace('/', File.separatorChar) - .replace('\\', File.separatorChar); + for (String excl : excls) { + String pattern = excl.replace('/', File.separatorChar) + .replace('\\', File.separatorChar); if (pattern.endsWith(File.separator)) { pattern += "**"; } diff --git a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java index 867c579bd..01a71289a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java +++ b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java @@ -299,10 +299,9 @@ public class FixCRLF extends MatchingTask implements ChainableReader { Project.MSG_VERBOSE); DirectoryScanner ds = super.getDirectoryScanner(srcDir); - String[] files = ds.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - processFile(files[i]); + for (String filename : ds.getIncludedFiles()) { + processFile(filename); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Jar.java b/src/main/org/apache/tools/ant/taskdefs/Jar.java index f31ac6f75..26ee08753 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jar.java @@ -574,10 +574,8 @@ public class Jar extends Zip { private void writeManifest(ZipOutputStream zOut, Manifest manifest) throws IOException { - for (Enumeration e = manifest.getWarnings(); - e.hasMoreElements();) { - log("Manifest warning: " + e.nextElement(), - Project.MSG_WARN); + for (String warning : Collections.list(manifest.getWarnings())) { + log("Manifest warning: " + warning, Project.MSG_WARN); } zipDir((Resource) null, zOut, "META-INF/", ZipFileSet.DEFAULT_DIR_MODE, @@ -661,13 +659,12 @@ public class Jar extends Zip { cpEntries[c++] = tok.nextToken(); } } - String[] indexJarEntries = indexJars.list(); - for (int i = 0; i < indexJarEntries.length; i++) { - String name = findJarName(indexJarEntries[i], cpEntries); + for (String indexJarEntry : indexJars.list()) { + String name = findJarName(indexJarEntry, cpEntries); if (name != null) { ArrayList dirs = new ArrayList(); ArrayList files = new ArrayList(); - grabFilesAndDirs(indexJarEntries[i], dirs, files); + grabFilesAndDirs(indexJarEntry, dirs, files); if (dirs.size() + files.size() > 0) { writer.println(name); writeIndexLikeList(dirs, files, writer); @@ -830,8 +827,8 @@ public class Jar extends Zip { // checks here deferring them for the second run Resource[][] manifests = grabManifests(rcs); int count = 0; - for (int i = 0; i < manifests.length; i++) { - count += manifests[i].length; + for (Resource[] mf : manifests) { + count += mf.length; } log("found a total of " + count + " manifests in " + manifests.length + " resource collections", diff --git a/src/main/org/apache/tools/ant/taskdefs/Javac.java b/src/main/org/apache/tools/ant/taskdefs/Javac.java index 0237ab61c..5458720cd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Javac.java +++ b/src/main/org/apache/tools/ant/taskdefs/Javac.java @@ -1153,10 +1153,9 @@ public class Javac extends MatchingTask { */ protected void scanDir(final File srcDir, final File destDir, final String[] files) { final GlobPatternMapper m = new GlobPatternMapper(); - final String[] extensions = findSupportedFileExtensions(); - for (int i = 0; i < extensions.length; i++) { - m.setFrom(extensions[i]); + for (String extension : findSupportedFileExtensions()) { + m.setFrom(extension); m.setTo("*.class"); final SourceFileScanner sfs = new SourceFileScanner(this); final File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); @@ -1175,9 +1174,8 @@ public class Javac extends MatchingTask { } private void collectFileListFromSourcePath() { - final String[] list = src.list(); - for (int i = 0; i < list.length; i++) { - final File srcDir = getProject().resolveFile(list[i]); + for (String filename : src.list()) { + final File srcDir = getProject().resolveFile(filename); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() @@ -1195,7 +1193,8 @@ public class Javac extends MatchingTask { final FileUtils fu = FileUtils.getFileUtils(); for (String pathElement : moduleSourcepath.list()) { boolean valid = false; - for (Map.Entry> modules : resolveModuleSourcePathElement(getProject().getBaseDir(), pathElement).entrySet()) { + for (Map.Entry> modules : resolveModuleSourcePathElement( + getProject().getBaseDir(), pathElement).entrySet()) { final String moduleName = modules.getKey(); for (File srcDir : modules.getValue()) { if (srcDir.exists()) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java index 931449f2a..a78c526c5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java +++ b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java @@ -33,6 +33,7 @@ import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; +import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; @@ -1918,32 +1919,26 @@ public class Javadoc extends Task { private void doDoclet(final Commandline toExecute) { if (doclet != null) { if (doclet.getName() == null) { - throw new BuildException("The doclet name must be " - + "specified.", getLocation()); - } else { - toExecute.createArgument().setValue("-doclet"); - toExecute.createArgument().setValue(doclet.getName()); - if (doclet.getPath() != null) { - final Path docletPath - = doclet.getPath().concatSystemClasspath("ignore"); - if (docletPath.size() != 0) { - toExecute.createArgument().setValue("-docletpath"); - toExecute.createArgument().setPath(docletPath); - } + throw new BuildException("The doclet name must be specified.", + getLocation()); + } + toExecute.createArgument().setValue("-doclet"); + toExecute.createArgument().setValue(doclet.getName()); + if (doclet.getPath() != null) { + final Path docletPath + = doclet.getPath().concatSystemClasspath("ignore"); + if (docletPath.size() != 0) { + toExecute.createArgument().setValue("-docletpath"); + toExecute.createArgument().setPath(docletPath); } - for (final Enumeration e = doclet.getParams(); - e.hasMoreElements();) { - final DocletParam param = e.nextElement(); - if (param.getName() == null) { - throw new BuildException("Doclet parameters must " - + "have a name"); - } - - toExecute.createArgument().setValue(param.getName()); - if (param.getValue() != null) { - toExecute.createArgument() - .setValue(param.getValue()); - } + } + for (final DocletParam param : Collections.list(doclet.getParams())) { + if (param.getName() == null) { + throw new BuildException("Doclet parameters must have a name"); + } + toExecute.createArgument().setValue(param.getName()); + if (param.getValue() != null) { + toExecute.createArgument().setValue(param.getValue()); } } } @@ -2152,27 +2147,20 @@ public class Javadoc extends Task { // -tag arguments. final DirectoryScanner tagDefScanner = ta.getDirectoryScanner(getProject()); - final String[] files = tagDefScanner.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - final File tagDefFile = new File(tagDir, files[i]); + for (String file : tagDefScanner.getIncludedFiles()) { + final File tagDefFile = new File(tagDir, file); try { - final BufferedReader in - = new BufferedReader( - new FileReader(tagDefFile) - ); + final BufferedReader in = new BufferedReader( + new FileReader(tagDefFile)); String line = null; while ((line = in.readLine()) != null) { - toExecute.createArgument() - .setValue("-tag"); - toExecute.createArgument() - .setValue(line); + toExecute.createArgument().setValue("-tag"); + toExecute.createArgument().setValue(line); } in.close(); } catch (final IOException ioe) { - throw new BuildException( - "Couldn't read " - + " tag file from " - + tagDefFile.getAbsolutePath(), ioe); + throw new BuildException("Couldn't read tag file from " + + tagDefFile.getAbsolutePath(), ioe); } } } @@ -2278,9 +2266,8 @@ public class Javadoc extends Task { } private boolean containsWhitespace(final String s) { - final int len = s.length(); - for (int i = 0; i < len; i++) { - if (Character.isWhitespace(s.charAt(i))) { + for (char c : s.toCharArray()) { + if (Character.isWhitespace(c)) { return true; } } @@ -2290,10 +2277,8 @@ public class Javadoc extends Task { private String quoteString(final String str, final char delim) { final StringBuffer buf = new StringBuffer(str.length() * 2); buf.append(delim); - final int len = str.length(); boolean lastCharWasCR = false; - for (int i = 0; i < len; i++) { - final char c = str.charAt(i); + for (final char c : str.toCharArray()) { if (c == delim) { // can't put the non-constant delim into a case buf.append('\\').append(c); lastCharWasCR = false; @@ -2429,11 +2414,10 @@ public class Javadoc extends Task { final File baseDir = ds.getDir(getProject()); log("scanning " + baseDir + " for packages.", Project.MSG_DEBUG); final DirectoryScanner dsc = ds.getDirectoryScanner(getProject()); - final String[] dirs = dsc.getIncludedDirectories(); boolean containsPackages = false; - for (int i = 0; i < dirs.length; i++) { + for (String dir : dsc.getIncludedDirectories()) { // are there any java files in this directory? - final File pd = new File(baseDir, dirs[i]); + final File pd = new File(baseDir, dir); final String[] files = pd.list(new FilenameFilter () { public boolean accept(final File dir1, final String name) { return name.endsWith(".java") @@ -2443,7 +2427,7 @@ public class Javadoc extends Task { }); if (files.length > 0) { - if ("".equals(dirs[i])) { + if ("".equals(dir)) { log(baseDir + " contains source files in the default package," + " you must specify them as source files" @@ -2452,7 +2436,7 @@ public class Javadoc extends Task { } else { containsPackages = true; final String packageName = - dirs[i].replace(File.separatorChar, '.'); + dir.replace(File.separatorChar, '.'); if (!addedPackages.contains(packageName)) { addedPackages.add(packageName); pn.addElement(packageName); diff --git a/src/main/org/apache/tools/ant/taskdefs/Jikes.java b/src/main/org/apache/tools/ant/taskdefs/Jikes.java index c94becab5..89ac3f1f7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jikes.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jikes.java @@ -90,8 +90,8 @@ public class Jikes { tmpFile = FileUtils.getFileUtils().createTempFile("jikes", "tmp", null, false, true); out = new BufferedWriter(new FileWriter(tmpFile)); - for (int i = 0; i < args.length; i++) { - out.write(args[i]); + for (String arg : args) { + out.write(arg); out.newLine(); } out.flush(); diff --git a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java index 937cdd1e1..79b69848a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java +++ b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java @@ -262,8 +262,7 @@ public class MacroDef extends AntlibDefinition { + "\" has already been used by the text element"); } final int size = attributes.size(); - for (int i = 0; i < size; ++i) { - Attribute att = (Attribute) attributes.get(i); + for (Attribute att : attributes) { if (att.getName().equals(attribute.getName())) { throw new BuildException( "the name \"" + attribute.getName() diff --git a/src/main/org/apache/tools/ant/taskdefs/Move.java b/src/main/org/apache/tools/ant/taskdefs/Move.java index c549d1b71..0149cc827 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Move.java +++ b/src/main/org/apache/tools/ant/taskdefs/Move.java @@ -20,6 +20,7 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; import java.util.Iterator; +import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; @@ -167,17 +168,16 @@ public class Move extends Copy { if (includeEmpty) { int createCount = 0; - for (Iterator fromDirNames = dirCopyMap.keySet().iterator(); fromDirNames.hasNext();) { - String fromDirName = (String) fromDirNames.next(); - String[] toDirNames = (String[]) dirCopyMap.get(fromDirName); + for (Map.Entry entry : dirCopyMap.entrySet()) { + String fromDirName = entry.getKey(); boolean selfMove = false; - for (int i = 0; i < toDirNames.length; i++) { - if (fromDirName.equals(toDirNames[i])) { + for (String toDirName : entry.getValue()) { + if (fromDirName.equals(toDirName)) { log("Skipping self-move of " + fromDirName, verbosity); selfMove = true; continue; } - File d = new File(toDirNames[i]); + File d = new File(toDirName); if (!d.exists()) { if (!(d.mkdirs() || d.exists())) { log("Unable to create directory " diff --git a/src/main/org/apache/tools/ant/taskdefs/Parallel.java b/src/main/org/apache/tools/ant/taskdefs/Parallel.java index 469ba418e..f46d4ad69 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Parallel.java +++ b/src/main/org/apache/tools/ant/taskdefs/Parallel.java @@ -417,9 +417,9 @@ public class Parallel extends Task int tries = 0; do { oneAlive = false; - for (int i = 0; i < running.length; i++) { - if (running[i] != null && !running[i].isFinished()) { - running[i].interrupt(); + for (TaskRunnable runnable : running) { + if (runnable != null && !runnable.isFinished()) { + runnable.interrupt(); Thread.yield(); oneAlive = true; } diff --git a/src/main/org/apache/tools/ant/taskdefs/Recorder.java b/src/main/org/apache/tools/ant/taskdefs/Recorder.java index a6f6a883c..d632a85c4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Recorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/Recorder.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs; import java.util.Hashtable; -import java.util.Iterator; import java.util.Map; import org.apache.tools.ant.BuildEvent; @@ -68,7 +67,7 @@ public class Recorder extends Task implements SubBuildListener { /** Strip task banners if true. */ private boolean emacsMode = false; /** The list of recorder entries. */ - private static Hashtable recorderEntries = new Hashtable(); + private static Hashtable recorderEntries = new Hashtable<>(); ////////////////////////////////////////////////////////////////////// // CONSTRUCTORS / INITIALIZERS @@ -206,10 +205,9 @@ public class Recorder extends Task implements SubBuildListener { */ protected RecorderEntry getRecorder(String name, Project proj) throws BuildException { - Object o = recorderEntries.get(name); - RecorderEntry entry; + RecorderEntry entry = recorderEntries.get(name); - if (o == null) { + if (entry == null) { // create a recorder entry entry = new RecorderEntry(name); @@ -220,9 +218,8 @@ public class Recorder extends Task implements SubBuildListener { } entry.setProject(proj); recorderEntries.put(name, entry); - } else { - entry = (RecorderEntry) o; } + return entry; } @@ -308,12 +305,12 @@ public class Recorder extends Task implements SubBuildListener { * * @since Ant 1.7 */ + @SuppressWarnings("unchecked") private void cleanup() { - Hashtable entries = (Hashtable) recorderEntries.clone(); - Iterator itEntries = entries.entrySet().iterator(); - while (itEntries.hasNext()) { - Map.Entry entry = (Map.Entry) itEntries.next(); - RecorderEntry re = (RecorderEntry) entry.getValue(); + Hashtable entries + = (Hashtable) recorderEntries.clone(); + for (Map.Entry entry : entries.entrySet()) { + RecorderEntry re = entry.getValue(); if (re.getProject() == getProject()) { recorderEntries.remove(entry.getKey()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/Replace.java b/src/main/org/apache/tools/ant/taskdefs/Replace.java index 6ea6f650e..5932fd563 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Replace.java +++ b/src/main/org/apache/tools/ant/taskdefs/Replace.java @@ -70,7 +70,7 @@ public class Replace extends MatchingTask { private Resource propertyResource = null; private Resource replaceFilterResource = null; private Properties properties = null; - private ArrayList replacefilters = new ArrayList(); + private ArrayList replacefilters = new ArrayList(); private File dir = null; @@ -744,9 +744,7 @@ public class Replace extends MatchingTask { */ private StringBuffer buildFilterChain(StringBuffer inputBuffer) { StringBuffer buf = inputBuffer; - final int size = replacefilters.size(); - for (int i = 0; i < size; i++) { - Replacefilter filter = (Replacefilter) replacefilters.get(i); + for (Replacefilter filter : replacefilters) { filter.setInputBuffer(buf); buf = filter.getOutputBuffer(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/SubAnt.java b/src/main/org/apache/tools/ant/taskdefs/SubAnt.java index f3207aa29..ac023c48b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SubAnt.java +++ b/src/main/org/apache/tools/ant/taskdefs/SubAnt.java @@ -203,13 +203,13 @@ public class SubAnt extends Task { } */ BuildException buildException = null; - for (int i = 0; i < count; ++i) { + for (String filename : filenames) { File file = null; String subdirPath = null; Throwable thrownException = null; try { File directory = null; - file = new File(filenames[i]); + file = new File(filename); if (file.isDirectory()) { if (verbose) { subdirPath = file.getPath(); diff --git a/src/main/org/apache/tools/ant/taskdefs/Sync.java b/src/main/org/apache/tools/ant/taskdefs/Sync.java index e99bafd7f..57d2f092c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sync.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sync.java @@ -226,9 +226,8 @@ public class Sync extends Task { ds.addExcludes(excls); ds.scan(); - String[] files = ds.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - File f = new File(toDir, files[i]); + for (String file : ds.getIncludedFiles()) { + File f = new File(toDir, file); log("Removing orphan file: " + f, Project.MSG_DEBUG); f.delete(); ++removedCount[1]; @@ -286,13 +285,11 @@ public class Sync extends Task { int removedCount = 0; if (dir.isDirectory()) { File[] children = dir.listFiles(); - for (int i = 0; i < children.length; ++i) { - File file = children[i]; + for (File file : children) { // Test here again to avoid method call for non-directories! if (file.isDirectory()) { - removedCount += - removeEmptyDirectories(file, true, - preservedEmptyDirectories); + removedCount += removeEmptyDirectories(file, true, + preservedEmptyDirectories); } } if (children.length > 0) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Touch.java b/src/main/org/apache/tools/ant/taskdefs/Touch.java index 5b9722bdd..faedf9d35 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Touch.java +++ b/src/main/org/apache/tools/ant/taskdefs/Touch.java @@ -347,8 +347,8 @@ public class Touch extends Task { if (millis < 0 && r.isExists()) { modTime = r.getLastModified(); } - for (int i = 0; i < mapped.length; i++) { - touch(getProject().resolveFile(mapped[i]), modTime); + for (String fileName : mapped) { + touch(getProject().resolveFile(fileName), modTime); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Untar.java b/src/main/org/apache/tools/ant/taskdefs/Untar.java index 53b8239d1..27d2b7485 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Untar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Untar.java @@ -220,22 +220,19 @@ public class Untar extends Expand { * @exception BuildException thrown if bzip stream does not * start with expected magic values */ - public InputStream decompress(final String name, - final InputStream istream) - throws IOException, BuildException { + public InputStream decompress(final String name, final InputStream istream) + throws IOException, BuildException { final String v = getValue(); if (GZIP.equals(v)) { return new GZIPInputStream(istream); - } else { - if (BZIP2.equals(v)) { - final char[] magic = new char[] {'B', 'Z'}; - for (int i = 0; i < magic.length; i++) { - if (istream.read() != magic[i]) { - throw new BuildException("Invalid bz2 file." + name); - } + } + if (BZIP2.equals(v)) { + for (char c : new char[] {'B', 'Z'}) { + if (istream.read() != c) { + throw new BuildException("Invalid bz2 file." + name); } - return new CBZip2InputStream(istream); } + return new CBZip2InputStream(istream); } return istream; } diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java index a28e15346..ecd28f526 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java @@ -120,7 +120,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private boolean force = false; /** XSL output properties to be used */ - private final Vector outputProperties = new Vector(); + private final Vector outputProperties = new Vector(); /** for resolving entities such as dtds */ private final XMLCatalog xmlCatalog = new XMLCatalog(); @@ -940,7 +940,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * Get an enumeration on the outputproperties. * @return the outputproperties */ - public Enumeration getOutputProperties() { + public Enumeration getOutputProperties() { return outputProperties.elements(); } @@ -1513,7 +1513,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * return the attribute elements. * @return the enumeration of attributes */ - public Enumeration getAttributes() { + public Enumeration getAttributes() { return Collections.enumeration(attributes); } diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/Javac12.java b/src/main/org/apache/tools/ant/taskdefs/compilers/Javac12.java index 6865e055f..637ce0eff 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/Javac12.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/Javac12.java @@ -54,19 +54,16 @@ public class Javac12 extends DefaultCompilerAdapter { try { // Create an instance of the compiler, redirecting output to // the project log - Class c = Class.forName(CLASSIC_COMPILER_CLASSNAME); + Class c = Class.forName(CLASSIC_COMPILER_CLASSNAME); Constructor cons = - c.getConstructor(new Class[] {OutputStream.class, - String.class}); + c.getConstructor(OutputStream.class, String.class); Object compiler - = cons.newInstance(new Object[] {logstr, "javac"}); + = cons.newInstance(logstr, "javac"); // Call the compile() method - Method compile = c.getMethod("compile", - new Class [] {String[].class}); - Boolean ok = - (Boolean) compile.invoke(compiler, - new Object[] {cmd.getArguments()}); + Method compile = c.getMethod("compile", String[].class); + Boolean ok = (Boolean) compile.invoke(compiler, + new Object[] {cmd.getArguments()}); return ok.booleanValue(); } catch (ClassNotFoundException ex) { throw new BuildException("Cannot use classic compiler, as it is " diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/AntVersion.java b/src/main/org/apache/tools/ant/taskdefs/condition/AntVersion.java index ec21d4b48..24a6bd831 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/AntVersion.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/AntVersion.java @@ -100,18 +100,17 @@ public class AntVersion extends Task implements Condition { private DeweyDecimal getVersion() { Project p = new Project(); p.init(); - char[] versionString = p.getProperty("ant.version").toCharArray(); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); boolean foundFirstDigit = false; - for (int i = 0; i < versionString.length; i++) { - if (Character.isDigit(versionString[i])) { - sb.append(versionString[i]); + for (char versionChar : p.getProperty("ant.version").toCharArray()) { + if (Character.isDigit(versionChar)) { + sb.append(versionChar); foundFirstDigit = true; } - if (versionString[i] == '.' && foundFirstDigit) { - sb.append(versionString[i]); + if (versionChar == '.' && foundFirstDigit) { + sb.append(versionChar); } - if (Character.isLetter(versionString[i]) && foundFirstDigit) { + if (Character.isLetter(versionChar) && foundFirstDigit) { break; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/HasMethod.java b/src/main/org/apache/tools/ant/taskdefs/condition/HasMethod.java index 002af7a7b..6b8d85f17 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/HasMethod.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/HasMethod.java @@ -167,10 +167,8 @@ public class HasMethod extends ProjectComponent implements Condition { } } - private boolean isFieldFound(Class clazz) { - Field[] fields = clazz.getDeclaredFields(); - for (int i = 0; i < fields.length; i++) { - Field fieldEntry = fields[i]; + private boolean isFieldFound(Class clazz) { + for (Field fieldEntry : clazz.getDeclaredFields()) { if (fieldEntry.getName().equals(field)) { return true; } @@ -178,10 +176,8 @@ public class HasMethod extends ProjectComponent implements Condition { return false; } - private boolean isMethodFound(Class clazz) { - Method[] methods = clazz.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - Method methodEntry = methods[i]; + private boolean isMethodFound(Class clazz) { + for (Method methodEntry : clazz.getDeclaredMethods()) { if (methodEntry.getName().equals(method)) { return true; } diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java index 79111bd4c..4782e0f2a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java @@ -441,8 +441,8 @@ public class CvsTagDiff extends AbstractCvsTask { CollectionUtils.flattenToString(packageNames)); DOM_WRITER.openElement(root, writer, 0, "\t"); writer.println(); - for (int i = 0, c = entries.length; i < c; i++) { - writeTagEntry(doc, writer, entries[i]); + for (CvsTagEntry entry : entries) { + writeTagEntry(doc, writer, entry); } DOM_WRITER.closeElement(root, writer, 0, "\t", true); writer.flush(); diff --git a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java index 186d71e08..1b2a72d93 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java @@ -27,8 +27,10 @@ import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.security.Provider; import java.security.Security; +import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; +import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; @@ -263,21 +265,20 @@ public class MimeMailer extends Mailer { || sfe.getValidSentAddresses().length == 0) { throw new BuildException("Couldn't reach any recipient", sfe); - } else { - Address[] invalid = sfe.getInvalidAddresses(); - if (invalid == null) { - invalid = new Address[0]; - } - for (int i = 0; i < invalid.length; i++) { - didntReach(invalid[i], "invalid", sfe); - } - Address[] validUnsent = sfe.getValidUnsentAddresses(); - if (validUnsent == null) { - validUnsent = new Address[0]; - } - for (int i = 0; i < validUnsent.length; i++) { - didntReach(validUnsent[i], "valid", sfe); - } + } + Address[] invalid = sfe.getInvalidAddresses(); + if (invalid == null) { + invalid = new Address[0]; + } + for (Address address : invalid) { + didntReach(address, "invalid", sfe); + } + Address[] validUnsent = sfe.getValidUnsentAddresses(); + if (validUnsent == null) { + validUnsent = new Address[0]; + } + for (Address address : validUnsent) { + didntReach(address, "valid", sfe); } } } catch (final MessagingException e) { @@ -287,20 +288,17 @@ public class MimeMailer extends Mailer { } } - private static InternetAddress[] internetAddresses(final Vector list) + private static InternetAddress[] internetAddresses(final Vector list) throws AddressException, UnsupportedEncodingException { - final int size = list.size(); - final InternetAddress[] addrs = new InternetAddress[size]; - - for (int i = 0; i < size; ++i) { - final EmailAddress addr = (EmailAddress) list.elementAt(i); + final List addrs = new ArrayList(); + for (final EmailAddress addr : list) { final String name = addr.getName(); - addrs[i] = (name == null) + addrs.add((name == null) ? new InternetAddress(addr.getAddress()) - : new InternetAddress(addr.getAddress(), name); + : new InternetAddress(addr.getAddress(), name)); } - return addrs; + return addrs.toArray(new InternetAddress[addrs.size()]); } private String parseCharSetFromMimeType(final String type) { diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java index b7c914c8c..1085f3a0a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java @@ -103,13 +103,13 @@ public class VmsCommandLauncher extends Java13CommandLauncher { // add the environment as logicals to the DCL script if (env != null) { int eqIndex; - for (int i = 0; i < env.length; i++) { - eqIndex = env[i].indexOf('='); + for (String variable : env) { + eqIndex = variable.indexOf('='); if (eqIndex != -1) { out.write("$ DEFINE/NOLOG "); - out.write(env[i].substring(0, eqIndex)); + out.write(variable.substring(0, eqIndex)); out.write(" \""); - out.write(env[i].substring(eqIndex + 1)); + out.write(variable.substring(eqIndex + 1)); out.write('\"'); out.newLine(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java index 1474ccecc..acbee87b6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java @@ -254,10 +254,10 @@ public class Native2Ascii extends MatchingTask { String message = "Converting " + count + " file" + (count != 1 ? "s" : "") + " from "; log(message + srcDir + " to " + destDir); - for (int i = 0; i < files.length; i++) { - String[] dest = m.mapFileName(files[i]); + for (String file : files) { + String[] dest = m.mapFileName(file); if (dest != null && dest.length > 0) { - convert(files[i], dest[0]); + convert(file, dest[0]); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java b/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java index 569f5ed73..e52713145 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java @@ -29,7 +29,7 @@ import java.io.OutputStream; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; -import java.util.Enumeration; +import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; @@ -122,7 +122,7 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware private URIResolver uriResolver; /** transformer output properties */ - private final Vector outputProperties = new Vector(); + private final Vector outputProperties = new Vector(); /** stylesheet parameters */ private final Hashtable params = new Hashtable(); @@ -334,9 +334,7 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware if (uriResolver != null) { transformer.setURIResolver(uriResolver); } - final int size = outputProperties.size(); - for (int i = 0; i < size; i++) { - final String[] pair = (String[]) outputProperties.elementAt(i); + for (String[] pair : outputProperties) { transformer.setOutputProperty(pair[0], pair[1]); } @@ -376,11 +374,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * Sets the parameters for the transformer. */ private void setTransformationParameters() { - for (final Enumeration enumeration = params.keys(); - enumeration.hasMoreElements();) { - final String name = (String) enumeration.nextElement(); - final Object value = params.get(name); - transformer.setParameter(name, value); + for (Map.Entry entry : params.entrySet()) { + transformer.setParameter(entry.getKey(), entry.getValue()); } } @@ -435,8 +430,7 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware // specific attributes for the transformer final int size = attributes.size(); - for (int i = 0; i < size; i++) { - final Object[] pair = attributes.get(i); + for (final Object[] pair : attributes) { tfactory.setAttribute((String) pair[0], pair[1]); } @@ -636,10 +630,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware setFactory(factory.getName()); // configure factory attributes - for (final Enumeration attrs = factory.getAttributes(); - attrs.hasMoreElements();) { - final XSLTProcess.Factory.Attribute attr = - (XSLTProcess.Factory.Attribute) attrs.nextElement(); + for (final XSLTProcess.Factory.Attribute attr + : Collections.list(factory.getAttributes())) { setAttribute(attr.getName(), attr.getValue()); } for (final XSLTProcess.Factory.Feature feature @@ -657,10 +649,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware // configure output properties - for (final Enumeration props = xsltTask.getOutputProperties(); - props.hasMoreElements();) { - final XSLTProcess.OutputProperty prop - = (XSLTProcess.OutputProperty) props.nextElement(); + for (final XSLTProcess.OutputProperty prop + : Collections.list(xsltTask.getOutputProperties())) { setOutputProperty(prop.getName(), prop.getValue()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/XMLValidateTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/XMLValidateTask.java index 7b9d3bb85..f47ec570c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/XMLValidateTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/XMLValidateTask.java @@ -74,7 +74,7 @@ public class XMLValidateTask extends Task { /** file to be validated */ protected File file = null; /** sets of file to be validated */ - protected Vector filesets = new Vector(); + protected Vector filesets = new Vector(); protected Path classpath; /** @@ -90,12 +90,12 @@ public class XMLValidateTask extends Task { // CheckStyle:VisibilityModifier ON /** The vector to store all attributes (features) to be set on the parser. **/ - private Vector attributeList = new Vector(); + private Vector attributeList = new Vector(); /** * List of properties. */ - private final Vector propertyList = new Vector(); + private final Vector propertyList = new Vector(); private XMLCatalog xmlCatalog = new XMLCatalog(); /** Message for successful validation */ @@ -287,42 +287,35 @@ public class XMLValidateTask extends Task { */ public void execute() throws BuildException { try { - int fileProcessed = 0; - if (file == null && (filesets.size() == 0)) { - throw new BuildException( - "Specify at least one source - " + "a file or a fileset."); - } - - + int fileProcessed = 0; + if (file == null && (filesets.size() == 0)) { + throw new BuildException( + "Specify at least one source - " + "a file or a fileset."); + } - if (file != null) { - if (file.exists() && file.canRead() && file.isFile()) { - doValidate(file); - fileProcessed++; - } else { - String errorMsg = "File " + file + " cannot be read"; - if (failOnError) { - throw new BuildException(errorMsg); + if (file != null) { + if (file.exists() && file.canRead() && file.isFile()) { + doValidate(file); + fileProcessed++; } else { - log(errorMsg, Project.MSG_ERR); + String errorMsg = "File " + file + " cannot be read"; + if (failOnError) { + throw new BuildException(errorMsg); + } else { + log(errorMsg, Project.MSG_ERR); + } } } - } - - final int size = filesets.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) filesets.elementAt(i); - DirectoryScanner ds = fs.getDirectoryScanner(getProject()); - String[] files = ds.getIncludedFiles(); - - for (int j = 0; j < files.length; j++) { - File srcFile = new File(fs.getDir(getProject()), files[j]); - doValidate(srcFile); - fileProcessed++; + for (FileSet fs : filesets) { + DirectoryScanner ds = fs.getDirectoryScanner(getProject()); + for (String fileName : ds.getIncludedFiles()) { + File srcFile = new File(fs.getDir(getProject()), fileName); + doValidate(srcFile); + fileProcessed++; + } } - } - onSuccessfulValidation(fileProcessed); + onSuccessfulValidation(fileProcessed); } finally { cleanup(); } @@ -355,16 +348,12 @@ public class XMLValidateTask extends Task { setFeature(XmlConstants.FEATURE_VALIDATION, true); } // set the feature from the attribute list - final int attSize = attributeList.size(); - for (int i = 0; i < attSize; i++) { - Attribute feature = (Attribute) attributeList.elementAt(i); + for (Attribute feature : attributeList) { setFeature(feature.getName(), feature.getValue()); } // Sets properties - final int propSize = propertyList.size(); - for (int i = 0; i < propSize; i++) { - final Property prop = (Property) propertyList.elementAt(i); + for (Property prop : propertyList) { setProperty(prop.getName(), prop.getValue()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java index 790cad6bc..d39fb9ecc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java @@ -286,16 +286,16 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { int endOfPath = descriptorFileName.lastIndexOf(File.separator); String relativePath = descriptorFileName.substring(0, endOfPath + 1); - for (int i = 0; i < cmpDescriptors.length; i++) { - int endOfCmp = cmpDescriptors[i].lastIndexOf('/'); - String cmpDescriptor = cmpDescriptors[i].substring(endOfCmp + 1); + for (String descriptor : cmpDescriptors) { + int endOfCmp = descriptor.lastIndexOf('/'); + String cmpDescriptor = descriptor.substring(endOfCmp + 1); File cmpFile = new File(baseDir, relativePath + cmpDescriptor); if (!cmpFile.exists()) { throw new BuildException("The CMP descriptor file (" + cmpFile + ") could not be found.", getLocation()); } - files.put(cmpDescriptors[i], cmpFile); + files.put(descriptor, cmpFile); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java index 447a28826..23116d387 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; @@ -898,7 +897,7 @@ public class IPlanetEjbc { private boolean cmp = false; // Does this EJB support CMP? private boolean iiop = false; // Does this EJB support IIOP? private boolean hasession = false; // Does this EJB require failover? - private List cmpDescriptors = new ArrayList(); // CMP descriptor list + private List cmpDescriptors = new ArrayList(); // CMP descriptor list /** * Construct a new EJBInfo object with the given name. @@ -1233,10 +1232,8 @@ public class IPlanetEjbc { * Loop through each stub/skeleton class that must be generated, and * determine (if all exist) which file has the most recent timestamp */ - for (int i = 0; i < classnames.length; i++) { - - String pathToClass = - classnames[i].replace('.', File.separatorChar) + ".class"; + for (String classname : classnames) { + String pathToClass = classname.replace('.', File.separatorChar) + ".class"; File classFile = new File(destDir, pathToClass); /* @@ -1330,9 +1327,8 @@ public class IPlanetEjbc { + "\n\r iiop: " + iiop + "\n\r hasession: " + hasession; - Iterator i = cmpDescriptors.iterator(); - while (i.hasNext()) { - s += "\n\r CMP Descriptor: " + i.next(); + for (String cmpDescriptor : cmpDescriptors) { + s += "\n\r CMP Descriptor: " + cmpDescriptor; } return s; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java index 8f65fd43d..e631d3ac4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java @@ -109,9 +109,8 @@ public final class ExtensionUtil { final DirectoryScanner scanner = fileSet.getDirectoryScanner(project); final File basedir = scanner.getBasedir(); - final String[] files = scanner.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - final File file = new File(basedir, files[ i ]); + for (String fileName : scanner.getIncludedFiles()) { + final File file = new File(basedir, fileName); loadExtensions(file, extensions, includeImpl, includeURL); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java index 80627f4c2..3eebc63a5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java @@ -71,32 +71,28 @@ class LibraryDisplayer { printLine(size); if (0 != available.length) { System.out.println("Extensions Supported By Library:"); - for (int i = 0; i < available.length; i++) { - final Extension extension = available[ i ]; - System.out.println(extension.toString()); + for (Extension extension : available) { + System.out.println(extension); } } if (0 != required.length) { System.out.println("Extensions Required By Library:"); - for (int i = 0; i < required.length; i++) { - final Extension extension = required[ i ]; - System.out.println(extension.toString()); + for (Extension extension : required) { + System.out.println(extension); } } if (0 != options.length) { System.out.println("Extensions that will be used by Library if present:"); - for (int i = 0; i < options.length; i++) { - final Extension extension = options[ i ]; - System.out.println(extension.toString()); + for (Extension option : options) { + System.out.println(option); } } if (0 != specifications.length) { System.out.println("Specifications Supported By Library:"); - for (int i = 0; i < specifications.length; i++) { - final Specification specification = specifications[ i ]; + for (Specification specification : specifications) { displaySpecification(specification); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java index 26c59969a..330a98cf8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java @@ -500,10 +500,9 @@ public class Translate extends MatchingTask { for (int i = 0; i < size; i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); - String[] srcFiles = ds.getIncludedFiles(); - for (int j = 0; j < srcFiles.length; j++) { + for (String srcFile : ds.getIncludedFiles()) { try { - File dest = FILE_UTILS.resolveFile(toDir, srcFiles[j]); + File dest = FILE_UTILS.resolveFile(toDir, srcFile); //Make sure parent dirs exist, else, create them. try { File destDir = new File(dest.getParent()); @@ -516,7 +515,7 @@ public class Translate extends MatchingTask { Project.MSG_DEBUG); } destLastModified = dest.lastModified(); - File src = FILE_UTILS.resolveFile(ds.getBasedir(), srcFiles[j]); + File src = FILE_UTILS.resolveFile(ds.getBasedir(), srcFile); srcLastModified = src.lastModified(); //Check to see if dest file has to be recreated boolean needsWork = forceOverwrite @@ -530,14 +529,12 @@ public class Translate extends MatchingTask { } } if (needsWork) { - log("Processing " + srcFiles[j], - Project.MSG_DEBUG); + log("Processing " + srcFile, Project.MSG_DEBUG); translateOneFile(src, dest); ++filesProcessed; } else { - log("Skipping " + srcFiles[j] - + " as destination file is up to date", - Project.MSG_VERBOSE); + log("Skipping " + srcFile + " as destination file is up to date", + Project.MSG_VERBOSE); } } catch (IOException ioe) { throw new BuildException(ioe.getMessage(), getLocation()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java b/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java index 108d2e272..635b3bf2f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java @@ -223,8 +223,7 @@ public class Image extends MatchingTask { final File dstDir, final FileNameMapper mapper) { int writeCount = 0; - for (int i = 0; i < srcNames.length; ++i) { - final String srcName = srcNames[i]; + for (final String srcName : srcNames) { final File srcFile = new File(srcDir, srcName).getAbsoluteFile(); final String[] dstNames = mapper.mapFileName(srcName); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java index 0c143cfcd..ae4a892f9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java @@ -279,10 +279,7 @@ public class jlink { */ private void addDirContents(ZipOutputStream output, File dir, String prefix, boolean compress) throws IOException { - String[] contents = dir.list(); - - for (int i = 0; i < contents.length; ++i) { - String name = contents[i]; + for (String name : dir.list()) { File file = new File(dir, name); if (file.isDirectory()) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java index 4cadace35..42cab7e99 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java @@ -481,8 +481,8 @@ public class JspC extends MatchingTask { // lists and compile lists resetFileLists(); int filecount = 0; - for (int i = 0; i < list.length; i++) { - File srcDir = getProject().resolveFile(list[i]); + for (String fileName : list) { + File srcDir = getProject().resolveFile(fileName); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java index 08070248f..8eeccc87d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java @@ -112,8 +112,8 @@ public final class BatchTest extends BaseTest { void addTestsTo(Vector v) { JUnitTest[] tests = createAllJUnitTest(); v.ensureCapacity(v.size() + tests.length); - for (int i = 0; i < tests.length; i++) { - v.addElement(tests[i]); + for (JUnitTest test : tests) { + v.addElement(test); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java index e7ffa6756..c6a338b8c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; @@ -89,7 +88,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm private static final String LOG_PREFIX = " [junit]"; /** Class names of failed tests without duplicates. */ - private static SortedSet/**/ failedTests = new TreeSet(); + private static SortedSet failedTests = new TreeSet(); /** A writer for writing the generated source to. */ private BufferedWriter writer; @@ -299,8 +298,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm writer.newLine(); writer.write(" TestSuite suite = new TestSuite();"); writer.newLine(); - for (Iterator iter = failedTests.iterator(); iter.hasNext();) { - TestInfos testInfos = (TestInfos) iter.next(); + for (TestInfos testInfos : failedTests) { writer.write(" suite.addTest("); writer.write(String.valueOf(testInfos)); writer.write(");"); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java index f03a409b4..603495bbc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java @@ -137,9 +137,9 @@ public class JUnit4TestMethodAdapter implements Test { throw new IllegalArgumentException("methodNames is "); } methodsListDescription = Description.createSuiteDescription(testClass); - for (int i = 0; i < methodNames.length; i++) { + for (String methodName : methodNames) { methodsListDescription.addChild( - Description.createTestDescription(testClass, methodNames[i])); + Description.createTestDescription(testClass, methodName)); } this.testClass = testClass; this.methodNames = methodNames; @@ -176,12 +176,11 @@ public class JUnit4TestMethodAdapter implements Test { if (methodNames.length == 0) { buf.append("No methods"); } else { - buf.append(methodNames.length == 1 ? "Method" : "Methods"); - buf.append(' '); - buf.append(methodNames[0]); - for (int i = 1; i < methodNames.length; i++) { - buf.append(',').append(methodNames[i]); + buf.append(methodNames.length == 1 ? "Method " : "Methods "); + for (String methodName : methodNames) { + buf.append(methodName).append(','); } + buf.setLength(buf.length() - 1); } buf.append('(').append(testClass.getName()).append(')'); return buf.toString(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java index e587474bf..a4f856344 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java @@ -34,6 +34,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; @@ -968,18 +969,13 @@ public class JUnitTask extends Task { /* I assume we don't want to do this with "per batch" forking. */ List newlist = new ArrayList(); if (forkMode.getValue().equals(ForkMode.PER_TEST)) { - final Iterator i1 = testList.iterator(); - while (i1.hasNext()) { - final List l = i1.next(); - if (l.size() == 1) { - newlist.add(l); + for (List list : testList) { + if (list.size() == 1) { + newlist.add(list); } else { - final Iterator i2 = l.iterator(); - while (i2.hasNext()) { - final List tmpSingleton = new ArrayList(); - tmpSingleton.add(i2.next()); - newlist.add(tmpSingleton); - } + for (JUnitTest test : list) { + newlist.add(Collections.singletonList(test)); + } } } } else { @@ -1213,8 +1209,7 @@ public class JUnitTask extends Task { StringBuffer formatterArg = new StringBuffer(STRING_BUFFER_SIZE); final FormatterElement[] feArray = mergeFormatters(test); - for (int i = 0; i < feArray.length; i++) { - final FormatterElement fe = feArray[i]; + for (final FormatterElement fe : feArray) { if (fe.shouldUse(this)) { formatterArg.append(Constants.FORMATTER); formatterArg.append(fe.getClassname()); @@ -1264,9 +1259,9 @@ public class JUnitTask extends Task { final String[] environment = env.getVariables(); if (environment != null) { - for (int i = 0; i < environment.length; i++) { - log("Setting environment variable: " + environment[i], - Project.MSG_VERBOSE); + for (String variable : environment) { + log("Setting environment variable: " + variable, + Project.MSG_VERBOSE); } } execute.setNewenvironment(newEnvironment); @@ -1635,9 +1630,7 @@ public class JUnitTask extends Task { runner.setPermissions(perm); - final FormatterElement[] feArray = mergeFormatters(test); - for (int i = 0; i < feArray.length; i++) { - final FormatterElement fe = feArray[i]; + for (final FormatterElement fe : mergeFormatters(test)) { if (fe.shouldUse(this)) { final File outFile = getOutput(fe, test); if (outFile != null) { @@ -1958,8 +1951,7 @@ public class JUnitTask extends Task { test.setCounts(1, 0, 1, 0); test.setProperties(getProject().getProperties()); - for (int i = 0; i < feArray.length; i++) { - final FormatterElement fe = feArray[i]; + for (final FormatterElement fe : feArray) { if (fe.shouldUse(this)) { final JUnitTaskMirror.JUnitResultFormatterMirror formatter = fe.createFormatter(classLoader); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java index d4217ce5a..84104443f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java @@ -364,9 +364,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR public void run() { res = new IgnoredTestResult(); res.addListener(wrapListener(this)); - final int size = formatters.size(); - for (int i = 0; i < size; i++) { - res.addListener(wrapListener((TestListener) formatters.elementAt(i))); + for (JUnitTaskMirror.JUnitResultFormatterMirror f : formatters) { + res.addListener(wrapListener((TestListener) f)); } final ByteArrayOutputStream errStrm = new ByteArrayOutputStream(); @@ -507,9 +506,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR suite = TestSuite.createTest(testClass, methods[0]); } else { final TestSuite testSuite = new TestSuite(testClass.getName()); - for (int i = 0; i < methods.length; i++) { - testSuite.addTest( - TestSuite.createTest(testClass, methods[i])); + for (String method : methods) { + testSuite.addTest(TestSuite.createTest(testClass, method)); } suite = testSuite; } @@ -527,9 +525,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR fireStartTestSuite(); startTestSuiteSuccess = true; if (exception != null) { // had an exception constructing suite - final int formatterSize = formatters.size(); - for (int i = 0; i < formatterSize; i++) { - ((TestListener) formatters.elementAt(i)).addError(null, exception); + for (JUnitTaskMirror.JUnitResultFormatterMirror f : formatters) { + ((TestListener) f).addError(null, exception); } junitTest.setCounts(1, 0, 1, 0); junitTest.setRunTime(0); @@ -825,27 +822,22 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } private void sendOutAndErr(final String out, final String err) { - final int size = formatters.size(); - for (int i = 0; i < size; i++) { - final JUnitResultFormatter formatter = - ((JUnitResultFormatter) formatters.elementAt(i)); - + for (JUnitTaskMirror.JUnitResultFormatterMirror f : formatters) { + final JUnitResultFormatter formatter = (JUnitResultFormatter) f; formatter.setSystemOutput(out); formatter.setSystemError(err); } } private void fireStartTestSuite() { - final int size = formatters.size(); - for (int i = 0; i < size; i++) { - ((JUnitResultFormatter) formatters.elementAt(i)).startTestSuite(junitTest); + for (JUnitTaskMirror.JUnitResultFormatterMirror f : formatters) { + ((JUnitResultFormatter) f).startTestSuite(junitTest); } } private void fireEndTestSuite() { - final int size = formatters.size(); - for (int i = 0; i < size; i++) { - ((JUnitResultFormatter) formatters.elementAt(i)).endTestSuite(junitTest); + for (JUnitTaskMirror.JUnitResultFormatterMirror f : formatters) { + ((JUnitResultFormatter) f).endTestSuite(junitTest); } } @@ -924,52 +916,52 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR args[0] = args[0].substring(Constants.TESTSFILE.length()); } - for (int i = 1; i < args.length; i++) { - if (args[i].startsWith(Constants.METHOD_NAMES)) { + for (String arg : args) { + if (arg.startsWith(Constants.METHOD_NAMES)) { try { - final String methodsList = args[i].substring(Constants.METHOD_NAMES.length()); + final String methodsList = arg.substring(Constants.METHOD_NAMES.length()); methods = JUnitTest.parseTestMethodNamesList(methodsList); } catch (final IllegalArgumentException ex) { - System.err.println("Invalid specification of test method names: " + args[i]); + System.err.println("Invalid specification of test method names: " + arg); System.exit(ERRORS); } - } else if (args[i].startsWith(Constants.HALT_ON_ERROR)) { - haltError = Project.toBoolean(args[i].substring(Constants.HALT_ON_ERROR.length())); - } else if (args[i].startsWith(Constants.HALT_ON_FAILURE)) { - haltFail = Project.toBoolean(args[i].substring(Constants.HALT_ON_FAILURE.length())); - } else if (args[i].startsWith(Constants.FILTERTRACE)) { - stackfilter = Project.toBoolean(args[i].substring(Constants.FILTERTRACE.length())); - } else if (args[i].startsWith(Constants.CRASHFILE)) { - crashFile = args[i].substring(Constants.CRASHFILE.length()); + } else if (arg.startsWith(Constants.HALT_ON_ERROR)) { + haltError = Project.toBoolean(arg.substring(Constants.HALT_ON_ERROR.length())); + } else if (arg.startsWith(Constants.HALT_ON_FAILURE)) { + haltFail = Project.toBoolean(arg.substring(Constants.HALT_ON_FAILURE.length())); + } else if (arg.startsWith(Constants.FILTERTRACE)) { + stackfilter = Project.toBoolean(arg.substring(Constants.FILTERTRACE.length())); + } else if (arg.startsWith(Constants.CRASHFILE)) { + crashFile = arg.substring(Constants.CRASHFILE.length()); registerTestCase(Constants.BEFORE_FIRST_TEST); - } else if (args[i].startsWith(Constants.FORMATTER)) { + } else if (arg.startsWith(Constants.FORMATTER)) { try { - createAndStoreFormatter(args[i].substring(Constants.FORMATTER.length())); + createAndStoreFormatter(arg.substring(Constants.FORMATTER.length())); } catch (final BuildException be) { System.err.println(be.getMessage()); System.exit(ERRORS); } - } else if (args[i].startsWith(Constants.PROPSFILE)) { - final FileInputStream in = new FileInputStream(args[i] + } else if (arg.startsWith(Constants.PROPSFILE)) { + final FileInputStream in = new FileInputStream(arg .substring(Constants.PROPSFILE.length())); props.load(in); in.close(); - } else if (args[i].startsWith(Constants.SHOWOUTPUT)) { - showOut = Project.toBoolean(args[i].substring(Constants.SHOWOUTPUT.length())); - } else if (args[i].startsWith(Constants.LOGTESTLISTENEREVENTS)) { + } else if (arg.startsWith(Constants.SHOWOUTPUT)) { + showOut = Project.toBoolean(arg.substring(Constants.SHOWOUTPUT.length())); + } else if (arg.startsWith(Constants.LOGTESTLISTENEREVENTS)) { logTestListenerEvents = Project.toBoolean( - args[i].substring(Constants.LOGTESTLISTENEREVENTS.length())); - } else if (args[i].startsWith(Constants.OUTPUT_TO_FORMATTERS)) { + arg.substring(Constants.LOGTESTLISTENEREVENTS.length())); + } else if (arg.startsWith(Constants.OUTPUT_TO_FORMATTERS)) { outputToFormat = Project.toBoolean( - args[i].substring(Constants.OUTPUT_TO_FORMATTERS.length())); - } else if (args[i].startsWith(Constants.LOG_FAILED_TESTS)) { + arg.substring(Constants.OUTPUT_TO_FORMATTERS.length())); + } else if (arg.startsWith(Constants.LOG_FAILED_TESTS)) { logFailedTests = Project.toBoolean( - args[i].substring(Constants.LOG_FAILED_TESTS.length())); - } else if (args[i].startsWith(Constants.SKIP_NON_TESTS)) { + arg.substring(Constants.LOG_FAILED_TESTS.length())); + } else if (arg.startsWith(Constants.SKIP_NON_TESTS)) { skipNonTests = Project.toBoolean( - args[i].substring(Constants.SKIP_NON_TESTS.length())); - } else if (args[i].startsWith(Constants.THREADID)) { - antThreadID = Integer.parseInt(args[i].substring(Constants.THREADID.length())); + arg.substring(Constants.SKIP_NON_TESTS.length())); + } else if (arg.startsWith(Constants.THREADID)) { + antThreadID = Integer.parseInt(arg.substring(Constants.THREADID.length())); } } @@ -1045,7 +1037,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR System.exit(returnCode); } - private static Vector fromCmdLine = new Vector(); + private static Vector fromCmdLine = new Vector(); private static void transferFormatters(final JUnitTestRunner runner, final JUnitTest test) { @@ -1079,9 +1071,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR registerTestCase(JUnitVersionHelper.getTestCaseName(arg0)); } }); - final int size = fromCmdLine.size(); - for (int i = 0; i < size; i++) { - final FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i); + for (FormatterElement fe : fromCmdLine) { if (multipleTests && fe.getUseFile()) { final File destFile = new File(test.getTodir(), test.getOutfile() + fe.getExtension()); @@ -1163,8 +1153,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } private static boolean filterLine(final String line) { - for (int i = 0; i < DEFAULT_TRACE_FILTERS.length; i++) { - if (line.indexOf(DEFAULT_TRACE_FILTERS[i]) != -1) { + for (String filter : DEFAULT_TRACE_FILTERS) { + if (line.indexOf(filter) != -1) { return true; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java index 1ba6ff6d1..a85123377 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java @@ -42,7 +42,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; - /** * Aggregates all <junit> XML formatter testsuite data under * a specific directory and transforms the results via XSLT. @@ -244,15 +243,12 @@ public class XMLResultAggregator extends Task implements XMLConstants { generatedId = 0; // get all files and add them to the document - File[] files = getFiles(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; + for (File file : getFiles()) { try { log("Parsing file: '" + file + "'", Project.MSG_VERBOSE); if (file.length() > 0) { - Document testsuiteDoc - = builder.parse( - FileUtils.getFileUtils().toURI(files[i].getAbsolutePath())); + Document testsuiteDoc = builder.parse(FileUtils + .getFileUtils().toURI(file.getAbsolutePath())); Element elem = testsuiteDoc.getDocumentElement(); // make sure that this is REALLY a testsuite. if (TESTSUITE.equals(elem.getNodeName())) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java index da4836fde..afb88d973 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java @@ -74,10 +74,10 @@ public final class KaffeNative2Ascii extends DefaultNative2Ascii { * * @return null if neither class can get loaded. */ - private static Class getN2aClass() { - for (int i = 0; i < N2A_CLASSNAMES.length; i++) { + private static Class getN2aClass() { + for (String className : N2A_CLASSNAMES) { try { - return Class.forName(N2A_CLASSNAMES[i]); + return Class.forName(className); } catch (ClassNotFoundException cnfe) { // Ignore } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java index c55234442..b171df506 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java @@ -240,7 +240,7 @@ public class FTP extends Task implements FTPTaskConfig { */ public String getParent() { String result = ""; - for(int i = 0; i < parts.length - 1; i++){ + for (int i = 0; i < parts.length - 1; i++){ result += File.separatorChar + parts[i]; } return result; @@ -390,10 +390,10 @@ public class FTP extends Task implements FTPTaskConfig { Hashtable newroots = new Hashtable(); // put in the newroots vector the include patterns without // wildcard tokens - for (int icounter = 0; icounter < includes.length; icounter++) { - String newpattern = - SelectorUtils.rtrimWildcardTokens(includes[icounter]); - newroots.put(newpattern, includes[icounter]); + for (String include : includes) { + String newpattern + = SelectorUtils.rtrimWildcardTokens(include); + newroots.put(newpattern, include); } if (remotedir == null) { try { @@ -505,11 +505,10 @@ public class FTP extends Task implements FTPTaskConfig { ftp.changeToParentDirectory(); return; } - for (int i = 0; i < newfiles.length; i++) { - FTPFile file = newfiles[i]; + for (FTPFile file : newfiles) { if (file != null - && !".".equals(file.getName()) - && !"..".equals(file.getName())) { + && !".".equals(file.getName()) + && !"..".equals(file.getName())) { String name = vpath + file.getName(); scannedDirs.put(name, new FTPFileProxy(file)); if (isFunctioningAsDirectory(ftp, dir, file)) { @@ -519,7 +518,7 @@ public class FTP extends Task implements FTPTaskConfig { slowScanAllowed = false; } else if (isIncluded(name)) { accountForIncludedDir(name, - new AntFTPFile(ftp, file, completePath) , fast); + new AntFTPFile(ftp, file, completePath), fast); } else { dirsNotIncluded.addElement(name); if (fast && couldHoldIncluded(name)) { @@ -750,14 +749,14 @@ public class FTP extends Task implements FTPTaskConfig { } } private String fiddleName(String origin) { - StringBuffer result = new StringBuffer(); - for (int icounter = 0; icounter < origin.length(); icounter++) { - if (Character.isLowerCase(origin.charAt(icounter))) { - result.append(Character.toUpperCase(origin.charAt(icounter))); - } else if (Character.isUpperCase(origin.charAt(icounter))) { - result.append(Character.toLowerCase(origin.charAt(icounter))); + StringBuilder result = new StringBuilder(); + for (char ch : origin.toCharArray()) { + if (Character.isLowerCase(ch)) { + result.append(Character.toUpperCase(ch)); + } else if (Character.isUpperCase(ch)) { + result.append(Character.toLowerCase(ch)); } else { - result.append(origin.charAt(icounter)); + result.append(ch); } } return result.toString(); @@ -805,7 +804,7 @@ public class FTP extends Task implements FTPTaskConfig { public AntFTPFile(AntFTPFile parent, String path) { this.parent = parent; this.client = parent.client; - Vector pathElements = SelectorUtils.tokenizePath(path); + Vector pathElements = SelectorUtils.tokenizePath(path); try { boolean result = this.client.changeWorkingDirectory(parent.getAbsolutePath()); //this should not happen, except if parent has been deleted by another process @@ -817,9 +816,7 @@ public class FTP extends Task implements FTPTaskConfig { throw new BuildException("could not change working dir to " + parent.curpwd); } - final int size = pathElements.size(); - for (int fcount = 0; fcount < size - 1; fcount++) { - String currentPathElement = (String) pathElements.elementAt(fcount); + for (String currentPathElement : pathElements) { try { boolean result = this.client.changeWorkingDirectory(currentPathElement); if (!result && !isCaseSensitive() @@ -836,12 +833,12 @@ public class FTP extends Task implements FTPTaskConfig { + currentPathElement; } catch (IOException ioe) { throw new BuildException("could not change working dir to " - + (String) pathElements.elementAt(fcount) + + currentPathElement + " from " + this.curpwd); } } - String lastpathelement = (String) pathElements.elementAt(size - 1); + String lastpathelement = pathElements.elementAt(pathElements.size() - 1); FTPFile [] theFiles = listFiles(this.curpwd); this.ftpFile = getFile(theFiles, lastpathelement); } @@ -855,14 +852,13 @@ public class FTP extends Task implements FTPTaskConfig { String soughtPathElement) { // we are already in the right path, so the second parameter // is false - FTPFile[] theFiles = listFiles(parentPath, false); - if (theFiles == null) { + FTPFile[] files = listFiles(parentPath, false); + if (files == null) { return null; } - for (int icounter = 0; icounter < theFiles.length; icounter++) { - if (theFiles[icounter] != null - && theFiles[icounter].getName().equalsIgnoreCase(soughtPathElement)) { - return theFiles[icounter].getName(); + for (FTPFile file : files) { + if (file != null && file.getName().equalsIgnoreCase(soughtPathElement)) { + return file.getName(); } } return null; @@ -1783,11 +1779,10 @@ public class FTP extends Task implements FTPTaskConfig { this.granularityMillis = this.timestampGranularity.getMilliseconds(action); } - for (int i = 0; i < dsfiles.length; i++) { - final String dsfile = dsfiles[i]; + for (final String dsfile : dsfiles) { executeRetryable(h, new Retryable() { - public void execute() throws IOException { - switch (action) { + public void execute() throws IOException { + switch (action) { case SEND_FILES: sendFile(ftp, fdir, dsfile); break; @@ -1802,14 +1797,14 @@ public class FTP extends Task implements FTPTaskConfig { break; case CHMOD: doSiteCommand(ftp, "chmod " + chmod - + " " + resolveFile(dsfile)); + + " " + resolveFile(dsfile)); transferred++; break; default: throw new BuildException("unknown ftp action " + action); - } } - }, dsfile); + } + }, dsfile); } } } finally { @@ -1979,7 +1974,7 @@ public class FTP extends Task implements FTPTaskConfig { * find a suitable name for local and remote temporary file */ private File findFileName(FTPClient ftp) { - FTPFile [] theFiles = null; + FTPFile[] files = null; final int maxIterations = 1000; for (int counter = 1; counter < maxIterations; counter++) { File localFile = FILE_UTILS.createTempFile( @@ -1988,12 +1983,11 @@ public class FTP extends Task implements FTPTaskConfig { String fileName = localFile.getName(); boolean found = false; try { - if (theFiles == null) { - theFiles = ftp.listFiles(); + if (files == null) { + files = ftp.listFiles(); } - for (int counter2 = 0; counter2 < theFiles.length; counter2++) { - if (theFiles[counter2] != null - && theFiles[counter2].getName().equals(fileName)) { + for (FTPFile file : files) { + if (file != null && file.getName().equals(fileName)) { found = true; break; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java index 74ef819d0..b7235e19d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java @@ -291,10 +291,10 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { Hashtable newroots = new Hashtable(); // put in the newroots vector the include patterns without // wildcard tokens - for (int icounter = 0; icounter < includes.length; icounter++) { + for (String include : includes) { String newpattern = - SelectorUtils.rtrimWildcardTokens(includes[icounter]); - newroots.put(newpattern, includes[icounter]); + SelectorUtils.rtrimWildcardTokens(include); + newroots.put(newpattern, include); } if (task.getRemotedir() == null) { try { @@ -412,11 +412,10 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { ftp.changeToParentDirectory(); return; } - for (int i = 0; i < newfiles.length; i++) { - FTPFile file = newfiles[i]; + for (FTPFile file : newfiles) { if (file != null - && !file.getName().equals(".") - && !file.getName().equals("..")) { + && !".".equals(file.getName()) + && !"..".equals(file.getName())) { String name = vpath + file.getName(); scannedDirs.put(name, new FTPFileProxy(file)); if (isFunctioningAsDirectory(ftp, dir, file)) { @@ -426,7 +425,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { slowScanAllowed = false; } else if (isIncluded(name)) { accountForIncludedDir(name, - new AntFTPFile(ftp, file, completePath) , fast); + new AntFTPFile(ftp, file, completePath), fast); } else { dirsNotIncluded.addElement(name); if (fast && couldHoldIncluded(name)) { @@ -482,9 +481,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * @param fast boolean */ private void accountForIncludedDir(String name, AntFTPFile file, boolean fast) { - if (!dirsIncluded.contains(name) - && !dirsExcluded.contains(name)) { - + if (!dirsIncluded.contains(name) && !dirsExcluded.contains(name)) { if (!isExcluded(name)) { if (fast) { if (file.isSymbolicLink()) { @@ -658,14 +655,14 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } private String fiddleName(String origin) { - StringBuffer result = new StringBuffer(); - for (int icounter = 0; icounter < origin.length(); icounter++) { - if (Character.isLowerCase(origin.charAt(icounter))) { - result.append(Character.toUpperCase(origin.charAt(icounter))); - } else if (Character.isUpperCase(origin.charAt(icounter))) { - result.append(Character.toLowerCase(origin.charAt(icounter))); + StringBuilder result = new StringBuilder(); + for (char ch : origin.toCharArray()) { + if (Character.isLowerCase(ch)) { + result.append(Character.toUpperCase(ch)); + } else if (Character.isUpperCase(ch)) { + result.append(Character.toLowerCase(ch)); } else { - result.append(origin.charAt(icounter)); + result.append(ch); } } return result.toString(); @@ -713,7 +710,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public AntFTPFile(AntFTPFile parent, String path) { this.parent = parent; this.client = parent.client; - Vector pathElements = SelectorUtils.tokenizePath(path); + Vector pathElements = SelectorUtils.tokenizePath(path); try { boolean result = this.client.changeWorkingDirectory(parent.getAbsolutePath()); //this should not happen, except if parent has been deleted by another process @@ -722,18 +719,15 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } this.curpwd = parent.getAbsolutePath(); } catch (IOException ioe) { - throw new BuildException("could not change working dir to " - + parent.curpwd); + throw new BuildException("could not change working dir to " + parent.curpwd); } - final int size = pathElements.size(); - for (int fcount = 0; fcount < size - 1; fcount++) { - String currentPathElement = (String) pathElements.elementAt(fcount); + for (String currentPathElement : pathElements) { try { boolean result = this.client.changeWorkingDirectory(currentPathElement); if (!result && !isCaseSensitive() && (remoteSystemCaseSensitive || !remoteSensitivityChecked)) { currentPathElement = findPathElementCaseUnsensitive(this.curpwd, - currentPathElement); + currentPathElement); if (currentPathElement == null) { return; } @@ -744,14 +738,12 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { + currentPathElement; } catch (IOException ioe) { throw new BuildException("could not change working dir to " - + (String) pathElements.elementAt(fcount) - + " from " + this.curpwd); + + currentPathElement + " from " + this.curpwd); } } - String lastpathelement = (String) pathElements.elementAt(size - 1); - FTPFile [] theFiles = listFiles(this.curpwd); - this.ftpFile = getFile(theFiles, lastpathelement); + String lastpathelement = pathElements.get(pathElements.size() - 1); + this.ftpFile = getFile(listFiles(this.curpwd), lastpathelement); } /** * find a file in a directory in case insensitive way @@ -763,14 +755,13 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String soughtPathElement) { // we are already in the right path, so the second parameter // is false - FTPFile[] theFiles = listFiles(parentPath, false); - if (theFiles == null) { + FTPFile[] files = listFiles(parentPath, false); + if (files == null) { return null; } - for (int icounter = 0; icounter < theFiles.length; icounter++) { - if (theFiles[icounter] != null - && theFiles[icounter].getName().equalsIgnoreCase(soughtPathElement)) { - return theFiles[icounter].getName(); + for (FTPFile file : files) { + if (file != null && file.getName().equalsIgnoreCase(soughtPathElement)) { + return file.getName(); } } return null; @@ -1174,8 +1165,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { task.setGranularityMillis(task.getTimestampGranularity() .getMilliseconds(task.getAction())); } - for (int i = 0; i < dsfiles.length; i++) { - final String dsfile = dsfiles[i]; + for (final String dsfile : dsfiles) { executeRetryable(h, new Retryable() { public void execute() throws IOException { switch (task.getAction()) { @@ -1373,7 +1363,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * find a suitable name for local and remote temporary file */ private File findFileName(FTPClient ftp) { - FTPFile [] theFiles = null; + FTPFile[] files = null; final int maxIterations = 1000; for (int counter = 1; counter < maxIterations; counter++) { File localFile = FILE_UTILS.createTempFile( @@ -1382,12 +1372,11 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String fileName = localFile.getName(); boolean found = false; try { - if (theFiles == null) { - theFiles = ftp.listFiles(); + if (files == null) { + files = ftp.listFiles(); } - for (int counter2 = 0; counter2 < theFiles.length; counter2++) { - if (theFiles[counter2] != null - && theFiles[counter2].getName().equals(fileName)) { + for (FTPFile file : files) { + if (file != null && file.getName().equals(fileName)) { found = true; break; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sound/SoundTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/sound/SoundTask.java index dfb6e69ac..48e36b0f7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sound/SoundTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sound/SoundTask.java @@ -147,10 +147,9 @@ public class SoundTask extends Task { if (source.exists()) { if (source.isDirectory()) { // get the list of files in the dir - String[] entries = source.list(); - Vector files = new Vector(); - for (int i = 0; i < entries.length; i++) { - File f = new File(source, entries[i]); + Vector files = new Vector(); + for (String file : source.list()) { + File f = new File(source, file); if (f.isFile()) { files.addElement(f); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java index fb80c8cf7..bbc186ab2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java @@ -86,10 +86,9 @@ public class SSHSession extends SSHBase { * tunnel specifications */ public void setLocaltunnels(final String tunnels) { - final String[] specs = tunnels.split(", "); - for (int i = 0; i < specs.length; i++) { - if (specs[i].length() > 0) { - final String[] spec = specs[i].split(":", 3); + for (String tunnelSpec : tunnels.split(", ")) { + if (tunnelSpec.length() > 0) { + final String[] spec = tunnelSpec.split(":", 3); final int lport = Integer.parseInt(spec[0]); final String rhost = spec[1]; final int rport = Integer.parseInt(spec[2]); @@ -109,10 +108,9 @@ public class SSHSession extends SSHBase { * tunnel specifications */ public void setRemotetunnels(final String tunnels) { - final String[] specs = tunnels.split(", "); - for (int i = 0; i < specs.length; i++) { - if (specs[i].length() > 0) { - final String[] spec = specs[i].split(":", 3); + for (String tunnelSpec : tunnels.split(", ")) { + if (tunnelSpec.length() > 0) { + final String[] spec = tunnelSpec.split(":", 3); final int rport = Integer.parseInt(spec[0]); final String lhost = spec[1]; final int lport = Integer.parseInt(spec[2]); diff --git a/src/main/org/apache/tools/ant/taskdefs/rmic/DefaultRmicAdapter.java b/src/main/org/apache/tools/ant/taskdefs/rmic/DefaultRmicAdapter.java index 37a14cbd8..420597aa9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/rmic/DefaultRmicAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/rmic/DefaultRmicAdapter.java @@ -206,8 +206,8 @@ public abstract class DefaultRmicAdapter implements RmicAdapter { Commandline cmd = new Commandline(); if (options != null) { - for (int i = 0; i < options.length; i++) { - cmd.createArgument().setValue(options[i]); + for (String option : options) { + cmd.createArgument().setValue(option); } } @@ -329,13 +329,12 @@ public abstract class DefaultRmicAdapter implements RmicAdapter { */ protected String[] filterJvmCompilerArgs(String[] compilerArgs) { int len = compilerArgs.length; - List args = new ArrayList(len); - for (int i = 0; i < len; i++) { - String arg = compilerArgs[i]; - if (!arg.startsWith("-J")) { - args.add(arg); - } else { + List args = new ArrayList(len); + for (String arg : compilerArgs) { + if (arg.startsWith("-J")) { attributes.log("Dropping " + arg + " from compiler arguments"); + } else { + args.add(arg); } } int count = args.size(); diff --git a/src/main/org/apache/tools/ant/taskdefs/rmic/KaffeRmic.java b/src/main/org/apache/tools/ant/taskdefs/rmic/KaffeRmic.java index f5f0bff0d..5b2233f46 100644 --- a/src/main/org/apache/tools/ant/taskdefs/rmic/KaffeRmic.java +++ b/src/main/org/apache/tools/ant/taskdefs/rmic/KaffeRmic.java @@ -60,15 +60,14 @@ public class KaffeRmic extends DefaultRmicAdapter { Class c = getRmicClass(); if (c == null) { - StringBuffer buf = new StringBuffer("Cannot use Kaffe rmic, as it" - + " is not available. None" - + " of "); - for (int i = 0; i < RMIC_CLASSNAMES.length; i++) { - if (i != 0) { + StringBuilder buf = new StringBuilder( + "Cannot use Kaffe rmic, as it is not available. None of "); + for (String className : RMIC_CLASSNAMES) { + if (buf.length() > 0) { buf.append(", "); } - buf.append(RMIC_CLASSNAMES[i]); + buf.append(className); } buf.append(" have been found. A common solution is to set the" + " environment variable JAVA_HOME or CLASSPATH."); @@ -101,10 +100,10 @@ public class KaffeRmic extends DefaultRmicAdapter { * * @return null if neither class can get loaded. */ - private static Class getRmicClass() { - for (int i = 0; i < RMIC_CLASSNAMES.length; i++) { + private static Class getRmicClass() { + for (String className : RMIC_CLASSNAMES) { try { - return Class.forName(RMIC_CLASSNAMES[i]); + return Class.forName(className); } catch (ClassNotFoundException cnfe) { // Ignore } diff --git a/src/main/org/apache/tools/ant/types/AbstractFileSet.java b/src/main/org/apache/tools/ant/types/AbstractFileSet.java index 1dca341c1..f2764a540 100644 --- a/src/main/org/apache/tools/ant/types/AbstractFileSet.java +++ b/src/main/org/apache/tools/ant/types/AbstractFileSet.java @@ -277,8 +277,8 @@ public abstract class AbstractFileSet extends DataType throw tooManyAttributes(); } if (includes != null) { - for (int i = 0; i < includes.length; i++) { - defaultPatterns.createInclude().setName(includes[i]); + for (String include : includes) { + defaultPatterns.createInclude().setName(include); } directoryScanner = null; } @@ -312,8 +312,8 @@ public abstract class AbstractFileSet extends DataType throw tooManyAttributes(); } if (excludes != null) { - for (int i = 0; i < excludes.length; i++) { - defaultPatterns.createExclude().setName(excludes[i]); + for (String exclude : excludes) { + defaultPatterns.createExclude().setName(exclude); } directoryScanner = null; } diff --git a/src/main/org/apache/tools/ant/types/Commandline.java b/src/main/org/apache/tools/ant/types/Commandline.java index c8f4eaf31..1b634efbf 100644 --- a/src/main/org/apache/tools/ant/types/Commandline.java +++ b/src/main/org/apache/tools/ant/types/Commandline.java @@ -354,8 +354,8 @@ public class Commandline implements Cloneable { * @param line an array of arguments to append. */ public void addArguments(String[] line) { - for (int i = 0; i < line.length; i++) { - createArgument().setValue(line[i]); + for (String l : line) { + createArgument().setValue(l); } } @@ -398,13 +398,11 @@ public class Commandline implements Cloneable { * @since Ant 1.6 */ public void addArgumentsToList(ListIterator list) { - final int size = arguments.size(); - for (int i = 0; i < size; i++) { - Argument arg = arguments.get(i); + for (Argument arg : arguments) { String[] s = arg.getParts(); if (s != null) { - for (int j = 0; j < s.length; j++) { - list.add(s[j]); + for (String value : s) { + list.add(value); } } } diff --git a/src/main/org/apache/tools/ant/types/CommandlineJava.java b/src/main/org/apache/tools/ant/types/CommandlineJava.java index e6f82cf9a..1771e3a61 100644 --- a/src/main/org/apache/tools/ant/types/CommandlineJava.java +++ b/src/main/org/apache/tools/ant/types/CommandlineJava.java @@ -108,8 +108,8 @@ public class CommandlineJava implements Cloneable { public void addDefinitionsToList(ListIterator listIt) { String[] props = super.getVariables(); if (props != null) { - for (int i = 0; i < props.length; i++) { - listIt.add("-D" + props[i]); + for (String prop : props) { + listIt.add("-D" + prop); } } Properties propertySetProperties = mergePropertySets(); diff --git a/src/main/org/apache/tools/ant/types/FilterChain.java b/src/main/org/apache/tools/ant/types/FilterChain.java index da7d96716..6bad602dc 100644 --- a/src/main/org/apache/tools/ant/types/FilterChain.java +++ b/src/main/org/apache/tools/ant/types/FilterChain.java @@ -17,7 +17,6 @@ */ package org.apache.tools.ant.types; -import java.util.Iterator; import java.util.Stack; import java.util.Vector; @@ -405,8 +404,7 @@ public class FilterChain extends DataType { if (isReference()) { super.dieOnCircularReference(stk, p); } else { - for (Iterator i = filterReaders.iterator(); i.hasNext();) { - Object o = i.next(); + for (Object o : filterReaders) { if (o instanceof DataType) { pushAndInvokeCircularReferenceCheck((DataType) o, stk, p); } diff --git a/src/main/org/apache/tools/ant/types/FilterSet.java b/src/main/org/apache/tools/ant/types/FilterSet.java index 2c1f2e71b..fbfff11d0 100644 --- a/src/main/org/apache/tools/ant/types/FilterSet.java +++ b/src/main/org/apache/tools/ant/types/FilterSet.java @@ -228,9 +228,8 @@ public class FilterSet extends DataType implements Cloneable { //silly hack to avoid stack overflow... if (!readingFiles) { readingFiles = true; - final int size = filtersFiles.size(); - for (int i = 0; i < size; i++) { - readFiltersFromFile(filtersFiles.get(i)); + for (File filtersFile : filtersFiles) { + readFiltersFromFile(filtersFile); } filtersFiles.clear(); readingFiles = false; diff --git a/src/main/org/apache/tools/ant/types/Path.java b/src/main/org/apache/tools/ant/types/Path.java index 70358d8fd..deaad3efc 100644 --- a/src/main/org/apache/tools/ant/types/Path.java +++ b/src/main/org/apache/tools/ant/types/Path.java @@ -20,6 +20,7 @@ package org.apache.tools.ant.types; import java.io.File; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Locale; @@ -326,17 +327,16 @@ public class Path extends DataType implements Cloneable, ResourceCollection { * @param tryUserDir if true try the user directory if the file is not present */ public void addExisting(Path source, boolean tryUserDir) { - String[] list = source.list(); File userDir = (tryUserDir) ? new File(System.getProperty("user.dir")) : null; - for (int i = 0; i < list.length; i++) { - File f = resolveFile(getProject(), list[i]); + for (String name : source.list()) { + File f = resolveFile(getProject(), name); // probably not the best choice, but it solves the problem of // relative paths in CLASSPATH if (tryUserDir && !f.exists()) { - f = new File(userDir, list[i]); + f = new File(userDir, name); } if (f.exists()) { setLocation(f); @@ -624,28 +624,25 @@ public class Path extends DataType implements Cloneable, ResourceCollection { + File.separator + "rt.jar")); // Sun's and Apple's 1.4 have JCE and JSSE in separate jars. - String[] secJars = {"jce", "jsse"}; - for (int i = 0; i < secJars.length; i++) { + for (String secJar : Arrays.asList("jce", "jsse")) { addExisting(new Path(null, - System.getProperty("java.home") - + File.separator + "lib" - + File.separator + secJars[i] + ".jar")); + System.getProperty("java.home") + + File.separator + "lib" + + File.separator + secJar + ".jar")); addExisting(new Path(null, - System.getProperty("java.home") - + File.separator + ".." - + File.separator + "Classes" - + File.separator + secJars[i] + ".jar")); + System.getProperty("java.home") + + File.separator + ".." + + File.separator + "Classes" + + File.separator + secJar + ".jar")); } // IBM's 1.4 has rt.jar split into 4 smaller jars and a combined // JCE/JSSE in security.jar. - String[] ibmJars - = {"core", "graphics", "security", "server", "xml"}; - for (int i = 0; i < ibmJars.length; i++) { + for (String ibmJar : Arrays.asList("core", "graphics", "security", "server", "xml")) { addExisting(new Path(null, - System.getProperty("java.home") - + File.separator + "lib" - + File.separator + ibmJars[i] + ".jar")); + System.getProperty("java.home") + + File.separator + "lib" + + File.separator + ibmJar + ".jar")); } // Added for MacOS X @@ -679,9 +676,8 @@ public class Path extends DataType implements Cloneable, ResourceCollection { } } - String[] dirs = extdirs.list(); - for (int i = 0; i < dirs.length; i++) { - File dir = resolveFile(getProject(), dirs[i]); + for (String d : extdirs.list()) { + File dir = resolveFile(getProject(), d); if (dir.exists() && dir.isDirectory()) { FileSet fs = new FileSet(); fs.setDir(dir); diff --git a/src/main/org/apache/tools/ant/types/PatternSet.java b/src/main/org/apache/tools/ant/types/PatternSet.java index cd5797b2d..6b0a52e7c 100644 --- a/src/main/org/apache/tools/ant/types/PatternSet.java +++ b/src/main/org/apache/tools/ant/types/PatternSet.java @@ -266,13 +266,13 @@ public class PatternSet extends DataType implements Cloneable { String[] nestedExcludes = p.getExcludePatterns(getProject()); if (nestedIncludes != null) { - for (int i = 0; i < nestedIncludes.length; i++) { - createInclude().setName(nestedIncludes[i]); + for (String nestedInclude : nestedIncludes) { + createInclude().setName(nestedInclude); } } if (nestedExcludes != null) { - for (int i = 0; i < nestedExcludes.length; i++) { - createExclude().setName(nestedExcludes[i]); + for (String nestedExclude : nestedExcludes) { + createExclude().setName(nestedExclude); } } } @@ -447,14 +447,14 @@ public class PatternSet extends DataType implements Cloneable { dieOnCircularReference(p); String[] incl = other.getIncludePatterns(p); if (incl != null) { - for (int i = 0; i < incl.length; i++) { - createInclude().setName(incl[i]); + for (String include : incl) { + createInclude().setName(include); } } String[] excl = other.getExcludePatterns(p); if (excl != null) { - for (int i = 0; i < excl.length; i++) { - createExclude().setName(excl[i]); + for (String exclude : excl) { + createExclude().setName(exclude); } } } diff --git a/src/main/org/apache/tools/ant/types/Quantifier.java b/src/main/org/apache/tools/ant/types/Quantifier.java index fae3dc51a..76b88d65a 100644 --- a/src/main/org/apache/tools/ant/types/Quantifier.java +++ b/src/main/org/apache/tools/ant/types/Quantifier.java @@ -120,8 +120,8 @@ public class Quantifier extends EnumeratedAttribute { */ public boolean evaluate(boolean[] b) { int t = 0; - for (int i = 0; i < b.length; i++) { - if (b[i]) { + for (boolean bn : b) { + if (bn) { t++; } } diff --git a/src/main/org/apache/tools/ant/types/RedirectorElement.java b/src/main/org/apache/tools/ant/types/RedirectorElement.java index 79ab146b8..b57afecf3 100644 --- a/src/main/org/apache/tools/ant/types/RedirectorElement.java +++ b/src/main/org/apache/tools/ant/types/RedirectorElement.java @@ -573,12 +573,12 @@ public class RedirectorElement extends DataType { } //remove any null elements ArrayList list = new ArrayList(name.length); - for (int i = 0; i < name.length; i++) { - if (name[i] != null) { - list.add(getProject().resolveFile(name[i])); + for (String n : name) { + if (n != null) { + list.add(getProject().resolveFile(n)); } } - return (File[]) (list.toArray(new File[list.size()])); + return list.toArray(new File[list.size()]); } /** @@ -596,11 +596,10 @@ public class RedirectorElement extends DataType { if (isReference()) { super.dieOnCircularReference(stk, p); } else { - Mapper[] m = new Mapper[] {inputMapper, outputMapper, errorMapper}; - for (int i = 0; i < m.length; i++) { - if (m[i] != null) { - stk.push(m[i]); - m[i].dieOnCircularReference(stk, p); + for (Mapper m : Arrays.asList(inputMapper, outputMapper, errorMapper)) { + if (m != null) { + stk.push(m); + m.dieOnCircularReference(stk, p); stk.pop(); } } diff --git a/src/main/org/apache/tools/ant/types/XMLCatalog.java b/src/main/org/apache/tools/ant/types/XMLCatalog.java index 7001359a0..c857bd831 100644 --- a/src/main/org/apache/tools/ant/types/XMLCatalog.java +++ b/src/main/org/apache/tools/ant/types/XMLCatalog.java @@ -1105,14 +1105,13 @@ public class XMLCatalog extends DataType if (catPath != null) { log("Using catalogpath '" + getCatalogPath() + "'", Project.MSG_DEBUG); - String[] catPathList = getCatalogPath().list(); - for (int i = 0; i < catPathList.length; i++) { - File catFile = new File(catPathList[i]); + for (String catFileName : getCatalogPath().list()) { + File catFile = new File(catFileName); log("Parsing " + catFile, Project.MSG_DEBUG); try { parseCatalog.invoke(resolverImpl, - new Object[] {catFile.getPath()}); + new Object[]{catFile.getPath()}); } catch (Exception ex) { throw new BuildException(ex); } diff --git a/src/main/org/apache/tools/ant/types/optional/depend/ClassfileSet.java b/src/main/org/apache/tools/ant/types/optional/depend/ClassfileSet.java index f2fe69b12..7fc8d3dcf 100644 --- a/src/main/org/apache/tools/ant/types/optional/depend/ClassfileSet.java +++ b/src/main/org/apache/tools/ant/types/optional/depend/ClassfileSet.java @@ -129,10 +129,9 @@ public class ClassfileSet extends FileSet { for (FileSet additionalRootSet : rootFileSets) { DirectoryScanner additionalScanner = additionalRootSet.getDirectoryScanner(p); - String[] files = additionalScanner.getIncludedFiles(); - for (int i = 0; i < files.length; ++i) { - if (files[i].endsWith(".class")) { - String classFilePath = StringUtils.removeSuffix(files[i], ".class"); + for (String file : additionalScanner.getIncludedFiles()) { + if (file.endsWith(".class")) { + String classFilePath = StringUtils.removeSuffix(file, ".class"); String className = classFilePath.replace('/', '.').replace('\\', '.'); allRootClasses.addElement(className); diff --git a/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java b/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java index 0c2dd4be8..3527bf31b 100644 --- a/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java +++ b/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java @@ -54,8 +54,8 @@ public class BZip2Resource extends CompressedResource { * @throws IOException if there is a problem. */ protected InputStream wrapStream(InputStream in) throws IOException { - for (int i = 0; i < MAGIC.length; i++) { - if (in.read() != MAGIC[i]) { + for (char ch : MAGIC) { + if (in.read() != ch) { throw new IOException("Invalid bz2 stream."); } } @@ -69,8 +69,8 @@ public class BZip2Resource extends CompressedResource { * @throws IOException if there is a problem. */ protected OutputStream wrapStream(OutputStream out) throws IOException { - for (int i = 0; i < MAGIC.length; i++) { - out.write(MAGIC[i]); + for (char ch : MAGIC) { + out.write(ch); } return new CBZip2OutputStream(out); } diff --git a/src/main/org/apache/tools/ant/types/resources/Files.java b/src/main/org/apache/tools/ant/types/resources/Files.java index a28e3a75c..a66b8ad0e 100644 --- a/src/main/org/apache/tools/ant/types/resources/Files.java +++ b/src/main/org/apache/tools/ant/types/resources/Files.java @@ -181,8 +181,8 @@ public class Files extends AbstractSelectorContainer public synchronized void appendIncludes(String[] includes) { checkAttributesAllowed(); if (includes != null) { - for (int i = 0; i < includes.length; i++) { - defaultPatterns.createInclude().setName(includes[i]); + for (String include : includes) { + defaultPatterns.createInclude().setName(include); } ds = null; } @@ -211,8 +211,8 @@ public class Files extends AbstractSelectorContainer public synchronized void appendExcludes(String[] excludes) { checkAttributesAllowed(); if (excludes != null) { - for (int i = 0; i < excludes.length; i++) { - defaultPatterns.createExclude().setName(excludes[i]); + for (String exclude : excludes) { + defaultPatterns.createExclude().setName(exclude); } ds = null; } diff --git a/src/main/org/apache/tools/ant/types/selectors/ContainsRegexpSelector.java b/src/main/org/apache/tools/ant/types/selectors/ContainsRegexpSelector.java index 7140b97ff..5b03e5356 100644 --- a/src/main/org/apache/tools/ant/types/selectors/ContainsRegexpSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/ContainsRegexpSelector.java @@ -119,17 +119,16 @@ public class ContainsRegexpSelector extends BaseExtendSelector public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (EXPRESSION_KEY.equalsIgnoreCase(paramname)) { - setExpression(parameters[i].getValue()); + setExpression(parameter.getValue()); } else if (CS_KEY.equalsIgnoreCase(paramname)) { - setCaseSensitive(Project - .toBoolean(parameters[i].getValue())); + setCaseSensitive(Project.toBoolean(parameter.getValue())); } else if (ML_KEY.equalsIgnoreCase(paramname)) { - setMultiLine(Project.toBoolean(parameters[i].getValue())); + setMultiLine(Project.toBoolean(parameter.getValue())); } else if (SL_KEY.equalsIgnoreCase(paramname)) { - setSingleLine(Project.toBoolean(parameters[i].getValue())); + setSingleLine(Project.toBoolean(parameter.getValue())); } else { setError("Invalid parameter " + paramname); } diff --git a/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java b/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java index a1004a8f2..d0a7a8f59 100644 --- a/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java @@ -120,16 +120,16 @@ public class ContainsSelector extends BaseExtendSelector implements ResourceSele public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (CONTAINS_KEY.equalsIgnoreCase(paramname)) { - setText(parameters[i].getValue()); + setText(parameter.getValue()); } else if (CASE_KEY.equalsIgnoreCase(paramname)) { setCasesensitive(Project.toBoolean( - parameters[i].getValue())); + parameter.getValue())); } else if (WHITESPACE_KEY.equalsIgnoreCase(paramname)) { setIgnorewhitespace(Project.toBoolean( - parameters[i].getValue())); + parameter.getValue())); } else { setError("Invalid parameter " + paramname); } diff --git a/src/main/org/apache/tools/ant/types/selectors/DateSelector.java b/src/main/org/apache/tools/ant/types/selectors/DateSelector.java index f8db485ef..bcbf11c4b 100644 --- a/src/main/org/apache/tools/ant/types/selectors/DateSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/DateSelector.java @@ -169,30 +169,30 @@ public class DateSelector extends BaseExtendSelector { public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (MILLIS_KEY.equalsIgnoreCase(paramname)) { try { - setMillis(Long.parseLong(parameters[i].getValue())); + setMillis(Long.parseLong(parameter.getValue())); } catch (NumberFormatException nfe) { setError("Invalid millisecond setting " - + parameters[i].getValue()); + + parameter.getValue()); } } else if (DATETIME_KEY.equalsIgnoreCase(paramname)) { - setDatetime(parameters[i].getValue()); + setDatetime(parameter.getValue()); } else if (CHECKDIRS_KEY.equalsIgnoreCase(paramname)) { - setCheckdirs(Project.toBoolean(parameters[i].getValue())); + setCheckdirs(Project.toBoolean(parameter.getValue())); } else if (GRANULARITY_KEY.equalsIgnoreCase(paramname)) { try { - setGranularity(Integer.parseInt(parameters[i].getValue())); + setGranularity(Integer.parseInt(parameter.getValue())); } catch (NumberFormatException nfe) { setError("Invalid granularity setting " - + parameters[i].getValue()); + + parameter.getValue()); } } else if (WHEN_KEY.equalsIgnoreCase(paramname)) { - setWhen(new TimeComparison(parameters[i].getValue())); + setWhen(new TimeComparison(parameter.getValue())); } else if (PATTERN_KEY.equalsIgnoreCase(paramname)) { - setPattern(parameters[i].getValue()); + setPattern(parameter.getValue()); } else { setError("Invalid parameter " + paramname); } diff --git a/src/main/org/apache/tools/ant/types/selectors/DepthSelector.java b/src/main/org/apache/tools/ant/types/selectors/DepthSelector.java index a80f9aa96..a8a14d35d 100644 --- a/src/main/org/apache/tools/ant/types/selectors/DepthSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/DepthSelector.java @@ -92,21 +92,21 @@ public class DepthSelector extends BaseExtendSelector { public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (MIN_KEY.equalsIgnoreCase(paramname)) { try { - setMin(Integer.parseInt(parameters[i].getValue())); + setMin(Integer.parseInt(parameter.getValue())); } catch (NumberFormatException nfe1) { setError("Invalid minimum value " - + parameters[i].getValue()); + + parameter.getValue()); } } else if (MAX_KEY.equalsIgnoreCase(paramname)) { try { - setMax(Integer.parseInt(parameters[i].getValue())); + setMax(Integer.parseInt(parameter.getValue())); } catch (NumberFormatException nfe1) { setError("Invalid maximum value " - + parameters[i].getValue()); + + parameter.getValue()); } } else { setError("Invalid parameter " + paramname); diff --git a/src/main/org/apache/tools/ant/types/selectors/FilenameSelector.java b/src/main/org/apache/tools/ant/types/selectors/FilenameSelector.java index 1b998f9f3..ec34e23e3 100644 --- a/src/main/org/apache/tools/ant/types/selectors/FilenameSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/FilenameSelector.java @@ -132,17 +132,17 @@ public class FilenameSelector extends BaseExtendSelector { public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (NAME_KEY.equalsIgnoreCase(paramname)) { - setName(parameters[i].getValue()); + setName(parameter.getValue()); } else if (CASE_KEY.equalsIgnoreCase(paramname)) { setCasesensitive(Project.toBoolean( - parameters[i].getValue())); + parameter.getValue())); } else if (NEGATE_KEY.equalsIgnoreCase(paramname)) { - setNegate(Project.toBoolean(parameters[i].getValue())); + setNegate(Project.toBoolean(parameter.getValue())); } else if (REGEX_KEY.equalsIgnoreCase(paramname)) { - setRegex(parameters[i].getValue()); + setRegex(parameter.getValue()); } else { setError("Invalid parameter " + paramname); } diff --git a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java index 277470b7f..24630e865 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java +++ b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java @@ -369,8 +369,8 @@ public final class SelectorUtils { char ch; boolean containsStar = false; - for (int i = 0; i < patArr.length; i++) { - if (patArr[i] == '*') { + for (char ch : patArr) { + if (ch == '*') { containsStar = true; break; } diff --git a/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java b/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java index 3157ee536..6f8d2d857 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java @@ -167,22 +167,22 @@ public class SizeSelector extends BaseExtendSelector { public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (SIZE_KEY.equalsIgnoreCase(paramname)) { try { - setValue(Long.parseLong(parameters[i].getValue())); + setValue(Long.parseLong(parameter.getValue())); } catch (NumberFormatException nfe) { setError("Invalid size setting " - + parameters[i].getValue()); + + parameter.getValue()); } } else if (UNITS_KEY.equalsIgnoreCase(paramname)) { ByteUnits units = new ByteUnits(); - units.setValue(parameters[i].getValue()); + units.setValue(parameter.getValue()); setUnits(units); } else if (WHEN_KEY.equalsIgnoreCase(paramname)) { SizeComparisons scmp = new SizeComparisons(); - scmp.setValue(parameters[i].getValue()); + scmp.setValue(parameter.getValue()); setWhen(scmp); } else { setError("Invalid parameter " + paramname); diff --git a/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java b/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java index ed899e4c0..cd0770b14 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java +++ b/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java @@ -141,17 +141,17 @@ public class TokenizedPath { * @return boolean */ public boolean isSymlink(File base) { - for (int i = 0; i < tokenizedPath.length; i++) { + for (String token : tokenizedPath) { try { if ((base != null - && SYMLINK_UTILS.isSymbolicLink(base, tokenizedPath[i])) + && SYMLINK_UTILS.isSymbolicLink(base, token)) || (base == null - && SYMLINK_UTILS.isSymbolicLink(tokenizedPath[i])) + && SYMLINK_UTILS.isSymbolicLink(token)) ) { return true; } - base = new File(base, tokenizedPath[i]); + base = new File(base, token); } catch (java.io.IOException ioe) { String msg = "IOException caught while checking " + "for links, couldn't get canonical path!"; @@ -188,7 +188,7 @@ public class TokenizedPath { */ private static File findFile(File base, final String[] pathElements, final boolean cs) { - for (int current = 0; current < pathElements.length; current++) { + for (String pathElement : pathElements) { if (!base.isDirectory()) { return null; } @@ -202,8 +202,8 @@ public class TokenizedPath { for (int i = 0; !found && i < matchCase.length; i++) { for (int j = 0; !found && j < files.length; j++) { if (matchCase[i] - ? files[j].equals(pathElements[current]) - : files[j].equalsIgnoreCase(pathElements[current])) { + ? files[j].equals(pathElement) + : files[j].equalsIgnoreCase(pathElement)) { base = new File(base, files[j]); found = true; } diff --git a/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java b/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java index fd3684d6e..a9d8186d7 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java @@ -69,11 +69,11 @@ public class TypeSelector extends BaseExtendSelector { public void setParameters(Parameter[] parameters) { super.setParameters(parameters); if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - String paramname = parameters[i].getName(); + for (Parameter parameter : parameters) { + String paramname = parameter.getName(); if (TYPE_KEY.equalsIgnoreCase(paramname)) { FileType t = new FileType(); - t.setValue(parameters[i].getValue()); + t.setValue(parameter.getValue()); setType(t); } else { setError("Invalid parameter " + paramname); diff --git a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java index a4b2ffd5d..988a25649 100644 --- a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java +++ b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java @@ -153,12 +153,12 @@ public class DigestAlgorithm implements Algorithm { */ // implementation adapted from ...taskdefs.Checksum, thanks to Magesh for hint public String getValue(File file) { + if (!file.canRead()) { + return null; + } initMessageDigest(); String checksum = null; try { - if (!file.canRead()) { - return null; - } FileInputStream fis = null; byte[] buf = new byte[readBufferSize]; diff --git a/src/main/org/apache/tools/ant/util/DOMElementWriter.java b/src/main/org/apache/tools/ant/util/DOMElementWriter.java index 2dad80f0c..78a893b5e 100644 --- a/src/main/org/apache/tools/ant/util/DOMElementWriter.java +++ b/src/main/org/apache/tools/ant/util/DOMElementWriter.java @@ -576,8 +576,8 @@ public class DOMElementWriter { } String name = ent.substring(1, ent.length() - 1); - for (int i = 0; i < knownEntities.length; i++) { - if (name.equals(knownEntities[i])) { + for (String knownEntity : knownEntities) { + if (name.equals(knownEntity)) { return true; } } diff --git a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java index e4b2675bf..277107323 100644 --- a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java +++ b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java @@ -543,8 +543,7 @@ public class LayoutPreservingProperties extends Properties { final String escaped = "tfrn\\:=#!"; final StringBuffer buffy = new StringBuffer(s.length()); boolean leadingSpace = true; - for (int i = 0; i < ch.length; i++) { - final char c = ch[i]; + for (final char c : ch) { if (c == ' ') { if (escapeAllSpaces || leadingSpace) { buffy.append("\\"); diff --git a/src/main/org/apache/tools/ant/util/ResourceUtils.java b/src/main/org/apache/tools/ant/util/ResourceUtils.java index 004cb6cd6..c3b80d255 100644 --- a/src/main/org/apache/tools/ant/util/ResourceUtils.java +++ b/src/main/org/apache/tools/ant/util/ResourceUtils.java @@ -206,15 +206,13 @@ public class ResourceUtils { Project.MSG_VERBOSE); continue; } - for (int i = 0; i < targetnames.length; i++) { - if (targetnames[i] == null) { - targetnames[i] = "(no name)"; - } - } final Union targetColl = new Union(); - for (int i = 0; i < targetnames.length; i++) { + for (String targetname : targetnames) { + if (targetname == null) { + targetname = "(no name)"; + } targetColl.add(targets.getResource( - targetnames[i].replace(File.separatorChar, '/'))); + targetname.replace(File.separatorChar, '/'))); } //find the out-of-date targets: final Restrict r = new Restrict(); diff --git a/src/main/org/apache/tools/ant/util/SplitClassLoader.java b/src/main/org/apache/tools/ant/util/SplitClassLoader.java index 9d657dae6..98577552f 100644 --- a/src/main/org/apache/tools/ant/util/SplitClassLoader.java +++ b/src/main/org/apache/tools/ant/util/SplitClassLoader.java @@ -64,9 +64,9 @@ public final class SplitClassLoader extends AntClassLoader { private boolean isSplit(String classname) { String simplename = classname.substring(classname.lastIndexOf('.') + 1); - for (int i = 0; i < splitClasses.length; i++) { - if (simplename.equals(splitClasses[i]) - || simplename.startsWith(splitClasses[i] + '$')) { + for (String splitClass : splitClasses) { + if (simplename.equals(splitClass) + || simplename.startsWith(splitClass + '$')) { return true; } } diff --git a/src/main/org/apache/tools/ant/util/StringTokenizer.java b/src/main/org/apache/tools/ant/util/StringTokenizer.java index 7addf3106..1e3a8a904 100644 --- a/src/main/org/apache/tools/ant/util/StringTokenizer.java +++ b/src/main/org/apache/tools/ant/util/StringTokenizer.java @@ -144,8 +144,8 @@ public class StringTokenizer extends ProjectComponent implements Tokenizer { if (delims == null) { return Character.isWhitespace(ch); } - for (int i = 0; i < delims.length; ++i) { - if (delims[i] == ch) { + for (char delim : delims) { + if (delim == ch) { return true; } } diff --git a/src/main/org/apache/tools/ant/util/WeakishReference.java b/src/main/org/apache/tools/ant/util/WeakishReference.java index 9568a28a2..816ee4e7f 100644 --- a/src/main/org/apache/tools/ant/util/WeakishReference.java +++ b/src/main/org/apache/tools/ant/util/WeakishReference.java @@ -37,7 +37,7 @@ import java.lang.ref.WeakReference; public class WeakishReference { - private WeakReference weakref; + private WeakReference weakref; /** * create a new soft reference, which is bound to a @@ -47,7 +47,7 @@ public class WeakishReference { * @see java.lang.ref.WeakReference */ WeakishReference(Object reference) { - this.weakref = new WeakReference(reference); + this.weakref = new WeakReference(reference); } /** diff --git a/src/main/org/apache/tools/ant/util/depend/AbstractAnalyzer.java b/src/main/org/apache/tools/ant/util/depend/AbstractAnalyzer.java index b5ef999e4..a6e81f48c 100644 --- a/src/main/org/apache/tools/ant/util/depend/AbstractAnalyzer.java +++ b/src/main/org/apache/tools/ant/util/depend/AbstractAnalyzer.java @@ -256,8 +256,8 @@ public abstract class AbstractAnalyzer implements DependencyAnalyzer { */ private File getResourceContainer(String resourceLocation, String[] paths) throws IOException { - for (int i = 0; i < paths.length; ++i) { - File element = new File(paths[i]); + for (String path : paths) { + File element = new File(path); if (!element.exists()) { continue; } diff --git a/src/main/org/apache/tools/mail/MailMessage.java b/src/main/org/apache/tools/mail/MailMessage.java index b1ca493b7..0906fde72 100644 --- a/src/main/org/apache/tools/mail/MailMessage.java +++ b/src/main/org/apache/tools/mail/MailMessage.java @@ -113,17 +113,17 @@ public class MailMessage { private String from; /** list of email addresses to reply to */ - private Vector replyto; + private Vector replyto = new Vector(); /** list of email addresses to send to */ - private Vector to; + private Vector to = new Vector(); /** list of email addresses to cc to */ - private Vector cc; + private Vector cc = new Vector(); /** headers to send in the mail */ - private Vector headersKeys; - private Vector headersValues; + private Vector headersKeys = new Vector(); + private Vector headersValues = new Vector(); private MailPrintStream out; @@ -139,46 +139,41 @@ public class MailMessage { private static final int OK_DOT = 250; private static final int OK_QUIT = 221; - /** - * Constructs a new MailMessage to send an email. - * Use localhost as the mail server with port 25. - * - * @exception IOException if there's any problem contacting the mail server - */ - public MailMessage() throws IOException { - this(DEFAULT_HOST, DEFAULT_PORT); - } - - /** - * Constructs a new MailMessage to send an email. - * Use the given host as the mail server with port 25. - * - * @param host the mail server to use - * @exception IOException if there's any problem contacting the mail server - */ - public MailMessage(String host) throws IOException { - this(host, DEFAULT_PORT); - } - - /** - * Constructs a new MailMessage to send an email. - * Use the given host and port as the mail server. - * - * @param host the mail server to use - * @param port the port to connect to - * @exception IOException if there's any problem contacting the mail server - */ - public MailMessage(String host, int port) throws IOException { - this.port = port; - this.host = host; - replyto = new Vector(); - to = new Vector(); - cc = new Vector(); - headersKeys = new Vector(); - headersValues = new Vector(); - connect(); - sendHelo(); - } + /** + * Constructs a new MailMessage to send an email. + * Use localhost as the mail server with port 25. + * + * @exception IOException if there's any problem contacting the mail server + */ + public MailMessage() throws IOException { + this(DEFAULT_HOST, DEFAULT_PORT); + } + + /** + * Constructs a new MailMessage to send an email. + * Use the given host as the mail server with port 25. + * + * @param host the mail server to use + * @exception IOException if there's any problem contacting the mail server + */ + public MailMessage(String host) throws IOException { + this(host, DEFAULT_PORT); + } + + /** + * Constructs a new MailMessage to send an email. + * Use the given host and port as the mail server. + * + * @param host the mail server to use + * @param port the port to connect to + * @exception IOException if there's any problem contacting the mail server + */ + public MailMessage(String host, int port) throws IOException { + this.port = port; + this.host = host; + connect(); + sendHelo(); + } /** * Set the port to connect to the SMTP host. @@ -208,231 +203,230 @@ public class MailMessage { * */ public void replyto(String rto) { - this.replyto.addElement(rto); - } - - /** - * Sets the to address. Also sets the "To" header. This method may be - * called multiple times. - * - * @param to the to address - * @exception IOException if there's any problem reported by the mail server - */ - public void to(String to) throws IOException { - sendRcpt(to); - this.to.addElement(to); - } - - /** - * Sets the cc address. Also sets the "Cc" header. This method may be - * called multiple times. - * - * @param cc the cc address - * @exception IOException if there's any problem reported by the mail server - */ - public void cc(String cc) throws IOException { - sendRcpt(cc); - this.cc.addElement(cc); - } - - /** - * Sets the bcc address. Does NOT set any header since it's a *blind* copy. - * This method may be called multiple times. - * - * @param bcc the bcc address - * @exception IOException if there's any problem reported by the mail server - */ - public void bcc(String bcc) throws IOException { - sendRcpt(bcc); - // No need to keep track of Bcc'd addresses - } - - /** - * Sets the subject of the mail message. Actually sets the "Subject" - * header. - * @param subj the subject of the mail message - */ - public void setSubject(String subj) { - setHeader("Subject", subj); - } - - /** - * Sets the named header to the given value. RFC 822 provides the rules for - * what text may constitute a header name and value. - * @param name name of the header - * @param value contents of the header - */ - public void setHeader(String name, String value) { - // Blindly trust the user doesn't set any invalid headers - headersKeys.add(name); - headersValues.add(value); - } - - /** - * Returns a PrintStream that can be used to write the body of the message. - * A stream is used since email bodies are byte-oriented. A writer can - * be wrapped on top if necessary for internationalization. - * This is actually done in Message.java - * - * @return a printstream containing the data and the headers of the email - * @exception IOException if there's any problem reported by the mail server - * @see org.apache.tools.ant.taskdefs.email.Message - */ - public PrintStream getPrintStream() throws IOException { - setFromHeader(); - setReplyToHeader(); - setToHeader(); - setCcHeader(); - setHeader("X-Mailer", "org.apache.tools.mail.MailMessage (ant.apache.org)"); - sendData(); - flushHeaders(); - return out; - } - - - // RFC 822 s4.1: "From:" header must be sent - // We rely on error checking by the MTA - void setFromHeader() { - setHeader("From", from); - } - - // RFC 822 s4.1: "Reply-To:" header is optional - void setReplyToHeader() { - if (!replyto.isEmpty()) { - setHeader("Reply-To", vectorToList(replyto)); - } - } - - void setToHeader() { - if (!to.isEmpty()) { - setHeader("To", vectorToList(to)); - } - } - - void setCcHeader() { - if (!cc.isEmpty()) { - setHeader("Cc", vectorToList(cc)); - } - } - - String vectorToList(Vector v) { - StringBuffer buf = new StringBuffer(); - Enumeration e = v.elements(); - while (e.hasMoreElements()) { - buf.append(e.nextElement()); - if (e.hasMoreElements()) { - buf.append(", "); - } - } - return buf.toString(); - } - - void flushHeaders() throws IOException { - // RFC 822 s4.1: - // "Header fields are NOT required to occur in any particular order, - // except that the message body MUST occur AFTER the headers" - // (the same section specifies a recommended order, which we ignore) - final int size = headersKeys.size(); - for (int i = 0; i < size; i++) { - String name = (String) headersKeys.elementAt(i); - String value = (String) headersValues.elementAt(i); - out.println(name + ": " + value); - } - out.println(); - out.flush(); - } - - /** - * Sends the message and closes the connection to the server. - * The MailMessage object cannot be reused. - * - * @exception IOException if there's any problem reported by the mail server - */ - public void sendAndClose() throws IOException { - try { - sendDot(); - sendQuit(); - } finally { - disconnect(); - } - } - - // Make a limited attempt to extract a sanitized email address - // Prefer text in , ignore anything in (parentheses) - static String sanitizeAddress(String s) { - int paramDepth = 0; - int start = 0; - int end = 0; - int len = s.length(); - - for (int i = 0; i < len; i++) { - char c = s.charAt(i); - if (c == '(') { - paramDepth++; - if (start == 0) { - end = i; // support "address (name)" + this.replyto.addElement(rto); + } + + /** + * Sets the to address. Also sets the "To" header. This method may be + * called multiple times. + * + * @param to the to address + * @exception IOException if there's any problem reported by the mail server + */ + public void to(String to) throws IOException { + sendRcpt(to); + this.to.addElement(to); + } + + /** + * Sets the cc address. Also sets the "Cc" header. This method may be + * called multiple times. + * + * @param cc the cc address + * @exception IOException if there's any problem reported by the mail server + */ + public void cc(String cc) throws IOException { + sendRcpt(cc); + this.cc.addElement(cc); + } + + /** + * Sets the bcc address. Does NOT set any header since it's a *blind* copy. + * This method may be called multiple times. + * + * @param bcc the bcc address + * @exception IOException if there's any problem reported by the mail server + */ + public void bcc(String bcc) throws IOException { + sendRcpt(bcc); + // No need to keep track of Bcc'd addresses + } + + /** + * Sets the subject of the mail message. Actually sets the "Subject" + * header. + * @param subj the subject of the mail message + */ + public void setSubject(String subj) { + setHeader("Subject", subj); + } + + /** + * Sets the named header to the given value. RFC 822 provides the rules for + * what text may constitute a header name and value. + * @param name name of the header + * @param value contents of the header + */ + public void setHeader(String name, String value) { + // Blindly trust the user doesn't set any invalid headers + headersKeys.add(name); + headersValues.add(value); + } + + /** + * Returns a PrintStream that can be used to write the body of the message. + * A stream is used since email bodies are byte-oriented. A writer can + * be wrapped on top if necessary for internationalization. + * This is actually done in Message.java + * + * @return a printstream containing the data and the headers of the email + * @exception IOException if there's any problem reported by the mail server + * @see org.apache.tools.ant.taskdefs.email.Message + */ + public PrintStream getPrintStream() throws IOException { + setFromHeader(); + setReplyToHeader(); + setToHeader(); + setCcHeader(); + setHeader("X-Mailer", "org.apache.tools.mail.MailMessage (ant.apache.org)"); + sendData(); + flushHeaders(); + return out; + } + + // RFC 822 s4.1: "From:" header must be sent + // We rely on error checking by the MTA + void setFromHeader() { + setHeader("From", from); + } + + // RFC 822 s4.1: "Reply-To:" header is optional + void setReplyToHeader() { + if (!replyto.isEmpty()) { + setHeader("Reply-To", vectorToList(replyto)); + } + } + + void setToHeader() { + if (!to.isEmpty()) { + setHeader("To", vectorToList(to)); + } + } + + void setCcHeader() { + if (!cc.isEmpty()) { + setHeader("Cc", vectorToList(cc)); + } + } + + String vectorToList(Vector v) { + StringBuffer buf = new StringBuffer(); + Enumeration e = v.elements(); + while (e.hasMoreElements()) { + buf.append(e.nextElement()); + if (e.hasMoreElements()) { + buf.append(", "); + } } - } else if (c == ')') { - paramDepth--; + return buf.toString(); + } + + void flushHeaders() { + // RFC 822 s4.1: + // "Header fields are NOT required to occur in any particular order, + // except that the message body MUST occur AFTER the headers" + // (the same section specifies a recommended order, which we ignore) + final int size = headersKeys.size(); + for (int i = 0; i < size; i++) { + String name = headersKeys.elementAt(i); + String value = headersValues.elementAt(i); + out.println(name + ": " + value); + } + out.println(); + out.flush(); + } + + /** + * Sends the message and closes the connection to the server. + * The MailMessage object cannot be reused. + * + * @exception IOException if there's any problem reported by the mail server + */ + public void sendAndClose() throws IOException { + try { + sendDot(); + sendQuit(); + } finally { + disconnect(); + } + } + + // Make a limited attempt to extract a sanitized email address + // Prefer text in , ignore anything in (parentheses) + static String sanitizeAddress(String s) { + int paramDepth = 0; + int start = 0; + int end = 0; + int len = s.length(); + + for (int i = 0; i < len; i++) { + char c = s.charAt(i); + if (c == '(') { + paramDepth++; + if (start == 0) { + end = i; // support "address (name)" + } + } else if (c == ')') { + paramDepth--; + if (end == 0) { + start = i + 1; // support "(name) address" + } + } else if (paramDepth == 0 && c == '<') { + start = i + 1; + } else if (paramDepth == 0 && c == '>') { + end = i; + } + } + if (end == 0) { - start = i + 1; // support "(name) address" + end = len; } - } else if (paramDepth == 0 && c == '<') { - start = i + 1; - } else if (paramDepth == 0 && c == '>') { - end = i; - } - } - - if (end == 0) { - end = len; - } - - return s.substring(start, end); - } - - // * * * * * Raw protocol methods below here * * * * * - - void connect() throws IOException { - socket = new Socket(host, port); - out = new MailPrintStream( - new BufferedOutputStream( - socket.getOutputStream())); - in = new SmtpResponseReader(socket.getInputStream()); - getReady(); - } - - void getReady() throws IOException { - String response = in.getResponse(); - int[] ok = {OK_READY}; - if (!isResponseOK(response, ok)) { - throw new IOException( - "Didn't get introduction from server: " + response); - } - } - void sendHelo() throws IOException { - String local = InetAddress.getLocalHost().getHostName(); - int[] ok = {OK_HELO}; - send("HELO " + local, ok); - } - void sendFrom(String from) throws IOException { - int[] ok = {OK_FROM}; - send("MAIL FROM: " + "<" + sanitizeAddress(from) + ">", ok); - } - void sendRcpt(String rcpt) throws IOException { - int[] ok = {OK_RCPT_1, OK_RCPT_2}; - send("RCPT TO: " + "<" + sanitizeAddress(rcpt) + ">", ok); - } - - void sendData() throws IOException { - int[] ok = {OK_DATA}; - send("DATA", ok); - } - - void sendDot() throws IOException { - int[] ok = {OK_DOT}; - send("\r\n.", ok); // make sure dot is on new line - } + + return s.substring(start, end); + } + + // * * * * * Raw protocol methods below here * * * * * + + void connect() throws IOException { + socket = new Socket(host, port); + out = new MailPrintStream(new BufferedOutputStream(socket.getOutputStream())); + in = new SmtpResponseReader(socket.getInputStream()); + getReady(); + } + + void getReady() throws IOException { + String response = in.getResponse(); + int[] ok = {OK_READY}; + if (!isResponseOK(response, ok)) { + throw new IOException("Didn't get introduction from server: " + response); + } + } + + void sendHelo() throws IOException { + String local = InetAddress.getLocalHost().getHostName(); + int[] ok = {OK_HELO}; + send("HELO " + local, ok); + } + + void sendFrom(String from) throws IOException { + int[] ok = {OK_FROM}; + send("MAIL FROM: " + "<" + sanitizeAddress(from) + ">", ok); + } + + void sendRcpt(String rcpt) throws IOException { + int[] ok = {OK_RCPT_1, OK_RCPT_2}; + send("RCPT TO: " + "<" + sanitizeAddress(rcpt) + ">", ok); + } + + void sendData() throws IOException { + int[] ok = {OK_DATA}; + send("DATA", ok); + } + + void sendDot() throws IOException { + int[] ok = {OK_DOT}; + send("\r\n.", ok); // make sure dot is on new line + } void sendQuit() throws IOException { int[] ok = {OK_QUIT}; @@ -452,17 +446,17 @@ public class MailMessage { } } - boolean isResponseOK(String response, int[] ok) { - // Check that the response is one of the valid codes - for (int i = 0; i < ok.length; i++) { - if (response.startsWith("" + ok[i])) { - return true; - } + boolean isResponseOK(String response, int[] ok) { + // Check that the response is one of the valid codes + for (int status : ok) { + if (response.startsWith("" + status)) { + return true; + } + } + return false; } - return false; - } - void disconnect() throws IOException { + void disconnect() { if (out != null) { out.close(); } @@ -489,42 +483,40 @@ public class MailMessage { */ class MailPrintStream extends PrintStream { - private int lastChar; + private int lastChar; - public MailPrintStream(OutputStream out) { - super(out, true); // deprecated, but email is byte-oriented - } + public MailPrintStream(OutputStream out) { + super(out, true); // deprecated, but email is byte-oriented + } - // Mac does \n\r, but that's tough to distinguish from Windows \r\n\r\n. - // Don't tackle that problem right now. - public void write(int b) { - if (b == '\n' && lastChar != '\r') { - rawWrite('\r'); // ensure always \r\n - rawWrite(b); - } else if (b == '.' && lastChar == '\n') { - rawWrite('.'); // add extra dot - rawWrite(b); - } else { - rawWrite(b); + // Mac does \n\r, but that's tough to distinguish from Windows \r\n\r\n. + // Don't tackle that problem right now. + public void write(int b) { + if (b == '\n' && lastChar != '\r') { + rawWrite('\r'); // ensure always \r\n + rawWrite(b); + } else if (b == '.' && lastChar == '\n') { + rawWrite('.'); // add extra dot + rawWrite(b); + } else { + rawWrite(b); + } + lastChar = b; } - lastChar = b; - } - public void write(byte[] buf, int off, int len) { - for (int i = 0; i < len; i++) { - write(buf[off + i]); + public void write(byte[] buf, int off, int len) { + for (int i = 0; i < len; i++) { + write(buf[off + i]); + } } - } - void rawWrite(int b) { - super.write(b); - } + void rawWrite(int b) { + super.write(b); + } - void rawPrint(String s) { - int len = s.length(); - for (int i = 0; i < len; i++) { - rawWrite(s.charAt(i)); + void rawPrint(String s) { + for (char ch : s.toCharArray()) { + rawWrite(ch); + } } - } } - diff --git a/src/main/org/apache/tools/tar/TarUtils.java b/src/main/org/apache/tools/tar/TarUtils.java index 93d1583c8..fcd0c4e1f 100644 --- a/src/main/org/apache/tools/tar/TarUtils.java +++ b/src/main/org/apache/tools/tar/TarUtils.java @@ -65,8 +65,7 @@ public class TarUtils { final int length = buffer.length; final StringBuilder result = new StringBuilder(length); - for (int i = 0; i < length; ++i) { - final byte b = buffer[i]; + for (final byte b : buffer) { if (b == 0) { // Trailing null break; } diff --git a/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java b/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java index 261beec56..789c04522 100644 --- a/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java +++ b/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java @@ -107,8 +107,8 @@ class Simple8BitZipEncoding implements ZipEncoding { byte code = 127; - for (int i = 0; i < this.highChars.length; ++i) { - temp.add(new Simple8BitChar(++code, this.highChars[i])); + for (char highChar : this.highChars) { + temp.add(new Simple8BitChar(++code, highChar)); } Collections.sort(temp); diff --git a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java index b76ef1d74..cc9a0fe66 100644 --- a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java +++ b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java @@ -203,8 +203,8 @@ public class IntrospectionHelperTest { } } - private Map getExpectedNestedElements() { - Map elemMap = new Hashtable(); + private Map> getExpectedNestedElements() { + Map> elemMap = new Hashtable<>(); elemMap.put("six", String.class); elemMap.put("thirteen", StringBuffer.class); elemMap.put("fourteen", StringBuffer.class); @@ -214,7 +214,7 @@ public class IntrospectionHelperTest { @Test public void testGetNestedElements() { - Map elemMap = getExpectedNestedElements(); + Map> elemMap = getExpectedNestedElements(); Enumeration e = ih.getNestedElements(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); @@ -229,12 +229,11 @@ public class IntrospectionHelperTest { @Test public void testGetNestedElementMap() { - Map elemMap = getExpectedNestedElements(); - Map actualMap = ih.getNestedElementMap(); - for (Iterator i = actualMap.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); + Map> elemMap = getExpectedNestedElements(); + Map> actualMap = ih.getNestedElementMap(); + for (Map.Entry> entry : actualMap.entrySet()) { String elemName = (String) entry.getKey(); - Class elemClass = (Class) elemMap.get(elemName); + Class elemClass = (Class) elemMap.get(elemName); assertNotNull("Support for " + elemName + " in IntrospectionHelperTest?", elemClass); assertEquals("Type of " + elemName, elemClass, entry.getValue()); @@ -506,10 +505,9 @@ public class IntrospectionHelperTest { @Test public void testGetAttributeMap() { - Map attrMap = getExpectedAttributes(); - Map actualMap = ih.getAttributeMap(); - for (Iterator i = actualMap.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); + Map> attrMap = getExpectedAttributes(); + Map> actualMap = ih.getAttributeMap(); + for (Map.Entry> entry : actualMap.entrySet()) { String attrName = (String) entry.getKey(); Class attrClass = (Class) attrMap.get(attrName); assertNotNull("Support for " + attrName + diff --git a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java index 1bad429c7..003f1a964 100644 --- a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java +++ b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java @@ -96,7 +96,7 @@ public class UnknownElementTest { } public static class Parent extends Task implements TaskContainer { - List children = new ArrayList(); + List children = new ArrayList<>(); public void addTask(Task t) { children.add(t); } @@ -106,8 +106,8 @@ public class UnknownElementTest { } public void execute() { - for (Iterator i = children.iterator(); i.hasNext();) { - UnknownElement el = (UnknownElement) i.next(); + for (Task task : children) { + UnknownElement el = (UnknownElement) task; el.maybeConfigure(); Child child = (Child) el.getRealThing(); child.injectParent(this); diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java index 575651943..93715483f 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java @@ -242,16 +242,16 @@ public class AntTest { buildRule.getProject().resolveFile("ant/test3.log"), buildRule.getProject().resolveFile("ant/test4.log") }; - for (int i=0; i files = new Hashtable(); + for (String scannedFile : scanner.getIncludedFiles()) { + files.put(scannedFile, scannedFile); } return files; } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java index f32b4ff4a..e456d6f6d 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java @@ -66,7 +66,7 @@ public class ScpTest { private int port = Integer.parseInt(System.getProperty("scp.port", "22")); private String knownHosts = System.getProperty("scp.known.hosts"); - private List cleanUpList = new ArrayList(); + private List cleanUpList = new ArrayList(); @Before public void setUp() { @@ -79,8 +79,7 @@ public class ScpTest { @After public void tearDown() { - for (Iterator i = cleanUpList.iterator(); i.hasNext();) { - File file = (File) i.next(); + for (File file : cleanUpList) { file.delete(); } } @@ -113,7 +112,7 @@ public class ScpTest { @Test public void testMultiUploadAndDownload() throws IOException { assertNotNull("system property scp.tmp must be set", tempDir); - List uploadList = new ArrayList(); + List uploadList = new ArrayList(); for (int i = 0; i < 5; i++) { uploadList.add(createTemporaryFile()); } @@ -137,8 +136,7 @@ public class ScpTest { scpTask.execute(); FilesMatch match = new FilesMatch(); - for (Iterator i = uploadList.iterator(); i.hasNext();) { - File f = (File) i.next(); + for (File f : uploadList) { match.setFile1(f); File f2 = new File(multi, f.getName()); match.setFile2(f2); diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java index ce86f06aa..e225f13a2 100644 --- a/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java +++ b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java @@ -59,8 +59,8 @@ public class ClassFileSetTest { DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); String[] scannedFiles = scanner.getIncludedFiles(); Hashtable files = new Hashtable(); - for (int i = 0; i < scannedFiles.length; ++i) { - files.put(scannedFiles[i], scannedFiles[i]); + for (String scannedFile : scannedFiles) { + files.put(scannedFile, scannedFile); } assertEquals("Classfileset did not pick up expected number of " + "class files", 4, files.size()); @@ -85,8 +85,8 @@ public class ClassFileSetTest { DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); String[] scannedFiles = scanner.getIncludedFiles(); Hashtable files = new Hashtable(); - for (int i = 0; i < scannedFiles.length; ++i) { - files.put(scannedFiles[i], scannedFiles[i]); + for (String scannedFile : scannedFiles) { + files.put(scannedFile, scannedFile); } assertEquals("Classfileset did not pick up expected number of " + "class files", 2, files.size()); @@ -107,8 +107,8 @@ public class ClassFileSetTest { DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); String[] scannedFiles = scanner.getIncludedFiles(); Hashtable files = new Hashtable(); - for (int i = 0; i < scannedFiles.length; ++i) { - files.put(scannedFiles[i], scannedFiles[i]); + for (String scannedFile : scannedFiles) { + files.put(scannedFile, scannedFile); } assertEquals("Classfileset did not pick up expected number of " + "class files", 1, files.size()); @@ -135,8 +135,8 @@ public class ClassFileSetTest { DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); String[] scannedFiles = scanner.getIncludedFiles(); Hashtable files = new Hashtable(); - for (int i = 0; i < scannedFiles.length; ++i) { - files.put(scannedFiles[i], scannedFiles[i]); + for (String scannedFile : scannedFiles) { + files.put(scannedFile, scannedFile); } assertEquals("Classfileset did not pick up expected number of " + "class files", 5, files.size()); @@ -163,8 +163,8 @@ public class ClassFileSetTest { DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); String[] scannedFiles = scanner.getIncludedFiles(); Hashtable files = new Hashtable(); - for (int i = 0; i < scannedFiles.length; ++i) { - files.put(scannedFiles[i], scannedFiles[i]); + for (String scannedFile : scannedFiles) { + files.put(scannedFile, scannedFile); } assertEquals("Classfileset did not pick up expected number of " + "class files", 4, files.size()); From 64809d976e89e1dc36efd825772caf2b07c4f7da Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 20:03:32 +0200 Subject: [PATCH 4/9] Bad merge: missed a diamond --- src/main/org/apache/tools/ant/taskdefs/Recorder.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/org/apache/tools/ant/taskdefs/Recorder.java b/src/main/org/apache/tools/ant/taskdefs/Recorder.java index d632a85c4..2640e9097 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Recorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/Recorder.java @@ -67,7 +67,8 @@ public class Recorder extends Task implements SubBuildListener { /** Strip task banners if true. */ private boolean emacsMode = false; /** The list of recorder entries. */ - private static Hashtable recorderEntries = new Hashtable<>(); + private static Hashtable recorderEntries + = new Hashtable(); ////////////////////////////////////////////////////////////////////// // CONSTRUCTORS / INITIALIZERS From baba2b85bb3a9ec802f3131d5500232e3d874792 Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 20:31:34 +0200 Subject: [PATCH 5/9] More merge problems --- .../apache/tools/ant/filters/BaseParamFilterReader.java | 2 +- .../apache/tools/ant/types/selectors/SelectorUtils.java | 9 ++++----- .../org/apache/tools/ant/IntrospectionHelperTest.java | 2 +- .../junit/org/apache/tools/ant/UnknownElementTest.java | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/org/apache/tools/ant/filters/BaseParamFilterReader.java b/src/main/org/apache/tools/ant/filters/BaseParamFilterReader.java index f3a8e5e03..54bc9ff92 100644 --- a/src/main/org/apache/tools/ant/filters/BaseParamFilterReader.java +++ b/src/main/org/apache/tools/ant/filters/BaseParamFilterReader.java @@ -58,7 +58,7 @@ public abstract class BaseParamFilterReader * @param parameters The parameters to be used by this filter. * Should not be null. */ - public final void setParameters(final Parameter... parameters) { + public final void setParameters(final Parameter[] parameters) { this.parameters = parameters; setInitialized(false); } diff --git a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java index 24630e865..a2804c2ee 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java +++ b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java @@ -366,7 +366,6 @@ public final class SelectorUtils { int patIdxEnd = patArr.length - 1; int strIdxStart = 0; int strIdxEnd = strArr.length - 1; - char ch; boolean containsStar = false; for (char ch : patArr) { @@ -382,7 +381,7 @@ public final class SelectorUtils { return false; // Pattern and string do not have the same size } for (int i = 0; i <= patIdxEnd; i++) { - ch = patArr[i]; + char ch = patArr[i]; if (ch != '?') { if (different(caseSensitive, ch, strArr[i])) { return false; // Character mismatch @@ -398,7 +397,7 @@ public final class SelectorUtils { // Process characters before first star while (true) { - ch = patArr[patIdxStart]; + char ch = patArr[patIdxStart]; if (ch == '*' || strIdxStart > strIdxEnd) { break; } @@ -418,7 +417,7 @@ public final class SelectorUtils { // Process characters after last star while (true) { - ch = patArr[patIdxEnd]; + char ch = patArr[patIdxEnd]; if (ch == '*' || strIdxStart > strIdxEnd) { break; } @@ -459,7 +458,7 @@ public final class SelectorUtils { strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { - ch = patArr[patIdxStart + j + 1]; + char ch = patArr[patIdxStart + j + 1]; if (ch != '?') { if (different(caseSensitive, ch, strArr[strIdxStart + i + j])) { diff --git a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java index cc9a0fe66..058e62842 100644 --- a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java +++ b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java @@ -204,7 +204,7 @@ public class IntrospectionHelperTest { } private Map> getExpectedNestedElements() { - Map> elemMap = new Hashtable<>(); + Map> elemMap = new Hashtable>(); elemMap.put("six", String.class); elemMap.put("thirteen", StringBuffer.class); elemMap.put("fourteen", StringBuffer.class); diff --git a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java index 003f1a964..22688d6d2 100644 --- a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java +++ b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java @@ -96,7 +96,7 @@ public class UnknownElementTest { } public static class Parent extends Task implements TaskContainer { - List children = new ArrayList<>(); + List children = new ArrayList(); public void addTask(Task t) { children.add(t); } From 4c03d7113ce8b00272640d20f3422c9667db71ec Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 22:08:45 +0200 Subject: [PATCH 6/9] More foreach loops (cherry-pick 061d29b) --- src/main/org/apache/tools/ant/Project.java | 4 +--- src/main/org/apache/tools/ant/taskdefs/CVSPass.java | 6 +++--- src/main/org/apache/tools/ant/taskdefs/Concat.java | 7 ++----- src/main/org/apache/tools/ant/taskdefs/MacroInstance.java | 3 +-- src/main/org/apache/tools/ant/taskdefs/SQLExec.java | 6 ++---- .../org/apache/tools/ant/taskdefs/condition/IsSigned.java | 6 ++---- .../tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java | 7 ++----- .../tools/ant/taskdefs/optional/jsp/JspNameMangler.java | 3 +-- src/main/org/apache/tools/ant/util/StringUtils.java | 3 +-- src/main/org/apache/tools/tar/TarOutputStream.java | 7 +++---- 10 files changed, 18 insertions(+), 34 deletions(-) diff --git a/src/main/org/apache/tools/ant/Project.java b/src/main/org/apache/tools/ant/Project.java index b8636d945..49061c029 100644 --- a/src/main/org/apache/tools/ant/Project.java +++ b/src/main/org/apache/tools/ant/Project.java @@ -946,9 +946,7 @@ public class Project implements ResourceFactory { */ public void setSystemProperties() { final Properties systemP = System.getProperties(); - final Enumeration e = systemP.propertyNames(); - while (e.hasMoreElements()) { - final String propertyName = (String) e.nextElement(); + for (final String propertyName : systemP.stringPropertyNames()) { final String value = systemP.getProperty(propertyName); if (value != null) { this.setPropertyInternal(propertyName, value); diff --git a/src/main/org/apache/tools/ant/taskdefs/CVSPass.java b/src/main/org/apache/tools/ant/taskdefs/CVSPass.java index e39adef05..1d3ad8365 100644 --- a/src/main/org/apache/tools/ant/taskdefs/CVSPass.java +++ b/src/main/org/apache/tools/ant/taskdefs/CVSPass.java @@ -129,9 +129,9 @@ public class CVSPass extends Task { } private final String mangle(String password) { - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < password.length(); i++) { - buf.append(shifts[password.charAt(i)]); + StringBuilder buf = new StringBuilder(); + for (final char ch : password.toCharArray()) { + buf.append(shifts[ch]); } return buf.toString(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/Concat.java b/src/main/org/apache/tools/ant/taskdefs/Concat.java index 93560ce06..a095a4e54 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Concat.java +++ b/src/main/org/apache/tools/ant/taskdefs/Concat.java @@ -185,12 +185,9 @@ public class Concat extends Task implements ResourceCollection { value = ""; } if (trimLeading) { - char[] current = value.toCharArray(); - StringBuffer b = new StringBuffer(current.length); + StringBuilder b = new StringBuilder(); boolean startOfLine = true; - int pos = 0; - while (pos < current.length) { - char ch = current[pos++]; + for (final char ch : value.toCharArray()) { if (startOfLine) { if (ch == ' ' || ch == '\t') { continue; diff --git a/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java b/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java index 9ffa9b2e1..124f09e7e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java +++ b/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java @@ -173,8 +173,7 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain StringBuffer macroName = null; int state = STATE_NORMAL; - for (int i = 0; i < s.length(); ++i) { - char ch = s.charAt(i); + for (final char ch : s.toCharArray()) { switch (state) { case STATE_NORMAL: if (ch == '@') { diff --git a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java index e801ac02f..3f56c47ca 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java @@ -937,11 +937,9 @@ public class SQLExec extends JDBCTask { if (csvQuoteChar == null || s == null || (!forceCsvQuoteChar && s.indexOf(csvColumnSep) == -1 && s.indexOf(csvQuoteChar) == -1)) { return s; } - StringBuffer sb = new StringBuffer(csvQuoteChar); - int len = s.length(); + StringBuilder sb = new StringBuilder(csvQuoteChar); char q = csvQuoteChar.charAt(0); - for (int i = 0; i < len; i++) { - char c = s.charAt(i); + for (final char c : s.toCharArray()) { if (c == q) { sb.append(q); } diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/IsSigned.java b/src/main/org/apache/tools/ant/taskdefs/condition/IsSigned.java index 585fb3a78..277a921fa 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/IsSigned.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/IsSigned.java @@ -135,11 +135,9 @@ public class IsSigned extends DataType implements Condition { } private static String replaceInvalidChars(final String name) { - StringBuffer sb = new StringBuffer(); - final int len = name.length(); + StringBuilder sb = new StringBuilder(); boolean changes = false; - for (int i = 0; i < len; i++) { - final char ch = name.charAt(i); + for (final char ch : name.toCharArray()) { if (ManifestTask.VALID_ATTRIBUTE_CHARS.indexOf(ch) < 0) { sb.append("_"); changes = true; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java index 609938c95..c71a6d5ef 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java @@ -37,17 +37,14 @@ public class Jasper41Mangler implements JspMangler { public String mapJspToJavaName(File jspFile) { String jspUri = jspFile.getAbsolutePath(); int start = jspUri.lastIndexOf(File.separatorChar) + 1; - int end = jspUri.length(); - StringBuffer modifiedClassName; - modifiedClassName = new StringBuffer(jspUri.length() - start); + StringBuilder modifiedClassName = new StringBuilder(jspUri.length() - start); if (!Character.isJavaIdentifierStart(jspUri.charAt(start)) || jspUri.charAt(start) == '_') { // If the first char is not a start of Java identifier or is _ // prepend a '_'. modifiedClassName.append('_'); } - for (int i = start; i < end; i++) { - char ch = jspUri.charAt(i); + for (final char ch : jspUri.substring(start).toCharArray()) { if (Character.isJavaIdentifierPart(ch)) { modifiedClassName.append(ch); } else if (ch == '.') { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java index 965f41308..855376ac0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java @@ -92,8 +92,7 @@ public class JspNameMangler implements JspMangler { modifiedClassName.append(mangleChar(firstChar)); } // this is the rest - for (int i = 1; i < className.length(); i++) { - char subChar = className.charAt(i); + for (final char subChar : className.substring(1).toCharArray()) { if (Character.isJavaIdentifierPart(subChar)) { modifiedClassName.append(subChar); } else { diff --git a/src/main/org/apache/tools/ant/util/StringUtils.java b/src/main/org/apache/tools/ant/util/StringUtils.java index 4bb349707..a387821c2 100644 --- a/src/main/org/apache/tools/ant/util/StringUtils.java +++ b/src/main/org/apache/tools/ant/util/StringUtils.java @@ -151,8 +151,7 @@ public final class StringUtils { public static String resolveBackSlash(String input) { StringBuffer b = new StringBuffer(); boolean backSlashSeen = false; - for (int i = 0; i < input.length(); ++i) { - char c = input.charAt(i); + for (final char c : input.toCharArray()) { if (!backSlashSeen) { if (c == '\\') { backSlashSeen = true; diff --git a/src/main/org/apache/tools/tar/TarOutputStream.java b/src/main/org/apache/tools/tar/TarOutputStream.java index 217ed208d..d055caa2b 100644 --- a/src/main/org/apache/tools/tar/TarOutputStream.java +++ b/src/main/org/apache/tools/tar/TarOutputStream.java @@ -521,10 +521,9 @@ public class TarOutputStream extends FilterOutputStream { } private String stripTo7Bits(String name) { - final int length = name.length(); - StringBuilder result = new StringBuilder(length); - for (int i = 0; i < length; i++) { - char stripped = (char) (name.charAt(i) & 0x7F); + StringBuilder result = new StringBuilder(name.length()); + for (final char ch : name.toCharArray()) { + char stripped = (char) (ch & 0x7F); if (stripped != 0) { // would be read as Trailing null result.append(stripped); } From 520c0c6de1a9c5551ffdf8c5b6936d2b1976c633 Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 22:31:48 +0200 Subject: [PATCH 7/9] Revert use of Java 6 --- src/main/org/apache/tools/ant/Project.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/org/apache/tools/ant/Project.java b/src/main/org/apache/tools/ant/Project.java index 49061c029..b8636d945 100644 --- a/src/main/org/apache/tools/ant/Project.java +++ b/src/main/org/apache/tools/ant/Project.java @@ -946,7 +946,9 @@ public class Project implements ResourceFactory { */ public void setSystemProperties() { final Properties systemP = System.getProperties(); - for (final String propertyName : systemP.stringPropertyNames()) { + final Enumeration e = systemP.propertyNames(); + while (e.hasMoreElements()) { + final String propertyName = (String) e.nextElement(); final String value = systemP.getProperty(propertyName); if (value != null) { this.setPropertyInternal(propertyName, value); From 4e3e565ece3420005a63b663128dd11ae477cc1c Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 22:51:23 +0200 Subject: [PATCH 8/9] Use String#contains() (cherry-pick 92f18cf) --- .../tools/ant/filters/LineContains.java | 2 +- .../apache/tools/ant/filters/TokenFilter.java | 2 +- .../org/apache/tools/ant/taskdefs/Copy.java | 2 +- .../org/apache/tools/ant/taskdefs/Exec.java | 6 +- .../apache/tools/ant/taskdefs/ExecTask.java | 2 +- .../apache/tools/ant/taskdefs/JDBCTask.java | 4 +- .../org/apache/tools/ant/taskdefs/Jar.java | 2 +- .../apache/tools/ant/taskdefs/Javadoc.java | 4 +- .../org/apache/tools/ant/taskdefs/Jikes.java | 2 +- .../tools/ant/taskdefs/JikesOutputParser.java | 4 +- .../org/apache/tools/ant/taskdefs/Rmic.java | 2 +- .../apache/tools/ant/taskdefs/SQLExec.java | 5 +- .../apache/tools/ant/taskdefs/VerifyJar.java | 8 +- .../compilers/DefaultCompilerAdapter.java | 2 +- .../ant/taskdefs/condition/Contains.java | 4 +- .../tools/ant/taskdefs/condition/Os.java | 30 +++--- .../taskdefs/condition/ResourceContains.java | 2 +- .../tools/ant/taskdefs/optional/ANTLR.java | 11 +-- .../tools/ant/taskdefs/optional/NetRexxC.java | 14 +-- .../ant/taskdefs/optional/depend/Depend.java | 2 +- .../optional/ejb/JonasDeploymentTool.java | 2 +- .../ant/taskdefs/optional/javah/Gcjh.java | 2 +- .../ant/taskdefs/optional/javah/Kaffeh.java | 2 +- .../ant/taskdefs/optional/jlink/jlink.java | 4 +- .../optional/junit/JUnitTestRunner.java | 2 +- .../tools/ant/taskdefs/optional/net/FTP.java | 9 +- .../optional/net/FTPTaskMirrorImpl.java | 9 +- .../ant/taskdefs/optional/ssh/SSHExec.java | 2 +- .../ant/taskdefs/optional/ssh/SSHSession.java | 2 +- .../apache/tools/ant/types/Commandline.java | 18 ++-- .../org/apache/tools/ant/types/FilterSet.java | 3 +- src/main/org/apache/tools/ant/types/Path.java | 5 +- .../ant/types/resources/selectors/Name.java | 2 +- .../ant/types/selectors/ContainsSelector.java | 2 +- .../tools/ant/util/RegexpPatternMapper.java | 2 +- src/main/org/apache/tools/tar/TarEntry.java | 2 +- .../org/apache/tools/ant/BuildFileTest.java | 15 +-- .../org/apache/tools/ant/LocationTest.java | 10 +- .../apache/tools/ant/TaskContainerTest.java | 14 +-- .../apache/tools/ant/taskdefs/AntTest.java | 6 +- .../apache/tools/ant/taskdefs/ConcatTest.java | 10 +- .../apache/tools/ant/taskdefs/CopyTest.java | 2 +- .../apache/tools/ant/taskdefs/JarTest.java | 24 ++--- .../tools/ant/taskdefs/LoadFileTest.java | 6 +- .../tools/ant/taskdefs/MacroDefTest.java | 2 +- .../tools/ant/taskdefs/MakeUrlTest.java | 2 +- .../tools/ant/taskdefs/ManifestTest.java | 4 +- .../tools/ant/taskdefs/PropertyTest.java | 2 +- .../tools/ant/taskdefs/RmicAdvancedTest.java | 2 +- .../tools/ant/taskdefs/SQLExecTest.java | 2 +- .../apache/tools/ant/taskdefs/StyleTest.java | 2 +- .../apache/tools/ant/taskdefs/SyncTest.java | 16 ++-- .../tools/ant/taskdefs/TaskdefTest.java | 6 +- .../taskdefs/optional/EchoPropertiesTest.java | 2 +- .../taskdefs/optional/XmlValidateTest.java | 3 +- .../tools/ant/taskdefs/optional/XsltTest.java | 2 +- .../taskdefs/optional/image/ImageTest.java | 2 +- .../optional/junit/JUnitTestRunnerTest.java | 2 +- .../optional/script/ScriptDefTest.java | 14 +-- .../tools/ant/types/CommandlineJavaTest.java | 2 +- .../org/apache/tools/ant/types/PathTest.java | 2 +- .../ant/types/RedirectorElementTest.java | 2 +- .../types/selectors/ModifiedSelectorTest.java | 2 +- .../util/LayoutPreservingPropertiesTest.java | 94 ++++++++----------- 64 files changed, 202 insertions(+), 228 deletions(-) diff --git a/src/main/org/apache/tools/ant/filters/LineContains.java b/src/main/org/apache/tools/ant/filters/LineContains.java index d74d4dd91..a5492518a 100644 --- a/src/main/org/apache/tools/ant/filters/LineContains.java +++ b/src/main/org/apache/tools/ant/filters/LineContains.java @@ -118,7 +118,7 @@ public final class LineContains boolean matches = true; for (int i = 0; matches && i < containsSize; i++) { String containsStr = (String) contains.elementAt(i); - matches = line.indexOf(containsStr) >= 0; + matches = line.contains(containsStr); } if (matches ^ isNegated()) { break; diff --git a/src/main/org/apache/tools/ant/filters/TokenFilter.java b/src/main/org/apache/tools/ant/filters/TokenFilter.java index ebad76027..7da00cd60 100644 --- a/src/main/org/apache/tools/ant/filters/TokenFilter.java +++ b/src/main/org/apache/tools/ant/filters/TokenFilter.java @@ -428,7 +428,7 @@ public class TokenFilter extends BaseFilterReader if (contains == null) { throw new BuildException("Missing contains in containsstring"); } - if (string.indexOf(contains) > -1) { + if (string.contains(contains)) { return string; } return null; diff --git a/src/main/org/apache/tools/ant/taskdefs/Copy.java b/src/main/org/apache/tools/ant/taskdefs/Copy.java index 5845523a0..371c366d7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Copy.java +++ b/src/main/org/apache/tools/ant/taskdefs/Copy.java @@ -1091,7 +1091,7 @@ public class Copy extends Task { } message.append(ex.getMessage()); } - if (ex.getClass().getName().indexOf("MalformedInput") != -1) { + if (ex.getClass().getName().contains("MalformedInput")) { message.append(LINE_SEPARATOR); message.append( "This is normally due to the input file containing invalid"); diff --git a/src/main/org/apache/tools/ant/taskdefs/Exec.java b/src/main/org/apache/tools/ant/taskdefs/Exec.java index cfc6b76c8..8247023db 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Exec.java +++ b/src/main/org/apache/tools/ant/taskdefs/Exec.java @@ -87,7 +87,7 @@ public class Exec extends Task { // test if os match String myos = System.getProperty("os.name"); log("Myos = " + myos, Project.MSG_VERBOSE); - if ((os != null) && (os.indexOf(myos) < 0)) { + if (os != null && !os.contains(myos)) { // this command will be executed only on the specified OS log("Not found in " + os, Project.MSG_VERBOSE); return 0; @@ -98,9 +98,9 @@ public class Exec extends Task { dir = getProject().getBaseDir(); } - if (myos.toLowerCase(Locale.ENGLISH).indexOf("windows") >= 0) { + if (myos.toLowerCase(Locale.ENGLISH).contains("windows")) { if (!dir.equals(getProject().resolveFile("."))) { - if (myos.toLowerCase(Locale.ENGLISH).indexOf("nt") >= 0) { + if (myos.toLowerCase(Locale.ENGLISH).contains("nt")) { command = "cmd /c cd " + dir + " && " + command; } else { String ant = getProject().getProperty(MagicNames.ANT_HOME); diff --git a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java index cc3c2bdf8..30f673a75 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ExecTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ExecTask.java @@ -563,7 +563,7 @@ public class ExecTask extends Task { //for the current os.name String myos = System.getProperty("os.name"); log("Current OS is " + myos, Project.MSG_VERBOSE); - if ((os != null) && (os.indexOf(myos) < 0)) { + if (os != null && !os.contains(myos)) { // this command will be executed only on the specified OS log("This OS, " + myos + " was not found in the specified list of valid OSes: " + os, diff --git a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java index 0954e7069..312211543 100644 --- a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java @@ -270,7 +270,7 @@ public abstract class JDBCTask extends Task { String theVendor = dmd.getDatabaseProductName().toLowerCase(); log("RDBMS = " + theVendor, Project.MSG_VERBOSE); - if (theVendor == null || theVendor.indexOf(rdbms) < 0) { + if (theVendor == null || !theVendor.contains(rdbms)) { log("Not the required RDBMS: " + rdbms, Project.MSG_VERBOSE); return false; } @@ -282,7 +282,7 @@ public abstract class JDBCTask extends Task { log("Version = " + theVersion, Project.MSG_VERBOSE); if (theVersion == null || !(theVersion.startsWith(version) - || theVersion.indexOf(" " + version) >= 0)) { + || theVersion.contains(" " + version))) { log("Not the required version: \"" + version + "\"", Project.MSG_VERBOSE); return false; } diff --git a/src/main/org/apache/tools/ant/taskdefs/Jar.java b/src/main/org/apache/tools/ant/taskdefs/Jar.java index 26ee08753..adea841d0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jar.java @@ -714,7 +714,7 @@ public class Jar extends Zip { + " be replaced by a newly generated one.", Project.MSG_WARN); } else { - if (index && vPath.indexOf("/") == -1) { + if (index && !vPath.contains("/")) { rootEntries.addElement(vPath); } super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode); diff --git a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java index a78c526c5..7a5c2ec84 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java +++ b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java @@ -2230,7 +2230,7 @@ public class Javadoc extends Task { if (useExternalFile) { // TODO what is the following doing? // should it run if !javadoc4 && executable != null? - if (sourceFileName.indexOf(" ") > -1) { + if (sourceFileName.contains(" ")) { String name = sourceFileName; if (File.separatorChar == '\\') { name = sourceFileName.replace(File.separatorChar, '/'); @@ -2516,7 +2516,7 @@ public class Javadoc extends Task { // check if file may be vulnerable because it was not // patched with "validURL(url)": - if (fileContents.indexOf("function validURL(url) {") < 0) { + if (!fileContents.contains("function validURL(url) {")) { // we need to patch the file! final String patchedFileContents = patchContent(fileContents, fixData); if (!patchedFileContents.equals(fileContents)) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Jikes.java b/src/main/org/apache/tools/ant/taskdefs/Jikes.java index 89ac3f1f7..3896001a4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jikes.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jikes.java @@ -83,7 +83,7 @@ public class Jikes { // Windows has a 32k limit on total arg size, so // create a temporary file to store all the arguments - if (myos.toLowerCase(Locale.ENGLISH).indexOf("windows") >= 0 + if (myos.toLowerCase(Locale.ENGLISH).contains("windows") && args.length > MAX_FILES_ON_COMMAND_LINE) { BufferedWriter out = null; try { diff --git a/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java b/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java index b0fc19ddb..5ffb954d3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java +++ b/src/main/org/apache/tools/ant/taskdefs/JikesOutputParser.java @@ -136,9 +136,9 @@ public class JikesOutputParser implements ExecuteStreamHandler { if (line.trim().equals("")) { continue; } - if (lower.indexOf("error") != -1) { + if (lower.contains("error")) { setError(true); - } else if (lower.indexOf("warning") != -1) { + } else if (lower.contains("warning")) { setError(false); } else { // If we don't know the type of the line diff --git a/src/main/org/apache/tools/ant/taskdefs/Rmic.java b/src/main/org/apache/tools/ant/taskdefs/Rmic.java index e093e498a..e20518ac7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Rmic.java +++ b/src/main/org/apache/tools/ant/taskdefs/Rmic.java @@ -761,7 +761,7 @@ public class Rmic extends MatchingTask { if (idl) { log("will leave uptodate test to rmic implementation in idl mode.", Project.MSG_VERBOSE); - } else if (iiop && iiopOpts != null && iiopOpts.indexOf("-always") > -1) { + } else if (iiop && iiopOpts != null && iiopOpts.contains("-always")) { log("no uptodate test as -always option has been specified", Project.MSG_VERBOSE); } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java index 3f56c47ca..25bc68abd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java @@ -778,7 +778,7 @@ public class SQLExec extends JDBCTask { // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it - if (!keepformat && line.indexOf("--") >= 0) { + if (!keepformat && line.contains("--")) { sql.append("\n"); } int lastDelimPos = lastDelimiterPosition(sql, line); @@ -934,7 +934,8 @@ public class SQLExec extends JDBCTask { } private String maybeQuote(String s) { - if (csvQuoteChar == null || s == null || (!forceCsvQuoteChar && s.indexOf(csvColumnSep) == -1 && s.indexOf(csvQuoteChar) == -1)) { + if (csvQuoteChar == null || s == null + || (!forceCsvQuoteChar && !s.contains(csvColumnSep) && !s.contains(csvQuoteChar))) { return s; } StringBuilder sb = new StringBuilder(csvQuoteChar); diff --git a/src/main/org/apache/tools/ant/taskdefs/VerifyJar.java b/src/main/org/apache/tools/ant/taskdefs/VerifyJar.java index 187a02171..77408df38 100644 --- a/src/main/org/apache/tools/ant/taskdefs/VerifyJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/VerifyJar.java @@ -180,15 +180,15 @@ public class VerifyJar extends AbstractJarSignerTask { String results = outputCache.toString(); //deal with jdk1.4.2 bug: if (ex != null) { - if (results.indexOf("zip file closed") >= 0) { - log("You are running " + JARSIGNER_COMMAND + " against a JVM with" - + " a known bug that manifests as an IllegalStateException.", + if (results.contains("zip file closed")) { + log("You are running " + JARSIGNER_COMMAND + + " against a JVM with a known bug that manifests as an IllegalStateException.", Project.MSG_WARN); } else { throw ex; } } - if (results.indexOf(VERIFIED_TEXT) < 0) { + if (!results.contains(VERIFIED_TEXT)) { throw new BuildException(ERROR_NO_VERIFY + jar); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java b/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java index 1cd5e6233..9577632bf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java @@ -559,7 +559,7 @@ public abstract class DefaultCompilerAdapter "files", "", getJavac().getTempdir(), true, true); out = new BufferedWriter(new FileWriter(tmpFile)); for (int i = firstFileName; i < args.length; i++) { - if (quoteFiles && args[i].indexOf(" ") > -1) { + if (quoteFiles && args[i].contains(" ")) { args[i] = args[i].replace(File.separatorChar, '/'); out.write("\"" + args[i] + "\""); } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/Contains.java b/src/main/org/apache/tools/ant/taskdefs/condition/Contains.java index 8830a39dc..347c47409 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/Contains.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/Contains.java @@ -70,7 +70,7 @@ public class Contains implements Condition { } return caseSensitive - ? string.indexOf(subString) > -1 - : string.toLowerCase().indexOf(subString.toLowerCase()) > -1; + ? string.contains(subString) + : string.toLowerCase().contains(subString.toLowerCase()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/Os.java b/src/main/org/apache/tools/ant/taskdefs/condition/Os.java index 7bd5b0123..ace0c66bd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/Os.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/Os.java @@ -257,17 +257,17 @@ public class Os implements Condition { //windows probing logic relies on the word 'windows' in //the OS - boolean isWindows = OS_NAME.indexOf(FAMILY_WINDOWS) > -1; + boolean isWindows = OS_NAME.contains(FAMILY_WINDOWS); boolean is9x = false; boolean isNT = false; if (isWindows) { //there are only four 9x platforms that we look for - is9x = (OS_NAME.indexOf("95") >= 0 - || OS_NAME.indexOf("98") >= 0 - || OS_NAME.indexOf("me") >= 0 + is9x = (OS_NAME.contains("95") + || OS_NAME.contains("98") + || OS_NAME.contains("me") //wince isn't really 9x, but crippled enough to //be a muchness. Ant doesn't run on CE, anyway. - || OS_NAME.indexOf("ce") >= 0); + || OS_NAME.contains("ce")); isNT = !is9x; } if (family.equals(FAMILY_WINDOWS)) { @@ -277,28 +277,28 @@ public class Os implements Condition { } else if (family.equals(FAMILY_NT)) { isFamily = isWindows && isNT; } else if (family.equals(FAMILY_OS2)) { - isFamily = OS_NAME.indexOf(FAMILY_OS2) > -1; + isFamily = OS_NAME.contains(FAMILY_OS2); } else if (family.equals(FAMILY_NETWARE)) { - isFamily = OS_NAME.indexOf(FAMILY_NETWARE) > -1; + isFamily = OS_NAME.contains(FAMILY_NETWARE); } else if (family.equals(FAMILY_DOS)) { isFamily = PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE); } else if (family.equals(FAMILY_MAC)) { - isFamily = OS_NAME.indexOf(FAMILY_MAC) > -1 - || OS_NAME.indexOf(DARWIN) > -1; + isFamily = OS_NAME.contains(FAMILY_MAC) + || OS_NAME.contains(DARWIN); } else if (family.equals(FAMILY_TANDEM)) { - isFamily = OS_NAME.indexOf("nonstop_kernel") > -1; + isFamily = OS_NAME.contains("nonstop_kernel"); } else if (family.equals(FAMILY_UNIX)) { isFamily = PATH_SEP.equals(":") && !isFamily(FAMILY_VMS) && (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x") - || OS_NAME.indexOf(DARWIN) > -1); + || OS_NAME.contains(DARWIN)); } else if (family.equals(FAMILY_ZOS)) { - isFamily = OS_NAME.indexOf(FAMILY_ZOS) > -1 - || OS_NAME.indexOf("os/390") > -1; + isFamily = OS_NAME.contains(FAMILY_ZOS) + || OS_NAME.contains("os/390"); } else if (family.equals(FAMILY_OS400)) { - isFamily = OS_NAME.indexOf(FAMILY_OS400) > -1; + isFamily = OS_NAME.contains(FAMILY_OS400); } else if (family.equals(FAMILY_VMS)) { - isFamily = OS_NAME.indexOf(FAMILY_VMS) > -1; + isFamily = OS_NAME.contains(FAMILY_VMS); } else { throw new BuildException( "Don\'t know how to detect os family \"" diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/ResourceContains.java b/src/main/org/apache/tools/ant/taskdefs/condition/ResourceContains.java index 76a9ad35d..aed4c4375 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/ResourceContains.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/ResourceContains.java @@ -155,7 +155,7 @@ public class ResourceContains implements Condition { contents = contents.toLowerCase(); sub = sub.toLowerCase(); } - return contents.indexOf(sub) >= 0; + return contents.contains(sub); } catch (IOException e) { throw new BuildException("There was a problem accessing resource : " + resource); } finally { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java index ba8afd275..2f73c3fe8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java @@ -302,12 +302,11 @@ public class ANTLR extends Task { int err = run(commandline.getCommandline()); if (err != 0) { throw new BuildException("ANTLR returned: " + err, getLocation()); - } else { - String output = bos.toString(); - if (output.indexOf("error:") > -1) { - throw new BuildException("ANTLR signaled an error: " - + output, getLocation()); - } + } + String output = bos.toString(); + if (output.contains("error:")) { + throw new BuildException("ANTLR signaled an error: " + + output, getLocation()); } } else { log("Skipped grammar file. Generated file " + generatedFile diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java index a8aec7b6b..5d7b8b2e5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java @@ -887,24 +887,24 @@ public class NetRexxC extends MatchingTask { } // verbose level logging for suppressed messages if (suppressMethodArgumentNotUsed - && l.indexOf(MSG_METHOD_ARGUMENT_NOT_USED) != -1) { + && l.contains(MSG_METHOD_ARGUMENT_NOT_USED)) { log(l, Project.MSG_VERBOSE); } else if (suppressPrivatePropertyNotUsed - && l.indexOf(MSG_PRIVATE_PROPERTY_NOT_USED) != -1) { + && l.contains(MSG_PRIVATE_PROPERTY_NOT_USED)) { log(l, Project.MSG_VERBOSE); } else if (suppressVariableNotUsed - && l.indexOf(MSG_VARIABLE_NOT_USED) != -1) { + && l.contains(MSG_VARIABLE_NOT_USED)) { log(l, Project.MSG_VERBOSE); } else if (suppressExceptionNotSignalled - && l.indexOf(MSG_EXCEPTION_NOT_SIGNALLED) != -1) { + && l.contains(MSG_EXCEPTION_NOT_SIGNALLED)) { log(l, Project.MSG_VERBOSE); } else if (suppressDeprecation - && l.indexOf(MSG_DEPRECATION) != -1) { + && l.contains(MSG_DEPRECATION)) { log(l, Project.MSG_VERBOSE); - } else if (l.indexOf("Error:") != -1) { + } else if (l.contains("Error:")) { // error level logging for compiler errors log(l, Project.MSG_ERR); - } else if (l.indexOf("Warning:") != -1) { + } else if (l.contains("Warning:")) { // warning for all warning messages log(l, Project.MSG_WARN); } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java index 7b5113392..99a49c4d6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java @@ -522,7 +522,7 @@ public class Depend extends MatchingTask { // without closure we may delete an inner class but not the // top level class which would not trigger a recompile. - if (affectedClass.indexOf("$") == -1) { + if (!affectedClass.contains("$")) { continue; } // need to delete the main class diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java index d474f8b47..07ca610b9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java @@ -465,7 +465,7 @@ public class JonasDeploymentTool extends GenericDeploymentTool { if (getConfig().namingScheme.getValue().equals(EjbJar.NamingScheme.DESCRIPTOR)) { // try to find JOnAS specific convention name - if (descriptorFileName.indexOf(getConfig().baseNameTerminator) == -1) { + if (!descriptorFileName.contains(getConfig().baseNameTerminator)) { // baseNameTerminator not found: the descriptor use the // JOnAS naming convention, ie [Foo.xml,jonas-Foo.xml] and diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javah/Gcjh.java b/src/main/org/apache/tools/ant/taskdefs/optional/javah/Gcjh.java index 712bb76ab..c04eea348 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javah/Gcjh.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javah/Gcjh.java @@ -42,7 +42,7 @@ public class Gcjh implements JavahAdapter { Execute.runCommand(javah, cmd.getCommandline()); return true; } catch (BuildException e) { - if (e.getMessage().indexOf("failed with return code") == -1) { + if (!e.getMessage().contains("failed with return code")) { throw e; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javah/Kaffeh.java b/src/main/org/apache/tools/ant/taskdefs/optional/javah/Kaffeh.java index d37f77175..6bcba8caa 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javah/Kaffeh.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javah/Kaffeh.java @@ -47,7 +47,7 @@ public class Kaffeh implements JavahAdapter { Execute.runCommand(javah, cmd.getCommandline()); return true; } catch (BuildException e) { - if (e.getMessage().indexOf("failed with return code") == -1) { + if (!e.getMessage().contains("failed with return code")) { throw e; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java index ae4a892f9..744fa400e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java @@ -245,9 +245,7 @@ public class jlink { //entry from another mergefile was called "com". //In that case, just ignore the error and go on to the //next entry. - String mess = ex.getMessage(); - - if (mess.indexOf("duplicate") >= 0) { + if (ex.getMessage().contains("duplicate")) { //It was the duplicate entry. continue; } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java index 84104443f..7a0a2f6d0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java @@ -1154,7 +1154,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private static boolean filterLine(final String line) { for (String filter : DEFAULT_TRACE_FILTERS) { - if (line.indexOf(filter) != -1) { + if (line.contains(filter)) { return true; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java index b171df506..35c406569 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java @@ -2093,12 +2093,9 @@ public class FTP extends Task implements FTPTaskConfig { if (!rc) { log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN); } else { - - myReply = ftp.getReplyStrings(); - - for (int x = 0; x < myReply.length; x++) { - if (myReply[x] != null && myReply[x].indexOf("200") == -1) { - log(myReply[x], Project.MSG_WARN); + for (String reply : ftp.getReplyStrings()) { + if (reply != null && !reply.contains("200")) { + log(reply, Project.MSG_WARN); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java index b7235e19d..85d028980 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java @@ -1480,12 +1480,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (!rc) { task.log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN); } else { - - myReply = ftp.getReplyStrings(); - - for (int x = 0; x < myReply.length; x++) { - if (myReply[x].indexOf("200") == -1) { - task.log(myReply[x], Project.MSG_WARN); + for (String reply : ftp.getReplyStrings()) { + if (!reply.contains("200")) { + task.log(reply, Project.MSG_WARN); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java index 80e0ddaf5..13615a296 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java @@ -461,7 +461,7 @@ public class SSHExec extends SSHBase { } catch (final BuildException e) { throw e; } catch (final JSchException e) { - if (e.getMessage().indexOf("session is down") >= 0) { + if (e.getMessage().contains("session is down")) { if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE, e); } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java index bbc186ab2..6394c8686 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java @@ -174,7 +174,7 @@ public class SSHSession extends SSHBase { // completed successfully } catch (final JSchException e) { - if (e.getMessage().indexOf("session is down") >= 0) { + if (e.getMessage().contains("session is down")) { if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE, e); } else { diff --git a/src/main/org/apache/tools/ant/types/Commandline.java b/src/main/org/apache/tools/ant/types/Commandline.java index 1b634efbf..a1859ba79 100644 --- a/src/main/org/apache/tools/ant/types/Commandline.java +++ b/src/main/org/apache/tools/ant/types/Commandline.java @@ -428,21 +428,19 @@ public class Commandline implements Cloneable { * and double quotes. */ public static String quoteArgument(String argument) { - if (argument.indexOf("\"") > -1) { - if (argument.indexOf("\'") > -1) { + if (argument.contains("\"")) { + if (argument.contains("\'")) { throw new BuildException("Can\'t handle single and double" + " quotes in same argument"); - } else { - return '\'' + argument + '\''; } - } else if (argument.indexOf("\'") > -1 - || argument.indexOf(" ") > -1 - // WIN9x uses a bat file for executing commands - || (IS_WIN_9X && argument.indexOf(';') != -1)) { + return '\'' + argument + '\''; + } + if (argument.contains("\'") || argument.contains(" ") + // WIN9x uses a bat file for executing commands + || (IS_WIN_9X && argument.contains(";"))) { return '\"' + argument + '\"'; - } else { - return argument; } + return argument; } /** diff --git a/src/main/org/apache/tools/ant/types/FilterSet.java b/src/main/org/apache/tools/ant/types/FilterSet.java index fbfff11d0..15352f2b6 100644 --- a/src/main/org/apache/tools/ant/types/FilterSet.java +++ b/src/main/org/apache/tools/ant/types/FilterSet.java @@ -616,8 +616,7 @@ public class FilterSet extends DataType implements Cloneable { } passedTokens.addElement(parent); String value = iReplaceTokens(line); - if (value.indexOf(beginToken) == -1 && !duplicateToken - && recurseDepth == 1) { + if (!value.contains(beginToken) && !duplicateToken && recurseDepth == 1) { passedTokens = null; } else if (duplicateToken) { // should always be the case... diff --git a/src/main/org/apache/tools/ant/types/Path.java b/src/main/org/apache/tools/ant/types/Path.java index deaad3efc..f2d4476f5 100644 --- a/src/main/org/apache/tools/ant/types/Path.java +++ b/src/main/org/apache/tools/ant/types/Path.java @@ -601,7 +601,7 @@ public class Path extends DataType implements Cloneable, ResourceCollection { addExisting(systemBootClasspath); } - if (System.getProperty("java.vendor").toLowerCase(Locale.ENGLISH).indexOf("microsoft") >= 0) { + if (System.getProperty("java.vendor").toLowerCase(Locale.ENGLISH).contains("microsoft")) { // TODO is this code still necessary? is there any 1.2+ port? // Pull in *.zip from packages directory FileSet msZipFiles = new FileSet(); @@ -765,8 +765,7 @@ public class Path extends DataType implements Cloneable, ResourceCollection { * @since Ant 1.8.2 */ private static boolean containsWildcards(String path) { - return path != null - && (path.indexOf("*") > -1 || path.indexOf("?") > -1); + return path != null && (path.contains("*") || path.contains("?")); } } diff --git a/src/main/org/apache/tools/ant/types/resources/selectors/Name.java b/src/main/org/apache/tools/ant/types/resources/selectors/Name.java index baf9a3c25..5a4da15a0 100644 --- a/src/main/org/apache/tools/ant/types/resources/selectors/Name.java +++ b/src/main/org/apache/tools/ant/types/resources/selectors/Name.java @@ -143,7 +143,7 @@ public class Name implements ResourceSelector { } private String modify(String s) { - if (s == null || !handleDirSep || s.indexOf("\\") == -1) { + if (s == null || !handleDirSep || !s.contains("\\")) { return s; } return s.replace('\\', '/'); diff --git a/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java b/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java index d0a7a8f59..be149d0f8 100644 --- a/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/ContainsSelector.java @@ -204,7 +204,7 @@ public class ContainsSelector extends BaseExtendSelector implements ResourceSele if (ignorewhitespace) { teststr = SelectorUtils.removeWhitespace(teststr); } - if (teststr.indexOf(userstr) > -1) { + if (teststr.contains(userstr)) { return true; } teststr = in.readLine(); diff --git a/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java b/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java index 6a2f4b5c7..599b7ef58 100644 --- a/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java +++ b/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java @@ -118,7 +118,7 @@ public class RegexpPatternMapper implements FileNameMapper { return null; } if (handleDirSep) { - if (sourceFileName.indexOf("\\") != -1) { + if (sourceFileName.contains("\\")) { sourceFileName = sourceFileName.replace('\\', '/'); } } diff --git a/src/main/org/apache/tools/tar/TarEntry.java b/src/main/org/apache/tools/tar/TarEntry.java index c44e47f7a..afdd9511e 100644 --- a/src/main/org/apache/tools/tar/TarEntry.java +++ b/src/main/org/apache/tools/tar/TarEntry.java @@ -1042,7 +1042,7 @@ public class TarEntry implements TarConstants { fileName = fileName.substring(2); } } - } else if (osname.indexOf("netware") > -1) { + } else if (osname.contains("netware")) { int colon = fileName.indexOf(':'); if (colon != -1) { fileName = fileName.substring(colon + 1); diff --git a/src/tests/junit/org/apache/tools/ant/BuildFileTest.java b/src/tests/junit/org/apache/tools/ant/BuildFileTest.java index e821bae6d..51e2dad12 100644 --- a/src/tests/junit/org/apache/tools/ant/BuildFileTest.java +++ b/src/tests/junit/org/apache/tools/ant/BuildFileTest.java @@ -122,7 +122,7 @@ public abstract class BuildFileTest extends TestCase { String realLog = getLog(); assertTrue("expecting log to contain \"" + substring + "\" log was \"" + realLog + "\"", - realLog.indexOf(substring) >= 0); + realLog.contains(substring)); } /** @@ -134,7 +134,7 @@ public abstract class BuildFileTest extends TestCase { String realLog = getLog(); assertFalse("didn't expect log to contain \"" + substring + "\" log was \"" + realLog + "\"", - realLog.indexOf(substring) >= 0); + realLog.contains(substring)); } /** @@ -160,7 +160,7 @@ public abstract class BuildFileTest extends TestCase { String realMessage = (message != null) ? message : "expecting output to contain \"" + substring + "\" output was \"" + realOutput + "\""; - assertTrue(realMessage, realOutput.indexOf(substring) >= 0); + assertTrue(realMessage, realOutput.contains(substring)); } /** @@ -176,7 +176,7 @@ public abstract class BuildFileTest extends TestCase { String realMessage = (message != null) ? message : "expecting output to not contain \"" + substring + "\" output was \"" + realOutput + "\""; - assertFalse(realMessage, realOutput.indexOf(substring) >= 0); + assertFalse(realMessage, realOutput.contains(substring)); } /** @@ -237,7 +237,7 @@ public abstract class BuildFileTest extends TestCase { assertTrue("expecting debug log to contain \"" + substring + "\" log was \"" + realLog + "\"", - realLog.indexOf(substring) >= 0); + realLog.contains(substring)); } /** @@ -425,8 +425,9 @@ public abstract class BuildFileTest extends TestCase { executeTarget(target); } catch (org.apache.tools.ant.BuildException ex) { buildException = ex; - if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) { - fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)"); + if (null != contains && !ex.getMessage().contains(contains)) { + fail("Should throw BuildException because '" + cause + "' with message containing '" + + contains + "' (actual message '" + ex.getMessage() + "' instead)"); } return; } diff --git a/src/tests/junit/org/apache/tools/ant/LocationTest.java b/src/tests/junit/org/apache/tools/ant/LocationTest.java index c8048a31a..ca7f9b1d9 100644 --- a/src/tests/junit/org/apache/tools/ant/LocationTest.java +++ b/src/tests/junit/org/apache/tools/ant/LocationTest.java @@ -70,18 +70,16 @@ public class LocationTest { public void testMacrodefWrappedTask() { buildRule.executeTarget("testMacrodefWrappedTask"); Echo e = (Echo) buildRule.getProject().getReference("echo3"); - assertTrue(buildRule.getLog().indexOf("Line: " - + (e.getLocation().getLineNumber() + 1)) - > -1); + assertTrue(buildRule.getLog().contains("Line: " + + (e.getLocation().getLineNumber() + 1))); } @Test public void testPresetdefWrappedTask() { buildRule.executeTarget("testPresetdefWrappedTask"); Echo e = (Echo) buildRule.getProject().getReference("echo4"); - assertTrue(buildRule.getLog().indexOf("Line: " - + (e.getLocation().getLineNumber() + 1)) - > -1); + assertTrue(buildRule.getLog().contains("Line: " + + (e.getLocation().getLineNumber() + 1))); } public static class EchoLocation extends Task { diff --git a/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java b/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java index 1fc745fae..491d3618f 100644 --- a/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java +++ b/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java @@ -38,29 +38,29 @@ public class TaskContainerTest { public void testPropertyExpansion() { buildRule.executeTarget("testPropertyExpansion"); assertTrue("attribute worked", - buildRule.getLog().indexOf("As attribute: it worked") > -1); + buildRule.getLog().contains("As attribute: it worked")); assertTrue("nested text worked", - buildRule.getLog().indexOf("As nested text: it worked") > -1); + buildRule.getLog().contains("As nested text: it worked")); } @Test public void testTaskdef() { buildRule.executeTarget("testTaskdef"); assertTrue("attribute worked", - buildRule.getLog().indexOf("As attribute: it worked") > -1); + buildRule.getLog().contains("As attribute: it worked")); assertTrue("nested text worked", - buildRule.getLog().indexOf("As nested text: it worked") > -1); + buildRule.getLog().contains("As nested text: it worked")); assertTrue("nested text worked", - buildRule.getLog().indexOf("As nested task: it worked") > -1); + buildRule.getLog().contains("As nested task: it worked")); } @Test public void testCaseInsensitive() { buildRule.executeTarget("testCaseInsensitive"); assertTrue("works outside of container", - buildRule.getLog().indexOf("hello ") > -1); + buildRule.getLog().contains("hello ")); assertTrue("works inside of container", - buildRule.getLog().indexOf("world") > -1); + buildRule.getLog().contains("world")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java index 93715483f..aee91fe15 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java @@ -318,9 +318,9 @@ public class AntTest { @Test public void testPropertySet() { buildRule.executeTarget("test-propertyset"); - assertTrue(buildRule.getLog().indexOf("test1 is ${test1}") > -1); - assertTrue(buildRule.getLog().indexOf("test2 is ${test2}") > -1); - assertTrue(buildRule.getLog().indexOf("test1.x is 1") > -1); + assertTrue(buildRule.getLog().contains("test1 is ${test1}")); + assertTrue(buildRule.getLog().contains("test2 is ${test2}")); + assertTrue(buildRule.getLog().contains("test1.x is 1")); } @Test diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java index b42165033..daec44bf7 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java @@ -199,7 +199,7 @@ public class ConcatTest { @Test public void testFilter() { buildRule.executeTarget("testfilter"); - assertTrue(buildRule.getLog().indexOf("REPLACED") > -1); + assertTrue(buildRule.getLog().contains("REPLACED")); } @Test @@ -251,7 +251,7 @@ public class ConcatTest { @Test public void testfilterinline() { buildRule.executeTarget("testfilterinline"); - assertTrue(buildRule.getLog().indexOf("REPLACED") > -1); + assertTrue(buildRule.getLog().contains("REPLACED")); } /** @@ -260,8 +260,8 @@ public class ConcatTest { @Test public void testmultireader() { buildRule.executeTarget("testmultireader"); - assertTrue(buildRule.getLog().indexOf("Bye") > -1); - assertTrue(buildRule.getLog().indexOf("Hello") == -1); + assertTrue(buildRule.getLog().contains("Bye")); + assertTrue(!buildRule.getLog().contains("Hello")); } /** * Check if fixlastline works @@ -302,7 +302,7 @@ public class ConcatTest { assertTrue( "expecting file " + filename + " to contain " + contains + - " but got " + content, content.indexOf(contains) > -1); + " but got " + content, content.contains(contains)); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java index f7780e3bf..db2daf811 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java @@ -110,7 +110,7 @@ public class CopyTest { @Test public void testFilterTest() { buildRule.executeTarget("filtertest"); - assertTrue(buildRule.getLog().indexOf("loop in tokens") == -1); + assertTrue(!buildRule.getLog().contains("loop in tokens")); } @Test diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java index 3b916b6d1..402979c27 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java @@ -344,33 +344,33 @@ public class JarTest { @Test public void testNoVersionInfoIgnore() { buildRule.executeTarget("testNoVersionInfoIgnore"); - assertTrue(buildRule.getFullLog().indexOf("No Implementation-Title set.") > -1); - assertTrue(buildRule.getFullLog().indexOf("No Implementation-Version set.") > -1); - assertTrue(buildRule.getFullLog().indexOf("No Implementation-Vendor set.") > -1); + assertTrue(buildRule.getFullLog().contains("No Implementation-Title set.")); + assertTrue(buildRule.getFullLog().contains("No Implementation-Version set.")); + assertTrue(buildRule.getFullLog().contains("No Implementation-Vendor set.")); } @Test public void testNoVersionInfoWarn() { buildRule.executeTarget("testNoVersionInfoWarn"); - assertTrue(buildRule.getLog().indexOf("No Implementation-Title set.") > -1); - assertTrue(buildRule.getLog().indexOf("No Implementation-Version set.") > -1); - assertTrue(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1); + assertTrue(buildRule.getLog().contains("No Implementation-Title set.")); + assertTrue(buildRule.getLog().contains("No Implementation-Version set.")); + assertTrue(buildRule.getLog().contains("No Implementation-Vendor set.")); } @Test public void testNoVersionInfoNoStrict() { buildRule.executeTarget("testNoVersionInfoNoStrict"); - assertFalse(buildRule.getLog().indexOf("No Implementation-Title set.") > -1); - assertFalse(buildRule.getLog().indexOf("No Implementation-Version set.") > -1); - assertFalse(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1); + assertFalse(buildRule.getLog().contains("No Implementation-Title set.")); + assertFalse(buildRule.getLog().contains("No Implementation-Version set.")); + assertFalse(buildRule.getLog().contains("No Implementation-Vendor set.")); } @Test public void testHasVersionInfo() { buildRule.executeTarget("testHasVersionInfo"); - assertFalse(buildRule.getLog().indexOf("No Implementation-Title set.") > -1); - assertFalse(buildRule.getLog().indexOf("No Implementation-Version set.") > -1); - assertFalse(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1); + assertFalse(buildRule.getLog().contains("No Implementation-Title set.")); + assertFalse(buildRule.getLog().contains("No Implementation-Version set.")); + assertFalse(buildRule.getLog().contains("No Implementation-Vendor set.")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java index 48f47b890..ab665adc1 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java @@ -102,7 +102,7 @@ public class LoadFileTest { @Test public void testLoadAFile() throws BuildException { buildRule.executeTarget("testLoadAFile"); - if(buildRule.getProject().getProperty("testLoadAFile").indexOf("eh?")<0) { + if(!buildRule.getProject().getProperty("testLoadAFile").contains("eh?")) { fail("property is not all in the file"); } } @@ -122,7 +122,7 @@ public class LoadFileTest { @Test public void testEvalProps() throws BuildException { buildRule.executeTarget("testEvalProps"); - if(buildRule.getProject().getProperty("testEvalProps").indexOf("rain")<0) { + if(!buildRule.getProject().getProperty("testEvalProps").contains("rain")) { fail("property eval broken"); } } @@ -133,7 +133,7 @@ public class LoadFileTest { @Test public void testFilterChain() throws BuildException { buildRule.executeTarget("testFilterChain"); - if(buildRule.getProject().getProperty("testFilterChain").indexOf("World!")<0) { + if(!buildRule.getProject().getProperty("testFilterChain").contains("World!")) { fail("Filter Chain broken"); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java index 9ee7b20d2..59b6bd74f 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java @@ -188,7 +188,7 @@ public class MacroDefTest { try { buildRule.executeTarget("backtraceoff"); } catch (BuildException ex) { - if (ex.getMessage().indexOf("following error occurred") != -1) { + if (ex.getMessage().contains("following error occurred")) { fail("error message contained backtrace - " + ex.getMessage()); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java index 592f1d7ec..b60604b90 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java @@ -161,7 +161,7 @@ public class MakeUrlTest { String result = getProperty(property); assertTrue("expected " + contains + " in " + result, - result != null && result.indexOf(contains) >= 0); + result != null && result.contains(contains)); } /** diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java index ca1a94d8f..e51878219 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java @@ -395,14 +395,14 @@ public class ManifestTest { String mfAsString = mf.toString(); assertNotNull(mfAsString); assertTrue(mfAsString.startsWith("Manifest-Version: 2.0")); - assertTrue(mfAsString.indexOf("Foo: Bar") > -1); + assertTrue(mfAsString.contains("Foo: Bar")); mf = getManifest(new File(outDir, "mftest2.mf")); assertNotNull(mf); mfAsString = mf.toString(); assertNotNull(mfAsString); assertEquals(-1, mfAsString.indexOf("Foo: Bar")); - assertTrue(mfAsString.indexOf("Foo: Baz") > -1); + assertTrue(mfAsString.contains("Foo: Baz")); } @Test diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java index adb7843ea..16c4d8aae 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java @@ -69,7 +69,7 @@ public class PropertyTest { fail("Did not throw exception on circular exception"); } catch (BuildException e) { assertTrue("Circular definition not detected - ", - e.getMessage().indexOf("was circularly defined") != -1); + e.getMessage().contains("was circularly defined")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java index 4991143d5..676eda4b2 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java @@ -465,7 +465,7 @@ public class RmicAdvancedTest { buildRule.executeTarget(target); fail("Target should have thrown a BuildException"); } catch (BuildException ex) { - if (target.indexOf("IDL") > -1) { + if (target.contains("IDL")) { assertEquals("this rmic implementation doesn't support the -idl switch", ex.getMessage()); } else { assertEquals("this rmic implementation doesn't support the -iiop switch", ex.getMessage()); diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java index 24b042d85..faa890e26 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java @@ -90,7 +90,7 @@ public class SQLExecTest { try { sql.execute(); } catch (BuildException e){ - assertTrue(e.getCause().getMessage().indexOf("No suitable Driver") != -1); + assertTrue(e.getCause().getMessage().contains("No suitable Driver")); } assertTrue(JDBCTask.getLoaderMap().containsKey(NULL_DRIVER)); assertSame(sql.getLoader(), JDBCTask.getLoaderMap().get(NULL_DRIVER)); diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java index 9fd4667fb..e95852476 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java @@ -232,7 +232,7 @@ public class StyleTest { "expecting file " + filename + " to contain " + contains + " but got " + content, - content.indexOf(contains) > -1); + content.contains(contains)); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java index 93431dcbc..b296b7ba5 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java @@ -41,7 +41,7 @@ public class SyncTest { buildRule.executeTarget("simplecopy"); String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d"; assertFileIsPresent(d); - assertTrue(buildRule.getFullLog().indexOf("dangling") == -1); + assertTrue(!buildRule.getFullLog().contains("dangling")); } @Test @@ -51,7 +51,7 @@ public class SyncTest { assertFileIsNotPresent(d); String c = buildRule.getProject().getProperty("dest") + "/a/b/c"; assertFileIsNotPresent(c); - assertTrue(buildRule.getFullLog().indexOf("dangling") == -1); + assertTrue(!buildRule.getFullLog().contains("dangling")); } @Test @@ -61,7 +61,7 @@ public class SyncTest { assertFileIsNotPresent(d); String c = buildRule.getProject().getProperty("dest") + "/a/b/c"; assertFileIsPresent(c); - assertTrue(buildRule.getFullLog().indexOf("dangling") == -1); + assertTrue(!buildRule.getFullLog().contains("dangling")); } @Test @@ -85,7 +85,7 @@ public class SyncTest { assertFileIsPresent(d); String f = buildRule.getProject().getProperty("dest") + "/e/f"; assertFileIsNotPresent(f); - assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") > -1); + assertTrue(buildRule.getFullLog().contains("Removing orphan file:")); assertContains("Removed 1 dangling file from", buildRule.getFullLog()); assertContains("Removed 1 dangling directory from", buildRule.getFullLog()); } @@ -97,7 +97,7 @@ public class SyncTest { assertFileIsPresent(d); String f = buildRule.getProject().getProperty("dest") + "/e/f"; assertFileIsNotPresent(f); - assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") > -1); + assertTrue(buildRule.getFullLog().contains("Removing orphan file:")); assertContains("Removed 1 dangling file from", buildRule.getFullLog()); assertContains("Removed 1 dangling directory from", buildRule.getFullLog()); } @@ -111,7 +111,7 @@ public class SyncTest { assertFileIsPresent(c); String f = buildRule.getProject().getProperty("dest") + "/e/f"; assertFileIsNotPresent(f); - assertTrue(buildRule.getFullLog().indexOf("Removing orphan directory:") > -1); + assertTrue(buildRule.getFullLog().contains("Removing orphan directory:")); assertContains("NO dangling file to remove from", buildRule.getFullLog()); assertContains("Removed 2 dangling directories from", buildRule.getFullLog()); } @@ -123,7 +123,7 @@ public class SyncTest { assertFileIsPresent(d); String f = buildRule.getProject().getProperty("dest") + "/e/f"; assertFileIsPresent(f); - assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") == -1); + assertTrue(!buildRule.getFullLog().contains("Removing orphan file:")); } @Test @@ -133,7 +133,7 @@ public class SyncTest { assertFileIsPresent(d); String f = buildRule.getProject().getProperty("dest") + "/e/f"; assertFileIsPresent(f); - assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") == -1); + assertTrue(!buildRule.getFullLog().contains("Removing orphan file:")); } public void assertFileIsPresent(String f) { diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java index 7f28de05c..24e509097 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java @@ -119,10 +119,10 @@ public class TaskdefTest { buildRule.executeTarget("testOverride"); String log = buildRule.getLog(); assertTrue("override warning sent", - log.indexOf("Trying to override old definition of task copy") > -1); + log.contains("Trying to override old definition of task copy")); assertTrue("task inside target worked", - log.indexOf("In target") > -1); + log.contains("In target")); assertTrue("task inside target worked", - log.indexOf("In TaskContainer") > -1); + log.contains("In TaskContainer")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java index d1c3aea12..9d34760ea 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java @@ -131,7 +131,7 @@ public class EchoPropertiesTest { try { String read = null; while ((read = br.readLine()) != null) { - if (read.indexOf("") >= 0) { + if (read.contains("")) { // found the property we set - it's good. return; } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java index 9cd6eb2e9..108e7d056 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java @@ -136,8 +136,7 @@ public class XmlValidateTest { " doesn't support feature http://apache.org/xml/features/validation/schema")) { throw new AssumptionViolatedException("parser doesn't support schema"); } else { - assertTrue( - e.getMessage().indexOf("not a valid XML document") > -1); + assertTrue(e.getMessage().contains("not a valid XML document")); } } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java index d84fc6907..e757faeee 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java @@ -77,7 +77,7 @@ public class XsltTest { @Test public void testStyleSheetWithInclude() throws Exception { buildRule.executeTarget("testStyleSheetWithInclude"); - if (buildRule.getLog().indexOf("java.io.FileNotFoundException") != -1) { + if (buildRule.getLog().contains("java.io.FileNotFoundException")) { fail("xsl:include was not found"); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java index b39832ba8..532054198 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java @@ -112,7 +112,7 @@ public class ImageTest { } catch (RuntimeException re){ assertTrue("Run time exception should say 'Unable to process image stream'. :" + re.toString(), - re.toString().indexOf("Unable to process image stream") > -1); + re.toString().contains("Unable to process image stream")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java index f4f1541f1..dede70d9e 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java @@ -80,7 +80,7 @@ public class JUnitTestRunnerTest { runner.run(); String error = runner.getFormatter().getError(); assertEquals(error, JUnitTestRunner.ERRORS, runner.getRetCode()); - assertTrue(error, error.indexOf("thrown on purpose") != -1); + assertTrue(error, error.contains("thrown on purpose")); } // check that something which is not a testcase generates no errors diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java index 66e656745..bfba29852 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java @@ -56,10 +56,10 @@ public class ScriptDefTest { File baseDir = fileset.getDir(p); String log = buildRule.getLog(); assertTrue("Expecting attribute value printed", - log.indexOf("Attribute attr1 = test") != -1); + log.contains("Attribute attr1 = test")); assertTrue("Expecting nested element value printed", - log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1); + log.contains("Fileset basedir = " + baseDir.getAbsolutePath())); } @Test @@ -91,10 +91,10 @@ public class ScriptDefTest { File baseDir = fileset.getDir(p); String log = buildRule.getLog(); assertTrue("Expecting attribute value to be printed", - log.indexOf("Attribute attr1 = test") != -1); + log.contains("Attribute attr1 = test")); assertTrue("Expecting nested element value to be printed", - log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1); + log.contains("Fileset basedir = " + baseDir.getAbsolutePath())); } @Test @@ -117,8 +117,8 @@ public class ScriptDefTest { public void testDoubleDef() { buildRule.executeTarget("doubledef"); String log = buildRule.getLog(); - assertTrue("Task1 did not execute", log.indexOf("Task1") != -1); - assertTrue("Task2 did not execute", log.indexOf("Task2") != -1); + assertTrue("Task1 did not execute", log.contains("Task1")); + assertTrue("Task2 did not execute", log.contains("Task2")); } @Test @@ -137,7 +137,7 @@ public class ScriptDefTest { // get the fileset and its basedir String log = buildRule.getLog(); assertTrue("Expecting property in attribute value replaced", - log.indexOf("Attribute value = test") != -1); + log.contains("Attribute value = test")); } diff --git a/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java index db70ac49e..5f6bb506d 100644 --- a/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java +++ b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java @@ -94,7 +94,7 @@ public class CommandlineJavaTest { assertEquals("with classpath", "-Djava.compiler=NONE", s[1]); assertEquals("with classpath", "-classpath", s[2]); assertTrue("build.xml contained", - s[3].indexOf("build.xml"+java.io.File.pathSeparator) >= 0); + s[3].contains("build.xml" + java.io.File.pathSeparator)); assertTrue("ant.jar contained", s[3].endsWith("ant.jar")); assertEquals("with classpath", "junit.textui.TestRunner", s[4]); assertEquals("with classpath", diff --git a/src/tests/junit/org/apache/tools/ant/types/PathTest.java b/src/tests/junit/org/apache/tools/ant/types/PathTest.java index 20c0b3a9e..b75e9f506 100644 --- a/src/tests/junit/org/apache/tools/ant/types/PathTest.java +++ b/src/tests/junit/org/apache/tools/ant/types/PathTest.java @@ -572,7 +572,7 @@ public class PathTest { assertEquals(0, p.list().length); } catch (BuildException x) { String m = x.toString(); - assertTrue(m, m.indexOf("circular") != -1); + assertTrue(m, m.contains("circular")); } } diff --git a/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java index b7bfa5d09..9ed6ef64d 100644 --- a/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java +++ b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java @@ -73,7 +73,7 @@ public class RedirectorElementTest { @Test public void testLogInputString() { buildRule.executeTarget("testLogInputString"); - if (buildRule.getLog().indexOf("testLogInputString can-cat") >= 0) { + if (buildRule.getLog().contains("testLogInputString can-cat")) { AntAssert.assertContains("Using input string", buildRule.getFullLog()); } } diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java index e9591b528..0b940ad64 100644 --- a/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java @@ -185,7 +185,7 @@ public class ModifiedSelectorTest { assertNotNull("'fs.full.value' must be set.", fsFullValue); assertTrue("'fs.full.value' must not be null.", !"".equals(fsFullValue)); - assertTrue("'fs.full.value' must contain ant.bat.", fsFullValue.indexOf("ant.bat")>-1); + assertTrue("'fs.full.value' must contain ant.bat.", fsFullValue.contains("ant.bat")); assertNotNull("'fs.mod.value' must be set.", fsModValue); // must be empty according to the Mock* implementations diff --git a/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java b/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java index 4309098f8..1e0bdfbd1 100644 --- a/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java +++ b/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java @@ -59,8 +59,8 @@ public class LayoutPreservingPropertiesTest { // and now make sure that the comments made it into the new file String s = readFile(tmp); - assertTrue("missing comment", s.indexOf("# a comment") > -1); - assertTrue("missing comment", s.indexOf("! more comment") > -1); + assertTrue("missing comment", s.contains("# a comment")); + assertTrue("missing comment", s.contains("! more comment")); } /** @@ -89,16 +89,15 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue(s.indexOf("\\ prop\\ one\\ =\\ \\ leading and trailing" - + " spaces ") > -1); - assertTrue(s.indexOf("prop\\ttwo=contains\\ttab") > -1); - assertTrue(s.indexOf("prop\\nthree=contains\\nnewline") > -1); - assertTrue(s.indexOf("prop\\rfour=contains\\rcarriage return") > -1); - assertTrue(s.indexOf("prop\\\\six=contains\\\\backslash") > -1); - assertTrue(s.indexOf("prop\\:seven=contains\\:colon") > -1); - assertTrue(s.indexOf("prop\\=eight=contains\\=equals") > -1); - assertTrue(s.indexOf("prop\\#nine=contains\\#hash") > -1); - assertTrue(s.indexOf("prop\\!ten=contains\\!exclamation") > -1); + assertTrue(s.contains("\\ prop\\ one\\ =\\ \\ leading and trailing spaces ")); + assertTrue(s.contains("prop\\ttwo=contains\\ttab")); + assertTrue(s.contains("prop\\nthree=contains\\nnewline")); + assertTrue(s.contains("prop\\rfour=contains\\rcarriage return")); + assertTrue(s.contains("prop\\\\six=contains\\\\backslash")); + assertTrue(s.contains("prop\\:seven=contains\\:colon")); + assertTrue(s.contains("prop\\=eight=contains\\=equals")); + assertTrue(s.contains("prop\\#nine=contains\\#hash")); + assertTrue(s.contains("prop\\!ten=contains\\!exclamation")); } /** @@ -125,13 +124,12 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue(s.indexOf("\\ prop\\ one\\ =\\ \\ leading and" - + " trailing spaces ") == -1); - assertTrue(s.indexOf("\\ prop\\ one\\ =new one") > -1); - assertTrue(s.indexOf("prop\\ttwo=contains\\ttab") == -1); - assertTrue(s.indexOf("prop\\ttwo=new two") > -1); - assertTrue(s.indexOf("prop\\nthree=contains\\nnewline") == -1); - assertTrue(s.indexOf("prop\\nthree=new three") > -1); + assertTrue(!s.contains("\\ prop\\ one\\ =\\ \\ leading and trailing spaces ")); + assertTrue(s.contains("\\ prop\\ one\\ =new one")); + assertTrue(!s.contains("prop\\ttwo=contains\\ttab")); + assertTrue(s.contains("prop\\ttwo=new two")); + assertTrue(!s.contains("prop\\nthree=contains\\nnewline")); + assertTrue(s.contains("prop\\nthree=new three")); } @Test @@ -171,19 +169,13 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue("should have had no properties ", - s.indexOf("prop.alpha") == -1); - assertTrue("should have had no properties ", - s.indexOf("prop.beta") == -1); - assertTrue("should have had no properties ", - s.indexOf("prop.gamma") == -1); - - assertTrue("should have had no comments", - s.indexOf("# a comment") == -1); - assertTrue("should have had no comments", - s.indexOf("! more comment") == -1); - assertTrue("should have had no comments", - s.indexOf("# now a line wrapping one") == -1); + assertTrue("should have had no properties ", !s.contains("prop.alpha")); + assertTrue("should have had no properties ", !s.contains("prop.beta")); + assertTrue("should have had no properties ", !s.contains("prop.gamma")); + + assertTrue("should have had no comments", !s.contains("# a comment")); + assertTrue("should have had no comments", !s.contains("! more comment")); + assertTrue("should have had no comments", !s.contains("# now a line wrapping one")); } @Test @@ -203,10 +195,8 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue("should not have had prop.beta", - s.indexOf("prop.beta") == -1); - assertTrue("should have had prop.beta's comment", - s.indexOf("! more comment") > -1); + assertTrue("should not have had prop.beta", !s.contains("prop.beta")); + assertTrue("should have had prop.beta's comment", s.contains("! more comment")); } @Test @@ -228,10 +218,8 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue("should not have had prop.beta", - s.indexOf("prop.beta") == -1); - assertTrue("should not have had prop.beta's comment", - s.indexOf("! more comment") == -1); + assertTrue("should not have had prop.beta", !s.contains("prop.beta")); + assertTrue("should not have had prop.beta's comment", !s.contains("! more comment")); } @Test @@ -262,13 +250,13 @@ public class LayoutPreservingPropertiesTest { String s2 = readFile(tmp2); // check original is untouched - assertTrue("should have had 'simple'", s1.indexOf("simple") > -1); - assertTrue("should not have had prop.new", s1.indexOf("prop.new") == -1); + assertTrue("should have had 'simple'", s1.contains("simple")); + assertTrue("should not have had prop.new", !s1.contains("prop.new")); // check clone has the changes assertTrue("should have had 'a new value for beta'", - s2.indexOf("a new value for beta") > -1); - assertTrue("should have had prop.new", s2.indexOf("prop.new") > -1); + s2.contains("a new value for beta")); + assertTrue("should have had prop.new", s2.contains("prop.new")); } @Test @@ -293,16 +281,16 @@ public class LayoutPreservingPropertiesTest { // and check that the resulting file looks okay String s = readFile(tmp); - assertTrue(s.indexOf("prop\\:seven=new value for seven") > -1); - assertTrue(s.indexOf("prop\\=eight=new value for eight") > -1); - assertTrue(s.indexOf("prop\\ eleven=new value for eleven") > -1); - assertTrue(s.indexOf("alpha=new value for alpha") > -1); - assertTrue(s.indexOf("beta=new value for beta") > -1); + assertTrue(s.contains("prop\\:seven=new value for seven")); + assertTrue(s.contains("prop\\=eight=new value for eight")); + assertTrue(s.contains("prop\\ eleven=new value for eleven")); + assertTrue(s.contains("alpha=new value for alpha")); + assertTrue(s.contains("beta=new value for beta")); - assertTrue(s.indexOf("prop\\:seven=contains\\:colon") == -1); - assertTrue(s.indexOf("prop\\=eight=contains\\=equals") == -1); - assertTrue(s.indexOf("alpha:set with a colon") == -1); - assertTrue(s.indexOf("beta set with a space") == -1); + assertTrue(!s.contains("prop\\:seven=contains\\:colon")); + assertTrue(!s.contains("prop\\=eight=contains\\=equals")); + assertTrue(!s.contains("alpha:set with a colon")); + assertTrue(!s.contains("beta set with a space")); } private static String readFile(File f) throws IOException { From 291a214ace6bcf71e9972d6e86432f55b98d9bfa Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sat, 26 May 2018 23:05:07 +0200 Subject: [PATCH 9/9] Fix javadoc and imports --- src/main/org/apache/tools/ant/PropertyHelper.java | 2 +- src/main/org/apache/tools/ant/RuntimeConfigurable.java | 1 - src/main/org/apache/tools/ant/taskdefs/Java.java | 2 -- src/main/org/apache/tools/ant/taskdefs/Touch.java | 1 - .../ant/taskdefs/optional/junit/AggregateTransformer.java | 3 --- src/main/org/apache/tools/ant/util/ScriptRunnerBase.java | 2 +- .../junit/org/apache/tools/ant/IntrospectionHelperTest.java | 1 - src/tests/junit/org/apache/tools/ant/UnknownElementTest.java | 1 - .../tools/ant/taskdefs/optional/junit/JUnitTaskTest.java | 1 - .../org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java | 1 - 10 files changed, 2 insertions(+), 13 deletions(-) diff --git a/src/main/org/apache/tools/ant/PropertyHelper.java b/src/main/org/apache/tools/ant/PropertyHelper.java index c7f385e66..a447ef787 100644 --- a/src/main/org/apache/tools/ant/PropertyHelper.java +++ b/src/main/org/apache/tools/ant/PropertyHelper.java @@ -211,7 +211,7 @@ public class PropertyHelper implements GetProperty { // CheckStyle:LineLengthCheck OFF see too long /** * {@inheritDoc} - * @see org.apache.tools.ant.property.PropertyExpander#parsePropertyName(java.lang.String, java.text.ParsePosition, org.apache.tools.ant.PropertyHelper) + * @see org.apache.tools.ant.property.PropertyExpander#parsePropertyName(java.lang.String, java.text.ParsePosition, org.apache.tools.ant.property.ParseNextProperty) */ // CheckStyle:LineLengthCheck ON public String parsePropertyName( diff --git a/src/main/org/apache/tools/ant/RuntimeConfigurable.java b/src/main/org/apache/tools/ant/RuntimeConfigurable.java index 477ae3ae7..ebd6c114f 100644 --- a/src/main/org/apache/tools/ant/RuntimeConfigurable.java +++ b/src/main/org/apache/tools/ant/RuntimeConfigurable.java @@ -24,7 +24,6 @@ import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map.Entry; import org.apache.tools.ant.attribute.EnableAttribute; diff --git a/src/main/org/apache/tools/ant/taskdefs/Java.java b/src/main/org/apache/tools/ant/taskdefs/Java.java index ed9f90659..a49a34fee 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Java.java +++ b/src/main/org/apache/tools/ant/taskdefs/Java.java @@ -20,8 +20,6 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; import java.util.Vector; import org.apache.tools.ant.BuildException; diff --git a/src/main/org/apache/tools/ant/taskdefs/Touch.java b/src/main/org/apache/tools/ant/taskdefs/Touch.java index faedf9d35..6ade0cd1c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Touch.java +++ b/src/main/org/apache/tools/ant/taskdefs/Touch.java @@ -23,7 +23,6 @@ import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Locale; import java.util.Vector; import org.apache.tools.ant.BuildException; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java index 2c1b13d7f..911fb4b2b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java @@ -23,9 +23,6 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; diff --git a/src/main/org/apache/tools/ant/util/ScriptRunnerBase.java b/src/main/org/apache/tools/ant/util/ScriptRunnerBase.java index 5e2857ee1..42df9a268 100644 --- a/src/main/org/apache/tools/ant/util/ScriptRunnerBase.java +++ b/src/main/org/apache/tools/ant/util/ScriptRunnerBase.java @@ -205,7 +205,7 @@ public abstract class ScriptRunnerBase { /** * Read some source in from the given reader - * @param in the input stream to pass into a buffered reader. + * @param reader the input stream to pass into a buffered reader. * @param name the name to use in error messages */ private void readSource(Reader reader, String name) { diff --git a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java index 058e62842..c318c6887 100644 --- a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java +++ b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java @@ -24,7 +24,6 @@ import java.lang.reflect.Method; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; diff --git a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java index 22688d6d2..76f0d8fed 100644 --- a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java +++ b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java @@ -24,7 +24,6 @@ import org.junit.Rule; import org.junit.Test; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import static org.junit.Assert.assertEquals; diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java index 6c0d4b42b..5f5d44f90 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java @@ -34,7 +34,6 @@ import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.Arrays; import java.util.Set; import java.util.TreeSet; diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java index e456d6f6d..1c2a17db7 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java @@ -22,7 +22,6 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.apache.tools.ant.BuildException;