From 1b76f1b6dae88a7a158e50222bb19f6f5ca26d70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Mat=C3=A8rne?= Date: Fri, 4 Jul 2014 09:14:00 +0200 Subject: [PATCH] checkstyle --- .../org/apache/tools/ant/AntClassLoader.java | 312 +++++++------ .../apache/tools/ant/ArgumentProcessor.java | 4 +- .../tools/ant/ArgumentProcessorRegistry.java | 2 +- .../org/apache/tools/ant/BuildListener.java | 2 +- .../apache/tools/ant/DirectoryScanner.java | 69 +-- src/main/org/apache/tools/ant/Evaluable.java | 2 +- .../org/apache/tools/ant/ExtensionPoint.java | 9 +- .../apache/tools/ant/IntrospectionHelper.java | 365 ++++++++------- src/main/org/apache/tools/ant/Main.java | 283 ++++++------ src/main/org/apache/tools/ant/Project.java | 419 +++++++++--------- .../org/apache/tools/ant/ProjectHelper.java | 8 +- .../tools/ant/filters/ConcatFilter.java | 8 +- .../org/apache/tools/ant/launch/Launcher.java | 82 ++-- .../org/apache/tools/ant/launch/Locator.java | 2 - .../tools/ant/listener/AnsiColorLogger.java | 5 +- .../tools/ant/listener/SilentLogger.java | 20 +- .../tools/ant/taskdefs/AntStructure.java | 77 ++-- .../tools/ant/taskdefs/BindTargets.java | 27 +- .../tools/ant/taskdefs/Componentdef.java | 2 +- .../org/apache/tools/ant/taskdefs/Copy.java | 201 ++++----- .../apache/tools/ant/taskdefs/EchoXML.java | 5 +- .../org/apache/tools/ant/taskdefs/Get.java | 39 +- .../org/apache/tools/ant/taskdefs/Input.java | 34 +- .../apache/tools/ant/taskdefs/JDBCTask.java | 4 +- .../org/apache/tools/ant/taskdefs/Javac.java | 151 +++---- .../apache/tools/ant/taskdefs/Javadoc.java | 20 +- .../apache/tools/ant/taskdefs/MakeUrl.java | 9 +- .../apache/tools/ant/taskdefs/Manifest.java | 34 +- .../tools/ant/taskdefs/PathConvert.java | 11 +- .../tools/ant/taskdefs/ProjectHelperTask.java | 5 +- .../apache/tools/ant/taskdefs/Property.java | 15 +- .../apache/tools/ant/taskdefs/Redirector.java | 161 +++---- .../org/apache/tools/ant/taskdefs/Rmic.java | 13 +- .../apache/tools/ant/taskdefs/SQLExec.java | 17 +- .../apache/tools/ant/taskdefs/SignJar.java | 5 +- .../org/apache/tools/ant/taskdefs/Sleep.java | 7 +- .../org/apache/tools/ant/taskdefs/SubAnt.java | 20 +- .../org/apache/tools/ant/taskdefs/Sync.java | 24 +- .../org/apache/tools/ant/taskdefs/War.java | 13 +- .../tools/ant/taskdefs/XSLTLiaison.java | 2 +- .../tools/ant/taskdefs/XSLTLiaison4.java | 2 - .../tools/ant/taskdefs/XSLTProcess.java | 41 +- .../org/apache/tools/ant/taskdefs/Zip.java | 49 +- .../compilers/AptCompilerAdapter.java | 13 +- .../compilers/CompilerAdapterExtension.java | 4 +- .../compilers/DefaultCompilerAdapter.java | 69 +-- .../ant/taskdefs/condition/IsReachable.java | 11 +- .../ant/taskdefs/cvslib/ChangeLogParser.java | 4 +- .../tools/ant/taskdefs/cvslib/CvsTagDiff.java | 10 +- .../taskdefs/launcher/CommandLauncher.java | 4 +- .../launcher/CommandLauncherProxy.java | 2 +- .../launcher/Java13CommandLauncher.java | 2 +- .../taskdefs/launcher/MacCommandLauncher.java | 2 +- .../taskdefs/launcher/OS2CommandLauncher.java | 2 +- .../launcher/PerlScriptCommandLauncher.java | 2 +- .../launcher/ScriptCommandLauncher.java | 2 +- .../taskdefs/launcher/VmsCommandLauncher.java | 4 +- .../launcher/WinNTCommandLauncher.java | 2 +- .../ant/taskdefs/optional/PropertyFile.java | 20 +- .../ant/taskdefs/optional/ReplaceRegExp.java | 7 +- .../ant/taskdefs/optional/TraXLiaison.java | 35 +- .../depend/constantpool/MethodTypeCPInfo.java | 13 +- .../optional/ejb/IPlanetDeploymentTool.java | 23 +- .../taskdefs/optional/ejb/IPlanetEjbc.java | 1 - .../optional/extension/ExtensionSet.java | 13 +- .../junit/JUnit4TestMethodAdapter.java | 21 +- .../taskdefs/optional/junit/JUnitTask.java | 51 ++- .../taskdefs/optional/junit/JUnitTest.java | 7 +- .../optional/junit/JUnitTestRunner.java | 293 ++++++------ .../optional/junit/TearDownOnVmCrash.java | 29 +- .../junit/XMLJUnitResultFormatter.java | 35 +- .../taskdefs/optional/net/FTPTaskMirror.java | 3 +- .../taskdefs/optional/splash/SplashTask.java | 20 +- .../ant/taskdefs/optional/ssh/Directory.java | 9 +- .../ant/taskdefs/optional/ssh/SSHExec.java | 90 ++-- .../ant/taskdefs/optional/ssh/SSHSession.java | 10 +- .../tools/ant/taskdefs/optional/ssh/Scp.java | 12 +- .../ant/taskdefs/optional/unix/Symlink.java | 17 +- .../apache/tools/ant/types/FilterChain.java | 8 +- .../org/apache/tools/ant/types/FilterSet.java | 16 +- .../apache/tools/ant/types/Permissions.java | 69 +-- .../tools/ant/types/ResourceCollection.java | 2 - .../ant/types/mappers/CutDirsMapper.java | 17 +- .../tools/ant/types/resources/Archives.java | 22 +- .../ContentTransformingResource.java | 19 +- .../LazyResourceCollectionWrapper.java | 28 +- .../ant/types/resources/MappedResource.java | 20 +- .../ant/types/resources/MultiRootFileSet.java | 32 +- .../ant/types/resources/selectors/Type.java | 16 +- .../ant/types/selectors/MappingSelector.java | 8 +- .../ant/types/selectors/PresentSelector.java | 28 +- .../ant/types/selectors/TokenizedPath.java | 17 +- .../tools/ant/util/DOMElementWriter.java | 2 +- .../apache/tools/ant/util/JavaEnvUtils.java | 2 +- .../ant/util/LayoutPreservingProperties.java | 165 +++---- .../ant/util/LineOrientedOutputStream.java | 12 +- .../LineOrientedOutputStreamRedirector.java | 24 +- .../apache/tools/ant/util/ResourceUtils.java | 224 +++++----- .../tools/ant/util/SymbolicLinkUtils.java | 5 +- .../apache/tools/ant/util/UnicodeUtil.java | 2 +- .../org/apache/tools/tar/TarConstants.java | 42 +- .../org/apache/tools/tar/TarInputStream.java | 10 +- .../org/apache/tools/tar/TarOutputStream.java | 9 +- src/main/org/apache/tools/tar/TarUtils.java | 31 +- .../tools/zip/AbstractUnicodeExtraField.java | 19 +- .../apache/tools/zip/FallbackZipEncoding.java | 17 +- .../apache/tools/zip/GeneralPurposeBit.java | 2 +- .../org/apache/tools/zip/NioZipEncoding.java | 13 +- .../tools/zip/Simple8BitZipEncoding.java | 24 +- .../tools/zip/UnicodeCommentExtraField.java | 9 +- .../tools/zip/UnicodePathExtraField.java | 11 +- .../org/apache/tools/zip/ZipEncoding.java | 16 +- .../apache/tools/zip/ZipEncodingHelper.java | 138 +++--- src/main/org/apache/tools/zip/ZipEntry.java | 85 ++-- src/main/org/apache/tools/zip/ZipFile.java | 7 +- .../org/apache/tools/zip/ZipOutputStream.java | 23 +- src/main/org/apache/tools/zip/ZipUtil.java | 2 +- 117 files changed, 2516 insertions(+), 2102 deletions(-) diff --git a/src/main/org/apache/tools/ant/AntClassLoader.java b/src/main/org/apache/tools/ant/AntClassLoader.java index 6098dec68..88a81c498 100644 --- a/src/main/org/apache/tools/ant/AntClassLoader.java +++ b/src/main/org/apache/tools/ant/AntClassLoader.java @@ -86,7 +86,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { /** * The name of the resource being searched for. */ - private String resourceName; + private final String resourceName; /** * The index of the next classpath element to search. @@ -106,7 +106,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param name the name of the resource to search for. */ - ResourceEnumeration(String name) { + ResourceEnumeration(final String name) { this.resourceName = name; this.pathElementsIndex = 0; findNextResource(); @@ -119,7 +119,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return true if there are more elements in the * enumeration; false otherwise. */ - public boolean hasMoreElements() { + @Override + public boolean hasMoreElements() { return (this.nextResource != null); } @@ -128,8 +129,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @return the next resource in the enumeration */ - public URL nextElement() { - URL ret = this.nextResource; + @Override + public URL nextElement() { + final URL ret = this.nextResource; if (ret == null) { throw new NoSuchElementException(); } @@ -147,10 +149,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { URL url = null; while ((pathElementsIndex < pathComponents.size()) && (url == null)) { try { - File pathComponent = (File) pathComponents.elementAt(pathElementsIndex); + final File pathComponent = pathComponents.elementAt(pathElementsIndex); url = getResourceURL(pathComponent, this.resourceName); pathElementsIndex++; - } catch (BuildException e) { + } catch (final BuildException e) { // ignore path elements which are not valid relative to the // project } @@ -173,7 +175,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * The components of the classpath that the classloader searches * for classes. */ - private Vector pathComponents = new VectorSet(); + private final Vector pathComponents = new VectorSet(); /** * The project to which this class loader belongs. @@ -191,14 +193,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * loader regardless of whether the parent class loader is being searched * first or not. */ - private Vector systemPackages = new Vector(); + private final Vector systemPackages = new Vector(); /** * These are the package roots that are to be loaded by this class loader * regardless of whether the parent class loader is being searched first * or not. */ - private Vector loaderPackages = new Vector(); + private final Vector loaderPackages = new Vector(); /** * Whether or not this classloader will ignore the base @@ -219,7 +221,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { private Hashtable jarFiles = new Hashtable(); /** Static map of jar file/time to manifest class-path entries */ - private static Map pathMap = Collections.synchronizedMap(new HashMap()); + private static Map pathMap = + Collections.synchronizedMap(new HashMap()); /** * The context loader saved when setting the thread's current @@ -241,7 +244,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * belong. * @param classpath The classpath to use to load classes. */ - public AntClassLoader(ClassLoader parent, Project project, Path classpath) { + public AntClassLoader(final ClassLoader parent, final Project project, final Path classpath) { setParent(parent); setClassPath(classpath); setProject(project); @@ -265,7 +268,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * May be null, in which case no path * elements are set up to start with. */ - public AntClassLoader(Project project, Path classpath) { + public AntClassLoader(final Project project, final Path classpath) { setParent(null); setProject(project); setClassPath(classpath); @@ -288,7 +291,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * load the a class through this loader. */ public AntClassLoader( - ClassLoader parent, Project project, Path classpath, boolean parentFirst) { + final ClassLoader parent, final Project project, final Path classpath, final boolean parentFirst) { this(project, classpath); if (parent != null) { setParent(parent); @@ -309,7 +312,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * classloader should be consulted before trying to * load the a class through this loader. */ - public AntClassLoader(Project project, Path classpath, boolean parentFirst) { + public AntClassLoader(final Project project, final Path classpath, final boolean parentFirst) { this(null, project, classpath, parentFirst); } @@ -326,7 +329,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * classloader should be consulted before trying to * load the a class through this loader. */ - public AntClassLoader(ClassLoader parent, boolean parentFirst) { + public AntClassLoader(final ClassLoader parent, final boolean parentFirst) { setParent(parent); project = null; this.parentFirst = parentFirst; @@ -337,7 +340,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param project the project instance */ - public void setProject(Project project) { + public void setProject(final Project project) { this.project = project; if (project != null) { project.addBuildListener(this); @@ -351,15 +354,15 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param classpath the search classpath consisting of directories and * jar/zip files. */ - public void setClassPath(Path classpath) { + public void setClassPath(final Path classpath) { pathComponents.removeAllElements(); if (classpath != null) { - Path actualClasspath = classpath.concatSystemClasspath("ignore"); - String[] pathElements = actualClasspath.list(); + final Path actualClasspath = classpath.concatSystemClasspath("ignore"); + final String[] pathElements = actualClasspath.list(); for (int i = 0; i < pathElements.length; ++i) { try { addPathElement(pathElements[i]); - } catch (BuildException e) { + } catch (final BuildException e) { // ignore path elements which are invalid // relative to the project } @@ -373,7 +376,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param parent the parent class loader. */ - public void setParent(ClassLoader parent) { + public void setParent(final ClassLoader parent) { this.parent = parent == null ? AntClassLoader.class.getClassLoader() : parent; } @@ -385,7 +388,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param parentFirst if true, delegate initial class search to the parent * classloader. */ - public void setParentFirst(boolean parentFirst) { + public void setParentFirst(final boolean parentFirst) { this.parentFirst = parentFirst; } @@ -397,7 +400,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param priority The logging priority of the message. */ - protected void log(String message, int priority) { + protected void log(final String message, final int priority) { if (project != null) { project.log(message, priority); } @@ -443,12 +446,12 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception BuildException if the given path element cannot be resolved * against the project. */ - public void addPathElement(String pathElement) throws BuildException { - File pathComponent = project != null ? project.resolveFile(pathElement) : new File( + public void addPathElement(final String pathElement) throws BuildException { + final File pathComponent = project != null ? project.resolveFile(pathElement) : new File( pathElement); try { addPathFile(pathComponent); - } catch (IOException e) { + } catch (final IOException e) { throw new BuildException(e); } } @@ -460,7 +463,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * their CLASSPATH entry in the manifest file. * @param file the jar file or directory to add. */ - public void addPathComponent(File file) { + public void addPathComponent(final File file) { if (pathComponents.contains(file)) { return; } @@ -477,7 +480,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @throws IOException if data needed from the file cannot be read. */ - protected void addPathFile(File pathComponent) throws IOException { + protected void addPathFile(final File pathComponent) throws IOException { if (!pathComponents.contains(pathComponent)) { pathComponents.addElement(pathComponent); } @@ -485,14 +488,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { return; } - String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + final String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-" + pathComponent.length(); - String classpath = (String) pathMap.get(absPathPlusTimeAndLength); + String classpath = pathMap.get(absPathPlusTimeAndLength); if (classpath == null) { JarFile jarFile = null; try { jarFile = new JarFile(pathComponent); - Manifest manifest = jarFile.getManifest(); + final Manifest manifest = jarFile.getManifest(); if (manifest == null) { return; } @@ -510,19 +513,19 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { } if (!"".equals(classpath)) { - URL baseURL = FILE_UTILS.getFileURL(pathComponent); - StringTokenizer st = new StringTokenizer(classpath); + final URL baseURL = FILE_UTILS.getFileURL(pathComponent); + final StringTokenizer st = new StringTokenizer(classpath); while (st.hasMoreTokens()) { - String classpathElement = st.nextToken(); - URL libraryURL = new URL(baseURL, classpathElement); + final String classpathElement = st.nextToken(); + final URL libraryURL = new URL(baseURL, classpathElement); if (!libraryURL.getProtocol().equals("file")) { log("Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader", Project.MSG_VERBOSE); continue; } - String decodedPath = Locator.decodeUri(libraryURL.getFile()); - File libraryFile = new File(decodedPath); + final String decodedPath = Locator.decodeUri(libraryURL.getFile()); + final File libraryFile = new File(decodedPath); if (libraryFile.exists() && !isInPath(libraryFile)) { addPathFile(libraryFile); } @@ -539,7 +542,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { public String getClasspath() { final StringBuilder sb = new StringBuilder(); boolean firstPass = true; - Enumeration componentEnum = pathComponents.elements(); + final Enumeration componentEnum = pathComponents.elements(); while (componentEnum.hasMoreElements()) { if (!firstPass) { sb.append(System.getProperty("path.separator")); @@ -560,7 +563,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param isolated Whether or not this classloader should run in * isolated mode. */ - public synchronized void setIsolated(boolean isolated) { + public synchronized void setIsolated(final boolean isolated) { ignoreBase = isolated; } @@ -574,7 +577,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @deprecated since 1.6.x. * Use Class.forName with initialize=true instead. */ - public static void initializeClass(Class theClass) { + @Deprecated + public static void initializeClass(final Class theClass) { // ***HACK*** We ask the VM to create an instance // by voluntarily providing illegal arguments to force // the VM to run the class' static initializer, while @@ -589,7 +593,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { cons[0].newInstance((Object[]) strs); // Expecting an exception to be thrown by this call: // IllegalArgumentException: wrong number of Arguments - } catch (Exception e) { + } catch (final Exception e) { // Ignore - we are interested only in the side // effect - that of getting the static initializers // invoked. As we do not want to call a valid @@ -616,7 +620,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param packageRoot The root of all packages to be included. * Should not be null. */ - public void addSystemPackageRoot(String packageRoot) { + public void addSystemPackageRoot(final String packageRoot) { systemPackages.addElement(packageRoot + (packageRoot.endsWith(".") ? "" : ".")); } @@ -629,7 +633,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param packageRoot The root of all packages to be included. * Should not be null. */ - public void addLoaderPackageRoot(String packageRoot) { + public void addLoaderPackageRoot(final String packageRoot) { loaderPackages.addElement(packageRoot + (packageRoot.endsWith(".") ? "" : ".")); } @@ -648,7 +652,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception ClassNotFoundException if the requested class does not exist * on this loader's classpath. */ - public Class forceLoadClass(String classname) throws ClassNotFoundException { + public Class forceLoadClass(final String classname) throws ClassNotFoundException { log("force loading " + classname, Project.MSG_DEBUG); Class theClass = findLoadedClass(classname); @@ -675,7 +679,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception ClassNotFoundException if the requested class does not exist * on this loader's classpath. */ - public Class forceLoadSystemClass(String classname) throws ClassNotFoundException { + public Class forceLoadSystemClass(final String classname) throws ClassNotFoundException { log("force system loading " + classname, Project.MSG_DEBUG); Class theClass = findLoadedClass(classname); @@ -695,7 +699,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return a stream to the required resource or null if the * resource cannot be found on the loader's classpath. */ - public InputStream getResourceAsStream(String name) { + @Override + public InputStream getResourceAsStream(final String name) { InputStream resourceStream = null; if (isParentFirst(name)) { resourceStream = loadBaseResource(name); @@ -712,7 +717,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { } if (resourceStream == null && !isParentFirst(name)) { if (ignoreBase) { - resourceStream = getRootLoader() == null ? null : getRootLoader().getResourceAsStream(name); + resourceStream = getRootLoader() == null + ? null + : getRootLoader().getResourceAsStream(name); } else { resourceStream = loadBaseResource(name); } @@ -736,14 +743,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return a stream to the required resource or null if * the resource cannot be found on the loader's classpath. */ - private InputStream loadResource(String name) { + private InputStream loadResource(final String name) { // we need to search the components of the path to see if we can // find the class we want. InputStream stream = null; - Enumeration e = pathComponents.elements(); + final Enumeration e = pathComponents.elements(); while (e.hasMoreElements() && stream == null) { - File pathComponent = e.nextElement(); + final File pathComponent = e.nextElement(); stream = getResourceStream(pathComponent, name); } return stream; @@ -759,7 +766,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return a stream to the named resource, or null if * the resource cannot be found. */ - private InputStream loadBaseResource(String name) { + private InputStream loadBaseResource(final String name) { return parent == null ? super.getResourceAsStream(name) : parent.getResourceAsStream(name); } @@ -775,11 +782,11 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return a stream to the required resource or null if * the resource cannot be found in the given file. */ - private InputStream getResourceStream(File file, String resourceName) { + private InputStream getResourceStream(final File file, final String resourceName) { try { - JarFile jarFile = (JarFile) jarFiles.get(file); + JarFile jarFile = jarFiles.get(file); if (jarFile == null && file.isDirectory()) { - File resource = new File(file, resourceName); + final File resource = new File(file, resourceName); if (resource.exists()) { return new FileInputStream(resource); } @@ -793,14 +800,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { } //to eliminate a race condition, retrieve the entry //that is in the hash table under that filename - jarFile = (JarFile) jarFiles.get(file); + jarFile = jarFiles.get(file); } - JarEntry entry = jarFile.getJarEntry(resourceName); + final JarEntry entry = jarFile.getJarEntry(resourceName); if (entry != null) { return jarFile.getInputStream(entry); } } - } catch (Exception e) { + } catch (final Exception e) { log("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage() + " reading resource " + resourceName + " from " + file, Project.MSG_VERBOSE); } @@ -820,7 +827,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return whether or not the parent classloader should be checked for a * resource before this one is. */ - private boolean isParentFirst(String resourceName) { + private boolean isParentFirst(final String resourceName) { // default to the global setting and then see // if this class belongs to a package which has been // designated to use a specific loader first @@ -830,15 +837,15 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { boolean useParentFirst = parentFirst; - for (Enumeration e = systemPackages.elements(); e.hasMoreElements();) { - String packageName = e.nextElement(); + for (final Enumeration e = systemPackages.elements(); e.hasMoreElements();) { + final String packageName = e.nextElement(); if (resourceName.startsWith(packageName)) { useParentFirst = true; break; } } - for (Enumeration e = loaderPackages.elements(); e.hasMoreElements();) { - String packageName = e.nextElement(); + for (final Enumeration e = loaderPackages.elements(); e.hasMoreElements();) { + final String packageName = e.nextElement(); if (resourceName.startsWith(packageName)) { useParentFirst = false; break; @@ -871,7 +878,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * resource could not be found or the caller doesn't have * adequate privileges to get the resource. */ - public URL getResource(String name) { + @Override + public URL getResource(final String name) { // we need to search the components of the path to see if // we can find the class we want. URL url = null; @@ -883,9 +891,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { } else { // try and load from this loader if the parent either didn't find // it or wasn't consulted. - Enumeration e = pathComponents.elements(); + final Enumeration e = pathComponents.elements(); while (e.hasMoreElements() && url == null) { - File pathComponent = e.nextElement(); + final File pathComponent = e.nextElement(); url = getResourceURL(pathComponent, name); if (url != null) { log("Resource " + name + " loaded from ant loader", Project.MSG_DEBUG); @@ -917,9 +925,13 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { *

Would override getResources if that wasn't final in Java * 1.4.

* + * @param name name of the resource + * @return possible URLs as enumeration + * @throws IOException + * @see {@link #findResources(String, boolean)} * @since Ant 1.8.0 */ - public Enumeration getNamedResources(String name) + public Enumeration getNamedResources(final String name) throws IOException { return findResources(name, false); } @@ -933,7 +945,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return an enumeration of URLs for the resources * @exception IOException if I/O errors occurs (can't happen) */ - protected Enumeration findResources(String name) throws IOException { + @Override + protected Enumeration findResources(final String name) throws IOException { return findResources(name, true); } @@ -949,10 +962,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return an enumeration of URLs for the resources * @exception IOException if I/O errors occurs (can't happen) */ - protected Enumeration findResources(String name, - boolean parentHasBeenSearched) + protected Enumeration findResources(final String name, + final boolean parentHasBeenSearched) throws IOException { - Enumeration mine = new ResourceEnumeration(name); + final Enumeration mine = new ResourceEnumeration(name); Enumeration base; if (parent != null && (!parentHasBeenSearched || parent != getParent())) { // Delegate to the parent: @@ -989,16 +1002,16 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @return a stream to the required resource or null if the * resource cannot be found in the given file object. */ - protected URL getResourceURL(File file, String resourceName) { + protected URL getResourceURL(final File file, final String resourceName) { try { - JarFile jarFile = (JarFile) jarFiles.get(file); + JarFile jarFile = jarFiles.get(file); if (jarFile == null && file.isDirectory()) { - File resource = new File(file, resourceName); + final File resource = new File(file, resourceName); if (resource.exists()) { try { return FILE_UTILS.getFileURL(resource); - } catch (MalformedURLException ex) { + } catch (final MalformedURLException ex) { return null; } } @@ -1006,7 +1019,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { if (jarFile == null) { if (file.exists()) { if (!isZip(file)) { - String msg = "CLASSPATH element " + file + final String msg = "CLASSPATH element " + file + " is not a JAR."; log(msg, Project.MSG_WARN); System.err.println(msg); @@ -1018,19 +1031,19 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { return null; } // potential race-condition - jarFile = (JarFile) jarFiles.get(file); + jarFile = jarFiles.get(file); } - JarEntry entry = jarFile.getJarEntry(resourceName); + final JarEntry entry = jarFile.getJarEntry(resourceName); if (entry != null) { try { return new URL("jar:" + FILE_UTILS.getFileURL(file) + "!/" + entry); - } catch (MalformedURLException ex) { + } catch (final MalformedURLException ex) { return null; } } } - } catch (Exception e) { - String msg = "Unable to obtain resource from " + file + ": "; + } catch (final Exception e) { + final String msg = "Unable to obtain resource from " + file + ": "; log(msg + e, Project.MSG_WARN); System.err.println(msg); e.printStackTrace(); @@ -1058,7 +1071,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * on the system classpath (when not in isolated mode) or this loader's * classpath. */ - protected synchronized Class loadClass(String classname, boolean resolve) + @Override + protected synchronized Class loadClass(final String classname, final boolean resolve) throws ClassNotFoundException { // 'sync' is needed - otherwise 2 threads can load the same class // twice, resulting in LinkageError: duplicated class definition. @@ -1073,7 +1087,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { theClass = findBaseClass(classname); log("Class " + classname + " loaded from parent loader " + "(parentFirst)", Project.MSG_DEBUG); - } catch (ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException cnfe) { theClass = findClass(classname); log("Class " + classname + " loaded from ant loader " + "(parentFirst)", Project.MSG_DEBUG); @@ -1082,7 +1096,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { try { theClass = findClass(classname); log("Class " + classname + " loaded from ant loader", Project.MSG_DEBUG); - } catch (ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException cnfe) { if (ignoreBase) { throw cnfe; } @@ -1105,7 +1119,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @return the classname in filesystem format (eg java/lang/Integer.class) */ - private String getClassFilename(String classname) { + private String getClassFilename(final String classname) { return classname.replace('.', '/') + ".class"; } @@ -1122,15 +1136,15 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @throws IOException if the class data cannot be read. */ - protected Class defineClassFromData(File container, byte[] classData, String classname) + protected Class defineClassFromData(final File container, final byte[] classData, final String classname) throws IOException { definePackage(container, classname); - ProtectionDomain currentPd = Project.class.getProtectionDomain(); - String classResource = getClassFilename(classname); - CodeSource src = new CodeSource(FILE_UTILS.getFileURL(container), + final ProtectionDomain currentPd = Project.class.getProtectionDomain(); + final String classResource = getClassFilename(classname); + final CodeSource src = new CodeSource(FILE_UTILS.getFileURL(container), getCertificates(container, classResource)); - ProtectionDomain classesPd = + final ProtectionDomain classesPd = new ProtectionDomain(src, currentPd.getPermissions(), this, currentPd.getPrincipals()); @@ -1148,18 +1162,18 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception IOException if the package information cannot be read from the * container. */ - protected void definePackage(File container, String className) throws IOException { - int classIndex = className.lastIndexOf('.'); + protected void definePackage(final File container, final String className) throws IOException { + final int classIndex = className.lastIndexOf('.'); if (classIndex == -1) { return; } - String packageName = className.substring(0, classIndex); + final String packageName = className.substring(0, classIndex); if (getPackage(packageName) != null) { // already defined return; } // define the package now - Manifest manifest = getJarManifest(container); + final Manifest manifest = getJarManifest(container); if (manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); @@ -1179,11 +1193,11 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @exception IOException if the manifest cannot be read. */ - private Manifest getJarManifest(File container) throws IOException { + private Manifest getJarManifest(final File container) throws IOException { if (container.isDirectory()) { return null; } - JarFile jarFile = (JarFile) jarFiles.get(container); + final JarFile jarFile = jarFiles.get(container); if (jarFile == null) { return null; } @@ -1201,16 +1215,16 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @exception IOException if the manifest cannot be read. */ - private Certificate[] getCertificates(File container, String entry) + private Certificate[] getCertificates(final File container, final String entry) throws IOException { if (container.isDirectory()) { return null; } - JarFile jarFile = (JarFile) jarFiles.get(container); + final JarFile jarFile = jarFiles.get(container); if (jarFile == null) { return null; } - JarEntry ent = jarFile.getJarEntry(entry); + final JarEntry ent = jarFile.getJarEntry(entry); return ent == null ? null : ent.getCertificates(); } @@ -1222,8 +1236,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @param packageName the name of the package being defined. * @param manifest the jar's manifest */ - protected void definePackage(File container, String packageName, Manifest manifest) { - String sectionName = packageName.replace('.', '/') + "/"; + protected void definePackage(final File container, final String packageName, final Manifest manifest) { + final String sectionName = packageName.replace('.', '/') + "/"; String specificationTitle = null; String specificationVendor = null; @@ -1234,7 +1248,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { String sealedString = null; URL sealBase = null; - Attributes sectionAttributes = manifest.getAttributes(sectionName); + final Attributes sectionAttributes = manifest.getAttributes(sectionName); if (sectionAttributes != null) { specificationTitle = sectionAttributes.getValue(Name.SPECIFICATION_TITLE); specificationVendor = sectionAttributes.getValue(Name.SPECIFICATION_VENDOR); @@ -1244,7 +1258,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { implementationVersion = sectionAttributes.getValue(Name.IMPLEMENTATION_VERSION); sealedString = sectionAttributes.getValue(Name.SEALED); } - Attributes mainAttributes = manifest.getMainAttributes(); + final Attributes mainAttributes = manifest.getMainAttributes(); if (mainAttributes != null) { if (specificationTitle == null) { specificationTitle = mainAttributes.getValue(Name.SPECIFICATION_TITLE); @@ -1271,7 +1285,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { if (sealedString != null && sealedString.equalsIgnoreCase("true")) { try { sealBase = new URL(FileUtils.getFileUtils().toURI(container.getAbsolutePath())); - } catch (MalformedURLException e) { + } catch (final MalformedURLException e) { // ignore } } @@ -1295,16 +1309,16 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception SecurityException if there is a security problem while * reading the class from the stream. */ - private Class getClassFromStream(InputStream stream, String classname, File container) + private Class getClassFromStream(final InputStream stream, final String classname, final File container) throws IOException, SecurityException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = -1; - byte[] buffer = new byte[BUFFER_SIZE]; + final byte[] buffer = new byte[BUFFER_SIZE]; while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) { baos.write(buffer, 0, bytesRead); } - byte[] classData = baos.toByteArray(); + final byte[] classData = baos.toByteArray(); return defineClassFromData(container, classData, classname); } @@ -1319,7 +1333,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception ClassNotFoundException if the requested class does not exist * on this loader's classpath. */ - public Class findClass(String name) throws ClassNotFoundException { + @Override + public Class findClass(final String name) throws ClassNotFoundException { log("Finding class " + name, Project.MSG_DEBUG); return findClassInComponents(name); } @@ -1331,7 +1346,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @return true if the file is in the class path */ - protected boolean isInPath(File component) { + protected boolean isInPath(final File component) { return pathComponents.contains(component); } @@ -1346,14 +1361,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception ClassNotFoundException if the requested class does not exist * on this loader's classpath. */ - private Class findClassInComponents(String name) + private Class findClassInComponents(final String name) throws ClassNotFoundException { // we need to search the components of the path to see if // we can find the class we want. - String classFilename = getClassFilename(name); - Enumeration e = pathComponents.elements(); + final String classFilename = getClassFilename(name); + final Enumeration e = pathComponents.elements(); while (e.hasMoreElements()) { - File pathComponent = (File) e.nextElement(); + final File pathComponent = e.nextElement(); InputStream stream = null; try { stream = getResourceStream(pathComponent, classFilename); @@ -1362,9 +1377,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { + classFilename, Project.MSG_DEBUG); return getClassFromStream(stream, name, pathComponent); } - } catch (SecurityException se) { + } catch (final SecurityException se) { throw se; - } catch (IOException ioe) { + } catch (final IOException ioe) { // ioe.printStackTrace(); log("Exception reading component " + pathComponent + " (reason: " + ioe.getMessage() + ")", Project.MSG_VERBOSE); @@ -1390,7 +1405,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @exception ClassNotFoundException if the requested class does not exist * on this loader's classpath. */ - private Class findBaseClass(String name) throws ClassNotFoundException { + private Class findBaseClass(final String name) throws ClassNotFoundException { return parent == null ? findSystemClass(name) : parent.loadClass(name); } @@ -1399,11 +1414,11 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * files are closed. */ public synchronized void cleanup() { - for (Enumeration e = jarFiles.elements(); e.hasMoreElements();) { - JarFile jarFile = e.nextElement(); + for (final Enumeration e = jarFiles.elements(); e.hasMoreElements();) { + final JarFile jarFile = e.nextElement(); try { jarFile.close(); - } catch (IOException ioe) { + } catch (final IOException ioe) { // ignore } } @@ -1418,6 +1433,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * Gets the parent as has been specified in the constructor or via * setParent. * + * @return classloader * @since Ant 1.8.0 */ public ClassLoader getConfiguredParent() { @@ -1429,7 +1445,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the buildStarted event */ - public void buildStarted(BuildEvent event) { + @Override + public void buildStarted(final BuildEvent event) { // Not significant for the class loader. } @@ -1439,7 +1456,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the buildFinished event */ - public void buildFinished(BuildEvent event) { + @Override + public void buildFinished(final BuildEvent event) { cleanup(); } @@ -1452,7 +1470,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @since Ant 1.6.2 */ - public void subBuildFinished(BuildEvent event) { + @Override + public void subBuildFinished(final BuildEvent event) { if (event.getProject() == project) { cleanup(); } @@ -1465,7 +1484,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @since Ant 1.6.2 */ - public void subBuildStarted(BuildEvent event) { + @Override + public void subBuildStarted(final BuildEvent event) { // Not significant for the class loader. } @@ -1474,7 +1494,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the targetStarted event */ - public void targetStarted(BuildEvent event) { + @Override + public void targetStarted(final BuildEvent event) { // Not significant for the class loader. } @@ -1483,7 +1504,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the targetFinished event */ - public void targetFinished(BuildEvent event) { + @Override + public void targetFinished(final BuildEvent event) { // Not significant for the class loader. } @@ -1492,7 +1514,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the taskStarted event */ - public void taskStarted(BuildEvent event) { + @Override + public void taskStarted(final BuildEvent event) { // Not significant for the class loader. } @@ -1501,7 +1524,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the taskFinished event */ - public void taskFinished(BuildEvent event) { + @Override + public void taskFinished(final BuildEvent event) { // Not significant for the class loader. } @@ -1510,7 +1534,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @param event the messageLogged event */ - public void messageLogged(BuildEvent event) { + @Override + public void messageLogged(final BuildEvent event) { // Not significant for the class loader. } @@ -1519,10 +1544,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * here */ public void addJavaLibraries() { - Vector packages = JavaEnvUtils.getJrePackages(); - Enumeration e = packages.elements(); + final Vector packages = JavaEnvUtils.getJrePackages(); + final Enumeration e = packages.elements(); while (e.hasMoreElements()) { - String packageName = e.nextElement(); + final String packageName = e.nextElement(); addSystemPackageRoot(packageName); } } @@ -1531,7 +1556,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * Returns a String representing this loader. * @return the path that this classloader has. */ - public String toString() { + @Override + public String toString() { return "AntClassLoader[" + getClasspath() + "]"; } @@ -1545,7 +1571,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { try { subClassToLoad = Class.forName("org.apache.tools.ant.loader.AntClassLoader5"); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // this is Java5 but the installation is lacking our subclass } } @@ -1554,10 +1580,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { /** * Factory method */ - public static AntClassLoader newAntClassLoader(ClassLoader parent, - Project project, - Path path, - boolean parentFirst) { + public static AntClassLoader newAntClassLoader(final ClassLoader parent, + final Project project, + final Path path, + final boolean parentFirst) { if (subClassToLoad != null) { return (AntClassLoader) ReflectUtil.newInstance(subClassToLoad, @@ -1574,10 +1600,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { private static final ZipLong SINGLE_SEGMENT_SPLIT_MARKER = new ZipLong(0X30304B50L); - private static boolean isZip(File file) throws IOException { - byte[] sig = new byte[4]; + private static boolean isZip(final File file) throws IOException { + final byte[] sig = new byte[4]; if (readFully(file, sig)) { - ZipLong start = new ZipLong(sig); + final ZipLong start = new ZipLong(sig); return ZipLong.LFH_SIG.equals(start) // normal file || EOCD_SIG.equals(start) // empty zip || ZipLong.DD_SIG.equals(start) // split zip @@ -1586,8 +1612,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { return false; } - private static boolean readFully(File f, byte[] b) throws IOException { - FileInputStream fis = new FileInputStream(f); + private static boolean readFully(final File f, final byte[] b) throws IOException { + final FileInputStream fis = new FileInputStream(f); try { final int len = b.length; int count = 0, x = 0; diff --git a/src/main/org/apache/tools/ant/ArgumentProcessor.java b/src/main/org/apache/tools/ant/ArgumentProcessor.java index f93e6c6d7..07812f2fe 100644 --- a/src/main/org/apache/tools/ant/ArgumentProcessor.java +++ b/src/main/org/apache/tools/ant/ArgumentProcessor.java @@ -27,7 +27,7 @@ import java.util.List; * ones. It is then recommended to chose specific 'enough' argument name, * avoiding for instance one letter arguments. By the way, if there any * conflict, Ant will take precedence. - * + * * @since 1.9 */ public interface ArgumentProcessor { @@ -64,7 +64,7 @@ public interface ArgumentProcessor { /** * Print the usage of the supported arguments - * + * * @see org.apache.tools.ant.Main#printUsage() */ void printUsage(PrintStream writer); diff --git a/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java b/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java index e65854307..bdb7c0a8a 100644 --- a/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java +++ b/src/main/org/apache/tools/ant/ArgumentProcessorRegistry.java @@ -39,7 +39,7 @@ import org.apache.tools.ant.util.LoaderUtils; *

* Use the system property ant.argument-processor.debug to enable * the print of debug log. - * + * * @since 1.9 */ public class ArgumentProcessorRegistry { diff --git a/src/main/org/apache/tools/ant/BuildListener.java b/src/main/org/apache/tools/ant/BuildListener.java index 09a77f3a5..ed6731cf2 100644 --- a/src/main/org/apache/tools/ant/BuildListener.java +++ b/src/main/org/apache/tools/ant/BuildListener.java @@ -37,7 +37,7 @@ public interface BuildListener extends EventListener { *

This event is fired before the project instance is fully * configured. In particular no properties have been set and the * project may not know its name or default target, yet.

- * + * * @param event An event with any relevant extra information. * Must not be null. */ diff --git a/src/main/org/apache/tools/ant/DirectoryScanner.java b/src/main/org/apache/tools/ant/DirectoryScanner.java index 5b3755585..cf93eb7c3 100644 --- a/src/main/org/apache/tools/ant/DirectoryScanner.java +++ b/src/main/org/apache/tools/ant/DirectoryScanner.java @@ -145,7 +145,8 @@ public class DirectoryScanner * Use the {@link #getDefaultExcludes getDefaultExcludes} * method instead. */ - protected static final String[] DEFAULTEXCLUDES = { + @Deprecated + protected static final String[] DEFAULTEXCLUDES = { // Miscellaneous typical temporary files SelectorUtils.DEEP_TREE_MATCH + "/*~", SelectorUtils.DEEP_TREE_MATCH + "/#*#", @@ -558,7 +559,7 @@ public class DirectoryScanner */ public static String[] getDefaultExcludes() { synchronized (defaultExcludes) { - return (String[]) defaultExcludes.toArray(new String[defaultExcludes + return defaultExcludes.toArray(new String[defaultExcludes .size()]); } } @@ -618,7 +619,8 @@ public class DirectoryScanner * * @param basedir The base directory to scan. */ - public void setBasedir(String basedir) { + @Override + public void setBasedir(String basedir) { setBasedir(basedir == null ? (File) null : new File(basedir.replace('/', File.separatorChar).replace( '\\', File.separatorChar))); @@ -630,7 +632,8 @@ public class DirectoryScanner * * @param basedir The base directory for scanning. */ - public synchronized void setBasedir(File basedir) { + @Override + public synchronized void setBasedir(File basedir) { this.basedir = basedir; } @@ -640,7 +643,8 @@ public class DirectoryScanner * * @return the base directory to be scanned. */ - public synchronized File getBasedir() { + @Override + public synchronized File getBasedir() { return basedir; } @@ -661,7 +665,8 @@ public class DirectoryScanner * @param isCaseSensitive whether or not the file system should be * regarded as a case sensitive one. */ - public synchronized void setCaseSensitive(boolean isCaseSensitive) { + @Override + public synchronized void setCaseSensitive(boolean isCaseSensitive) { this.isCaseSensitive = isCaseSensitive; } @@ -719,7 +724,8 @@ public class DirectoryScanner * list is given, all elements must be * non-null. */ - public synchronized void setIncludes(String[] includes) { + @Override + public synchronized void setIncludes(String[] includes) { if (includes == null) { this.includes = null; } else { @@ -742,7 +748,8 @@ public class DirectoryScanner * should be excluded. If a non-null list is * given, all elements must be non-null. */ - public synchronized void setExcludes(String[] excludes) { + @Override + public synchronized void setExcludes(String[] excludes) { if (excludes == null) { this.excludes = null; } else { @@ -807,7 +814,8 @@ public class DirectoryScanner * * @param selectors specifies the selectors to be invoked on a scan. */ - public synchronized void setSelectors(FileSelector[] selectors) { + @Override + public synchronized void setSelectors(FileSelector[] selectors) { this.selectors = selectors; } @@ -832,7 +840,8 @@ public class DirectoryScanner * @exception IllegalStateException if the base directory was set * incorrectly (i.e. if it doesn't exist or isn't a directory). */ - public void scan() throws IllegalStateException { + @Override + public void scan() throws IllegalStateException { synchronized (scanLock) { if (scanning) { while (scanning) { @@ -1023,7 +1032,7 @@ public class DirectoryScanner scandir(myfile, currentPath, true); } } else if (myfile.isFile()) { - String originalpattern = (String) entry.getValue(); + String originalpattern = entry.getValue(); boolean included = isCaseSensitive() ? originalpattern.equals(currentelement) : originalpattern.equalsIgnoreCase(currentelement); @@ -1239,7 +1248,7 @@ public class DirectoryScanner noLinks.add(newfiles[i]); } } - newfiles = (String[]) (noLinks.toArray(new String[noLinks.size()])); + newfiles = (noLinks.toArray(new String[noLinks.size()])); } else { directoryNamesFollowed.addFirst(dir.getName()); } @@ -1424,7 +1433,7 @@ public class DirectoryScanner } } for (Iterator iter = includeNonPatterns.values().iterator(); - iter.hasNext(); ) { + iter.hasNext();) { if (couldHoldIncluded(tokenizedName, iter.next().toPattern())) { return true; @@ -1567,7 +1576,8 @@ public class DirectoryScanner * @return the names of the files which matched at least one of the * include patterns and none of the exclude patterns. */ - public String[] getIncludedFiles() { + @Override + public String[] getIncludedFiles() { String[] files; synchronized (this) { if (filesIncluded == null) { @@ -1602,7 +1612,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getNotIncludedFiles() { + @Override + public synchronized String[] getNotIncludedFiles() { slowScan(); String[] files = new String[filesNotIncluded.size()]; filesNotIncluded.copyInto(files); @@ -1620,7 +1631,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getExcludedFiles() { + @Override + public synchronized String[] getExcludedFiles() { slowScan(); String[] files = new String[filesExcluded.size()]; filesExcluded.copyInto(files); @@ -1638,7 +1650,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getDeselectedFiles() { + @Override + public synchronized String[] getDeselectedFiles() { slowScan(); String[] files = new String[filesDeselected.size()]; filesDeselected.copyInto(files); @@ -1653,7 +1666,8 @@ public class DirectoryScanner * @return the names of the directories which matched at least one of the * include patterns and none of the exclude patterns. */ - public String[] getIncludedDirectories() { + @Override + public String[] getIncludedDirectories() { String[] directories; synchronized (this) { if (dirsIncluded == null) { @@ -1688,7 +1702,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getNotIncludedDirectories() { + @Override + public synchronized String[] getNotIncludedDirectories() { slowScan(); String[] directories = new String[dirsNotIncluded.size()]; dirsNotIncluded.copyInto(directories); @@ -1706,7 +1721,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getExcludedDirectories() { + @Override + public synchronized String[] getExcludedDirectories() { slowScan(); String[] directories = new String[dirsExcluded.size()]; dirsExcluded.copyInto(directories); @@ -1724,7 +1740,8 @@ public class DirectoryScanner * * @see #slowScan */ - public synchronized String[] getDeselectedDirectories() { + @Override + public synchronized String[] getDeselectedDirectories() { slowScan(); String[] directories = new String[dirsDeselected.size()]; dirsDeselected.copyInto(directories); @@ -1743,7 +1760,7 @@ public class DirectoryScanner public synchronized String[] getNotFollowedSymlinks() { String[] links; synchronized (this) { - links = (String[]) notFollowedSymlinks + links = notFollowedSymlinks .toArray(new String[notFollowedSymlinks.size()]); } Arrays.sort(links); @@ -1753,7 +1770,8 @@ public class DirectoryScanner /** * Add default exclusions to the current exclusions set. */ - public synchronized void addDefaultExcludes() { + @Override + public synchronized void addDefaultExcludes() { int excludesLength = excludes == null ? 0 : excludes.length; String[] newExcludes; String[] defaultExcludesTemp = getDefaultExcludes(); @@ -1776,7 +1794,8 @@ public class DirectoryScanner * @return the resource with the given name. * @since Ant 1.5.2 */ - public synchronized Resource getResource(String name) { + @Override + public synchronized Resource getResource(String name) { return new FileResource(basedir, name); } @@ -1847,7 +1866,7 @@ public class DirectoryScanner al.add(new TokenizedPattern(patterns[i])); } } - return (TokenizedPattern[]) al.toArray(new TokenizedPattern[al.size()]); + return al.toArray(new TokenizedPattern[al.size()]); } /** diff --git a/src/main/org/apache/tools/ant/Evaluable.java b/src/main/org/apache/tools/ant/Evaluable.java index abf2ba280..47f09c739 100644 --- a/src/main/org/apache/tools/ant/Evaluable.java +++ b/src/main/org/apache/tools/ant/Evaluable.java @@ -19,7 +19,7 @@ package org.apache.tools.ant; /** * Kind of task attribute that can be evaluated before being assigned - * + * * @see RuntimeConfigurable */ public interface Evaluable { diff --git a/src/main/org/apache/tools/ant/ExtensionPoint.java b/src/main/org/apache/tools/ant/ExtensionPoint.java index 494c4a2d3..d944437e2 100644 --- a/src/main/org/apache/tools/ant/ExtensionPoint.java +++ b/src/main/org/apache/tools/ant/ExtensionPoint.java @@ -26,7 +26,6 @@ package org.apache.tools.ant; public class ExtensionPoint extends Target { public ExtensionPoint() { - } /** @@ -45,15 +44,17 @@ public class ExtensionPoint extends Target { /** * Throws an exception. */ - public final void addTask(Task task) { + @Override + public final void addTask(Task task) { throw new BuildException(NO_CHILDREN_ALLOWED); } /** * Throws an exception. */ - public final void addDataType(RuntimeConfigurable r) { + @Override + public final void addDataType(RuntimeConfigurable r) { throw new BuildException(NO_CHILDREN_ALLOWED); } - + } diff --git a/src/main/org/apache/tools/ant/IntrospectionHelper.java b/src/main/org/apache/tools/ant/IntrospectionHelper.java index e8a41abcc..a1e6874d9 100644 --- a/src/main/org/apache/tools/ant/IntrospectionHelper.java +++ b/src/main/org/apache/tools/ant/IntrospectionHelper.java @@ -75,9 +75,9 @@ public final class IntrospectionHelper { // Set up PRIMITIVE_TYPE_MAP static { - Class[] primitives = {Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, + final Class[] primitives = {Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE}; - Class[] wrappers = {Boolean.class, Byte.class, Character.class, Short.class, + final Class[] wrappers = {Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class}; for (int i = 0; i < primitives.length; i++) { PRIMITIVE_TYPE_MAP.put (primitives[i], wrappers[i]); @@ -178,13 +178,13 @@ public final class IntrospectionHelper { */ private IntrospectionHelper(final Class bean) { this.bean = bean; - Method[] methods = bean.getMethods(); + final Method[] methods = bean.getMethods(); Method addTextMethod = null; for (int i = 0; i < methods.length; i++) { final Method m = methods[i]; final String name = m.getName(); - Class returnType = m.getReturnType(); - Class[] args = m.getParameterTypes(); + final Class returnType = m.getReturnType(); + final Class[] args = m.getParameterTypes(); // check of add[Configured](Class) pattern if (args.length == 1 && java.lang.Void.TYPE.equals(returnType) @@ -207,8 +207,8 @@ public final class IntrospectionHelper { addTextMethod = methods[i]; } else if (name.startsWith("set") && java.lang.Void.TYPE.equals(returnType) && args.length == 1 && !args[0].isArray()) { - String propName = getPropertyName(name, "set"); - AttributeSetter as = (AttributeSetter) attributeSetters.get(propName); + final String propName = getPropertyName(name, "set"); + AttributeSetter as = attributeSetters.get(propName); if (as != null) { if (java.lang.String.class.equals(args[0])) { /* @@ -243,7 +243,7 @@ public final class IntrospectionHelper { } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive() && args.length == 0) { - String propName = getPropertyName(name, "create"); + final String propName = getPropertyName(name, "create"); // Check if a create of this property is already present // add takes preference over create for CB purposes if (nestedCreators.get(propName) == null) { @@ -258,14 +258,14 @@ public final class IntrospectionHelper { Constructor constructor = null; try { constructor = args[0].getConstructor(); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { constructor = args[0].getConstructor(Project.class); } - String propName = getPropertyName(name, "addConfigured"); + final String propName = getPropertyName(name, "addConfigured"); nestedTypes.put(propName, args[0]); nestedCreators.put(propName, new AddNestedCreator(m, constructor, AddNestedCreator.ADD_CONFIGURED)); - } catch (NoSuchMethodException nse) { + } catch (final NoSuchMethodException nse) { // ignore } } else if (name.startsWith("add") @@ -276,10 +276,10 @@ public final class IntrospectionHelper { Constructor constructor = null; try { constructor = args[0].getConstructor(); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { constructor = args[0].getConstructor(Project.class); } - String propName = getPropertyName(name, "add"); + final String propName = getPropertyName(name, "add"); if (nestedTypes.get(propName) != null) { /* * Ignore this method as there is an addConfigured @@ -291,7 +291,7 @@ public final class IntrospectionHelper { nestedTypes.put(propName, args[0]); nestedCreators.put(propName, new AddNestedCreator(m, constructor, AddNestedCreator.ADD)); - } catch (NoSuchMethodException nse) { + } catch (final NoSuchMethodException nse) { // ignore } } @@ -307,7 +307,7 @@ public final class IntrospectionHelper { * @param type the type of the set method's parameter * @return true if the given set method is to be hidden. */ - private boolean isHiddenSetMethod(String name, Class type) { + private boolean isHiddenSetMethod(final String name, final Class type) { if ("setLocation".equals(name) && org.apache.tools.ant.Location.class.equals(type)) { return true; } @@ -326,7 +326,7 @@ public final class IntrospectionHelper { * * @return a helper for the specified class */ - public static synchronized IntrospectionHelper getHelper(Class c) { + public static synchronized IntrospectionHelper getHelper(final Class c) { return getHelper(null, c); } @@ -343,7 +343,7 @@ public final class IntrospectionHelper { * * @return a helper for the specified class */ - public synchronized static IntrospectionHelper getHelper(Project p, Class c) { + public static synchronized IntrospectionHelper getHelper(final Project p, final Class c) { IntrospectionHelper ih = HELPERS.get(c.getName()); // If a helper cannot be found, or if the helper is for another // classloader, create a new IH @@ -376,43 +376,43 @@ public final class IntrospectionHelper { * the given attribute, or if the setting * method fails. */ - public void setAttribute(Project p, Object element, String attributeName, - Object value) throws BuildException { - AttributeSetter as = (AttributeSetter) attributeSetters.get( + public void setAttribute(final Project p, final Object element, final String attributeName, + final Object value) throws BuildException { + final AttributeSetter as = attributeSetters.get( attributeName.toLowerCase(Locale.ENGLISH)); if (as == null && value != null) { if (element instanceof DynamicAttributeNS) { - DynamicAttributeNS dc = (DynamicAttributeNS) element; - String uriPlusPrefix = ProjectHelper.extractUriFromComponentName(attributeName); - String uri = ProjectHelper.extractUriFromComponentName(uriPlusPrefix); - String localName = ProjectHelper.extractNameFromComponentName(attributeName); - String qName = "".equals(uri) ? localName : uri + ":" + localName; + final DynamicAttributeNS dc = (DynamicAttributeNS) element; + final String uriPlusPrefix = ProjectHelper.extractUriFromComponentName(attributeName); + final String uri = ProjectHelper.extractUriFromComponentName(uriPlusPrefix); + final String localName = ProjectHelper.extractNameFromComponentName(attributeName); + final String qName = "".equals(uri) ? localName : uri + ":" + localName; dc.setDynamicAttribute(uri, localName, qName, value.toString()); return; } if (element instanceof DynamicObjectAttribute) { - DynamicObjectAttribute dc = (DynamicObjectAttribute) element; + final DynamicObjectAttribute dc = (DynamicObjectAttribute) element; dc.setDynamicAttribute(attributeName.toLowerCase(Locale.ENGLISH), value); return; } if (element instanceof DynamicAttribute) { - DynamicAttribute dc = (DynamicAttribute) element; + final DynamicAttribute dc = (DynamicAttribute) element; dc.setDynamicAttribute(attributeName.toLowerCase(Locale.ENGLISH), value.toString()); return; } if (attributeName.indexOf(':') >= 0) { return; // Ignore attribute from unknown uri's } - String msg = getElementName(p, element) + final String msg = getElementName(p, element) + " doesn't support the \"" + attributeName + "\" attribute."; throw new UnsupportedAttributeException(msg, attributeName); } try { as.setObject(p, element, value); - } catch (IllegalAccessException ie) { + } catch (final IllegalAccessException ie) { // impossible as getMethods should only return public methods throw new BuildException(ie); - } catch (InvocationTargetException ite) { + } catch (final InvocationTargetException ite) { throw extractBuildException(ite); } } @@ -435,8 +435,8 @@ public final class IntrospectionHelper { * the given attribute, or if the setting * method fails. */ - public void setAttribute(Project p, Object element, String attributeName, - String value) throws BuildException { + public void setAttribute(final Project p, final Object element, final String attributeName, + final String value) throws BuildException { setAttribute(p, element, attributeName, (Object) value); } @@ -457,7 +457,7 @@ public final class IntrospectionHelper { * method is available to handle it, or if * the handling method fails. */ - public void addText(Project project, Object element, String text) + public void addText(final Project project, final Object element, String text) throws BuildException { if (addText == null) { text = text.trim(); @@ -472,10 +472,10 @@ public final class IntrospectionHelper { } try { addText.invoke(element, new Object[] {text}); - } catch (IllegalAccessException ie) { + } catch (final IllegalAccessException ie) { // impossible as getMethods should only return public methods throw new BuildException(ie); - } catch (InvocationTargetException ite) { + } catch (final InvocationTargetException ite) { throw extractBuildException(ite); } } @@ -502,8 +502,8 @@ public final class IntrospectionHelper { * @param parent the object which doesn't support a requested element * @param elementName the name of the Element which is trying to be created. */ - public void throwNotSupported(Project project, Object parent, String elementName) { - String msg = project.getElementName(parent) + public void throwNotSupported(final Project project, final Object parent, final String elementName) { + final String msg = project.getElementName(parent) + NOT_SUPPORTED_CHILD_PREFIX + elementName + NOT_SUPPORTED_CHILD_POSTFIX; throw new UnsupportedElementException(msg, elementName); @@ -521,11 +521,11 @@ public final class IntrospectionHelper { * @throws BuildException if the parent does not support child elements of that name */ private NestedCreator getNestedCreator( - Project project, String parentUri, Object parent, - String elementName, UnknownElement child) throws BuildException { + final Project project, String parentUri, final Object parent, + final String elementName, final UnknownElement child) throws BuildException { String uri = ProjectHelper.extractUriFromComponentName(elementName); - String name = ProjectHelper.extractNameFromComponentName(elementName); + final String name = ProjectHelper.extractNameFromComponentName(elementName); if (uri.equals(ProjectHelper.ANT_CORE_URI)) { uri = ""; @@ -535,7 +535,7 @@ public final class IntrospectionHelper { } NestedCreator nc = null; if (uri.equals(parentUri) || uri.length() == 0) { - nc = (NestedCreator) nestedCreators.get(name.toLowerCase(Locale.ENGLISH)); + nc = nestedCreators.get(name.toLowerCase(Locale.ENGLISH)); } if (nc == null) { nc = createAddTypeCreator(project, parent, elementName); @@ -544,14 +544,15 @@ public final class IntrospectionHelper { (parent instanceof DynamicElementNS || parent instanceof DynamicElement) ) { - String qName = child == null ? name : child.getQName(); + final String qName = child == null ? name : child.getQName(); final Object nestedElement = createDynamicElement(parent, child == null ? "" : child.getNamespace(), name, qName); if (nestedElement != null) { nc = new NestedCreator(null) { - Object create(Project project, Object parent, Object ignore) { + @Override + Object create(final Project project, final Object parent, final Object ignore) { return nestedElement; } }; @@ -569,15 +570,15 @@ public final class IntrospectionHelper { * * @since Ant 1.8.0. */ - private Object createDynamicElement(Object parent, String ns, - String localName, String qName) { + private Object createDynamicElement(final Object parent, final String ns, + final String localName, final String qName) { Object nestedElement = null; if (parent instanceof DynamicElementNS) { - DynamicElementNS dc = (DynamicElementNS) parent; + final DynamicElementNS dc = (DynamicElementNS) parent; nestedElement = dc.createDynamicElement(ns, localName, qName); } if (nestedElement == null && parent instanceof DynamicElement) { - DynamicElement dc = (DynamicElement) parent; + final DynamicElement dc = (DynamicElement) parent; nestedElement = dc.createDynamicElement(localName.toLowerCase(Locale.ENGLISH)); } @@ -606,22 +607,23 @@ public final class IntrospectionHelper { * @exception BuildException if no method is available to create the * element instance, or if the creating method fails. */ - public Object createElement(Project project, Object parent, String elementName) + @Deprecated + public Object createElement(final Project project, final Object parent, final String elementName) throws BuildException { - NestedCreator nc = getNestedCreator(project, "", parent, elementName, null); + final NestedCreator nc = getNestedCreator(project, "", parent, elementName, null); try { - Object nestedElement = nc.create(project, parent, null); + final Object nestedElement = nc.create(project, parent, null); if (project != null) { project.setProjectReference(nestedElement); } return nestedElement; - } catch (IllegalAccessException ie) { + } catch (final IllegalAccessException ie) { // impossible as getMethods should only return public methods throw new BuildException(ie); - } catch (InstantiationException ine) { + } catch (final InstantiationException ine) { // impossible as getMethods should only return public methods throw new BuildException(ine); - } catch (InvocationTargetException ite) { + } catch (final InvocationTargetException ite) { throw extractBuildException(ite); } } @@ -639,8 +641,8 @@ public final class IntrospectionHelper { * @return a creator object to create and store the element instance. */ public Creator getElementCreator( - Project project, String parentUri, Object parent, String elementName, UnknownElement ue) { - NestedCreator nc = getNestedCreator(project, parentUri, parent, elementName, ue); + final Project project, final String parentUri, final Object parent, final String elementName, final UnknownElement ue) { + final NestedCreator nc = getNestedCreator(project, parentUri, parent, elementName, ue); return new Creator(project, parent, nc); } @@ -682,7 +684,7 @@ public final class IntrospectionHelper { * * @return true if the given nested element is supported */ - public boolean supportsNestedElement(String elementName) { + public boolean supportsNestedElement(final String elementName) { return supportsNestedElement("", elementName); } @@ -701,7 +703,7 @@ public final class IntrospectionHelper { * * @return true if the given nested element is supported */ - public boolean supportsNestedElement(String parentUri, String elementName) { + public boolean supportsNestedElement(final String parentUri, final String elementName) { if (isDynamic() || addTypeMethods.size() > 0) { return true; } @@ -725,8 +727,8 @@ public final class IntrospectionHelper { * @return true if the given nested element is supported * @since Ant 1.8.0. */ - public boolean supportsNestedElement(String parentUri, String elementName, - Project project, Object parent) { + public boolean supportsNestedElement(final String parentUri, final String elementName, + final Project project, final Object parent) { if (addTypeMethods.size() > 0 && createAddTypeCreator(project, parent, elementName) != null) { return true; @@ -744,8 +746,8 @@ public final class IntrospectionHelper { * @since Ant 1.8.0 */ public boolean supportsReflectElement( - String parentUri, String elementName) { - String name = ProjectHelper.extractNameFromComponentName(elementName); + String parentUri, final String elementName) { + final String name = ProjectHelper.extractNameFromComponentName(elementName); if (!nestedCreators.containsKey(name.toLowerCase(Locale.ENGLISH))) { return false; } @@ -782,24 +784,24 @@ public final class IntrospectionHelper { * * @exception BuildException if the storage method fails. */ - public void storeElement(Project project, Object parent, Object child, - String elementName) throws BuildException { + public void storeElement(final Project project, final Object parent, final Object child, + final String elementName) throws BuildException { if (elementName == null) { return; } - NestedCreator ns = (NestedCreator) nestedCreators.get(elementName.toLowerCase(Locale.ENGLISH)); + final NestedCreator ns = nestedCreators.get(elementName.toLowerCase(Locale.ENGLISH)); if (ns == null) { return; } try { ns.store(parent, child); - } catch (IllegalAccessException ie) { + } catch (final IllegalAccessException ie) { // impossible as getMethods should only return public methods throw new BuildException(ie); - } catch (InstantiationException ine) { + } catch (final InstantiationException ine) { // impossible as getMethods should only return public methods throw new BuildException(ine); - } catch (InvocationTargetException ite) { + } catch (final InvocationTargetException ite) { throw extractBuildException(ite); } } @@ -811,8 +813,8 @@ public final class IntrospectionHelper { * @param ite * @return the nested exception */ - private static BuildException extractBuildException(InvocationTargetException ite) { - Throwable t = ite.getTargetException(); + private static BuildException extractBuildException(final InvocationTargetException ite) { + final Throwable t = ite.getTargetException(); if (t instanceof BuildException) { return (BuildException) t; } @@ -831,8 +833,8 @@ public final class IntrospectionHelper { * @exception BuildException if the introspected class does not * support the named nested element. */ - public Class getElementType(String elementName) throws BuildException { - Class nt = nestedTypes.get(elementName); + public Class getElementType(final String elementName) throws BuildException { + final Class nt = nestedTypes.get(elementName); if (nt == null) { throw new UnsupportedElementException("Class " + bean.getName() + " doesn't support the nested \"" @@ -853,8 +855,8 @@ public final class IntrospectionHelper { * @exception BuildException if the introspected class does not * support the named attribute. */ - public Class getAttributeType(String attributeName) throws BuildException { - Class at = attributeTypes.get(attributeName); + public Class getAttributeType(final String attributeName) throws BuildException { + final Class at = attributeTypes.get(attributeName); if (at == null) { throw new UnsupportedAttributeException("Class " + bean.getName() + " doesn't support the \"" @@ -893,8 +895,8 @@ public final class IntrospectionHelper { * support the named nested element. * @since Ant 1.6.3 */ - public Method getElementMethod(String elementName) throws BuildException { - Object creator = nestedCreators.get(elementName); + public Method getElementMethod(final String elementName) throws BuildException { + final Object creator = nestedCreators.get(elementName); if (creator == null) { throw new UnsupportedElementException("Class " + bean.getName() + " doesn't support the nested \"" @@ -914,8 +916,8 @@ public final class IntrospectionHelper { * support the named attribute. * @since Ant 1.6.3 */ - public Method getAttributeMethod(String attributeName) throws BuildException { - Object setter = attributeSetters.get(attributeName); + public Method getAttributeMethod(final String attributeName) throws BuildException { + final Object setter = attributeSetters.get(attributeName); if (setter == null) { throw new UnsupportedAttributeException("Class " + bean.getName() + " doesn't support the \"" @@ -1036,7 +1038,7 @@ public final class IntrospectionHelper { * if no appropriate conversion is available. */ private AttributeSetter createAttributeSetter(final Method m, - Class arg, + final Class arg, final String attrName) { // use wrappers for primitive classes, e.g. int and // Integer are treated identically @@ -1046,7 +1048,8 @@ public final class IntrospectionHelper { // Object.class - it gets handled differently by AttributeSetter if (java.lang.Object.class == reflectedArg) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException { throw new BuildException( @@ -1057,7 +1060,8 @@ public final class IntrospectionHelper { // simplest case - setAttribute expects String if (java.lang.String.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException { m.invoke(parent, (Object[]) new String[] {value}); } @@ -1066,7 +1070,8 @@ public final class IntrospectionHelper { // char and Character get special treatment - take the first character if (java.lang.Character.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException { if (value.length() == 0) { throw new BuildException("The value \"\" is not a " @@ -1079,7 +1084,8 @@ public final class IntrospectionHelper { // boolean and Boolean get special treatment because we have a nice method in Project if (java.lang.Boolean.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException { m.invoke(parent, (Object[]) new Boolean[] { Project.toBoolean(value) ? Boolean.TRUE : Boolean.FALSE }); @@ -1089,11 +1095,12 @@ public final class IntrospectionHelper { // Class doesn't have a String constructor but a decent factory method if (java.lang.Class.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { try { m.invoke(parent, new Object[] {Class.forName(value)}); - } catch (ClassNotFoundException ce) { + } catch (final ClassNotFoundException ce) { throw new BuildException(ce); } } @@ -1102,7 +1109,8 @@ public final class IntrospectionHelper { // resolve relative paths through Project if (java.io.File.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException { m.invoke(parent, new Object[] {p.resolveFile(value)}); } @@ -1111,49 +1119,52 @@ public final class IntrospectionHelper { // resolve Resources/FileProviders as FileResources relative to Project: if (Resource.class.equals(reflectedArg) || FileProvider.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - void set(Project p, Object parent, String value) throws InvocationTargetException, + @Override + void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { - m.invoke(parent, new Object[] { new FileResource(p, p.resolveFile(value)) }); + m.invoke(parent, new Object[] {new FileResource(p, p.resolveFile(value))}); }; }; } // EnumeratedAttributes have their own helper class if (EnumeratedAttribute.class.isAssignableFrom(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { try { - EnumeratedAttribute ea = (EnumeratedAttribute) reflectedArg.newInstance(); + final EnumeratedAttribute ea = (EnumeratedAttribute) reflectedArg.newInstance(); ea.setValue(value); m.invoke(parent, new Object[] {ea}); - } catch (InstantiationException ie) { + } catch (final InstantiationException ie) { throw new BuildException(ie); } } }; } - AttributeSetter setter = getEnumSetter(reflectedArg, m, arg); + final AttributeSetter setter = getEnumSetter(reflectedArg, m, arg); if (setter != null) { return setter; } if (java.lang.Long.class.equals(reflectedArg)) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { try { m.invoke(parent, new Object[] { new Long(StringUtils.parseHumanSizes(value)) }); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new BuildException("Can't assign non-numeric" + " value '" + value + "' to" + " attribute " + attrName); - } catch (InvocationTargetException e) { + } catch (final InvocationTargetException e) { throw e; - } catch (IllegalAccessException e) { + } catch (final IllegalAccessException e) { throw e; - } catch (Exception e) { + } catch (final Exception e) { throw new BuildException(e); } } @@ -1169,12 +1180,12 @@ public final class IntrospectionHelper { // First try with Project. c = reflectedArg.getConstructor(Project.class, String.class); includeProject = true; - } catch (NoSuchMethodException nme) { + } catch (final NoSuchMethodException nme) { // OK, try without. try { c = reflectedArg.getConstructor(String.class); includeProject = false; - } catch (NoSuchMethodException nme2) { + } catch (final NoSuchMethodException nme2) { // Well, no matching constructor. return null; } @@ -1183,19 +1194,20 @@ public final class IntrospectionHelper { final Constructor finalConstructor = c; return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { try { - Object[] args = finalIncludeProject + final Object[] args = finalIncludeProject ? new Object[] {p, value} : new Object[] {value}; - Object attribute = finalConstructor.newInstance(args); + final Object attribute = finalConstructor.newInstance(args); if (p != null) { p.setProjectReference(attribute); } m.invoke(parent, new Object[] {attribute}); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); + } catch (final InvocationTargetException e) { + final Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { throw new BuildException("Can't assign value '" + value + "' to attribute " + attrName @@ -1205,7 +1217,7 @@ public final class IntrospectionHelper { + cause.getMessage() + "'"); } throw e; - } catch (InstantiationException ie) { + } catch (final InstantiationException ie) { throw new BuildException(ie); } } @@ -1213,19 +1225,21 @@ public final class IntrospectionHelper { } private AttributeSetter getEnumSetter( - final Class reflectedArg, final Method m, Class arg) { + final Class reflectedArg, final Method m, final Class arg) { if (reflectedArg.isEnum()) { return new AttributeSetter(m, arg) { - public void set(Project p, Object parent, String value) + @Override + public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException { Enum setValue; try { @SuppressWarnings({ "unchecked", "rawtypes" }) + final Enum enumValue = Enum.valueOf((Class) reflectedArg, value); setValue = enumValue; - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { //there is specific logic here for the value // being out of the allowed set of enumerations. throw new BuildException("'" + value + "' is not a permitted value for " @@ -1249,7 +1263,7 @@ public final class IntrospectionHelper { * * @return a description of the element type */ - private String getElementName(Project project, Object element) { + private String getElementName(final Project project, final Object element) { return project.getElementName(element); } @@ -1264,7 +1278,7 @@ public final class IntrospectionHelper { * * @return the lower-cased method name with the prefix removed. */ - private static String getPropertyName(String methodName, String prefix) { + private static String getPropertyName(final String methodName, final String prefix) { return methodName.substring(prefix.length()).toLowerCase(Locale.ENGLISH); } @@ -1274,9 +1288,9 @@ public final class IntrospectionHelper { * The class is final as it has a private constructor. */ public static final class Creator { - private NestedCreator nestedCreator; - private Object parent; - private Project project; + private final NestedCreator nestedCreator; + private final Object parent; + private final Project project; private Object nestedObject; private String polyType; @@ -1293,7 +1307,7 @@ public final class IntrospectionHelper { * @param parent the parent object to create the object in * @param nestedCreator the nested creator object to use */ - private Creator(Project project, Object parent, NestedCreator nestedCreator) { + private Creator(final Project project, final Object parent, final NestedCreator nestedCreator) { this.project = project; this.parent = parent; this.nestedCreator = nestedCreator; @@ -1304,7 +1318,7 @@ public final class IntrospectionHelper { * * @param polyType a ant component type name */ - public void setPolyType(String polyType) { + public void setPolyType(final String polyType) { this.polyType = polyType; } @@ -1319,7 +1333,7 @@ public final class IntrospectionHelper { throw new BuildException( "Not allowed to use the polymorphic form for this element"); } - ComponentHelper helper = ComponentHelper.getComponentHelper(project); + final ComponentHelper helper = ComponentHelper.getComponentHelper(project); nestedObject = helper.createComponent(polyType); if (nestedObject == null) { throw new BuildException("Unable to create object of type " + polyType); @@ -1331,16 +1345,16 @@ public final class IntrospectionHelper { project.setProjectReference(nestedObject); } return nestedObject; - } catch (IllegalAccessException ex) { + } catch (final IllegalAccessException ex) { throw new BuildException(ex); - } catch (InstantiationException ex) { + } catch (final InstantiationException ex) { throw new BuildException(ex); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { if (polyType == null) { throw ex; } throw new BuildException("Invalid type used " + polyType); - } catch (InvocationTargetException ex) { + } catch (final InvocationTargetException ex) { throw extractBuildException(ex); } } @@ -1359,16 +1373,16 @@ public final class IntrospectionHelper { public void store() { try { nestedCreator.store(parent, nestedObject); - } catch (IllegalAccessException ex) { + } catch (final IllegalAccessException ex) { throw new BuildException(ex); - } catch (InstantiationException ex) { + } catch (final InstantiationException ex) { throw new BuildException(ex); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { if (polyType == null) { throw ex; } throw new BuildException("Invalid type used " + polyType); - } catch (InvocationTargetException ex) { + } catch (final InvocationTargetException ex) { throw extractBuildException(ex); } } @@ -1379,9 +1393,9 @@ public final class IntrospectionHelper { * in detail for reasons of source code readability. */ private abstract static class NestedCreator { - private Method method; // the method called to add/create the nested element + private final Method method; // the method called to add/create the nested element - protected NestedCreator(Method m) { + protected NestedCreator(final Method m) { method = m; } Method getMethod() { @@ -1396,18 +1410,19 @@ public final class IntrospectionHelper { abstract Object create(Project project, Object parent, Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException; - void store(Object parent, Object child) + void store(final Object parent, final Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException { // DO NOTHING } } private static class CreateNestedCreator extends NestedCreator { - CreateNestedCreator(Method m) { + CreateNestedCreator(final Method m) { super(m); } - Object create(Project project, Object parent, Object ignore) + @Override + Object create(final Project project, final Object parent, final Object ignore) throws InvocationTargetException, IllegalAccessException { return getMethod().invoke(parent, new Object[] {}); } @@ -1419,20 +1434,22 @@ public final class IntrospectionHelper { static final int ADD = 1; static final int ADD_CONFIGURED = 2; - private Constructor constructor; - private int behavior; // ADD or ADD_CONFIGURED + private final Constructor constructor; + private final int behavior; // ADD or ADD_CONFIGURED - AddNestedCreator(Method m, Constructor c, int behavior) { + AddNestedCreator(final Method m, final Constructor c, final int behavior) { super(m); this.constructor = c; this.behavior = behavior; } - boolean isPolyMorphic() { + @Override + boolean isPolyMorphic() { return true; } - Object create(Project project, Object parent, Object child) + @Override + Object create(final Project project, final Object parent, Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException { if (child == null) { child = constructor.newInstance( @@ -1448,14 +1465,15 @@ public final class IntrospectionHelper { return child; } - void store(Object parent, Object child) + @Override + void store(final Object parent, final Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException { if (behavior == ADD_CONFIGURED) { istore(parent, child); } } - private void istore(Object parent, Object child) + private void istore(final Object parent, final Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException { getMethod().invoke(parent, new Object[] {child}); } @@ -1466,13 +1484,13 @@ public final class IntrospectionHelper { * in detail for reasons of source code readability. */ private abstract static class AttributeSetter { - private Method method; // the method called to set the attribute - private Class type; - protected AttributeSetter(Method m, Class type) { + private final Method method; // the method called to set the attribute + private final Class type; + protected AttributeSetter(final Method m, final Class type) { method = m; this.type = type; } - void setObject(Project p, Object parent, Object value) + void setObject(final Project p, final Object parent, final Object value) throws InvocationTargetException, IllegalAccessException, BuildException { if (type != null) { Class useType = type; @@ -1499,7 +1517,7 @@ public final class IntrospectionHelper { /** * Clears the static cache of on build finished. */ - public synchronized static void clearCache() { + public static synchronized void clearCache() { HELPERS.clear(); } @@ -1513,15 +1531,15 @@ public final class IntrospectionHelper { * @throws BuildException */ private NestedCreator createAddTypeCreator( - Project project, Object parent, String elementName) throws BuildException { + final Project project, final Object parent, final String elementName) throws BuildException { if (addTypeMethods.size() == 0) { return null; } - ComponentHelper helper = ComponentHelper.getComponentHelper(project); + final ComponentHelper helper = ComponentHelper.getComponentHelper(project); - MethodAndObject restricted = createRestricted( + final MethodAndObject restricted = createRestricted( helper, elementName, addTypeMethods); - MethodAndObject topLevel = createTopLevel( + final MethodAndObject topLevel = createTopLevel( helper, elementName, addTypeMethods); if (restricted == null && topLevel == null) { @@ -1534,7 +1552,7 @@ public final class IntrospectionHelper { + elementName); } - MethodAndObject methodAndObject + final MethodAndObject methodAndObject = restricted != null ? restricted : topLevel; Object rObject = methodAndObject.object; @@ -1546,7 +1564,8 @@ public final class IntrospectionHelper { final Object realObject = rObject; return new NestedCreator(methodAndObject.method) { - Object create(Project project, Object parent, Object ignore) + @Override + Object create(final Project project, final Object parent, final Object ignore) throws InvocationTargetException, IllegalAccessException { if (!getMethod().getName().endsWith("Configured")) { getMethod().invoke(parent, new Object[] {realObject}); @@ -1554,11 +1573,13 @@ public final class IntrospectionHelper { return nestedObject; } - Object getRealObject() { + @Override + Object getRealObject() { return realObject; } - void store(Object parent, Object child) throws InvocationTargetException, + @Override + void store(final Object parent, final Object child) throws InvocationTargetException, IllegalAccessException, InstantiationException { if (getMethod().getName().endsWith("Configured")) { getMethod().invoke(parent, new Object[] {realObject}); @@ -1574,11 +1595,11 @@ public final class IntrospectionHelper { * If both add and addConfigured are present, the addConfigured will take priority. * @param method the Method to insert. */ - private void insertAddTypeMethod(Method method) { - Class argClass = method.getParameterTypes()[0]; + private void insertAddTypeMethod(final Method method) { + final Class argClass = method.getParameterTypes()[0]; final int size = addTypeMethods.size(); for (int c = 0; c < size; ++c) { - Method current = (Method) addTypeMethods.get(c); + final Method current = addTypeMethods.get(c); if (current.getParameterTypes()[0].equals(argClass)) { if (method.getName().equals("addConfigured")) { // add configured replaces the add method @@ -1601,7 +1622,7 @@ public final class IntrospectionHelper { * @param methods the List of methods to search. * @return a matching Method; null if none found. */ - private Method findMatchingMethod(Class paramClass, List methods) { + private Method findMatchingMethod(final Class paramClass, final List methods) { if (paramClass == null) { return null; } @@ -1610,8 +1631,8 @@ public final class IntrospectionHelper { final int size = methods.size(); for (int i = 0; i < size; ++i) { - Method method = methods.get(i); - Class methodClass = method.getParameterTypes()[0]; + final Method method = methods.get(i); + final Class methodClass = method.getParameterTypes()[0]; if (methodClass.isAssignableFrom(paramClass)) { if (matchedClass == null) { matchedClass = methodClass; @@ -1629,15 +1650,15 @@ public final class IntrospectionHelper { if (text.length() <= MAX_REPORT_NESTED_TEXT) { return text; } - int ends = (MAX_REPORT_NESTED_TEXT - ELLIPSIS.length()) / 2; + final int ends = (MAX_REPORT_NESTED_TEXT - ELLIPSIS.length()) / 2; return new StringBuffer(text).replace(ends, text.length() - ends, ELLIPSIS).toString(); } private static class MethodAndObject { - private Method method; - private Object object; - public MethodAndObject(Method method, Object object) { + private final Method method; + private final Object object; + public MethodAndObject(final Method method, final Object object) { this.method = method; this.object = object; } @@ -1647,23 +1668,23 @@ public final class IntrospectionHelper { * */ private AntTypeDefinition findRestrictedDefinition( - ComponentHelper helper, String componentName, List methods) { + final ComponentHelper helper, final String componentName, final List methods) { AntTypeDefinition definition = null; Class matchedDefinitionClass = null; - List definitions = helper.getRestrictedDefinitions(componentName); + final List definitions = helper.getRestrictedDefinitions(componentName); if (definitions == null) { return null; } synchronized (definitions) { final int size = definitions.size(); for (int i = 0; i < size; ++i) { - AntTypeDefinition d = definitions.get(i); - Class exposedClass = d.getExposedClass(helper.getProject()); + final AntTypeDefinition d = definitions.get(i); + final Class exposedClass = d.getExposedClass(helper.getProject()); if (exposedClass == null) { continue; } - Method method = findMatchingMethod(exposedClass, methods); + final Method method = findMatchingMethod(exposedClass, methods); if (method == null) { continue; } @@ -1681,25 +1702,25 @@ public final class IntrospectionHelper { } private MethodAndObject createRestricted( - ComponentHelper helper, String elementName, List addTypeMethods) { + final ComponentHelper helper, final String elementName, final List addTypeMethods) { - Project project = helper.getProject(); + final Project project = helper.getProject(); - AntTypeDefinition restrictedDefinition = + final AntTypeDefinition restrictedDefinition = findRestrictedDefinition(helper, elementName, addTypeMethods); if (restrictedDefinition == null) { return null; } - Method addMethod = findMatchingMethod( + final Method addMethod = findMatchingMethod( restrictedDefinition.getExposedClass(project), addTypeMethods); if (addMethod == null) { throw new BuildException( "Ant Internal Error - contract mismatch for " + elementName); } - Object addedObject = restrictedDefinition.create(project); + final Object addedObject = restrictedDefinition.create(project); if (addedObject == null) { throw new BuildException( "Failed to create object " + elementName @@ -1709,16 +1730,16 @@ public final class IntrospectionHelper { } private MethodAndObject createTopLevel( - ComponentHelper helper, String elementName, List methods) { - Class clazz = helper.getComponentClass(elementName); + final ComponentHelper helper, final String elementName, final List methods) { + final Class clazz = helper.getComponentClass(elementName); if (clazz == null) { return null; } - Method addMethod = findMatchingMethod(clazz, addTypeMethods); + final Method addMethod = findMatchingMethod(clazz, addTypeMethods); if (addMethod == null) { return null; } - Object addedObject = helper.createComponent(elementName); + final Object addedObject = helper.createComponent(elementName); return new MethodAndObject(addMethod, addedObject); } diff --git a/src/main/org/apache/tools/ant/Main.java b/src/main/org/apache/tools/ant/Main.java index c2ca785ac..6cf4718a9 100644 --- a/src/main/org/apache/tools/ant/Main.java +++ b/src/main/org/apache/tools/ant/Main.java @@ -86,16 +86,16 @@ public class Main implements AntMain { private static PrintStream err = System.err; /** The build targets. */ - private Vector targets = new Vector(); + private final Vector targets = new Vector(); /** Set of properties that can be used by tasks. */ - private Properties definedProps = new Properties(); + private final Properties definedProps = new Properties(); /** Names of classes to add as listeners to project. */ - private Vector listeners = new Vector(1); + private final Vector listeners = new Vector(1); /** File names of property files to load on startup. */ - private Vector propertyFiles = new Vector(1); + private final Vector propertyFiles = new Vector(1); /** Indicates whether this build is to support interactive input */ private boolean allowInput = true; @@ -154,13 +154,15 @@ public class Main implements AntMain { */ private boolean proxy = false; - private Map, List> extraArguments = new HashMap, List>(); + private final Map, List> extraArguments = new HashMap, List>(); - private static final GetProperty NOPROPERTIES = new GetProperty(){ - public Object getProperty(String aName) { + private static final GetProperty NOPROPERTIES = new GetProperty() { + @Override + public Object getProperty(final String aName) { // No existing property takes precedence return null; - }}; + } + }; @@ -172,8 +174,8 @@ public class Main implements AntMain { * @param t Throwable to print the message of. * Must not be null. */ - private static void printMessage(Throwable t) { - String message = t.getMessage(); + private static void printMessage(final Throwable t) { + final String message = t.getMessage(); if (message != null) { System.err.println(message); } @@ -191,9 +193,9 @@ public class Main implements AntMain { * @param coreLoader Classloader used for core classes. May be * null in which case the system classloader is used. */ - public static void start(String[] args, Properties additionalUserProperties, - ClassLoader coreLoader) { - Main m = new Main(); + public static void start(final String[] args, final Properties additionalUserProperties, + final ClassLoader coreLoader) { + final Main m = new Main(); m.startAnt(args, additionalUserProperties, coreLoader); } @@ -206,12 +208,13 @@ public class Main implements AntMain { * * @since Ant 1.6 */ - public void startAnt(String[] args, Properties additionalUserProperties, - ClassLoader coreLoader) { + @Override + public void startAnt(final String[] args, final Properties additionalUserProperties, + final ClassLoader coreLoader) { try { processArgs(args); - } catch (Throwable exc) { + } catch (final Throwable exc) { handleLogfile(); printMessage(exc); exit(1); @@ -219,10 +222,10 @@ public class Main implements AntMain { } if (additionalUserProperties != null) { - for (Enumeration e = additionalUserProperties.keys(); + for (final Enumeration e = additionalUserProperties.keys(); e.hasMoreElements();) { - String key = (String) e.nextElement(); - String property = additionalUserProperties.getProperty(key); + final String key = (String) e.nextElement(); + final String property = additionalUserProperties.getProperty(key); definedProps.put(key, property); } } @@ -233,17 +236,17 @@ public class Main implements AntMain { try { runBuild(coreLoader); exitCode = 0; - } catch (ExitStatusException ese) { + } catch (final ExitStatusException ese) { exitCode = ese.getStatus(); if (exitCode != 0) { throw ese; } } - } catch (BuildException be) { + } catch (final BuildException be) { if (err != System.err) { printMessage(be); } - } catch (Throwable exc) { + } catch (final Throwable exc) { exc.printStackTrace(); printMessage(exc); } finally { @@ -258,7 +261,7 @@ public class Main implements AntMain { * However, it is possible to do something else. * @param exitCode code to exit with */ - protected void exit(int exitCode) { + protected void exit(final int exitCode) { System.exit(exitCode); } @@ -281,7 +284,7 @@ public class Main implements AntMain { * * @param args Command line arguments. Must not be null. */ - public static void main(String[] args) { + public static void main(final String[] args) { start(args, null, null); } @@ -303,7 +306,8 @@ public class Main implements AntMain { * * @deprecated since 1.6.x */ - protected Main(String[] args) throws BuildException { + @Deprecated + protected Main(final String[] args) throws BuildException { processArgs(args); } @@ -316,7 +320,7 @@ public class Main implements AntMain { * * @since Ant 1.6 */ - private void processArgs(String[] args) { + private void processArgs(final String[] args) { String searchForThis = null; boolean searchForFile = false; PrintStream logTo = null; @@ -327,10 +331,10 @@ public class Main implements AntMain { boolean justPrintVersion = false; boolean justPrintDiagnostics = false; - ArgumentProcessorRegistry processorRegistry = ArgumentProcessorRegistry.getInstance(); - + final ArgumentProcessorRegistry processorRegistry = ArgumentProcessorRegistry.getInstance(); + for (int i = 0; i < args.length; i++) { - String arg = args[i]; + final String arg = args[i]; if (arg.equals("-help") || arg.equals("-h")) { justPrintUsage = true; @@ -350,17 +354,17 @@ public class Main implements AntMain { allowInput = false; } else if (arg.equals("-logfile") || arg.equals("-l")) { try { - File logFile = new File(args[i + 1]); + final File logFile = new File(args[i + 1]); i++; logTo = new PrintStream(new FileOutputStream(logFile)); isLogFileUsed = true; - } catch (IOException ioe) { - String msg = "Cannot write on the specified log file. " + } catch (final IOException ioe) { + final String msg = "Cannot write on the specified log file. " + "Make sure the path exists and you have write " + "permissions."; throw new BuildException(msg); - } catch (ArrayIndexOutOfBoundsException aioobe) { - String msg = "You must specify a log file when " + } catch (final ArrayIndexOutOfBoundsException aioobe) { + final String msg = "You must specify a log file when " + "using the -log argument"; throw new BuildException(msg); } @@ -396,7 +400,7 @@ public class Main implements AntMain { //catch script/ant mismatch with a meaningful message //we could ignore it, but there are likely to be other //version problems, so we stamp down on the configuration now - String msg = "Ant's Main method is being handed " + final String msg = "Ant's Main method is being handed " + "an option " + arg + " that is only for the launcher class." + "\nThis can be caused by a version mismatch between " + "the ant script/.bat file and Ant itself."; @@ -405,8 +409,8 @@ public class Main implements AntMain { proxy = true; } else if (arg.startsWith("-")) { boolean processed = false; - for (ArgumentProcessor processor : processorRegistry.getProcessors()) { - int newI = processor.readArguments(args, i); + for (final ArgumentProcessor processor : processorRegistry.getProcessors()) { + final int newI = processor.readArguments(args, i); if (newI != -1) { List extraArgs = extraArguments.get(processor.getClass()); if (extraArgs == null) { @@ -422,7 +426,7 @@ public class Main implements AntMain { } if (!processed) { // we don't have any more args to recognize! - String msg = "Unknown argument: " + arg; + final String msg = "Unknown argument: " + arg; System.err.println(msg); printUsage(); throw new BuildException(""); @@ -458,9 +462,9 @@ public class Main implements AntMain { } } else { // no search file specified: so search an existing default file - Iterator it = ProjectHelperRepository.getInstance().getHelpers(); + final Iterator it = ProjectHelperRepository.getInstance().getHelpers(); do { - ProjectHelper helper = it.next(); + final ProjectHelper helper = it.next(); searchForThis = helper.getDefaultBuildFile(); if (msgOutputLevel >= Project.MSG_VERBOSE) { System.out.println("Searching the default build file: " + searchForThis); @@ -473,9 +477,9 @@ public class Main implements AntMain { } } else { // no build file specified: so search an existing default file - Iterator it = ProjectHelperRepository.getInstance().getHelpers(); + final Iterator it = ProjectHelperRepository.getInstance().getHelpers(); do { - ProjectHelper helper = it.next(); + final ProjectHelper helper = it.next(); buildFile = new File(helper.getDefaultBuildFile()); if (msgOutputLevel >= Project.MSG_VERBOSE) { System.out.println("Trying the default build file: " + buildFile); @@ -491,7 +495,7 @@ public class Main implements AntMain { } if (buildFile.isDirectory()) { - File whatYouMeant = new File(buildFile, "build.xml"); + final File whatYouMeant = new File(buildFile, "build.xml"); if (whatYouMeant.isFile()) { buildFile = whatYouMeant; } else { @@ -525,11 +529,11 @@ public class Main implements AntMain { // -------------------------------------------------------- /** Handle the -buildfile, -file, -f argument */ - private int handleArgBuildFile(String[] args, int pos) { + private int handleArgBuildFile(final String[] args, int pos) { try { buildFile = new File( args[++pos].replace('/', File.separatorChar)); - } catch (ArrayIndexOutOfBoundsException aioobe) { + } catch (final ArrayIndexOutOfBoundsException aioobe) { throw new BuildException( "You must specify a buildfile when using the -buildfile argument"); } @@ -537,12 +541,12 @@ public class Main implements AntMain { } /** Handle -listener argument */ - private int handleArgListener(String[] args, int pos) { + private int handleArgListener(final String[] args, int pos) { try { listeners.addElement(args[pos + 1]); pos++; - } catch (ArrayIndexOutOfBoundsException aioobe) { - String msg = "You must specify a classname when " + } catch (final ArrayIndexOutOfBoundsException aioobe) { + final String msg = "You must specify a classname when " + "using the -listener argument"; throw new BuildException(msg); } @@ -550,7 +554,7 @@ public class Main implements AntMain { } /** Handler -D argument */ - private int handleArgDefine(String[] args, int argPos) { + private int handleArgDefine(final String[] args, int argPos) { /* Interestingly enough, we get to here when a user * uses -Dname=value. However, in some cases, the OS * goes ahead and parses this out to args @@ -561,10 +565,10 @@ public class Main implements AntMain { * I don't know how to predict when the JDK is going * to help or not, so we simply look for the equals sign. */ - String arg = args[argPos]; + final String arg = args[argPos]; String name = arg.substring(2, arg.length()); String value = null; - int posEq = name.indexOf("="); + final int posEq = name.indexOf("="); if (posEq > 0) { value = name.substring(posEq + 1); name = name.substring(0, posEq); @@ -579,14 +583,14 @@ public class Main implements AntMain { } /** Handle the -logger argument. */ - private int handleArgLogger(String[] args, int pos) { + private int handleArgLogger(final String[] args, int pos) { if (loggerClassname != null) { throw new BuildException( "Only one logger class may be specified."); } try { loggerClassname = args[++pos]; - } catch (ArrayIndexOutOfBoundsException aioobe) { + } catch (final ArrayIndexOutOfBoundsException aioobe) { throw new BuildException( "You must specify a classname when using the -logger argument"); } @@ -594,14 +598,14 @@ public class Main implements AntMain { } /** Handle the -inputhandler argument. */ - private int handleArgInputHandler(String[] args, int pos) { + private int handleArgInputHandler(final String[] args, int pos) { if (inputHandlerClassname != null) { throw new BuildException("Only one input handler class may " + "be specified."); } try { inputHandlerClassname = args[++pos]; - } catch (ArrayIndexOutOfBoundsException aioobe) { + } catch (final ArrayIndexOutOfBoundsException aioobe) { throw new BuildException("You must specify a classname when" + " using the -inputhandler" + " argument"); @@ -610,11 +614,11 @@ public class Main implements AntMain { } /** Handle the -propertyfile argument. */ - private int handleArgPropertyFile(String[] args, int pos) { + private int handleArgPropertyFile(final String[] args, int pos) { try { propertyFiles.addElement(args[++pos]); - } catch (ArrayIndexOutOfBoundsException aioobe) { - String msg = "You must specify a property filename when " + } catch (final ArrayIndexOutOfBoundsException aioobe) { + final String msg = "You must specify a property filename when " + "using the -propertyfile argument"; throw new BuildException(msg); } @@ -622,14 +626,14 @@ public class Main implements AntMain { } /** Handle the -nice argument. */ - private int handleArgNice(String[] args, int pos) { + private int handleArgNice(final String[] args, int pos) { try { threadPriority = Integer.decode(args[++pos]); - } catch (ArrayIndexOutOfBoundsException aioobe) { + } catch (final ArrayIndexOutOfBoundsException aioobe) { throw new BuildException( "You must supply a niceness value (1-10)" + " after the -nice option"); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new BuildException("Unrecognized niceness value: " + args[pos]); } @@ -648,13 +652,13 @@ public class Main implements AntMain { /** Load the property files specified by -propertyfile */ private void loadPropertyFiles() { - for (String filename : propertyFiles) { - Properties props = new Properties(); + for (final String filename : propertyFiles) { + final Properties props = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(filename); props.load(fis); - } catch (IOException e) { + } catch (final IOException e) { System.out.println("Could not load property file " + filename + ": " + e.getMessage()); } finally { @@ -662,9 +666,9 @@ public class Main implements AntMain { } // ensure that -D properties take precedence - Enumeration propertyNames = props.propertyNames(); + final Enumeration propertyNames = props.propertyNames(); while (propertyNames.hasMoreElements()) { - String name = (String) propertyNames.nextElement(); + final String name = (String) propertyNames.nextElement(); if (definedProps.getProperty(name) == null) { definedProps.put(name, props.getProperty(name)); } @@ -681,8 +685,9 @@ public class Main implements AntMain { * @param file File to find parent of. Must not be null. * @return Parent file or null if none */ - private File getParentFile(File file) { - File parent = file.getParentFile(); + @Deprecated + private File getParentFile(final File file) { + final File parent = file.getParentFile(); if (parent != null && msgOutputLevel >= Project.MSG_VERBOSE) { System.out.println("Searching in " + parent.getAbsolutePath()); @@ -706,7 +711,7 @@ public class Main implements AntMain { * * @return A handle to the build file if one is found, null if not */ - private File findBuildFile(String start, String suffix) { + private File findBuildFile(final String start, final String suffix) { if (msgOutputLevel >= Project.MSG_INFO) { System.out.println("Searching for " + suffix + " ..."); } @@ -743,16 +748,16 @@ public class Main implements AntMain { * * @exception BuildException if the build fails */ - private void runBuild(ClassLoader coreLoader) throws BuildException { + private void runBuild(final ClassLoader coreLoader) throws BuildException { if (!readyToRun) { return; } - ArgumentProcessorRegistry processorRegistry = ArgumentProcessorRegistry.getInstance(); + final ArgumentProcessorRegistry processorRegistry = ArgumentProcessorRegistry.getInstance(); - for (ArgumentProcessor processor : processorRegistry.getProcessors()) { - List extraArgs = extraArguments.get(processor.getClass()); + for (final ArgumentProcessor processor : processorRegistry.getProcessors()) { + final List extraArgs = extraArguments.get(processor.getClass()); if (extraArgs != null) { if (processor.handleArg(extraArgs)) { return; @@ -769,9 +774,9 @@ public class Main implements AntMain { addBuildListeners(project); addInputHandler(project); - PrintStream savedErr = System.err; - PrintStream savedOut = System.out; - InputStream savedIn = System.in; + final PrintStream savedErr = System.err; + final PrintStream savedOut = System.out; + final InputStream savedIn = System.in; // use a system manager that prevents from System.exit() SecurityManager oldsm = null; @@ -800,7 +805,7 @@ public class Main implements AntMain { project.log("Setting Ant's thread priority to " + threadPriority, Project.MSG_VERBOSE); Thread.currentThread().setPriority(threadPriority.intValue()); - } catch (SecurityException swallowed) { + } catch (final SecurityException swallowed) { //we cannot set the priority here. project.log("A security manager refused to set the -nice value"); } @@ -811,12 +816,12 @@ public class Main implements AntMain { project.setKeepGoingMode(keepGoingMode); if (proxy) { //proxy setup if enabled - ProxySetup proxySetup = new ProxySetup(project); + final ProxySetup proxySetup = new ProxySetup(project); proxySetup.enableProxies(); } - for (ArgumentProcessor processor : processorRegistry.getProcessors()) { - List extraArgs = extraArguments.get(processor.getClass()); + for (final ArgumentProcessor processor : processorRegistry.getProcessors()) { + final List extraArgs = extraArguments.get(processor.getClass()); if (extraArgs != null) { processor.prepareConfigure(project, extraArgs); } @@ -824,8 +829,8 @@ public class Main implements AntMain { ProjectHelper.configureProject(project, buildFile); - for (ArgumentProcessor processor : processorRegistry.getProcessors()) { - List extraArgs = extraArguments.get(processor.getClass()); + for (final ArgumentProcessor processor : processorRegistry.getProcessors()) { + final List extraArgs = extraArguments.get(processor.getClass()); if (extraArgs != null) { if (processor.handleArg(project, extraArgs)) { return; @@ -859,17 +864,17 @@ public class Main implements AntMain { System.setErr(savedErr); System.setIn(savedIn); } - } catch (RuntimeException exc) { + } catch (final RuntimeException exc) { error = exc; throw exc; - } catch (Error e) { + } catch (final Error e) { error = e; throw e; } finally { if (!projectHelp) { try { project.fireBuildFinished(error); - } catch (Throwable t) { + } catch (final Throwable t) { // yes, I know it is bad style to catch Throwable, // but if we don't, we lose valuable information System.err.println("Caught an exception while logging the" @@ -893,20 +898,22 @@ public class Main implements AntMain { project.init(); // resolve properties - PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(project); + final PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(project); @SuppressWarnings({ "rawtypes", "unchecked" }) + final Map raw = new HashMap(definedProps); @SuppressWarnings("unchecked") + final Map props = raw; - ResolvePropertyMap resolver = new ResolvePropertyMap(project, + final ResolvePropertyMap resolver = new ResolvePropertyMap(project, NOPROPERTIES, propertyHelper.getExpanders()); resolver.resolveAllProperties(props, null, false); // set user-define properties - for (Entry ent : props.entrySet()) { - String arg = ent.getKey(); - Object value = ent.getValue(); + for (final Entry ent : props.entrySet()) { + final String arg = ent.getKey(); + final Object value = ent.getValue(); project.setUserProperty(arg, String.valueOf(value)); } @@ -923,15 +930,15 @@ public class Main implements AntMain { * @param project The project to add listeners to. * Must not be null. */ - protected void addBuildListeners(Project project) { + protected void addBuildListeners(final Project project) { // Add the default listener project.addBuildListener(createLogger()); final int count = listeners.size(); for (int i = 0; i < count; i++) { - String className = (String) listeners.elementAt(i); - BuildListener listener = + final String className = listeners.elementAt(i); + final BuildListener listener = (BuildListener) ClasspathUtils.newInstance(className, Main.class.getClassLoader(), BuildListener.class); project.setProjectReference(listener); @@ -948,7 +955,7 @@ public class Main implements AntMain { * @exception BuildException if a specified InputHandler * implementation could not be loaded. */ - private void addInputHandler(Project project) throws BuildException { + private void addInputHandler(final Project project) throws BuildException { InputHandler handler = null; if (inputHandlerClassname == null) { handler = new DefaultInputHandler(); @@ -982,7 +989,7 @@ public class Main implements AntMain { logger = (BuildLogger) ClasspathUtils.newInstance( loggerClassname, Main.class.getClassLoader(), BuildLogger.class); - } catch (BuildException e) { + } catch (final BuildException e) { System.err.println("The specified logger class " + loggerClassname + " could not be used because " + e.getMessage()); @@ -1040,7 +1047,7 @@ public class Main implements AntMain { System.out.println(" -noclasspath Run ant without using CLASSPATH"); System.out.println(" -autoproxy Java1.5+: use the OS proxy settings"); System.out.println(" -main override Ant's normal entry point"); - for (ArgumentProcessor processor : ArgumentProcessorRegistry.getInstance().getProcessors()) { + for (final ArgumentProcessor processor : ArgumentProcessorRegistry.getInstance().getProcessors()) { processor.printUsage(System.out); } } @@ -1050,7 +1057,7 @@ public class Main implements AntMain { * * @exception BuildException if the version information is unavailable */ - private static void printVersion(int logLevel) throws BuildException { + private static void printVersion(final int logLevel) throws BuildException { System.out.println(getAntVersion()); } @@ -1063,7 +1070,7 @@ public class Main implements AntMain { * Cache of the short Ant version information when it has been loaded. */ private static String shortAntVersion = null; - + /** * Returns the Ant version information, if available. Once the information * has been loaded once, it's cached and returned from the cache on future @@ -1077,37 +1084,37 @@ public class Main implements AntMain { public static synchronized String getAntVersion() throws BuildException { if (antVersion == null) { try { - Properties props = new Properties(); - InputStream in = + final Properties props = new Properties(); + final InputStream in = Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt"); props.load(in); in.close(); shortAntVersion = props.getProperty("VERSION"); - StringBuffer msg = new StringBuffer(); + final StringBuffer msg = new StringBuffer(); msg.append("Apache Ant(TM) version "); msg.append(shortAntVersion); msg.append(" compiled on "); msg.append(props.getProperty("DATE")); antVersion = msg.toString(); - } catch (IOException ioe) { + } catch (final IOException ioe) { throw new BuildException("Could not load the version information:" + ioe.getMessage()); - } catch (NullPointerException npe) { + } catch (final NullPointerException npe) { throw new BuildException("Could not load the version information."); } } return antVersion; } - + /** * Returns the short Ant version information, if available. Once the information * has been loaded once, it's cached and returned from the cache on future * calls. - * + * * @return the short Ant version information as a String * (always non-null) - * + * * @throws BuildException BuildException if the version information is unavailable * @since Ant 1.9.3 */ @@ -1125,7 +1132,7 @@ public class Main implements AntMain { * @param project The project to display a description of. * Must not be null. */ - private static void printDescription(Project project) { + private static void printDescription(final Project project) { if (project.getDescription() != null) { project.log(project.getDescription()); } @@ -1139,12 +1146,12 @@ public class Main implements AntMain { * @param targets the targets to filter. * @return the filtered targets. */ - private static Map removeDuplicateTargets(Map targets) { - Map locationMap = new HashMap(); - for (Entry entry : targets.entrySet()) { - String name = entry.getKey(); - Target target = entry.getValue(); - Target otherTarget = locationMap.get(target.getLocation()); + private static Map removeDuplicateTargets(final Map targets) { + final Map locationMap = new HashMap(); + for (final Entry entry : targets.entrySet()) { + final String name = entry.getKey(); + final Target target = entry.getValue(); + final Target otherTarget = locationMap.get(target.getLocation()); // Place this entry in the location map if // a) location is not in the map // b) location is in map, but its name is longer @@ -1155,8 +1162,8 @@ public class Main implements AntMain { target.getLocation(), target); // Smallest name wins } } - Map ret = new HashMap(); - for (Target target : locationMap.values()) { + final Map ret = new HashMap(); + for (final Target target : locationMap.values()) { ret.put(target.getName(), target); } return ret; @@ -1171,34 +1178,34 @@ public class Main implements AntMain { * @param printSubTargets Whether or not subtarget names should also be * printed. */ - private static void printTargets(Project project, boolean printSubTargets, - boolean printDependencies) { + private static void printTargets(final Project project, boolean printSubTargets, + final boolean printDependencies) { // find the target with the longest name int maxLength = 0; - Map ptargets = removeDuplicateTargets(project.getTargets()); + final Map ptargets = removeDuplicateTargets(project.getTargets()); // split the targets in top-level and sub-targets depending // on the presence of a description - Vector topNames = new Vector(); - Vector topDescriptions = new Vector(); - Vector> topDependencies = new Vector>(); - Vector subNames = new Vector(); - Vector> subDependencies = new Vector>(); - - for (Target currentTarget : ptargets.values()) { - String targetName = currentTarget.getName(); + final Vector topNames = new Vector(); + final Vector topDescriptions = new Vector(); + final Vector> topDependencies = new Vector>(); + final Vector subNames = new Vector(); + final Vector> subDependencies = new Vector>(); + + for (final Target currentTarget : ptargets.values()) { + final String targetName = currentTarget.getName(); if (targetName.equals("")) { continue; } - String targetDescription = currentTarget.getDescription(); + final String targetDescription = currentTarget.getDescription(); // maintain a sorted list of targets if (targetDescription == null) { - int pos = findTargetPosition(subNames, targetName); + final int pos = findTargetPosition(subNames, targetName); subNames.insertElementAt(targetName, pos); if (printDependencies) { subDependencies.insertElementAt(currentTarget.getDependencies(), pos); } } else { - int pos = findTargetPosition(topNames, targetName); + final int pos = findTargetPosition(topNames, targetName); topNames.insertElementAt(targetName, pos); topDescriptions.insertElementAt(targetDescription, pos); if (targetName.length() > maxLength) { @@ -1221,7 +1228,7 @@ public class Main implements AntMain { printTargets(project, subNames, null, subDependencies, "Other targets:", 0); } - String defaultTarget = project.getDefaultTarget(); + final String defaultTarget = project.getDefaultTarget(); if (defaultTarget != null && !"".equals(defaultTarget)) { // shouldn't need to check but... project.log("Default target: " + defaultTarget); @@ -1238,7 +1245,7 @@ public class Main implements AntMain { * * @return the correct place in the list for the given name */ - private static int findTargetPosition(Vector names, String name) { + private static int findTargetPosition(final Vector names, final String name) { final int size = names.size(); int res = size; for (int i = 0; i < size && res == size; i++) { @@ -1272,18 +1279,18 @@ public class Main implements AntMain { * position so they line up (so long as the names really * are shorter than this). */ - private static void printTargets(Project project, Vector names, - Vector descriptions, Vector> dependencies, - String heading, - int maxlen) { + private static void printTargets(final Project project, final Vector names, + final Vector descriptions, final Vector> dependencies, + final String heading, + final int maxlen) { // now, start printing the targets and their descriptions - String lSep = System.getProperty("line.separator"); + final String lSep = System.getProperty("line.separator"); // got a bit annoyed that I couldn't find a pad function String spaces = " "; while (spaces.length() <= maxlen) { spaces += spaces; } - StringBuilder msg = new StringBuilder(); + final StringBuilder msg = new StringBuilder(); msg.append(heading + lSep + lSep); final int size = names.size(); for (int i = 0; i < size; i++) { @@ -1296,7 +1303,7 @@ public class Main implements AntMain { } msg.append(lSep); if (!dependencies.isEmpty()) { - Enumeration deps = dependencies.elementAt(i); + final Enumeration deps = dependencies.elementAt(i); if (deps.hasMoreElements()) { msg.append(" depends on: "); while (deps.hasMoreElements()) { diff --git a/src/main/org/apache/tools/ant/Project.java b/src/main/org/apache/tools/ant/Project.java index 52a4da9ad..02b23c95d 100644 --- a/src/main/org/apache/tools/ant/Project.java +++ b/src/main/org/apache/tools/ant/Project.java @@ -91,35 +91,40 @@ public class Project implements ResourceFactory { * @deprecated since 1.5.x. * Use {@link JavaEnvUtils#JAVA_1_0} instead. */ - public static final String JAVA_1_0 = JavaEnvUtils.JAVA_1_0; + @Deprecated + public static final String JAVA_1_0 = JavaEnvUtils.JAVA_1_0; /** * Version constant for Java 1.1 . * * @deprecated since 1.5.x. * Use {@link JavaEnvUtils#JAVA_1_1} instead. */ - public static final String JAVA_1_1 = JavaEnvUtils.JAVA_1_1; + @Deprecated + public static final String JAVA_1_1 = JavaEnvUtils.JAVA_1_1; /** * Version constant for Java 1.2 . * * @deprecated since 1.5.x. * Use {@link JavaEnvUtils#JAVA_1_2} instead. */ - public static final String JAVA_1_2 = JavaEnvUtils.JAVA_1_2; + @Deprecated + public static final String JAVA_1_2 = JavaEnvUtils.JAVA_1_2; /** * Version constant for Java 1.3 . * * @deprecated since 1.5.x. * Use {@link JavaEnvUtils#JAVA_1_3} instead. */ - public static final String JAVA_1_3 = JavaEnvUtils.JAVA_1_3; + @Deprecated + public static final String JAVA_1_3 = JavaEnvUtils.JAVA_1_3; /** * Version constant for Java 1.4 . * * @deprecated since 1.5.x. * Use {@link JavaEnvUtils#JAVA_1_4} instead. */ - public static final String JAVA_1_4 = JavaEnvUtils.JAVA_1_4; + @Deprecated + public static final String JAVA_1_4 = JavaEnvUtils.JAVA_1_4; /** Default filter start token. */ public static final String TOKEN_START = FilterSet.DEFAULT_TOKEN_START; @@ -136,18 +141,18 @@ public class Project implements ResourceFactory { /** Map of references within the project (paths etc) (String to Object). */ - private Hashtable references = new AntRefTable(); + private final Hashtable references = new AntRefTable(); /** Map of id references - used for indicating broken build files */ - private HashMap idReferences = new HashMap(); + private final HashMap idReferences = new HashMap(); /** Name of the project's default target. */ private String defaultTarget; /** Map from target names to targets (String to Target). */ - private Hashtable targets = new Hashtable(); + private final Hashtable targets = new Hashtable(); /** Set of global filters. */ - private FilterSet globalFilterSet = new FilterSet(); + private final FilterSet globalFilterSet = new FilterSet(); { // Initialize the globalFileSet's project globalFilterSet.setProject(this); @@ -158,7 +163,7 @@ public class Project implements ResourceFactory { * contains one FilterSet, but the wrapper is needed in order to * make it easier to use the FileUtils interface. */ - private FilterSetCollection globalFilters + private final FilterSetCollection globalFilters = new FilterSetCollection(globalFilterSet); /** Project base directory. */ @@ -173,7 +178,8 @@ public class Project implements ResourceFactory { /** for each thread, record whether it is currently executing messageLogged */ private final ThreadLocal isLoggingMessage = new ThreadLocal() { - protected Boolean initialValue() { + @Override + protected Boolean initialValue() { return Boolean.FALSE; } }; @@ -212,7 +218,7 @@ public class Project implements ResourceFactory { * * @param handler the InputHandler instance to use for gathering input. */ - public void setInputHandler(InputHandler handler) { + public void setInputHandler(final InputHandler handler) { inputHandler = handler; } @@ -225,7 +231,7 @@ public class Project implements ResourceFactory { * is requested. * @since Ant 1.6 */ - public void setDefaultInputStream(InputStream defaultInputStream) { + public void setDefaultInputStream(final InputStream defaultInputStream) { this.defaultInputStream = defaultInputStream; } @@ -266,8 +272,8 @@ public class Project implements ResourceFactory { public Project createSubProject() { Project subProject = null; try { - subProject = (Project) (getClass().newInstance()); - } catch (Exception e) { + subProject = (getClass().newInstance()); + } catch (final Exception e) { subProject = new Project(); } initSubProject(subProject); @@ -278,7 +284,7 @@ public class Project implements ResourceFactory { * Initialize a subproject. * @param subProject the subproject to initialize. */ - public void initSubProject(Project subProject) { + public void initSubProject(final Project subProject) { ComponentHelper.getComponentHelper(subProject) .initSubProject(ComponentHelper.getComponentHelper(this)); subProject.setDefaultInputStream(getDefaultInputStream()); @@ -319,7 +325,7 @@ public class Project implements ResourceFactory { * to the result */ private void setAntLib() { - File antlib = org.apache.tools.ant.launch.Locator.getClassSource( + final File antlib = org.apache.tools.ant.launch.Locator.getClassSource( Project.class); if (antlib != null) { setPropertyInternal(MagicNames.ANT_LIB, antlib.getAbsolutePath()); @@ -333,7 +339,7 @@ public class Project implements ResourceFactory { * * @return an appropriate classloader. */ - public AntClassLoader createClassLoader(Path path) { + public AntClassLoader createClassLoader(final Path path) { return AntClassLoader .newAntClassLoader(getClass().getClassLoader(), this, path, true); } @@ -348,7 +354,7 @@ public class Project implements ResourceFactory { * @return an appropriate classloader. */ public AntClassLoader createClassLoader( - ClassLoader parent, Path path) { + final ClassLoader parent, final Path path) { return AntClassLoader.newAntClassLoader(parent, this, path, true); } @@ -359,7 +365,7 @@ public class Project implements ResourceFactory { * @param coreLoader The classloader to use for the project. * May be null. */ - public void setCoreLoader(ClassLoader coreLoader) { + public void setCoreLoader(final ClassLoader coreLoader) { this.coreLoader = coreLoader; } @@ -382,7 +388,7 @@ public class Project implements ResourceFactory { * @param listener The listener to add to the list. * Must not be null. */ - public void addBuildListener(BuildListener listener) { + 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++) { @@ -391,7 +397,7 @@ public class Project implements ResourceFactory { } } // copy on write semantics - BuildListener[] newListeners = + final BuildListener[] newListeners = new BuildListener[listeners.length + 1]; System.arraycopy(listeners, 0, newListeners, 0, listeners.length); newListeners[listeners.length] = listener; @@ -406,12 +412,12 @@ public class Project implements ResourceFactory { * @param listener The listener to remove from the list. * Should not be null. */ - public void removeBuildListener(BuildListener listener) { + public void removeBuildListener(final BuildListener listener) { synchronized (listenersLock) { // copy on write semantics for (int i = 0; i < listeners.length; i++) { if (listeners[i] == listener) { - BuildListener[] newListeners = + final BuildListener[] newListeners = new BuildListener[listeners.length - 1]; System.arraycopy(listeners, 0, newListeners, 0, i); System.arraycopy(listeners, i + 1, newListeners, i, @@ -430,7 +436,7 @@ public class Project implements ResourceFactory { */ public Vector getBuildListeners() { synchronized (listenersLock) { - Vector r = new Vector(listeners.length); + final Vector r = new Vector(listeners.length); for (int i = 0; i < listeners.length; i++) { r.add(listeners[i]); } @@ -444,7 +450,7 @@ public class Project implements ResourceFactory { * @param message The text to log. Should not be null. */ - public void log(String message) { + public void log(final String message) { log(message, MSG_INFO); } @@ -453,7 +459,7 @@ public class Project implements ResourceFactory { * @param message The text to log. Should not be null. * @param msgLevel The log priority level to use. */ - public void log(String message, int msgLevel) { + public void log(final String message, final int msgLevel) { log(message, null, msgLevel); } @@ -464,7 +470,7 @@ public class Project implements ResourceFactory { * @param msgLevel The log priority level to use. * @since 1.7 */ - public void log(String message, Throwable throwable, int msgLevel) { + public void log(final String message, final Throwable throwable, final int msgLevel) { fireMessageLogged(this, message, throwable, msgLevel); } @@ -474,7 +480,7 @@ public class Project implements ResourceFactory { * @param message The text to log. Should not be null. * @param msgLevel The log priority level to use. */ - public void log(Task task, String message, int msgLevel) { + public void log(final Task task, final String message, final int msgLevel) { fireMessageLogged(task, message, null, msgLevel); } @@ -486,7 +492,7 @@ public class Project implements ResourceFactory { * @param msgLevel The log priority level to use. * @since 1.7 */ - public void log(Task task, String message, Throwable throwable, int msgLevel) { + public void log(final Task task, final String message, final Throwable throwable, final int msgLevel) { fireMessageLogged(task, message, throwable, msgLevel); } @@ -497,7 +503,7 @@ public class Project implements ResourceFactory { * @param message The text to log. Should not be null. * @param msgLevel The log priority level to use. */ - public void log(Target target, String message, int msgLevel) { + public void log(final Target target, final String message, final int msgLevel) { log(target, message, null, msgLevel); } @@ -510,8 +516,8 @@ public class Project implements ResourceFactory { * @param msgLevel The log priority level to use. * @since 1.7 */ - public void log(Target target, String message, Throwable throwable, - int msgLevel) { + public void log(final Target target, final String message, final Throwable throwable, + final int msgLevel) { fireMessageLogged(target, message, throwable, msgLevel); } @@ -532,7 +538,7 @@ public class Project implements ResourceFactory { * @param value The new value of the property. * Must not be null. */ - public void setProperty(String name, String value) { + public void setProperty(final String name, final String value) { PropertyHelper.getPropertyHelper(this).setProperty(name, value, true); } @@ -547,7 +553,7 @@ public class Project implements ResourceFactory { * Must not be null. * @since 1.5 */ - public void setNewProperty(String name, String value) { + public void setNewProperty(final String name, final String value) { PropertyHelper.getPropertyHelper(this).setNewProperty(name, value); } @@ -560,7 +566,7 @@ public class Project implements ResourceFactory { * Must not be null. * @see #setProperty(String,String) */ - public void setUserProperty(String name, String value) { + public void setUserProperty(final String name, final String value) { PropertyHelper.getPropertyHelper(this).setUserProperty(name, value); } @@ -576,7 +582,7 @@ public class Project implements ResourceFactory { * Must not be null. * @see #setProperty(String,String) */ - public void setInheritedProperty(String name, String value) { + public void setInheritedProperty(final String name, final String value) { PropertyHelper.getPropertyHelper(this).setInheritedProperty(name, value); } @@ -588,7 +594,7 @@ public class Project implements ResourceFactory { * Must not be null. * @param value The property value. Must not be null. */ - private void setPropertyInternal(String name, String value) { + private void setPropertyInternal(final String name, final String value) { PropertyHelper.getPropertyHelper(this).setProperty(name, value, false); } @@ -601,8 +607,8 @@ public class Project implements ResourceFactory { * @return the property value, or null for no match * or if a null name is provided. */ - public String getProperty(String propertyName) { - Object value = PropertyHelper.getPropertyHelper(this).getProperty(propertyName); + public String getProperty(final String propertyName) { + final Object value = PropertyHelper.getPropertyHelper(this).getProperty(propertyName); return value == null ? null : String.valueOf(value); } @@ -620,7 +626,7 @@ public class Project implements ResourceFactory { * @exception BuildException if the given value has an unclosed * property name, e.g. ${xxx. */ - public String replaceProperties(String value) throws BuildException { + public String replaceProperties(final String value) throws BuildException { return PropertyHelper.getPropertyHelper(this).replaceProperties(null, value, null); } @@ -633,7 +639,7 @@ public class Project implements ResourceFactory { * @return the property value, or null for no match * or if a null name is provided. */ - public String getUserProperty(String propertyName) { + public String getUserProperty(final String propertyName) { return (String) PropertyHelper.getPropertyHelper(this).getUserProperty(propertyName); } @@ -675,7 +681,7 @@ public class Project implements ResourceFactory { * * @since Ant 1.5 */ - public void copyUserProperties(Project other) { + public void copyUserProperties(final Project other) { PropertyHelper.getPropertyHelper(this).copyUserProperties(other); } @@ -691,7 +697,7 @@ public class Project implements ResourceFactory { * * @since Ant 1.5 */ - public void copyInheritedProperties(Project other) { + public void copyInheritedProperties(final Project other) { PropertyHelper.getPropertyHelper(this).copyInheritedProperties(other); } @@ -706,7 +712,8 @@ public class Project implements ResourceFactory { * Use setDefault. * @see #setDefault(String) */ - public void setDefaultTarget(String defaultTarget) { + @Deprecated + public void setDefaultTarget(final String defaultTarget) { setDefault(defaultTarget); } @@ -726,7 +733,7 @@ public class Project implements ResourceFactory { * May be null, indicating that there is * no default target. */ - public void setDefault(String defaultTarget) { + public void setDefault(final String defaultTarget) { if (defaultTarget != null) { setUserProperty(MagicNames.PROJECT_DEFAULT_TARGET, defaultTarget); } @@ -740,7 +747,7 @@ public class Project implements ResourceFactory { * @param name The name of the project. * Must not be null. */ - public void setName(String name) { + public void setName(final String name) { setUserProperty(MagicNames.PROJECT_NAME, name); this.name = name; } @@ -760,7 +767,7 @@ public class Project implements ResourceFactory { * @param description The description of the project. * May be null. */ - public void setDescription(String description) { + public void setDescription(final String description) { this.description = description; } @@ -790,7 +797,8 @@ public class Project implements ResourceFactory { * @see #getGlobalFilterSet() * @see FilterSet#addFilter(String,String) */ - public void addFilter(String token, String value) { + @Deprecated + public void addFilter(final String token, final String value) { if (token == null) { return; } @@ -809,7 +817,8 @@ public class Project implements ResourceFactory { * @see #getGlobalFilterSet() * @see FilterSet#getFilterHash() */ - public Hashtable getFilters() { + @Deprecated + public Hashtable getFilters() { // we need to build the hashtable dynamically return globalFilterSet.getFilterHash(); } @@ -823,7 +832,7 @@ public class Project implements ResourceFactory { * * @exception BuildException if the directory if invalid. */ - public void setBasedir(String baseD) throws BuildException { + public void setBasedir(final String baseD) throws BuildException { setBaseDir(new File(baseD)); } @@ -848,7 +857,7 @@ public class Project implements ResourceFactory { } this.baseDir = baseDir; setPropertyInternal(MagicNames.PROJECT_BASEDIR, this.baseDir.getPath()); - String msg = "Project base dir set to: " + this.baseDir; + final String msg = "Project base dir set to: " + this.baseDir; log(msg, MSG_VERBOSE); } @@ -862,7 +871,7 @@ public class Project implements ResourceFactory { if (baseDir == null) { try { setBasedir("."); - } catch (BuildException ex) { + } catch (final BuildException ex) { ex.printStackTrace(); } } @@ -878,7 +887,7 @@ public class Project implements ResourceFactory { * @param keepGoingMode "keep-going" mode * @since Ant 1.6 */ - public void setKeepGoingMode(boolean keepGoingMode) { + public void setKeepGoingMode(final boolean keepGoingMode) { this.keepGoingMode = keepGoingMode; } @@ -900,7 +909,8 @@ public class Project implements ResourceFactory { * @deprecated since 1.5.x. * Use org.apache.tools.ant.util.JavaEnvUtils instead. */ - public static String getJavaVersion() { + @Deprecated + public static String getJavaVersion() { return JavaEnvUtils.getJavaVersion(); } @@ -915,7 +925,7 @@ public class Project implements ResourceFactory { * @see org.apache.tools.ant.util.JavaEnvUtils#getJavaVersion */ public void setJavaVersionProperty() throws BuildException { - String javaVersion = JavaEnvUtils.getJavaVersion(); + final String javaVersion = JavaEnvUtils.getJavaVersion(); setPropertyInternal(MagicNames.ANT_JAVA_VERSION, javaVersion); // sanity check @@ -933,11 +943,11 @@ public class Project implements ResourceFactory { * user properties to the project properties. */ public void setSystemProperties() { - Properties systemP = System.getProperties(); - Enumeration e = systemP.propertyNames(); + final Properties systemP = System.getProperties(); + final Enumeration e = systemP.propertyNames(); while (e.hasMoreElements()) { - String propertyName = (String) e.nextElement(); - String value = systemP.getProperty(propertyName); + final String propertyName = (String) e.nextElement(); + final String value = systemP.getProperty(propertyName); if (value != null) { this.setPropertyInternal(propertyName, value); } @@ -964,7 +974,7 @@ public class Project implements ResourceFactory { * * @see #checkTaskClass(Class) */ - public void addTaskDefinition(String taskName, Class taskClass) + public void addTaskDefinition(final String taskName, final Class taskClass) throws BuildException { ComponentHelper.getComponentHelper(this).addTaskDefinition(taskName, taskClass); @@ -999,13 +1009,13 @@ public class Project implements ResourceFactory { taskClass.getConstructor(); // don't have to check for public, since // getConstructor finds public constructors only. - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { final String message = "No public no-arg constructor in " + taskClass; log(message, Project.MSG_ERR); throw new BuildException(message); - } catch (LinkageError e) { - String message = "Could not load " + taskClass + ": " + e; + } catch (final LinkageError e) { + final String message = "Could not load " + taskClass + ": " + e; log(message, Project.MSG_ERR); throw new BuildException(message, e); } @@ -1051,7 +1061,7 @@ public class Project implements ResourceFactory { * @param typeClass The full name of the class implementing the datatype. * Must not be null. */ - public void addDataTypeDefinition(String typeName, Class typeClass) { + public void addDataTypeDefinition(final String typeName, final Class typeClass) { ComponentHelper.getComponentHelper(this).addDataTypeDefinition(typeName, typeClass); } @@ -1090,7 +1100,7 @@ public class Project implements ResourceFactory { * * @see Project#addOrReplaceTarget(Target) */ - public void addTarget(Target target) throws BuildException { + public void addTarget(final Target target) throws BuildException { addTarget(target.getName(), target); } @@ -1106,7 +1116,7 @@ public class Project implements ResourceFactory { * * @see Project#addOrReplaceTarget(String, Target) */ - public void addTarget(String targetName, Target target) + public void addTarget(final String targetName, final Target target) throws BuildException { if (targets.get(targetName) != null) { throw new BuildException("Duplicate target: `" + targetName + "'"); @@ -1121,7 +1131,7 @@ public class Project implements ResourceFactory { * @param target The target to be added or replaced in the project. * Must not be null. */ - public void addOrReplaceTarget(Target target) { + public void addOrReplaceTarget(final Target target) { addOrReplaceTarget(target.getName(), target); } @@ -1134,8 +1144,8 @@ public class Project implements ResourceFactory { * @param target The target to be added or replaced in the project. * Must not be null. */ - public void addOrReplaceTarget(String targetName, Target target) { - String msg = " +Target: " + targetName; + public void addOrReplaceTarget(final String targetName, final Target target) { + final String msg = " +Target: " + targetName; log(msg, MSG_DEBUG); target.setProject(this); targets.put(targetName, target); @@ -1173,7 +1183,7 @@ public class Project implements ResourceFactory { * @exception BuildException if the task name is recognised but task * creation fails. */ - public Task createTask(String taskType) throws BuildException { + public Task createTask(final String taskType) throws BuildException { return ComponentHelper.getComponentHelper(this).createTask(taskType); } @@ -1189,7 +1199,7 @@ public class Project implements ResourceFactory { * @exception BuildException if the data type name is recognised but * instance creation fails. */ - public Object createDataType(String typeName) throws BuildException { + public Object createDataType(final String typeName) throws BuildException { return ComponentHelper.getComponentHelper(this).createDataType(typeName); } @@ -1197,7 +1207,7 @@ public class Project implements ResourceFactory { * Set the Executor instance for this Project. * @param e the Executor to use. */ - public void setExecutor(Executor e) { + public void setExecutor(final Executor e) { addReference(MagicNames.ANT_EXECUTOR_REFERENCE, e); } @@ -1215,14 +1225,14 @@ public class Project implements ResourceFactory { log("Attempting to create object of type " + classname, MSG_DEBUG); try { o = Class.forName(classname, true, coreLoader).newInstance(); - } catch (ClassNotFoundException seaEnEfEx) { + } catch (final ClassNotFoundException seaEnEfEx) { //try the current classloader try { o = Class.forName(classname).newInstance(); - } catch (Exception ex) { + } catch (final Exception ex) { log(ex.toString(), MSG_ERR); } - } catch (Exception ex) { + } catch (final Exception ex) { log(ex.toString(), MSG_ERR); } if (o == null) { @@ -1243,7 +1253,7 @@ public class Project implements ResourceFactory { * * @exception BuildException if the build failed. */ - public void executeTargets(Vector names) throws BuildException { + public void executeTargets(final Vector names) throws BuildException { setUserProperty(MagicNames.PROJECT_INVOKED_TARGETS, CollectionUtils.flattenToString(names)); getExecutor().executeTargets(this, names.toArray(new String[names.size()])); @@ -1258,8 +1268,8 @@ public class Project implements ResourceFactory { * @param isWarning Whether the text represents an warning (true) * or information (false). */ - public void demuxOutput(String output, boolean isWarning) { - Task task = getThreadTask(Thread.currentThread()); + public void demuxOutput(final String output, final boolean isWarning) { + final Task task = getThreadTask(Thread.currentThread()); if (task == null) { log(output, isWarning ? MSG_WARN : MSG_INFO); } else { @@ -1284,7 +1294,7 @@ public class Project implements ResourceFactory { * @exception IOException if the data cannot be read. * @since Ant 1.6 */ - public int defaultInput(byte[] buffer, int offset, int length) + public int defaultInput(final byte[] buffer, final int offset, final int length) throws IOException { if (defaultInputStream != null) { System.out.flush(); @@ -1306,9 +1316,9 @@ public class Project implements ResourceFactory { * @exception IOException if the data cannot be read. * @since Ant 1.6 */ - public int demuxInput(byte[] buffer, int offset, int length) + public int demuxInput(final byte[] buffer, final int offset, final int length) throws IOException { - Task task = getThreadTask(Thread.currentThread()); + final Task task = getThreadTask(Thread.currentThread()); if (task == null) { return defaultInput(buffer, offset, length); } else { @@ -1327,8 +1337,8 @@ public class Project implements ResourceFactory { * @param isError Whether the text represents an error (true) * or information (false). */ - public void demuxFlush(String output, boolean isError) { - Task task = getThreadTask(Thread.currentThread()); + public void demuxFlush(final String output, final boolean isError) { + final Task task = getThreadTask(Thread.currentThread()); if (task == null) { fireMessageLogged(this, output, isError ? MSG_ERR : MSG_INFO); } else { @@ -1348,13 +1358,13 @@ public class Project implements ResourceFactory { * * @exception BuildException if the build failed. */ - public void executeTarget(String targetName) throws BuildException { + public void executeTarget(final String targetName) throws BuildException { // sanity check ourselves, if we've been asked to build nothing // then we should complain if (targetName == null) { - String msg = "No target specified"; + final String msg = "No target specified"; throw new BuildException(msg); } @@ -1370,15 +1380,15 @@ public class Project implements ResourceFactory { * @param sortedTargets the aforementioned Vector. * @throws BuildException on error. */ - public void executeSortedTargets(Vector sortedTargets) + public void executeSortedTargets(final Vector sortedTargets) throws BuildException { - Set succeededTargets = new HashSet(); + final Set succeededTargets = new HashSet(); BuildException buildException = null; // first build exception - for (Target curtarget : sortedTargets) { + for (final Target curtarget : sortedTargets) { boolean canExecute = true; - for (Enumeration depIter = curtarget.getDependencies(); + for (final Enumeration depIter = curtarget.getDependencies(); depIter.hasMoreElements();) { - String dependencyName = depIter.nextElement(); + final String dependencyName = depIter.nextElement(); if (!succeededTargets.contains(dependencyName)) { canExecute = false; log(curtarget, @@ -1393,12 +1403,12 @@ public class Project implements ResourceFactory { try { curtarget.performTasks(); succeededTargets.add(curtarget.getName()); - } catch (RuntimeException ex) { + } catch (final RuntimeException ex) { if (!(keepGoingMode)) { throw ex; // throw further } thrownException = ex; - } catch (Throwable ex) { + } catch (final Throwable ex) { if (!(keepGoingMode)) { throw new BuildException(ex); } @@ -1450,7 +1460,8 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public File resolveFile(String fileName, File rootDir) { + @Deprecated + public File resolveFile(final String fileName, final File rootDir) { return FILE_UTILS.resolveFile(rootDir, fileName); } @@ -1466,7 +1477,7 @@ public class Project implements ResourceFactory { * @return the resolved File. * */ - public File resolveFile(String fileName) { + public File resolveFile(final String fileName) { return FILE_UTILS.resolveFile(baseDir, fileName); } @@ -1489,7 +1500,8 @@ public class Project implements ResourceFactory { * * @see PathTokenizer */ - public static String translatePath(String toProcess) { + @Deprecated + public static String translatePath(final String toProcess) { return FileUtils.translatePath(toProcess); } @@ -1506,7 +1518,8 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(String sourceFile, String destFile) + @Deprecated + public void copyFile(final String sourceFile, final String destFile) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile); } @@ -1526,7 +1539,8 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(String sourceFile, String destFile, boolean filtering) + @Deprecated + public void copyFile(final String sourceFile, final String destFile, final boolean filtering) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null); @@ -1550,8 +1564,9 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(String sourceFile, String destFile, boolean filtering, - boolean overwrite) throws IOException { + @Deprecated + public void copyFile(final String sourceFile, final String destFile, final boolean filtering, + final boolean overwrite) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null, overwrite); } @@ -1579,8 +1594,9 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(String sourceFile, String destFile, boolean filtering, - boolean overwrite, boolean preserveLastModified) + @Deprecated + public void copyFile(final String sourceFile, final String destFile, final boolean filtering, + final boolean overwrite, final boolean preserveLastModified) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null, overwrite, preserveLastModified); @@ -1599,7 +1615,8 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(File sourceFile, File destFile) throws IOException { + @Deprecated + public void copyFile(final File sourceFile, final File destFile) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile); } @@ -1618,7 +1635,8 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(File sourceFile, File destFile, boolean filtering) + @Deprecated + public void copyFile(final File sourceFile, final File destFile, final boolean filtering) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null); @@ -1642,8 +1660,9 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(File sourceFile, File destFile, boolean filtering, - boolean overwrite) throws IOException { + @Deprecated + public void copyFile(final File sourceFile, final File destFile, final boolean filtering, + final boolean overwrite) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null, overwrite); } @@ -1671,8 +1690,9 @@ public class Project implements ResourceFactory { * * @deprecated since 1.4.x */ - public void copyFile(File sourceFile, File destFile, boolean filtering, - boolean overwrite, boolean preserveLastModified) + @Deprecated + public void copyFile(final File sourceFile, final File destFile, final boolean filtering, + final boolean overwrite, final boolean preserveLastModified) throws IOException { FILE_UTILS.copyFile(sourceFile, destFile, filtering ? globalFilters : null, overwrite, preserveLastModified); @@ -1693,7 +1713,8 @@ public class Project implements ResourceFactory { * despite running on a platform with a version * above 1.1. */ - public void setFileLastModified(File file, long time) + @Deprecated + public void setFileLastModified(final File file, final long time) throws BuildException { FILE_UTILS.setFileLastModified(file, time); log("Setting modification time for " + file, MSG_VERBOSE); @@ -1710,7 +1731,7 @@ public class Project implements ResourceFactory { * "true" or "yes", or * false otherwise. */ - public static boolean toBoolean(String s) { + public static boolean toBoolean(final String s) { return ("on".equalsIgnoreCase(s) || "true".equalsIgnoreCase(s) || "yes".equalsIgnoreCase(s)); @@ -1722,16 +1743,16 @@ public class Project implements ResourceFactory { * @return Project instance, if any. * @since Ant 1.7.1 */ - public static Project getProject(Object o) { + public static Project getProject(final Object o) { if (o instanceof ProjectComponent) { return ((ProjectComponent) o).getProject(); } try { - Method m = o.getClass().getMethod("getProject", (Class[]) null); + final Method m = o.getClass().getMethod("getProject", (Class[]) null); if (Project.class == m.getReturnType()) { return (Project) m.invoke(o, (Object[]) null); } - } catch (Exception e) { + } catch (final Exception e) { //too bad } return null; @@ -1751,7 +1772,7 @@ public class Project implements ResourceFactory { * @exception BuildException if there is a cyclic dependency among the * targets, or if a named target does not exist. */ - public final Vector topoSort(String root, Hashtable targetTable) + public final Vector topoSort(final String root, final Hashtable targetTable) throws BuildException { return topoSort(new String[] {root}, targetTable, true); } @@ -1773,8 +1794,8 @@ public class Project implements ResourceFactory { * targets, or if a named target does not exist. * @since Ant 1.6.3 */ - public final Vector topoSort(String root, Hashtable targetTable, - boolean returnAll) throws BuildException { + public final Vector topoSort(final String root, final Hashtable targetTable, + final boolean returnAll) throws BuildException { return topoSort(new String[] {root}, targetTable, returnAll); } @@ -1795,11 +1816,11 @@ public class Project implements ResourceFactory { * targets, or if a named target does not exist. * @since Ant 1.6.3 */ - public final Vector topoSort(String[] root, Hashtable targetTable, - boolean returnAll) throws BuildException { - Vector ret = new VectorSet(); - Hashtable state = new Hashtable(); - Stack visiting = new Stack(); + public final Vector topoSort(final String[] root, final Hashtable targetTable, + final boolean returnAll) throws BuildException { + final Vector ret = new VectorSet(); + final Hashtable state = new Hashtable(); + final Stack visiting = new Stack(); // We first run a DFS based sort using each root as a starting node. // This creates the minimum sequence of Targets to the root node(s). @@ -1810,7 +1831,7 @@ public class Project implements ResourceFactory { // build Target. for (int i = 0; i < root.length; i++) { - String st = (String) (state.get(root[i])); + final String st = (state.get(root[i])); if (st == null) { tsort(root[i], targetTable, state, visiting, ret); } else if (st == VISITING) { @@ -1818,7 +1839,7 @@ public class Project implements ResourceFactory { + root[i]); } } - StringBuffer buf = new StringBuffer("Build sequence for target(s)"); + final StringBuffer buf = new StringBuffer("Build sequence for target(s)"); for (int j = 0; j < root.length; j++) { buf.append((j == 0) ? " `" : ", `").append(root[j]).append('\''); @@ -1826,10 +1847,10 @@ public class Project implements ResourceFactory { buf.append(" is " + ret); log(buf.toString(), MSG_VERBOSE); - Vector complete = (returnAll) ? ret : new Vector(ret); - for (Enumeration en = targetTable.keys(); en.hasMoreElements();) { - String curTarget = en.nextElement(); - String st = state.get(curTarget); + final Vector complete = (returnAll) ? ret : new Vector(ret); + for (final Enumeration en = targetTable.keys(); en.hasMoreElements();) { + final String curTarget = en.nextElement(); + final String st = state.get(curTarget); if (st == null) { tsort(curTarget, targetTable, state, visiting, complete); } else if (st == VISITING) { @@ -1881,34 +1902,34 @@ public class Project implements ResourceFactory { * @exception BuildException if a non-existent target is specified or if * a circular dependency is detected. */ - private void tsort(String root, Hashtable targetTable, - Hashtable state, Stack visiting, - Vector ret) + private void tsort(final String root, final Hashtable targetTable, + final Hashtable state, final Stack visiting, + final Vector ret) throws BuildException { state.put(root, VISITING); visiting.push(root); - Target target = targetTable.get(root); + final Target target = targetTable.get(root); // Make sure we exist if (target == null) { - StringBuilder sb = new StringBuilder("Target \""); + final StringBuilder sb = new StringBuilder("Target \""); sb.append(root); sb.append("\" does not exist in the project \""); sb.append(name); sb.append("\". "); visiting.pop(); if (!visiting.empty()) { - String parent = visiting.peek(); + final String parent = visiting.peek(); sb.append("It is used from target \""); sb.append(parent); sb.append("\"."); } throw new BuildException(new String(sb)); } - for (Enumeration en = target.getDependencies(); en.hasMoreElements();) { - String cur = en.nextElement(); - String m = state.get(cur); + for (final Enumeration en = target.getDependencies(); en.hasMoreElements();) { + final String cur = en.nextElement(); + final String m = state.get(cur); if (m == null) { // Not been visited tsort(cur, targetTable, state, visiting, ret); @@ -1917,7 +1938,7 @@ public class Project implements ResourceFactory { throw makeCircularException(cur, visiting); } } - String p = visiting.pop(); + final String p = visiting.pop(); if (root != p) { throw new RuntimeException("Unexpected internal error: expected to " + "pop " + root + " but got " + p); @@ -1935,7 +1956,7 @@ public class Project implements ResourceFactory { * * @return a BuildException detailing the specified circular dependency. */ - private static BuildException makeCircularException(String end, Stack stk) { + private static BuildException makeCircularException(final String end, final Stack stk) { final StringBuilder sb = new StringBuilder("Circular dependency: "); sb.append(end); String c; @@ -1951,7 +1972,7 @@ public class Project implements ResourceFactory { * Inherit the id references. * @param parent the parent project of this project. */ - public void inheritIDReferences(Project parent) { + public void inheritIDReferences(final Project parent) { } /** @@ -1960,7 +1981,7 @@ public class Project implements ResourceFactory { * @param id the id to set. * @param value the value to set it to (Unknown element in this case. */ - public void addIdReference(String id, Object value) { + public void addIdReference(final String id, final Object value) { idReferences.put(id, value); } @@ -1970,8 +1991,8 @@ public class Project implements ResourceFactory { * @param referenceName The name of the reference. Must not be null. * @param value The value of the reference. */ - public void addReference(String referenceName, Object value) { - Object old = ((AntRefTable) references).getReal(referenceName); + public void addReference(final String referenceName, final Object value) { + final Object old = ((AntRefTable) references).getReal(referenceName); if (old == value) { // no warning, this is not changing anything return; @@ -1999,7 +2020,7 @@ public class Project implements ResourceFactory { * * @since Ant 1.8.0 */ - public boolean hasReference(String key) { + public boolean hasReference(final String key) { return references.containsKey(key); } @@ -2025,7 +2046,7 @@ public class Project implements ResourceFactory { * @return the reference with the specified ID, or null if * there is no such reference in the project, with type inference. */ - public T getReference(String key) { + public T getReference(final String key) { @SuppressWarnings("unchecked") final T ret = (T) references.get(key); if (ret != null) { @@ -2037,7 +2058,7 @@ public class Project implements ResourceFactory { log("Unresolvable reference " + key + " might be a misuse of property expansion syntax.", MSG_WARN); } - } catch (Exception e) { + } catch (final Exception e) { //ignore } } @@ -2057,7 +2078,7 @@ public class Project implements ResourceFactory { * * @since 1.95, Ant 1.5 */ - public String getElementName(Object element) { + public String getElementName(final Object element) { return ComponentHelper.getComponentHelper(this).getElementName(element); } @@ -2066,8 +2087,8 @@ public class Project implements ResourceFactory { * to the build listeners for this project. */ public void fireBuildStarted() { - BuildEvent event = new BuildEvent(this); - BuildListener[] currListeners = listeners; + final BuildEvent event = new BuildEvent(this); + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].buildStarted(event); } @@ -2080,10 +2101,10 @@ public class Project implements ResourceFactory { * failure. May be null, indicating * a successful build. */ - public void fireBuildFinished(Throwable exception) { - BuildEvent event = new BuildEvent(this); + public void fireBuildFinished(final Throwable exception) { + final BuildEvent event = new BuildEvent(this); event.setException(exception); - BuildListener[] currListeners = listeners; + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].buildFinished(event); } @@ -2098,8 +2119,8 @@ public class Project implements ResourceFactory { * @since Ant 1.6.2 */ public void fireSubBuildStarted() { - BuildEvent event = new BuildEvent(this); - BuildListener[] currListeners = listeners; + 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); @@ -2116,10 +2137,10 @@ public class Project implements ResourceFactory { * * @since Ant 1.6.2 */ - public void fireSubBuildFinished(Throwable exception) { - BuildEvent event = new BuildEvent(this); + public void fireSubBuildFinished(final Throwable exception) { + final BuildEvent event = new BuildEvent(this); event.setException(exception); - BuildListener[] currListeners = listeners; + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { if (currListeners[i] instanceof SubBuildListener) { ((SubBuildListener) currListeners[i]).subBuildFinished(event); @@ -2134,9 +2155,9 @@ public class Project implements ResourceFactory { * @param target The target which is starting to build. * Must not be null. */ - protected void fireTargetStarted(Target target) { - BuildEvent event = new BuildEvent(target); - BuildListener[] currListeners = listeners; + 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); } @@ -2153,10 +2174,10 @@ public class Project implements ResourceFactory { * failure. May be null, indicating * a successful build. */ - protected void fireTargetFinished(Target target, Throwable exception) { - BuildEvent event = new BuildEvent(target); + protected void fireTargetFinished(final Target target, final Throwable exception) { + final BuildEvent event = new BuildEvent(target); event.setException(exception); - BuildListener[] currListeners = listeners; + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].targetFinished(event); } @@ -2170,11 +2191,11 @@ public class Project implements ResourceFactory { * @param task The target which is starting to execute. * Must not be null. */ - protected void fireTaskStarted(Task task) { + protected void fireTaskStarted(final Task task) { // register this as the current task on the current thread. registerThreadTask(Thread.currentThread(), task); - BuildEvent event = new BuildEvent(task); - BuildListener[] currListeners = listeners; + final BuildEvent event = new BuildEvent(task); + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].taskStarted(event); } @@ -2190,13 +2211,13 @@ public class Project implements ResourceFactory { * failure. May be null, indicating * a successful build. */ - protected void fireTaskFinished(Task task, Throwable exception) { + protected void fireTaskFinished(final Task task, final Throwable exception) { registerThreadTask(Thread.currentThread(), null); System.out.flush(); System.err.flush(); - BuildEvent event = new BuildEvent(task); + final BuildEvent event = new BuildEvent(task); event.setException(exception); - BuildListener[] currListeners = listeners; + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].taskFinished(event); } @@ -2214,14 +2235,14 @@ public class Project implements ResourceFactory { * @param message The message to send. Should not be null. * @param priority The priority of the message. */ - private void fireMessageLoggedEvent(BuildEvent event, String message, - int priority) { + private void fireMessageLoggedEvent(final BuildEvent event, String message, + final int priority) { if (message == null) { message = String.valueOf(message); } if (message.endsWith(StringUtils.LINE_SEP)) { - int endIndex = message.length() - StringUtils.LINE_SEP.length(); + final int endIndex = message.length() - StringUtils.LINE_SEP.length(); event.setMessage(message.substring(0, endIndex), priority); } else { event.setMessage(message, priority); @@ -2244,7 +2265,7 @@ public class Project implements ResourceFactory { } try { isLoggingMessage.set(Boolean.TRUE); - BuildListener[] currListeners = listeners; + final BuildListener[] currListeners = listeners; for (int i = 0; i < currListeners.length; i++) { currListeners[i].messageLogged(event); } @@ -2262,8 +2283,8 @@ public class Project implements ResourceFactory { * @param message The message to send. Should not be null. * @param priority The priority of the message. */ - protected void fireMessageLogged(Project project, String message, - int priority) { + protected void fireMessageLogged(final Project project, final String message, + final int priority) { fireMessageLogged(project, message, null, priority); } @@ -2278,9 +2299,9 @@ public class Project implements ResourceFactory { * @param priority The priority of the message. * @since 1.7 */ - protected void fireMessageLogged(Project project, String message, - Throwable throwable, int priority) { - BuildEvent event = new BuildEvent(project); + protected void fireMessageLogged(final Project project, final String message, + final Throwable throwable, final int priority) { + final BuildEvent event = new BuildEvent(project); event.setException(throwable); fireMessageLoggedEvent(event, message, priority); } @@ -2294,8 +2315,8 @@ public class Project implements ResourceFactory { * @param message The message to send. Should not be null. * @param priority The priority of the message. */ - protected void fireMessageLogged(Target target, String message, - int priority) { + protected void fireMessageLogged(final Target target, final String message, + final int priority) { fireMessageLogged(target, message, null, priority); } @@ -2310,9 +2331,9 @@ public class Project implements ResourceFactory { * @param priority The priority of the message. * @since 1.7 */ - protected void fireMessageLogged(Target target, String message, - Throwable throwable, int priority) { - BuildEvent event = new BuildEvent(target); + protected void fireMessageLogged(final Target target, final String message, + final Throwable throwable, final int priority) { + final BuildEvent event = new BuildEvent(target); event.setException(throwable); fireMessageLoggedEvent(event, message, priority); } @@ -2326,7 +2347,7 @@ public class Project implements ResourceFactory { * @param message The message to send. Should not be null. * @param priority The priority of the message. */ - protected void fireMessageLogged(Task task, String message, int priority) { + protected void fireMessageLogged(final Task task, final String message, final int priority) { fireMessageLogged(task, message, null, priority); } @@ -2341,9 +2362,9 @@ public class Project implements ResourceFactory { * @param priority The priority of the message. * @since 1.7 */ - protected void fireMessageLogged(Task task, String message, - Throwable throwable, int priority) { - BuildEvent event = new BuildEvent(task); + protected void fireMessageLogged(final Task task, final String message, + final Throwable throwable, final int priority) { + final BuildEvent event = new BuildEvent(task); event.setException(throwable); fireMessageLoggedEvent(event, message, priority); } @@ -2356,8 +2377,8 @@ public class Project implements ResourceFactory { * @param task the task to be registered. * @since Ant 1.5 */ - public void registerThreadTask(Thread thread, Task task) { - synchronized(threadTasks) { + public void registerThreadTask(final Thread thread, final Task task) { + synchronized (threadTasks) { if (task != null) { threadTasks.put(thread, task); threadGroupTasks.put(thread.getThreadGroup(), task); @@ -2375,13 +2396,13 @@ public class Project implements ResourceFactory { * @return the task which is currently registered for the given thread or * null if no task is registered. */ - public Task getThreadTask(Thread thread) { - synchronized(threadTasks) { - Task task = (Task) threadTasks.get(thread); + public Task getThreadTask(final Thread thread) { + synchronized (threadTasks) { + Task task = threadTasks.get(thread); if (task == null) { ThreadGroup group = thread.getThreadGroup(); while (task == null && group != null) { - task = (Task) threadGroupTasks.get(group); + task = threadGroupTasks.get(group); group = group.getParent(); } } @@ -2406,7 +2427,7 @@ public class Project implements ResourceFactory { * of UnknownElement (this is similar with the JDNI * refs behavior). */ - private Object getReal(Object key) { + private Object getReal(final Object key) { return super.get(key); } @@ -2421,11 +2442,12 @@ public class Project implements ResourceFactory { * @param key lookup key. * @return mapped value. */ - public Object get(Object key) { + @Override + public Object get(final Object key) { Object o = getReal(key); if (o instanceof UnknownElement) { // Make sure that - UnknownElement ue = (UnknownElement) o; + final UnknownElement ue = (UnknownElement) o; ue.maybeConfigure(); o = ue.getRealThing(); } @@ -2445,13 +2467,13 @@ public class Project implements ResourceFactory { return; } try { - Method method = + final Method method = obj.getClass().getMethod( "setProject", new Class[] {Project.class}); if (method != null) { method.invoke(obj, new Object[] {this}); } - } catch (Throwable e) { + } catch (final Throwable e) { // ignore this if the object does not have // a set project method or the method // is private/protected. @@ -2465,7 +2487,8 @@ public class Project implements ResourceFactory { * @return the file resource. * @since Ant 1.7 */ - public Resource getResource(String name) { + @Override + public Resource getResource(final String name) { return new FileResource(getBaseDir(), name); } } diff --git a/src/main/org/apache/tools/ant/ProjectHelper.java b/src/main/org/apache/tools/ant/ProjectHelper.java index a95c2668a..c6eaa0774 100644 --- a/src/main/org/apache/tools/ant/ProjectHelper.java +++ b/src/main/org/apache/tools/ant/ProjectHelper.java @@ -101,7 +101,7 @@ public class ProjectHelper { * * @since 1.8.2 */ - public final static class OnMissingExtensionPoint { + public static final class OnMissingExtensionPoint { /** fail if the extension-point is not defined */ public static final OnMissingExtensionPoint FAIL = new OnMissingExtensionPoint( @@ -181,7 +181,7 @@ public class ProjectHelper { return extensionStack; } - private final static ThreadLocal targetPrefix = new ThreadLocal(); + private static final ThreadLocal targetPrefix = new ThreadLocal(); /** * The prefix to prepend to imported target names. @@ -205,7 +205,7 @@ public class ProjectHelper { targetPrefix.set(prefix); } - private final static ThreadLocal prefixSeparator = new ThreadLocal() { + private static final ThreadLocal prefixSeparator = new ThreadLocal() { protected String initialValue() { return "."; } @@ -231,7 +231,7 @@ public class ProjectHelper { prefixSeparator.set(sep); } - private final static ThreadLocal inIncludeMode = new ThreadLocal() { + private static final ThreadLocal inIncludeMode = new ThreadLocal() { protected Boolean initialValue() { return Boolean.FALSE; } diff --git a/src/main/org/apache/tools/ant/filters/ConcatFilter.java b/src/main/org/apache/tools/ant/filters/ConcatFilter.java index 391a1ef66..a28edbfef 100644 --- a/src/main/org/apache/tools/ant/filters/ConcatFilter.java +++ b/src/main/org/apache/tools/ant/filters/ConcatFilter.java @@ -36,7 +36,7 @@ import org.apache.tools.ant.types.Parameter; * </filterchain> * </copy> * - * + * *

Copies all java sources from src to build and adds the * content of apache-license-java.txt add the beginning of each * file.

@@ -90,7 +90,8 @@ public final class ConcatFilter extends BaseParamFilterReader * @exception IOException if the underlying stream throws an IOException * during reading */ - public int read() throws IOException { + @Override + public int read() throws IOException { // do the "singleton" initialization if (!getInitialized()) { initialize(); @@ -170,7 +171,8 @@ public final class ConcatFilter extends BaseParamFilterReader * @return a new filter based on this configuration, but filtering * the specified reader */ - public Reader chain(final Reader rdr) { + @Override + public Reader chain(final Reader rdr) { ConcatFilter newFilter = new ConcatFilter(rdr); newFilter.setPrepend(getPrepend()); newFilter.setAppend(getAppend()); diff --git a/src/main/org/apache/tools/ant/launch/Launcher.java b/src/main/org/apache/tools/ant/launch/Launcher.java index ab05903fd..228f6f6a0 100644 --- a/src/main/org/apache/tools/ant/launch/Launcher.java +++ b/src/main/org/apache/tools/ant/launch/Launcher.java @@ -105,15 +105,15 @@ public class Launcher { * * @param args commandline arguments */ - public static void main(String[] args) { + public static void main(final String[] args) { int exitCode; try { - Launcher launcher = new Launcher(); + final Launcher launcher = new Launcher(); exitCode = launcher.run(args); - } catch (LaunchException e) { + } catch (final LaunchException e) { exitCode = EXIT_CODE_ERROR; System.err.println(e.getMessage()); - } catch (Throwable t) { + } catch (final Throwable t) { exitCode = EXIT_CODE_ERROR; t.printStackTrace(System.err); } @@ -136,26 +136,28 @@ public class Launcher { * @param libPathURLs the list of paths to add to * @throws MalformedURLException if we can't create a URL */ - private void addPath(String path, boolean getJars, List libPathURLs) + private void addPath(final String path, final boolean getJars, final List libPathURLs) throws MalformedURLException { - StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator); + final StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator); while (tokenizer.hasMoreElements()) { - String elementName = tokenizer.nextToken(); - File element = new File(elementName); + final String elementName = tokenizer.nextToken(); + final File element = new File(elementName); if (elementName.indexOf('%') != -1 && !element.exists()) { continue; } if (getJars && element.isDirectory()) { // add any jars in the directory - URL[] dirURLs = Locator.getLocationURLs(element); + 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]); } } - URL url = Locator.fileToURL(element); - if (launchDiag) { System.out.println("adding library URL: " + url) ;} + final URL url = Locator.fileToURL(element); + if (launchDiag) { + System.out.println("adding library URL: " + url); + } libPathURLs.add(url); } } @@ -170,13 +172,13 @@ public class Launcher { * cannot be created. * @throws LaunchException for launching problems */ - private int run(String[] args) + private int run(final String[] args) throws LaunchException, MalformedURLException { - String antHomeProperty = System.getProperty(ANTHOME_PROPERTY); + final String antHomeProperty = System.getProperty(ANTHOME_PROPERTY); File antHome = null; - File sourceJar = Locator.getClassSource(getClass()); - File jarDir = sourceJar.getParentFile(); + final File sourceJar = Locator.getClassSource(getClass()); + final File jarDir = sourceJar.getParentFile(); String mainClassname = MAIN_CLASS; if (antHomeProperty != null) { @@ -193,9 +195,9 @@ public class Launcher { + "ant could not be located (estimated value="+antHome.getAbsolutePath()+")"); } - List libPaths = new ArrayList(); + final List libPaths = new ArrayList(); String cpString = null; - List argList = new ArrayList(); + final List argList = new ArrayList(); String[] newArgs; boolean noUserLib = false; boolean noClassPath = false; @@ -244,21 +246,21 @@ public class Launcher { if (argList.size() == args.length) { newArgs = args; } else { - newArgs = (String[]) argList.toArray(new String[argList.size()]); + newArgs = argList.toArray(new String[argList.size()]); } - URL[] libURLs = getLibPathURLs( + final URL[] libURLs = getLibPathURLs( noClassPath ? null : cpString, libPaths); - URL[] systemURLs = getSystemURLs(jarDir); - URL[] userURLs = noUserLib ? new URL[0] : getUserURLs(); + final URL[] systemURLs = getSystemURLs(jarDir); + final URL[] userURLs = noUserLib ? new URL[0] : getUserURLs(); - File toolsJAR = Locator.getToolsJar(); + final File toolsJAR = Locator.getToolsJar(); logPath("tools.jar",toolsJAR); - URL[] jars = getJarArray( + final URL[] jars = getJarArray( libURLs, userURLs, systemURLs, toolsJAR); // now update the class.path property - StringBuffer baseClassPath + final StringBuffer baseClassPath = new StringBuffer(System.getProperty(JAVA_CLASS_PATH)); if (baseClassPath.charAt(baseClassPath.length() - 1) == File.pathSeparatorChar) { @@ -272,27 +274,27 @@ public class Launcher { setProperty(JAVA_CLASS_PATH, baseClassPath.toString()); - URLClassLoader loader = new URLClassLoader(jars, Launcher.class.getClassLoader()); + final URLClassLoader loader = new URLClassLoader(jars, Launcher.class.getClassLoader()); Thread.currentThread().setContextClassLoader(loader); Class mainClass = null; int exitCode = 0; Throwable thrown=null; try { mainClass = loader.loadClass(mainClassname); - AntMain main = (AntMain) mainClass.newInstance(); + final AntMain main = (AntMain) mainClass.newInstance(); main.startAnt(newArgs, null, null); - } catch (InstantiationException ex) { + } catch (final InstantiationException ex) { System.err.println( "Incompatible version of " + mainClassname + " detected"); - File mainJar = Locator.getClassSource(mainClass); + final File mainJar = Locator.getClassSource(mainClass); System.err.println( "Location of this class " + mainJar); thrown = ex; - } catch (ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException cnfe) { System.err.println( "Failed to locate" + mainClassname); thrown = cnfe; - } catch (Throwable t) { + } catch (final Throwable t) { t.printStackTrace(System.err); thrown=t; } @@ -314,15 +316,15 @@ public class Launcher { * @return an array of URLs. * @throws MalformedURLException if the URLs cannot be created. */ - private URL[] getLibPathURLs(String cpString, List libPaths) + private URL[] getLibPathURLs(final String cpString, final List libPaths) throws MalformedURLException { - List libPathURLs = new ArrayList(); + final List libPathURLs = new ArrayList(); if (cpString != null) { addPath(cpString, false, libPathURLs); } - for (String libPath : libPaths) { + for (final String libPath : libPaths) { addPath(libPath, true, libPathURLs); } @@ -337,9 +339,9 @@ public class Launcher { * @return the URLs * @throws MalformedURLException if the URLs cannot be created. */ - private URL[] getSystemURLs(File antLauncherDir) throws MalformedURLException { + private URL[] getSystemURLs(final File antLauncherDir) throws MalformedURLException { File antLibDir = null; - String antLibDirProperty = System.getProperty(ANTLIBDIR_PROPERTY); + final String antLibDirProperty = System.getProperty(ANTLIBDIR_PROPERTY); if (antLibDirProperty != null) { antLibDir = new File(antLibDirProperty); } @@ -356,7 +358,7 @@ public class Launcher { * @throws MalformedURLException if the URLs cannot be created. */ private URL[] getUserURLs() throws MalformedURLException { - File userLibDir + final File userLibDir = new File(System.getProperty(USER_HOMEDIR), USER_LIBDIR); return Locator.getLocationURLs(userLibDir); @@ -372,13 +374,13 @@ public class Launcher { * @throws MalformedURLException if there is a problem. */ private URL[] getJarArray ( - URL[] libJars, URL[] userJars, URL[] systemJars, File toolsJar) + final URL[] libJars, final URL[] userJars, final URL[] systemJars, final File toolsJar) throws MalformedURLException { int numJars = libJars.length + userJars.length + systemJars.length; if (toolsJar != null) { numJars++; } - URL[] jars = new URL[numJars]; + final URL[] jars = new URL[numJars]; System.arraycopy(libJars, 0, jars, 0, libJars.length); System.arraycopy(userJars, 0, jars, libJars.length, userJars.length); System.arraycopy(systemJars, 0, jars, userJars.length + libJars.length, @@ -395,14 +397,14 @@ public class Launcher { * @param name property name * @param value value */ - private void setProperty(String name, String value) { + private void setProperty(final String name, final String value) { if (launchDiag) { System.out.println("Setting \"" + name + "\" to \"" + value + "\""); } System.setProperty(name, value); } - private void logPath(String name,File path) { + private void logPath(final String name,final File path) { if(launchDiag) { System.out.println(name+"= \""+path+"\""); } diff --git a/src/main/org/apache/tools/ant/launch/Locator.java b/src/main/org/apache/tools/ant/launch/Locator.java index 5847f5c53..035b8b277 100644 --- a/src/main/org/apache/tools/ant/launch/Locator.java +++ b/src/main/org/apache/tools/ant/launch/Locator.java @@ -27,8 +27,6 @@ import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Locale; -import org.apache.tools.ant.util.FileUtils; - // CheckStyle:LineLengthCheck OFF - urls are long! /** * The Locator is a utility class which is used to find certain items diff --git a/src/main/org/apache/tools/ant/listener/AnsiColorLogger.java b/src/main/org/apache/tools/ant/listener/AnsiColorLogger.java index 08c1ebddf..9683c4146 100644 --- a/src/main/org/apache/tools/ant/listener/AnsiColorLogger.java +++ b/src/main/org/apache/tools/ant/listener/AnsiColorLogger.java @@ -78,7 +78,7 @@ import org.apache.tools.ant.Project; * 7 -> Reverse * 8 -> Hidden * - * + * * Foreground is one of the following:
  *  30 -> Black
  *  31 -> Red
@@ -207,7 +207,8 @@ public class AnsiColorLogger extends DefaultLogger {
      * @see DefaultLogger#printMessage
      */
     /** {@inheritDoc}. */
-    protected void printMessage(final String message,
+    @Override
+	protected void printMessage(final String message,
                                       final PrintStream stream,
                                       final int priority) {
         if (message != null && stream != null) {
diff --git a/src/main/org/apache/tools/ant/listener/SilentLogger.java b/src/main/org/apache/tools/ant/listener/SilentLogger.java
index 49da6e663..7b63b870d 100644
--- a/src/main/org/apache/tools/ant/listener/SilentLogger.java
+++ b/src/main/org/apache/tools/ant/listener/SilentLogger.java
@@ -22,34 +22,40 @@ import org.apache.tools.ant.DefaultLogger;
 
 /**
  * A logger which logs nothing but build failure and what task might output
- * 
+ *
  * @since 1.9.0
  */
 public class SilentLogger extends DefaultLogger {
 
-    public void buildStarted(BuildEvent event) {
+    @Override
+	public void buildStarted(BuildEvent event) {
         // log nothing
     }
 
-    public void buildFinished(BuildEvent event) {
+    @Override
+	public void buildFinished(BuildEvent event) {
         if (event.getException() != null) {
             super.buildFinished(event);
         }
     }
 
-    public void targetStarted(BuildEvent event) {
+    @Override
+	public void targetStarted(BuildEvent event) {
         // log nothing
     }
 
-    public void targetFinished(BuildEvent event) {
+    @Override
+	public void targetFinished(BuildEvent event) {
         // log nothing
     }
 
-    public void taskStarted(BuildEvent event) {
+    @Override
+	public void taskStarted(BuildEvent event) {
         // log nothing
     }
 
-    public void taskFinished(BuildEvent event) {
+    @Override
+	public void taskFinished(BuildEvent event) {
         // log nothing
     }
 
diff --git a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java
index 7155f4206..f5677d898 100644
--- a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java
+++ b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java
@@ -57,7 +57,7 @@ public class AntStructure extends Task {
      * The output file.
      * @param output the output file
      */
-    public void setOutput(File output) {
+    public void setOutput(final File output) {
         this.output = output;
     }
 
@@ -66,7 +66,7 @@ public class AntStructure extends Task {
      * @param p the printer to use.
      * @since Ant 1.7
      */
-    public void add(StructurePrinter p) {
+    public void add(final StructurePrinter p) {
         printer = p;
     }
 
@@ -75,7 +75,8 @@ public class AntStructure extends Task {
      *
      * @exception BuildException if the DTD cannot be written.
      */
-    public void execute() throws BuildException {
+    @Override
+	public void execute() throws BuildException {
 
         if (output == null) {
             throw new BuildException("output attribute is required", getLocation());
@@ -85,7 +86,7 @@ public class AntStructure extends Task {
         try {
             try {
                 out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF8"));
-            } catch (UnsupportedEncodingException ue) {
+            } catch (final UnsupportedEncodingException ue) {
                 /*
                  * Plain impossible with UTF8, see
                  * http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html
@@ -101,14 +102,14 @@ public class AntStructure extends Task {
 
             printer.printTargetDecl(out);
 
-            for (String typeName : getProject().getCopyOfDataTypeDefinitions()
+            for (final String typeName : getProject().getCopyOfDataTypeDefinitions()
                 .keySet()) {
                 printer.printElementDecl(
                                      out, getProject(), typeName,
                                      getProject().getDataTypeDefinitions().get(typeName));
             }
 
-            for (String tName : getProject().getCopyOfTaskDefinitions().keySet()) {
+            for (final String tName : getProject().getCopyOfTaskDefinitions().keySet()) {
                 printer.printElementDecl(out, getProject(), tName,
                                          getProject().getTaskDefinitions().get(tName));
             }
@@ -119,7 +120,7 @@ public class AntStructure extends Task {
                 throw new IOException("Encountered an error writing Ant"
                                       + " structure");
             }
-        } catch (IOException ioe) {
+        } catch (final IOException ioe) {
             throw new BuildException("Error writing "
                                      + output.getAbsolutePath(), ioe, getLocation());
         } finally {
@@ -136,7 +137,7 @@ public class AntStructure extends Task {
      * are called exactly once, {@link #printElementDecl} once for
      * each declared task and type.

*/ - public static interface StructurePrinter { + public interface StructurePrinter { /** * Prints the header of the generated output. * @@ -179,14 +180,16 @@ public class AntStructure extends Task { private static final String TASKS = "%tasks;"; private static final String TYPES = "%types;"; - private Hashtable visited = new Hashtable(); + private final Hashtable visited = new Hashtable(); - public void printTail(PrintWriter out) { + @Override + public void printTail(final PrintWriter out) { visited.clear(); } - public void printHead(PrintWriter out, Project p, Hashtable> tasks, - Hashtable> types) { + @Override + public void printHead(final PrintWriter out, final Project p, final Hashtable> tasks, + final Hashtable> types) { printHead(out, tasks.keys(), types.keys()); } @@ -197,14 +200,14 @@ public class AntStructure extends Task { *

Basically this prints the XML declaration, defines some * entities and the project element.

*/ - private void printHead(PrintWriter out, Enumeration tasks, - Enumeration types) { + private void printHead(final PrintWriter out, final Enumeration tasks, + final Enumeration types) { out.println(""); out.println(""); out.print(" element) { + @Override + public void printElementDecl(final PrintWriter out, final Project p, + final String name, final Class element) { if (visited.containsKey(name)) { return; @@ -287,7 +292,7 @@ public class AntStructure extends Task { IntrospectionHelper ih = null; try { ih = IntrospectionHelper.getHelper(p, element); - } catch (Throwable t) { + } catch (final Throwable t) { /* * TODO - failed to load the class properly. * @@ -309,7 +314,7 @@ public class AntStructure extends Task { return; } - Vector v = new Vector(); + final Vector v = new Vector(); if (ih.supportsCharacters()) { v.addElement("#PCDATA"); } @@ -348,14 +353,14 @@ public class AntStructure extends Task { e = ih.getAttributes(); while (e.hasMoreElements()) { - String attrName = (String) e.nextElement(); + final String attrName = e.nextElement(); if ("id".equals(attrName)) { continue; } sb.append(LINE_SEP).append(" ") .append(attrName).append(" "); - Class type = ih.getAttributeType(attrName); + final Class type = ih.getAttributeType(attrName); if (type.equals(java.lang.Boolean.class) || type.equals(java.lang.Boolean.TYPE)) { sb.append(BOOLEAN).append(" "); @@ -363,9 +368,9 @@ public class AntStructure extends Task { sb.append("IDREF "); } else if (EnumeratedAttribute.class.isAssignableFrom(type)) { try { - EnumeratedAttribute ea = + final EnumeratedAttribute ea = (EnumeratedAttribute) type.newInstance(); - String[] values = ea.getValues(); + final String[] values = ea.getValues(); if (values == null || values.length == 0 || !areNmtokens(values)) { @@ -380,15 +385,15 @@ public class AntStructure extends Task { } sb.append(") "); } - } catch (InstantiationException ie) { + } catch (final InstantiationException ie) { sb.append("CDATA "); - } catch (IllegalAccessException ie) { + } catch (final IllegalAccessException ie) { sb.append("CDATA "); } } else if (type.getSuperclass() != null && type.getSuperclass().getName().equals("java.lang.Enum")) { try { - Object[] values = (Object[]) type.getMethod("values", (Class[]) null) + final Object[] values = (Object[]) type.getMethod("values", (Class[]) null) .invoke(null, (Object[]) null); if (values.length == 0) { sb.append("CDATA "); @@ -403,7 +408,7 @@ public class AntStructure extends Task { } sb.append(") "); } - } catch (Exception x) { + } catch (final Exception x) { sb.append("CDATA "); } } else { @@ -416,7 +421,7 @@ public class AntStructure extends Task { final int count = v.size(); for (int i = 0; i < count; i++) { - String nestedName = (String) v.elementAt(i); + final String nestedName = v.elementAt(i); if (!"#PCDATA".equals(nestedName) && !TASKS.equals(nestedName) && !TYPES.equals(nestedName)) { @@ -430,10 +435,10 @@ public class AntStructure extends Task { * @param s the string to test * @return true if the string matches the XML-NMTOKEN */ - public static final boolean isNmtoken(String s) { + public static final boolean isNmtoken(final String s) { final int length = s.length(); for (int i = 0; i < length; i++) { - char c = s.charAt(i); + final char c = s.charAt(i); // TODO - we are committing CombiningChar and Extender here if (!Character.isLetterOrDigit(c) && c != '.' && c != '-' && c != '_' && c != ':') { @@ -451,7 +456,7 @@ public class AntStructure extends Task { * @param s the array of string to test * @return true if all the strings in the array math XML-NMTOKEN */ - public static final boolean areNmtokens(String[] s) { + public static final boolean areNmtokens(final String[] s) { for (int i = 0; i < s.length; i++) { if (!isNmtoken(s[i])) { return false; @@ -466,7 +471,7 @@ public class AntStructure extends Task { * @param s the string to test * @return true if the string matches the XML-NMTOKEN */ - protected boolean isNmtoken(String s) { + protected boolean isNmtoken(final String s) { return DTDPrinter.isNmtoken(s); } @@ -478,7 +483,7 @@ public class AntStructure extends Task { * @param s the array of string to test * @return true if all the strings in the array math XML-NMTOKEN */ - protected boolean areNmtokens(String[] s) { + protected boolean areNmtokens(final String[] s) { return DTDPrinter.areNmtokens(s); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/BindTargets.java b/src/main/org/apache/tools/ant/taskdefs/BindTargets.java index 203a98d0f..71034229c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/BindTargets.java +++ b/src/main/org/apache/tools/ant/taskdefs/BindTargets.java @@ -33,37 +33,38 @@ public class BindTargets extends Task { private String extensionPoint; - private List targets = new ArrayList(); + private final List targets = new ArrayList(); private OnMissingExtensionPoint onMissingExtensionPoint; - public void setExtensionPoint(String extensionPoint) { + public void setExtensionPoint(final String extensionPoint) { this.extensionPoint = extensionPoint; } - public void setOnMissingExtensionPoint(String onMissingExtensionPoint) { + public void setOnMissingExtensionPoint(final String onMissingExtensionPoint) { try { this.onMissingExtensionPoint = OnMissingExtensionPoint.valueOf(onMissingExtensionPoint); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { throw new BuildException("Invalid onMissingExtensionPoint: " + onMissingExtensionPoint); } } - public void setOnMissingExtensionPoint(OnMissingExtensionPoint onMissingExtensionPoint) { + public void setOnMissingExtensionPoint(final OnMissingExtensionPoint onMissingExtensionPoint) { this.onMissingExtensionPoint = onMissingExtensionPoint; } - public void setTargets(String target) { - String[] inputs = target.split(","); + public void setTargets(final String target) { + final String[] inputs = target.split(","); for (int i = 0; i < inputs.length; i++) { - String input = inputs[i].trim(); + final String input = inputs[i].trim(); if (input.length() > 0) { targets.add(input); } } } - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (extensionPoint == null) { throw new BuildException("extensionPoint required", getLocation()); } @@ -77,13 +78,13 @@ public class BindTargets extends Task { if (onMissingExtensionPoint == null) { onMissingExtensionPoint = OnMissingExtensionPoint.FAIL; } - ProjectHelper helper = (ProjectHelper) getProject().getReference( + final ProjectHelper helper = (ProjectHelper) getProject().getReference( ProjectHelper.PROJECTHELPER_REFERENCE); - for (Iterator itTarget = targets.iterator(); itTarget.hasNext();) { + for (final Iterator itTarget = targets.iterator(); itTarget.hasNext();) { helper.getExtensionStack().add( - new String[] { extensionPoint, itTarget.next(), - onMissingExtensionPoint.name() }); + new String[] {extensionPoint, itTarget.next(), + onMissingExtensionPoint.name()}); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/Componentdef.java b/src/main/org/apache/tools/ant/taskdefs/Componentdef.java index 36a0c0fda..1c5590cdf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Componentdef.java +++ b/src/main/org/apache/tools/ant/taskdefs/Componentdef.java @@ -23,7 +23,7 @@ package org.apache.tools.ant.taskdefs; *

Used in the current project two attributes are needed, the name that identifies * this component uniquely, and the full name of the class (including the packages) that * implements this component.

- * + * * @since Ant 1.8 * @ant.task category="internal" */ diff --git a/src/main/org/apache/tools/ant/taskdefs/Copy.java b/src/main/org/apache/tools/ant/taskdefs/Copy.java index e6f9cbd84..7fdfaf2f4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Copy.java +++ b/src/main/org/apache/tools/ant/taskdefs/Copy.java @@ -95,8 +95,8 @@ public class Copy extends Task { protected Mapper mapperElement = null; protected FileUtils fileUtils; //CheckStyle:VisibilityModifier ON - private Vector filterChains = new Vector(); - private Vector filterSets = new Vector(); + private final Vector filterChains = new Vector(); + private final Vector filterSets = new Vector(); private String inputEncoding = null; private String outputEncoding = null; private long granularity = 0; @@ -127,7 +127,7 @@ public class Copy extends Task { * Set a single source file to copy. * @param file the file to copy. */ - public void setFile(File file) { + public void setFile(final File file) { this.file = file; } @@ -135,7 +135,7 @@ public class Copy extends Task { * Set the destination file. * @param destFile the file to copy to. */ - public void setTofile(File destFile) { + public void setTofile(final File destFile) { this.destFile = destFile; } @@ -143,7 +143,7 @@ public class Copy extends Task { * Set the destination directory. * @param destDir the destination directory. */ - public void setTodir(File destDir) { + public void setTodir(final File destDir) { this.destDir = destDir; } @@ -152,7 +152,7 @@ public class Copy extends Task { * @return a filter chain object. */ public FilterChain createFilterChain() { - FilterChain filterChain = new FilterChain(); + final FilterChain filterChain = new FilterChain(); filterChains.addElement(filterChain); return filterChain; } @@ -162,7 +162,7 @@ public class Copy extends Task { * @return a filter set object. */ public FilterSet createFilterSet() { - FilterSet filterSet = new FilterSet(); + final FilterSet filterSet = new FilterSet(); filterSets.addElement(filterSet); return filterSet; } @@ -175,7 +175,8 @@ public class Copy extends Task { * replaced with setPreserveLastModified(boolean) to * consistently let the Introspection mechanism work. */ - public void setPreserveLastModified(String preserve) { + @Deprecated + public void setPreserveLastModified(final String preserve) { setPreserveLastModified(Project.toBoolean(preserve)); } @@ -183,7 +184,7 @@ public class Copy extends Task { * Give the copied files the same last modified time as the original files. * @param preserve if true preserve the modified time; default is false. */ - public void setPreserveLastModified(boolean preserve) { + public void setPreserveLastModified(final boolean preserve) { preserveLastModified = preserve; } @@ -220,7 +221,7 @@ public class Copy extends Task { * Set filtering mode. * @param filtering if true enable filtering; default is false. */ - public void setFiltering(boolean filtering) { + public void setFiltering(final boolean filtering) { this.filtering = filtering; } @@ -230,7 +231,7 @@ public class Copy extends Task { * even if the destination file(s) are younger than * the corresponding source file. Default is false. */ - public void setOverwrite(boolean overwrite) { + public void setOverwrite(final boolean overwrite) { this.forceOverwrite = overwrite; } @@ -241,7 +242,7 @@ public class Copy extends Task { * * @since Ant 1.8.2 */ - public void setForce(boolean f) { + public void setForce(final boolean f) { force = f; } @@ -263,7 +264,7 @@ public class Copy extends Task { * @param flatten if true flatten the destination directory. Default * is false. */ - public void setFlatten(boolean flatten) { + public void setFlatten(final boolean flatten) { this.flatten = flatten; } @@ -272,7 +273,7 @@ public class Copy extends Task { * @param verbose whether to output the names of copied files. * Default is false. */ - public void setVerbose(boolean verbose) { + public void setVerbose(final boolean verbose) { this.verbosity = verbose ? Project.MSG_INFO : Project.MSG_VERBOSE; } @@ -280,7 +281,7 @@ public class Copy extends Task { * Set whether to copy empty directories. * @param includeEmpty if true copy empty directories. Default is true. */ - public void setIncludeEmptyDirs(boolean includeEmpty) { + public void setIncludeEmptyDirs(final boolean includeEmpty) { this.includeEmpty = includeEmpty; } @@ -292,7 +293,7 @@ public class Copy extends Task { * whether or not to display error messages when a file or * directory does not exist. Default is false. */ - public void setQuiet(boolean quiet) { + public void setQuiet(final boolean quiet) { this.quiet = quiet; } @@ -307,7 +308,7 @@ public class Copy extends Task { * compatibility with earlier releases. * @since Ant 1.6 */ - public void setEnableMultipleMappings(boolean enableMultipleMappings) { + public void setEnableMultipleMappings(final boolean enableMultipleMappings) { this.enableMultipleMappings = enableMultipleMappings; } @@ -324,7 +325,7 @@ public class Copy extends Task { * to the output but keep going. Default is true. * @param failonerror true or false. */ - public void setFailOnError(boolean failonerror) { + public void setFailOnError(final boolean failonerror) { this.failonerror = failonerror; } @@ -332,7 +333,7 @@ public class Copy extends Task { * Add a set of files to copy. * @param set a set of files to copy. */ - public void addFileset(FileSet set) { + public void addFileset(final FileSet set) { add(set); } @@ -341,7 +342,7 @@ public class Copy extends Task { * @param res a resource collection to copy. * @since Ant 1.7 */ - public void add(ResourceCollection res) { + public void add(final ResourceCollection res) { rcs.add(res); } @@ -364,7 +365,7 @@ public class Copy extends Task { * @param fileNameMapper the mapper to add. * @since Ant 1.6.3 */ - public void add(FileNameMapper fileNameMapper) { + public void add(final FileNameMapper fileNameMapper) { createMapper().add(fileNameMapper); } @@ -373,7 +374,7 @@ public class Copy extends Task { * @param encoding the character encoding. * @since 1.32, Ant 1.5 */ - public void setEncoding(String encoding) { + public void setEncoding(final String encoding) { this.inputEncoding = encoding; if (outputEncoding == null) { outputEncoding = encoding; @@ -395,7 +396,7 @@ public class Copy extends Task { * @param encoding the output character encoding. * @since Ant 1.6 */ - public void setOutputEncoding(String encoding) { + public void setOutputEncoding(final String encoding) { this.outputEncoding = encoding; } @@ -419,7 +420,7 @@ public class Copy extends Task { * date. * @since Ant 1.6.2 */ - public void setGranularity(long granularity) { + public void setGranularity(final long granularity) { this.granularity = granularity; } @@ -427,21 +428,22 @@ public class Copy extends Task { * Perform the copy operation. * @exception BuildException if an error occurs. */ - public void execute() throws BuildException { - File savedFile = file; // may be altered in validateAttributes - File savedDestFile = destFile; - File savedDestDir = destDir; + @Override + public void execute() throws BuildException { + final File savedFile = file; // may be altered in validateAttributes + final File savedDestFile = destFile; + final File savedDestDir = destDir; ResourceCollection savedRc = null; if (file == null && destFile != null && rcs.size() == 1) { // will be removed in validateAttributes - savedRc = (ResourceCollection) rcs.elementAt(0); + savedRc = rcs.elementAt(0); } try { // make sure we don't have an illegal set of options try { validateAttributes(); - } catch (BuildException e) { + } catch (final BuildException e) { if (failonerror || !getMessage(e) .equals(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE)) { @@ -472,21 +474,21 @@ public class Copy extends Task { separate lists and then each list is handled in one go. */ - HashMap> filesByBasedir = new HashMap>(); - HashMap> dirsByBasedir = new HashMap>(); - HashSet baseDirs = new HashSet(); - ArrayList nonFileResources = new ArrayList(); + final HashMap> filesByBasedir = new HashMap>(); + final HashMap> dirsByBasedir = new HashMap>(); + final HashSet baseDirs = new HashSet(); + final ArrayList nonFileResources = new ArrayList(); final int size = rcs.size(); for (int i = 0; i < size; i++) { - ResourceCollection rc = rcs.elementAt(i); + final ResourceCollection rc = rcs.elementAt(i); // Step (1) - beware of the ZipFileSet if (rc instanceof FileSet && rc.isFilesystemOnly()) { - FileSet fs = (FileSet) rc; + final FileSet fs = (FileSet) rc; DirectoryScanner ds = null; try { ds = fs.getDirectoryScanner(getProject()); - } catch (BuildException e) { + } catch (final BuildException e) { if (failonerror || !getMessage(e).endsWith(DirectoryScanner .DOES_NOT_EXIST_POSTFIX)) { @@ -498,10 +500,10 @@ public class Copy extends Task { continue; } } - File fromDir = fs.getDir(getProject()); + final File fromDir = fs.getDir(getProject()); - String[] srcFiles = ds.getIncludedFiles(); - String[] srcDirs = ds.getIncludedDirectories(); + final String[] srcFiles = ds.getIncludedFiles(); + final String[] srcDirs = ds.getIncludedDirectories(); if (!flatten && mapperElement == null && ds.isEverythingIncluded() && !fs.hasPatterns()) { completeDirMap.put(fromDir, destDir); @@ -516,9 +518,9 @@ public class Copy extends Task { "Only FileSystem resources are supported."); } - for (Resource r : rc) { + for (final Resource r : rc) { if (!r.isExists()) { - String message = "Warning: Could not find resource " + final String message = "Warning: Could not find resource " + r.toLongString() + " to copy."; if (!failonerror) { if (!quiet) { @@ -532,9 +534,9 @@ public class Copy extends Task { File baseDir = NULL_FILE_PLACEHOLDER; String name = r.getName(); - FileProvider fp = r.as(FileProvider.class); + final FileProvider fp = r.as(FileProvider.class); if (fp != null) { - FileResource fr = ResourceUtils.asFileResource(fp); + final FileResource fr = ResourceUtils.asFileResource(fp); baseDir = getKeyFile(fr.getBaseDir()); if (fr.getBaseDir() == null) { name = fr.getFile().getAbsolutePath(); @@ -562,7 +564,7 @@ public class Copy extends Task { // do all the copy operations now... try { doFileOperations(); - } catch (BuildException e) { + } catch (final BuildException e) { if (!failonerror) { if (!quiet) { log("Warning: " + getMessage(e), Project.MSG_ERR); @@ -573,17 +575,17 @@ public class Copy extends Task { } if (nonFileResources.size() > 0 || singleResource != null) { - Resource[] nonFiles = - (Resource[]) nonFileResources.toArray(new Resource[nonFileResources.size()]); + final Resource[] nonFiles = + nonFileResources.toArray(new Resource[nonFileResources.size()]); // restrict to out-of-date resources - Map map = scan(nonFiles, destDir); + final Map map = scan(nonFiles, destDir); if (singleResource != null) { map.put(singleResource, - new String[] { destFile.getAbsolutePath() }); + new String[] {destFile.getAbsolutePath()}); } try { doResourceOperations(map); - } catch (BuildException e) { + } catch (final BuildException e) { if (!failonerror) { if (!quiet) { log("Warning: " + getMessage(e), Project.MSG_ERR); @@ -630,7 +632,7 @@ public class Copy extends Task { + " is up to date.", Project.MSG_VERBOSE); } } else { - String message = "Warning: Could not find file " + final String message = "Warning: Could not find file " + file.getAbsolutePath() + " to copy."; if (!failonerror) { if (!quiet) { @@ -644,11 +646,11 @@ public class Copy extends Task { } private void iterateOverBaseDirs( - HashSet baseDirs, HashMap> dirsByBasedir, HashMap> filesByBasedir) { + final HashSet baseDirs, final HashMap> dirsByBasedir, final HashMap> filesByBasedir) { - for (File f : baseDirs) { - List files = filesByBasedir.get(f); - List dirs = dirsByBasedir.get(f); + for (final File f : baseDirs) { + final List files = filesByBasedir.get(f); + final List dirs = dirsByBasedir.get(f); String[] srcFiles = new String[0]; if (files != null) { @@ -689,7 +691,7 @@ public class Copy extends Task { throw new BuildException( "Cannot concatenate multiple files into a single file."); } else { - ResourceCollection rc = (ResourceCollection) rcs.elementAt(0); + final ResourceCollection rc = rcs.elementAt(0); if (!rc.isFilesystemOnly() && !supportsNonFileResources()) { throw new BuildException("Only FileSystem resources are" + " supported."); @@ -697,8 +699,8 @@ public class Copy extends Task { if (rc.size() == 0) { throw new BuildException(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE); } else if (rc.size() == 1) { - Resource res = rc.iterator().next(); - FileProvider r = res.as(FileProvider.class); + final Resource res = rc.iterator().next(); + final FileProvider r = res.as(FileProvider.class); if (file == null) { if (r != null) { file = r.getFile(); @@ -730,9 +732,9 @@ public class Copy extends Task { * @param files A list of files to copy. * @param dirs A list of directories to copy. */ - protected void scan(File fromDir, File toDir, String[] files, - String[] dirs) { - FileNameMapper mapper = getMapper(); + protected void scan(final File fromDir, final File toDir, final String[] files, + final String[] dirs) { + final FileNameMapper mapper = getMapper(); buildMap(fromDir, toDir, files, mapper, fileCopyMap); if (includeEmpty) { @@ -752,7 +754,7 @@ public class Copy extends Task { * * @since Ant 1.7 */ - protected Map scan(Resource[] fromResources, File toDir) { + protected Map scan(final Resource[] fromResources, final File toDir) { return buildMap(fromResources, toDir, getMapper()); } @@ -765,11 +767,11 @@ public class Copy extends Task { * @param mapper a FileNameMapper value. * @param map a map of source file to array of destination files. */ - protected void buildMap(File fromDir, File toDir, String[] names, - FileNameMapper mapper, Hashtable map) { + protected void buildMap(final File fromDir, final File toDir, final String[] names, + final FileNameMapper mapper, final Hashtable map) { String[] toCopy = null; if (forceOverwrite) { - Vector v = new Vector(); + final Vector v = new Vector(); for (int i = 0; i < names.length; i++) { if (mapper.mapFileName(names[i]) != null) { v.addElement(names[i]); @@ -778,12 +780,12 @@ public class Copy extends Task { toCopy = new String[v.size()]; v.copyInto(toCopy); } else { - SourceFileScanner ds = new SourceFileScanner(this); + final SourceFileScanner ds = new SourceFileScanner(this); toCopy = ds.restrict(names, fromDir, toDir, mapper, granularity); } for (int i = 0; i < toCopy.length; i++) { - File src = new File(fromDir, toCopy[i]); - String[] mappedFiles = mapper.mapFileName(toCopy[i]); + final File src = new File(fromDir, toCopy[i]); + final String[] mappedFiles = mapper.mapFileName(toCopy[i]); if (!enableMultipleMappings) { map.put(src.getAbsolutePath(), @@ -807,12 +809,12 @@ public class Copy extends Task { * @return a map of source resource to array of destination files. * @since Ant 1.7 */ - protected Map buildMap(Resource[] fromResources, final File toDir, - FileNameMapper mapper) { - HashMap map = new HashMap(); + protected Map buildMap(final Resource[] fromResources, final File toDir, + final FileNameMapper mapper) { + final HashMap map = new HashMap(); Resource[] toCopy = null; if (forceOverwrite) { - Vector v = new Vector(); + final Vector v = new Vector(); for (int i = 0; i < fromResources.length; i++) { if (mapper.mapFileName(fromResources[i].getName()) != null) { v.addElement(fromResources[i]); @@ -825,14 +827,15 @@ public class Copy extends Task { ResourceUtils.selectOutOfDateSources(this, fromResources, mapper, new ResourceFactory() { - public Resource getResource(String name) { + @Override + public Resource getResource(final String name) { return new FileResource(toDir, name); } }, granularity); } for (int i = 0; i < toCopy.length; i++) { - String[] mappedFiles = mapper.mapFileName(toCopy[i].getName()); + final String[] mappedFiles = mapper.mapFileName(toCopy[i].getName()); for (int j = 0; j < mappedFiles.length; j++) { if (mappedFiles[j] == null) { throw new BuildException("Can't copy a resource without a" @@ -865,12 +868,12 @@ public class Copy extends Task { + " file" + (fileCopyMap.size() == 1 ? "" : "s") + " to " + destDir.getAbsolutePath()); - for (Map.Entry e : fileCopyMap.entrySet()) { - String fromFile = e.getKey(); - String[] toFiles = e.getValue(); + 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++) { - String toFile = toFiles[i]; + final String toFile = toFiles[i]; if (fromFile.equals(toFile)) { log("Skipping self-copy of " + fromFile, verbosity); @@ -879,13 +882,13 @@ public class Copy extends Task { try { log("Copying " + fromFile + " to " + toFile, verbosity); - FilterSetCollection executionFilters = + final FilterSetCollection executionFilters = new FilterSetCollection(); if (filtering) { executionFilters .addFilterSet(getProject().getGlobalFilterSet()); } - for (FilterSet filterSet : filterSets) { + for (final FilterSet filterSet : filterSets) { executionFilters.addFilterSet(filterSet); } fileUtils.copyFile(new File(fromFile), new File(toFile), @@ -895,10 +898,10 @@ public class Copy extends Task { /* append: */ false, inputEncoding, outputEncoding, getProject(), getForce()); - } catch (IOException ioe) { + } catch (final IOException ioe) { String msg = "Failed to copy " + fromFile + " to " + toFile + " due to " + getDueTo(ioe); - File targetFile = new File(toFile); + final File targetFile = new File(toFile); if (!(ioe instanceof ResourceUtils.ReadOnlyTargetFileException) && targetFile.exists() && !targetFile.delete()) { @@ -914,9 +917,9 @@ public class Copy extends Task { } if (includeEmpty) { int createCount = 0; - for (String[] dirs : dirCopyMap.values()) { + for (final String[] dirs : dirCopyMap.values()) { for (int i = 0; i < dirs.length; i++) { - File d = new File(dirs[i]); + final File d = new File(dirs[i]); if (!d.exists()) { if (!(d.mkdirs() || d.isDirectory())) { log("Unable to create directory " @@ -945,25 +948,25 @@ public class Copy extends Task { * @param map a map of source resource to array of destination files. * @since Ant 1.7 */ - protected void doResourceOperations(Map map) { + protected void doResourceOperations(final Map map) { if (map.size() > 0) { log("Copying " + map.size() + " resource" + (map.size() == 1 ? "" : "s") + " to " + destDir.getAbsolutePath()); - for (Map.Entry e : map.entrySet()) { - Resource fromResource = e.getKey(); - for (String toFile : e.getValue()) { + for (final Map.Entry e : map.entrySet()) { + final Resource fromResource = e.getKey(); + for (final String toFile : e.getValue()) { try { log("Copying " + fromResource + " to " + toFile, verbosity); - FilterSetCollection executionFilters = new FilterSetCollection(); + final FilterSetCollection executionFilters = new FilterSetCollection(); if (filtering) { executionFilters .addFilterSet(getProject().getGlobalFilterSet()); } - for (FilterSet filterSet : filterSets) { + for (final FilterSet filterSet : filterSets) { executionFilters.addFilterSet(filterSet); } ResourceUtils.copyResource(fromResource, @@ -978,11 +981,11 @@ public class Copy extends Task { outputEncoding, getProject(), getForce()); - } catch (IOException ioe) { + } catch (final IOException ioe) { String msg = "Failed to copy " + fromResource + " to " + toFile + " due to " + getDueTo(ioe); - File targetFile = new File(toFile); + final File targetFile = new File(toFile); if (!(ioe instanceof ResourceUtils.ReadOnlyTargetFileException) && targetFile.exists() && !targetFile.delete()) { @@ -1020,7 +1023,7 @@ public class Copy extends Task { * Adds the given strings to a list contained in the given map. * The file is the key into the map. */ - private static void add(File baseDir, String[] names, Map> m) { + private static void add(File baseDir, final String[] names, final Map> m) { if (names != null) { baseDir = getKeyFile(baseDir); List l = m.get(baseDir); @@ -1036,7 +1039,7 @@ public class Copy extends Task { * Adds the given string to a list contained in the given map. * The file is the key into the map. */ - private static void add(File baseDir, String name, Map> m) { + private static void add(final File baseDir, final String name, final Map> m) { if (name != null) { add(baseDir, new String[] {name}, m); } @@ -1045,7 +1048,7 @@ public class Copy extends Task { /** * Either returns its argument or a plaeholder if the argument is null. */ - private static File getKeyFile(File f) { + private static File getKeyFile(final File f) { return f == null ? NULL_FILE_PLACEHOLDER : f; } @@ -1071,7 +1074,7 @@ public class Copy extends Task { * @return ex.getMessage() if ex.getMessage() is not null * otherwise return ex.toString() */ - private String getMessage(Exception ex) { + private String getMessage(final Exception ex) { return ex.getMessage() == null ? ex.toString() : ex.getMessage(); } @@ -1082,9 +1085,9 @@ public class Copy extends Task { * output the message * if the exception is MalformedInput add a little note. */ - private String getDueTo(Exception ex) { - boolean baseIOException = ex.getClass() == IOException.class; - StringBuffer message = new StringBuffer(); + private String getDueTo(final Exception ex) { + final boolean baseIOException = ex.getClass() == IOException.class; + final StringBuffer message = new StringBuffer(); if (!baseIOException || ex.getMessage() == null) { message.append(ex.getClass().getName()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/EchoXML.java b/src/main/org/apache/tools/ant/taskdefs/EchoXML.java index 3aac33abe..16855bfdb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/EchoXML.java +++ b/src/main/org/apache/tools/ant/taskdefs/EchoXML.java @@ -65,7 +65,7 @@ public class EchoXML extends XMLFragment { public void setNamespacePolicy(NamespacePolicy n) { namespacePolicy = n; } - + /** * Set whether to append the output file. * @param b boolean append flag. @@ -115,7 +115,8 @@ public class EchoXML extends XMLFragment { setValue(s); } /** {@inheritDoc}. */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {IGNORE, ELEMENTS, ALL}; } diff --git a/src/main/org/apache/tools/ant/taskdefs/Get.java b/src/main/org/apache/tools/ant/taskdefs/Get.java index b3e40618b..de0792170 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Get.java +++ b/src/main/org/apache/tools/ant/taskdefs/Get.java @@ -84,7 +84,7 @@ public class Get extends Task { private boolean skipExisting = false; private boolean httpUseCaches = true; // on by default private Mapper mapperElement = null; - private String userAgent = + private String userAgent = System.getProperty(MagicNames.HTTP_AGENT_PROPERTY, DEFAULT_AGENT_PREFIX + "/" + Main.getShortAntVersion()); @@ -94,7 +94,8 @@ public class Get extends Task { * * @exception BuildException Thrown in unrecoverable error. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { checkAttributes(); for (Resource r : sources) { @@ -166,7 +167,8 @@ public class Get extends Task { * is false. * @deprecated only gets the first configured resource */ - public boolean doGet(int logLevel, DownloadProgress progress) + @Deprecated + public boolean doGet(int logLevel, DownloadProgress progress) throws IOException { checkAttributes(); for (Resource r : sources) { @@ -430,7 +432,7 @@ public class Get extends Task { public void setSkipExisting(boolean s) { this.skipExisting = s; } - + /** * HTTP connections only - set the user-agent to be used * when communicating with remote server. if null, then @@ -456,7 +458,7 @@ public class Get extends Task { public void setHttpUseCaches(boolean httpUseCache) { this.httpUseCaches = httpUseCache; } - + /** * Define the mapper to map source to destination files. * @return a mapper to be configured. @@ -518,7 +520,8 @@ public class Get extends Task { /** * begin a download */ - public void beginDownload() { + @Override + public void beginDownload() { } @@ -526,13 +529,15 @@ public class Get extends Task { * tick handler * */ - public void onTick() { + @Override + public void onTick() { } /** * end a download */ - public void endDownload() { + @Override + public void endDownload() { } } @@ -557,7 +562,8 @@ public class Get extends Task { /** * begin a download */ - public void beginDownload() { + @Override + public void beginDownload() { dots = 0; } @@ -565,7 +571,8 @@ public class Get extends Task { * tick handler * */ - public void onTick() { + @Override + public void onTick() { out.print("."); if (dots++ > DOTS_PER_LINE) { out.flush(); @@ -576,7 +583,8 @@ public class Get extends Task { /** * end a download */ - public void endDownload() { + @Override + public void endDownload() { out.println(); out.flush(); } @@ -599,7 +607,7 @@ public class Get extends Task { private URLConnection connection; private int redirections = 0; private String userAgent = null; - + GetThread(URL source, File dest, boolean h, long t, DownloadProgress p, int l, String userAgent) { this.source = source; @@ -611,7 +619,8 @@ public class Get extends Task { this.userAgent = userAgent; } - public void run() { + @Override + public void run() { try { success = get(); } catch (IOException ioex) { @@ -684,7 +693,7 @@ public class Get extends Task { } // Set the user agent connection.addRequestProperty("User-Agent", this.userAgent); - + // prepare Java 1.1 style credentials if (uname != null || pword != null) { String up = uname + ":" + pword; @@ -762,7 +771,7 @@ public class Get extends Task { } private boolean isMoved(int responseCode) { - return responseCode == HttpURLConnection.HTTP_MOVED_PERM || + return responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == HTTP_MOVED_TEMP; diff --git a/src/main/org/apache/tools/ant/taskdefs/Input.java b/src/main/org/apache/tools/ant/taskdefs/Input.java index 2250fe7d9..a1a0a2269 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Input.java +++ b/src/main/org/apache/tools/ant/taskdefs/Input.java @@ -56,7 +56,7 @@ public class Input extends Task { * this allows the use of a custom inputhandler. * @param refid the String refid. */ - public void setRefid(String refid) { + public void setRefid(final String refid) { this.refid = refid; } /** @@ -70,7 +70,7 @@ public class Input extends Task { * Set the InputHandler classname. * @param classname the String classname. */ - public void setClassname(String classname) { + public void setClassname(final String classname) { this.classname = classname; } /** @@ -84,7 +84,7 @@ public class Input extends Task { * Set the handler type. * @param type a HandlerType. */ - public void setType(HandlerType type) { + public void setType(final HandlerType type) { this.type = type; } /** @@ -101,7 +101,7 @@ public class Input extends Task { if (refid != null) { try { return (InputHandler) (getProject().getReference(refid)); - } catch (ClassCastException e) { + } catch (final ClassCastException e) { throw new BuildException( refid + " does not denote an InputHandler", e); } @@ -120,16 +120,17 @@ public class Input extends Task { * "default", "propertyfile", "greedy", "secure" (since Ant 1.8). */ public static class HandlerType extends EnumeratedAttribute { - private static final String[] VALUES = { "default", "propertyfile", "greedy", "secure" }; + private static final String[] VALUES = {"default", "propertyfile", "greedy", "secure"}; private static final InputHandler[] HANDLERS - = { new DefaultInputHandler(), + = {new DefaultInputHandler(), new PropertyFileInputHandler(), new GreedyInputHandler(), - new SecureInputHandler() }; + new SecureInputHandler()}; /** {@inheritDoc} */ - public String[] getValues() { + @Override + public String[] getValues() { return VALUES; } private InputHandler getInputHandler() { @@ -152,7 +153,7 @@ public class Input extends Task { * * @param validargs A comma separated String defining valid input args. */ - public void setValidargs (String validargs) { + public void setValidargs (final String validargs) { this.validargs = validargs; } @@ -163,7 +164,7 @@ public class Input extends Task { * * @param addproperty Name for the property to be created from input */ - public void setAddproperty (String addproperty) { + public void setAddproperty (final String addproperty) { this.addproperty = addproperty; } @@ -171,7 +172,7 @@ public class Input extends Task { * Sets the Message which gets displayed to the user during the build run. * @param message The message to be displayed. */ - public void setMessage (String message) { + public void setMessage (final String message) { this.message = message; messageAttribute = true; } @@ -183,7 +184,7 @@ public class Input extends Task { * @param defaultvalue Default value for the property if no input * is received */ - public void setDefaultvalue (String defaultvalue) { + public void setDefaultvalue (final String defaultvalue) { this.defaultvalue = defaultvalue; } @@ -191,7 +192,7 @@ public class Input extends Task { * Set a multiline message. * @param msg The message to be displayed. */ - public void addText(String msg) { + public void addText(final String msg) { if (messageAttribute && "".equals(msg.trim())) { return; } @@ -208,7 +209,8 @@ public class Input extends Task { * Actual method executed by ant. * @throws BuildException on error */ - public void execute () throws BuildException { + @Override + public void execute () throws BuildException { if (addproperty != null && getProject().getProperty(addproperty) != null) { log("skipping " + getTaskName() + " as property " + addproperty @@ -218,14 +220,14 @@ public class Input extends Task { InputRequest request = null; if (validargs != null) { - Vector accept = StringUtils.split(validargs, ','); + final Vector accept = StringUtils.split(validargs, ','); request = new MultipleChoiceInputRequest(message, accept); } else { request = new InputRequest(message); } request.setDefaultValue(defaultvalue); - InputHandler h = handler == null + final InputHandler h = handler == null ? getProject().getInputHandler() : handler.getInputHandler(); diff --git a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java index d65ddb459..2ca6e22ab 100644 --- a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java @@ -349,7 +349,7 @@ public abstract class JDBCTask extends Task { info.put("password", getPassword()); for (Iterator props = connectionProperties.iterator(); - props.hasNext(); ) { + props.hasNext();) { Property p = props.next(); String name = p.getName(); String value = p.getValue(); @@ -407,7 +407,7 @@ public abstract class JDBCTask extends Task { // in most cases. synchronized (LOADER_MAP) { if (caching) { - loader = (AntClassLoader) LOADER_MAP.get(driver); + loader = LOADER_MAP.get(driver); } if (loader == null) { log("Loading " + driver diff --git a/src/main/org/apache/tools/ant/taskdefs/Javac.java b/src/main/org/apache/tools/ant/taskdefs/Javac.java index 75880ca2b..a564f760f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Javac.java +++ b/src/main/org/apache/tools/ant/taskdefs/Javac.java @@ -180,7 +180,7 @@ public class Javac extends MatchingTask { * * @param v Value to assign to debugLevel. */ - public void setDebugLevel(String v) { + public void setDebugLevel(final String v) { this.debugLevel = v; } @@ -207,7 +207,7 @@ public class Javac extends MatchingTask { * * @param v Value to assign to source. */ - public void setSource(String v) { + public void setSource(final String v) { this.source = v; } @@ -237,7 +237,7 @@ public class Javac extends MatchingTask { * Set the source directories to find the source Java files. * @param srcDir the source directories as a path */ - public void setSrcdir(Path srcDir) { + public void setSrcdir(final Path srcDir) { if (src == null) { src = srcDir; } else { @@ -258,7 +258,7 @@ public class Javac extends MatchingTask { * files should be compiled. * @param destDir the destination director */ - public void setDestdir(File destDir) { + public void setDestdir(final File destDir) { this.destDir = destDir; } @@ -275,7 +275,7 @@ public class Javac extends MatchingTask { * Set the sourcepath to be used for this compilation. * @param sourcepath the source path */ - public void setSourcepath(Path sourcepath) { + public void setSourcepath(final Path sourcepath) { if (compileSourcepath == null) { compileSourcepath = sourcepath; } else { @@ -306,7 +306,7 @@ public class Javac extends MatchingTask { * Adds a reference to a source path defined elsewhere. * @param r a reference to a source path */ - public void setSourcepathRef(Reference r) { + public void setSourcepathRef(final Reference r) { createSourcepath().setRefid(r); } @@ -315,7 +315,7 @@ public class Javac extends MatchingTask { * * @param classpath an Ant Path object containing the compilation classpath. */ - public void setClasspath(Path classpath) { + public void setClasspath(final Path classpath) { if (compileClasspath == null) { compileClasspath = classpath; } else { @@ -346,7 +346,7 @@ public class Javac extends MatchingTask { * Adds a reference to a classpath defined elsewhere. * @param r a reference to a classpath */ - public void setClasspathRef(Reference r) { + public void setClasspathRef(final Reference r) { createClasspath().setRefid(r); } @@ -356,7 +356,7 @@ public class Javac extends MatchingTask { * @param bootclasspath a path to use as a boot class path (may be more * than one) */ - public void setBootclasspath(Path bootclasspath) { + public void setBootclasspath(final Path bootclasspath) { if (this.bootclasspath == null) { this.bootclasspath = bootclasspath; } else { @@ -388,7 +388,7 @@ public class Javac extends MatchingTask { * Adds a reference to a classpath defined elsewhere. * @param r a reference to a classpath */ - public void setBootClasspathRef(Reference r) { + public void setBootClasspathRef(final Reference r) { createBootclasspath().setRefid(r); } @@ -397,7 +397,7 @@ public class Javac extends MatchingTask { * compilation. * @param extdirs a path */ - public void setExtdirs(Path extdirs) { + public void setExtdirs(final Path extdirs) { if (this.extdirs == null) { this.extdirs = extdirs; } else { @@ -429,7 +429,7 @@ public class Javac extends MatchingTask { * If true, list the source files being handed off to the compiler. * @param list if true list the source files */ - public void setListfiles(boolean list) { + public void setListfiles(final boolean list) { listFiles = list; } @@ -446,7 +446,7 @@ public class Javac extends MatchingTask { * even if there are compilation errors; defaults to true. * @param fail if true halt the build on failure */ - public void setFailonerror(boolean fail) { + public void setFailonerror(final boolean fail) { failOnError = fail; } @@ -454,7 +454,7 @@ public class Javac extends MatchingTask { * @ant.attribute ignore="true" * @param proceed inverse of failoferror */ - public void setProceed(boolean proceed) { + public void setProceed(final boolean proceed) { failOnError = !proceed; } @@ -471,7 +471,7 @@ public class Javac extends MatchingTask { * compiled with deprecation information; defaults to off. * @param deprecation if true turn on deprecation information */ - public void setDeprecation(boolean deprecation) { + public void setDeprecation(final boolean deprecation) { this.deprecation = deprecation; } @@ -490,7 +490,7 @@ public class Javac extends MatchingTask { * (Examples: 83886080, 81920k, or 80m) * @param memoryInitialSize string to pass to VM */ - public void setMemoryInitialSize(String memoryInitialSize) { + public void setMemoryInitialSize(final String memoryInitialSize) { this.memoryInitialSize = memoryInitialSize; } @@ -509,7 +509,7 @@ public class Javac extends MatchingTask { * (Examples: 83886080, 81920k, or 80m) * @param memoryMaximumSize string to pass to VM */ - public void setMemoryMaximumSize(String memoryMaximumSize) { + public void setMemoryMaximumSize(final String memoryMaximumSize) { this.memoryMaximumSize = memoryMaximumSize; } @@ -525,7 +525,7 @@ public class Javac extends MatchingTask { * Set the Java source file encoding name. * @param encoding the source file encoding */ - public void setEncoding(String encoding) { + public void setEncoding(final String encoding) { this.encoding = encoding; } @@ -542,7 +542,7 @@ public class Javac extends MatchingTask { * with debug information; defaults to off. * @param debug if true compile with debug information */ - public void setDebug(boolean debug) { + public void setDebug(final boolean debug) { this.debug = debug; } @@ -558,7 +558,7 @@ public class Javac extends MatchingTask { * If true, compiles with optimization enabled. * @param optimize if true compile with optimization enabled */ - public void setOptimize(boolean optimize) { + public void setOptimize(final boolean optimize) { this.optimize = optimize; } @@ -575,7 +575,7 @@ public class Javac extends MatchingTask { * that support this (jikes and classic). * @param depend if true enable dependency-tracking */ - public void setDepend(boolean depend) { + public void setDepend(final boolean depend) { this.depend = depend; } @@ -591,7 +591,7 @@ public class Javac extends MatchingTask { * If true, asks the compiler for verbose output. * @param verbose if true, asks the compiler for verbose output */ - public void setVerbose(boolean verbose) { + public void setVerbose(final boolean verbose) { this.verbose = verbose; } @@ -609,7 +609,7 @@ public class Javac extends MatchingTask { * "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "5", "6", "7" and "8". * @param target the target VM */ - public void setTarget(String target) { + public void setTarget(final String target) { this.targetAttribute = target; } @@ -627,7 +627,7 @@ public class Javac extends MatchingTask { * If true, includes Ant's own classpath in the classpath. * @param include if true, includes Ant's own classpath in the classpath */ - public void setIncludeantruntime(boolean include) { + public void setIncludeantruntime(final boolean include) { includeAntRuntime = Boolean.valueOf(include); } @@ -643,7 +643,7 @@ public class Javac extends MatchingTask { * If true, includes the Java runtime libraries in the classpath. * @param include if true, includes the Java runtime libraries in the classpath */ - public void setIncludejavaruntime(boolean include) { + public void setIncludejavaruntime(final boolean include) { includeJavaRuntime = include; } @@ -661,7 +661,7 @@ public class Javac extends MatchingTask { * * @param f "true|false|on|off|yes|no" */ - public void setFork(boolean f) { + public void setFork(final boolean f) { fork = f; } @@ -672,7 +672,7 @@ public class Javac extends MatchingTask { * as the compiler.

* @param forkExec the name of the executable */ - public void setExecutable(String forkExec) { + public void setExecutable(final String forkExec) { forkedExecutable = forkExec; } @@ -719,7 +719,7 @@ public class Javac extends MatchingTask { * If true, enables the -nowarn option. * @param flag if true, enable the -nowarn option */ - public void setNowarn(boolean flag) { + public void setNowarn(final boolean flag) { this.nowarn = flag; } @@ -736,7 +736,7 @@ public class Javac extends MatchingTask { * @return a ImplementationSpecificArgument to be configured */ public ImplementationSpecificArgument createCompilerArg() { - ImplementationSpecificArgument arg = + final ImplementationSpecificArgument arg = new ImplementationSpecificArgument(); facade.addImplementationArgument(arg); return arg; @@ -747,15 +747,15 @@ public class Javac extends MatchingTask { * @return array of command line arguments, guaranteed to be non-null. */ public String[] getCurrentCompilerArgs() { - String chosen = facade.getExplicitChoice(); + final String chosen = facade.getExplicitChoice(); try { // make sure facade knows about magic properties and fork setting - String appliedCompiler = getCompiler(); + final String appliedCompiler = getCompiler(); facade.setImplementation(appliedCompiler); String[] result = facade.getArgs(); - String altCompilerName = getAltCompilerName(facade.getImplementation()); + final String altCompilerName = getAltCompilerName(facade.getImplementation()); if (result.length == 0 && altCompilerName != null) { facade.setImplementation(altCompilerName); @@ -769,7 +769,7 @@ public class Javac extends MatchingTask { } } - private String getAltCompilerName(String anImplementation) { + private String getAltCompilerName(final String anImplementation) { if (JAVAC19.equalsIgnoreCase(anImplementation) || JAVAC18.equalsIgnoreCase(anImplementation) || JAVAC17.equalsIgnoreCase(anImplementation) @@ -784,7 +784,7 @@ public class Javac extends MatchingTask { return CLASSIC; } if (MODERN.equalsIgnoreCase(anImplementation)) { - String nextSelected = assumedJavaVersion(); + final String nextSelected = assumedJavaVersion(); if (JAVAC19.equalsIgnoreCase(nextSelected) || JAVAC18.equalsIgnoreCase(nextSelected) || JAVAC17.equalsIgnoreCase(nextSelected) @@ -810,7 +810,7 @@ public class Javac extends MatchingTask { * @since Ant 1.6 * @param tmpDir the temporary directory */ - public void setTempdir(File tmpDir) { + public void setTempdir(final File tmpDir) { this.tmpDir = tmpDir; } @@ -831,7 +831,7 @@ public class Javac extends MatchingTask { * @param updatedProperty the property name to use. * @since Ant 1.7.1. */ - public void setUpdatedProperty(String updatedProperty) { + public void setUpdatedProperty(final String updatedProperty) { this.updatedProperty = updatedProperty; } @@ -842,7 +842,7 @@ public class Javac extends MatchingTask { * @param errorProperty the property name to use. * @since Ant 1.7.1. */ - public void setErrorProperty(String errorProperty) { + public void setErrorProperty(final String errorProperty) { this.errorProperty = errorProperty; } @@ -853,7 +853,7 @@ public class Javac extends MatchingTask { * The default value is "true". * @param includeDestClasses the value to use. */ - public void setIncludeDestClasses(boolean includeDestClasses) { + public void setIncludeDestClasses(final boolean includeDestClasses) { this.includeDestClasses = includeDestClasses; } @@ -888,7 +888,7 @@ public class Javac extends MatchingTask { * Set the compiler adapter explicitly. * @since Ant 1.8.0 */ - public void add(CompilerAdapter adapter) { + public void add(final CompilerAdapter adapter) { if (nestedAdapter != null) { throw new BuildException("Can't have more than one compiler" + " adapter"); @@ -903,7 +903,7 @@ public class Javac extends MatchingTask { * * @since Ant 1.8.3 */ - public void setCreateMissingPackageInfoClass(boolean b) { + public void setCreateMissingPackageInfoClass(final boolean b) { createMissingPackageInfoClass = b; } @@ -911,23 +911,24 @@ public class Javac extends MatchingTask { * Executes the task. * @exception BuildException if an error occurs */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { checkParameters(); resetFileLists(); // scan source directories and dest directory to build up // compile lists - String[] list = src.list(); + final String[] list = src.list(); for (int i = 0; i < list.length; i++) { - File srcDir = getProject().resolveFile(list[i]); + final File srcDir = getProject().resolveFile(list[i]); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation()); } - DirectoryScanner ds = this.getDirectoryScanner(srcDir); - String[] files = ds.getIncludedFiles(); + final DirectoryScanner ds = this.getDirectoryScanner(srcDir); + final String[] files = ds.getIncludedFiles(); scanDir(srcDir, destDir != null ? destDir : srcDir, files); } @@ -956,19 +957,19 @@ public class Javac extends MatchingTask { * @param destDir The destination directory * @param files An array of filenames */ - protected void scanDir(File srcDir, File destDir, String[] files) { - GlobPatternMapper m = new GlobPatternMapper(); - String[] extensions = findSupportedFileExtensions(); + 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]); m.setTo("*.class"); - SourceFileScanner sfs = new SourceFileScanner(this); - File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); + final SourceFileScanner sfs = new SourceFileScanner(this); + final File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); if (newFiles.length > 0) { lookForPackageInfos(srcDir, newFiles); - File[] newCompileList + final File[] newCompileList = new File[compileList.length + newFiles.length]; System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); @@ -980,8 +981,8 @@ public class Javac extends MatchingTask { } private String[] findSupportedFileExtensions() { - String compilerImpl = getCompiler(); - CompilerAdapter adapter = + final String compilerImpl = getCompiler(); + final CompilerAdapter adapter = nestedAdapter != null ? nestedAdapter : CompilerAdapterFactory.getCompiler(compilerImpl, this, createCompilerClasspath()); @@ -992,7 +993,7 @@ public class Javac extends MatchingTask { } if (extensions == null) { - extensions = new String[] { "java" }; + extensions = new String[] {"java"}; } // now process the extensions to ensure that they are the @@ -1021,7 +1022,7 @@ public class Javac extends MatchingTask { * "javac1.1", "javac1.2", "javac1.3", "javac1.4", "javac1.5", * "javac1.6", "javac1.7", "javac1.8" or "javac1.9". */ - protected boolean isJdkCompiler(String compilerImpl) { + protected boolean isJdkCompiler(final String compilerImpl) { return MODERN.equals(compilerImpl) || CLASSIC.equals(compilerImpl) || JAVAC19.equals(compilerImpl) @@ -1047,7 +1048,7 @@ public class Javac extends MatchingTask { * @param compiler the name of the compiler * @since Ant 1.5 */ - public void setCompiler(String compiler) { + public void setCompiler(final String compiler) { facade.setImplementation(compiler); } @@ -1133,7 +1134,7 @@ public class Javac extends MatchingTask { * @since Ant 1.5 */ protected void compile() { - String compilerImpl = getCompiler(); + final String compilerImpl = getCompiler(); if (compileList.length > 0) { log("Compiling " + compileList.length + " source file" @@ -1142,12 +1143,12 @@ public class Javac extends MatchingTask { if (listFiles) { for (int i = 0; i < compileList.length; i++) { - String filename = compileList[i].getAbsolutePath(); + final String filename = compileList[i].getAbsolutePath(); log(filename); } } - CompilerAdapter adapter = + final CompilerAdapter adapter = nestedAdapter != null ? nestedAdapter : CompilerAdapterFactory.getCompiler(compilerImpl, this, createCompilerClasspath()); @@ -1164,7 +1165,7 @@ public class Javac extends MatchingTask { ? destDir : getProject() .resolveFile(src.list()[0])); - } catch (IOException x) { + } catch (final IOException x) { // Should this be made a nonfatal warning? throw new BuildException(x, getLocation()); } @@ -1196,25 +1197,25 @@ public class Javac extends MatchingTask { /** * @param impl the name of the compiler */ - public void setCompiler(String impl) { + public void setCompiler(final String impl) { super.setImplementation(impl); } } - private void lookForPackageInfos(File srcDir, File[] newFiles) { + private void lookForPackageInfos(final File srcDir, final File[] newFiles) { for (int i = 0; i < newFiles.length; i++) { - File f = newFiles[i]; + final File f = newFiles[i]; if (!f.getName().equals("package-info.java")) { continue; } - String path = FILE_UTILS.removeLeadingPath(srcDir, f). + final String path = FILE_UTILS.removeLeadingPath(srcDir, f). replace(File.separatorChar, '/'); - String suffix = "/package-info.java"; + final String suffix = "/package-info.java"; if (!path.endsWith(suffix)) { log("anomalous package-info.java path: " + path, Project.MSG_WARN); continue; } - String pkg = path.substring(0, path.length() - suffix.length()); + final String pkg = path.substring(0, path.length() - suffix.length()); packageInfos.put(pkg, new Long(f.lastModified())); } } @@ -1224,22 +1225,22 @@ public class Javac extends MatchingTask { * Otherwise this task's up-to-date tracking mechanisms do not work. * @see Bug #43114 */ - private void generateMissingPackageInfoClasses(File dest) throws IOException { - for (Entry entry : packageInfos.entrySet()) { - String pkg = entry.getKey(); - Long sourceLastMod = entry.getValue(); - File pkgBinDir = new File(dest, pkg.replace('/', File.separatorChar)); + private void generateMissingPackageInfoClasses(final File dest) throws IOException { + for (final Entry entry : packageInfos.entrySet()) { + final String pkg = entry.getKey(); + final Long sourceLastMod = entry.getValue(); + final File pkgBinDir = new File(dest, pkg.replace('/', File.separatorChar)); pkgBinDir.mkdirs(); - File pkgInfoClass = new File(pkgBinDir, "package-info.class"); + final File pkgInfoClass = new File(pkgBinDir, "package-info.class"); if (pkgInfoClass.isFile() && pkgInfoClass.lastModified() >= sourceLastMod.longValue()) { continue; } log("Creating empty " + pkgInfoClass); - OutputStream os = new FileOutputStream(pkgInfoClass); + final OutputStream os = new FileOutputStream(pkgInfoClass); try { os.write(PACKAGE_INFO_CLASS_HEADER); - byte[] name = pkg.getBytes("UTF-8"); - int length = name.length + /* "/package-info" */ 13; + final byte[] name = pkg.getBytes("UTF-8"); + final int length = name.length + /* "/package-info" */ 13; os.write((byte) length / 256); os.write((byte) length % 256); os.write(name); diff --git a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java index 6ff1aacfb..5ce62ef86 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Javadoc.java +++ b/src/main/org/apache/tools/ant/taskdefs/Javadoc.java @@ -278,7 +278,8 @@ public class Javadoc extends Task { * Return a string rep for this object. * @return the package name. */ - public String toString() { + @Override + public String toString() { return getName(); } } @@ -362,7 +363,8 @@ public class Javadoc extends Task { /** * @return the allowed values for the access type. */ - public String[] getValues() { + @Override + public String[] getValues() { // Protected first so if any GUI tool offers a default // based on enum #0, it will be right. return new String[] {"protected", "public", "package", "private"}; @@ -862,7 +864,8 @@ public class Javadoc extends Task { * @deprecated since 1.5.x. * Use the {@link #setExtdirs(Path)} version. */ - public void setExtdirs(String path) { + @Deprecated + public void setExtdirs(String path) { cmd.createArgument().setValue("-extdirs"); cmd.createArgument().setValue(path); } @@ -1698,7 +1701,8 @@ public class Javadoc extends Task { * Execute the task. * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { checkTaskName(); Vector packagesToDoc = new Vector(); @@ -2428,7 +2432,8 @@ public class Javadoc extends Task { // are there any java files in this directory? File pd = new File(baseDir, dirs[i]); String[] files = pd.list(new FilenameFilter () { - public boolean accept(File dir1, String name) { + @Override + public boolean accept(File dir1, String name) { return name.endsWith(".java") || (includeNoSourcePackages && name.equals("package.html")); @@ -2570,7 +2575,8 @@ public class Javadoc extends Task { // private String queuedLine = null; private boolean sawWarnings = false; - protected void processLine(String line, int messageLevel) { + @Override + protected void processLine(String line, int messageLevel) { if (line.contains("warning")) { sawWarnings = true; } @@ -2600,7 +2606,7 @@ public class Javadoc extends Task { queuedLine = null; } } - + public boolean sawWarnings() { return sawWarnings; } diff --git a/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java b/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java index 2f4eec0fd..8aa3b0767 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java +++ b/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java @@ -34,7 +34,7 @@ import org.apache.tools.ant.util.FileUtils; /** *

This task takes file and turns them into a URL, which it then assigns * to a property. Use when for setting up RMI codebases.

- * + * *

nested filesets are supported; if present, these are turned into the * url with the given separator between them (default = " ").

* @@ -151,7 +151,7 @@ public class MakeUrl extends Task { StringBuilder urls = new StringBuilder(); ListIterator list = filesets.listIterator(); while (list.hasNext()) { - FileSet set = (FileSet) list.next(); + FileSet set = list.next(); DirectoryScanner scanner = set.getDirectoryScanner(getProject()); String[] files = scanner.getIncludedFiles(); for (int i = 0; i < files.length; i++) { @@ -200,7 +200,7 @@ public class MakeUrl extends Task { StringBuilder urls = new StringBuilder(); ListIterator list = paths.listIterator(); while (list.hasNext()) { - Path path = (Path) list.next(); + Path path = list.next(); String[] elements = path.list(); for (int i = 0; i < elements.length; i++) { File f = new File(elements[i]); @@ -234,7 +234,8 @@ public class MakeUrl extends Task { * @throws org.apache.tools.ant.BuildException * if something goes wrong with the build */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { validate(); //now exit here if the property is already set if (getProject().getProperty(property) != null) { diff --git a/src/main/org/apache/tools/ant/taskdefs/Manifest.java b/src/main/org/apache/tools/ant/taskdefs/Manifest.java index 984998325..9fa576f4c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Manifest.java +++ b/src/main/org/apache/tools/ant/taskdefs/Manifest.java @@ -166,7 +166,8 @@ public class Manifest { * @see java.lang.Object#hashCode * @return a hashcode based on the key and values. */ - public int hashCode() { + @Override + public int hashCode() { int hashCode = 0; if (name != null) { @@ -182,7 +183,8 @@ public class Manifest { * @see java.lang.Object#equals * @return true if the key and values are the same. */ - public boolean equals(Object rhs) { + @Override + public boolean equals(Object rhs) { if (rhs == null || rhs.getClass() != getClass()) { return false; } @@ -312,7 +314,7 @@ public class Manifest { * @param line the continuation line. */ public void addContinuation(String line) { - String currentValue = (String) values.elementAt(currentIndex); + String currentValue = values.elementAt(currentIndex); setValue(currentValue + line.substring(1)); } @@ -535,7 +537,7 @@ public class Manifest { Attribute currentCp = getAttribute(ATTRIBUTE_CLASSPATH); if (currentCp != null) { for (Enumeration attribEnum = currentCp.getValues(); - attribEnum.hasMoreElements(); ) { + attribEnum.hasMoreElements();) { String value = attribEnum.nextElement(); classpathAttribute.addValue(value); } @@ -598,7 +600,7 @@ public class Manifest { * instances. */ public Attribute getAttribute(String attributeName) { - return (Attribute) attributes.get(attributeName.toLowerCase(Locale.ENGLISH)); + return attributes.get(attributeName.toLowerCase(Locale.ENGLISH)); } /** @@ -686,7 +688,7 @@ public class Manifest { // classpath attributes go into a vector if (attributeKey.equals(ATTRIBUTE_CLASSPATH_LC)) { Attribute classpathAttribute = - (Attribute) attributes.get(attributeKey); + attributes.get(attributeKey); if (classpathAttribute == null) { storeAttribute(attribute); @@ -718,7 +720,8 @@ public class Manifest { * @return the cloned Section * @since Ant 1.5.2 */ - public Object clone() { + @Override + public Object clone() { Section cloned = new Section(); cloned.setName(name); Enumeration e = getAttributeKeys(); @@ -757,7 +760,8 @@ public class Manifest { * @see java.lang.Object#hashCode * @return a hash value based on the attributes. */ - public int hashCode() { + @Override + public int hashCode() { return attributes.hashCode(); } @@ -766,7 +770,8 @@ public class Manifest { * @param rhs the object to check for equality. * @return true if the attributes are the same. */ - public boolean equals(Object rhs) { + @Override + public boolean equals(Object rhs) { if (rhs == null || rhs.getClass() != getClass()) { return false; } @@ -1055,7 +1060,8 @@ public class Manifest { * @return a multiline string with the Manifest as it * appears in a Manifest file. */ - public String toString() { + @Override + public String toString() { StringWriter sw = new StringWriter(); try { write(new PrintWriter(sw)); @@ -1093,7 +1099,8 @@ public class Manifest { * @see java.lang.Object#hashCode * @return a hashcode based on the version, main and sections. */ - public int hashCode() { + @Override + public int hashCode() { int hashCode = 0; if (manifestVersion != null) { @@ -1110,7 +1117,8 @@ public class Manifest { * @param rhs the object to check for equality. * @return true if the version, main and sections are the same. */ - public boolean equals(Object rhs) { + @Override + public boolean equals(Object rhs) { if (rhs == null || rhs.getClass() != getClass()) { return false; } @@ -1161,7 +1169,7 @@ public class Manifest { * does not exist in the manifest */ public Section getSection(String name) { - return (Section) sections.get(name); + return sections.get(name); } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/PathConvert.java b/src/main/org/apache/tools/ant/taskdefs/PathConvert.java index 0bac30409..cf1f38913 100644 --- a/src/main/org/apache/tools/ant/taskdefs/PathConvert.java +++ b/src/main/org/apache/tools/ant/taskdefs/PathConvert.java @@ -168,7 +168,8 @@ public class PathConvert extends Task { /** * @return the list of values for this enumerated attribute. */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[]{"windows", "unix", "netware", "os/2", "tandem"}; } } @@ -225,7 +226,8 @@ public class PathConvert extends Task { * Use the method taking a TargetOs argument instead. * @see #setTargetos(PathConvert.TargetOs) */ - public void setTargetos(String target) { + @Deprecated + public void setTargetos(String target) { TargetOs to = new TargetOs(); to.setValue(target); setTargetos(to); @@ -331,7 +333,8 @@ public class PathConvert extends Task { * Do the execution. * @throws BuildException if something is invalid. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { Resources savedPath = path; String savedPathSep = pathSep; // may be altered in validateSetup String savedDirSep = dirSep; // may be altered in validateSetup @@ -370,7 +373,7 @@ public class PathConvert extends Task { } } boolean first = true; - for (Iterator mappedIter = ret.iterator(); mappedIter.hasNext(); ) { + for (Iterator mappedIter = ret.iterator(); mappedIter.hasNext();) { String elem = mapElement((String) mappedIter.next()); // Apply the path prefix map // Now convert the path and file separator characters from the diff --git a/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java b/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java index 6d222efd3..66580e460 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java @@ -28,7 +28,7 @@ import org.apache.tools.ant.Task; /** * Task to install project helper into Ant's runtime - * + * * @since Ant 1.8.2 */ public class ProjectHelperTask extends Task { @@ -39,7 +39,8 @@ public class ProjectHelperTask extends Task { this.projectHelpers.add(projectHelper); } - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { ProjectHelperRepository repo = ProjectHelperRepository.getInstance(); for (Iterator it = projectHelpers.iterator(); it.hasNext();) { ProjectHelper helper = (ProjectHelper) it.next(); diff --git a/src/main/org/apache/tools/ant/taskdefs/Property.java b/src/main/org/apache/tools/ant/taskdefs/Property.java index 4c8d2ebe6..eca3bd3e1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Property.java +++ b/src/main/org/apache/tools/ant/taskdefs/Property.java @@ -431,7 +431,8 @@ public class Property extends Task { * deprecated without replacement. * @ant.attribute ignore="true" */ - public void setUserProperty(boolean userProperty) { + @Deprecated + public void setUserProperty(boolean userProperty) { log("DEPRECATED: Ignoring request to set user property in Property" + " task.", Project.MSG_WARN); } @@ -440,7 +441,8 @@ public class Property extends Task { * get the value of this property * @return the current value or the empty string */ - public String toString() { + @Override + public String toString() { return value == null ? "" : value; } @@ -450,7 +452,8 @@ public class Property extends Task { * here is where it is loaded * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (getProject() == null) { throw new IllegalStateException("project has not been set"); } @@ -520,7 +523,7 @@ public class Property extends Task { } } } - + /** * load properties from a url * @param url url to load from @@ -651,7 +654,7 @@ public class Property extends Task { } log("Loading Environment " + prefix, Project.MSG_VERBOSE); Map osEnv = Execute.getEnvironmentVariables(); - for (Iterator e = osEnv.entrySet().iterator(); e.hasNext(); ) { + for (Iterator e = osEnv.entrySet().iterator(); e.hasNext();) { Map.Entry entry = (Map.Entry) e.next(); props.put(prefix + entry.getKey(), entry.getValue()); } @@ -712,7 +715,7 @@ public class Property extends Task { */ private void resolveAllProperties(Map props) throws BuildException { PropertyHelper propertyHelper - = (PropertyHelper) PropertyHelper.getPropertyHelper(getProject()); + = PropertyHelper.getPropertyHelper(getProject()); new ResolvePropertyMap( getProject(), propertyHelper, diff --git a/src/main/org/apache/tools/ant/taskdefs/Redirector.java b/src/main/org/apache/tools/ant/taskdefs/Redirector.java index 23a847af5..3735b70fa 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Redirector.java +++ b/src/main/org/apache/tools/ant/taskdefs/Redirector.java @@ -61,16 +61,17 @@ public class Redirector { .getProperty("file.encoding"); private class PropertyOutputStream extends ByteArrayOutputStream { - private String property; + private final String property; private boolean closed = false; - PropertyOutputStream(String property) { + PropertyOutputStream(final String property) { super(); this.property = property; } - public void close() throws IOException { + @Override + public void close() throws IOException { synchronized (outMutex) { if (!closed && !(appendOut && appendProperties)) { setPropertyFromBAOS(this, property); @@ -139,7 +140,7 @@ public class Redirector { private boolean createEmptyFilesErr = true; /** The task for which this redirector is working */ - private ProjectComponent managingTask; + private final ProjectComponent managingTask; /** The stream for output data */ private OutputStream outputStream = null; @@ -184,13 +185,13 @@ public class Redirector { private boolean logInputString = true; /** Mutex for in */ - private Object inMutex = new Object(); + private final Object inMutex = new Object(); /** Mutex for out */ - private Object outMutex = new Object(); + private final Object outMutex = new Object(); /** Mutex for err */ - private Object errMutex = new Object(); + private final Object errMutex = new Object(); /** Is the output binary or can we safely split it into lines? */ private boolean outputIsBinary = false; @@ -201,7 +202,7 @@ public class Redirector { * @param managingTask * the task for which the redirector is to work */ - public Redirector(Task managingTask) { + public Redirector(final Task managingTask) { this((ProjectComponent) managingTask); } @@ -212,7 +213,7 @@ public class Redirector { * the project component for which the redirector is to work * @since Ant 1.6.3 */ - public Redirector(ProjectComponent managingTask) { + public Redirector(final ProjectComponent managingTask) { this.managingTask = managingTask; } @@ -222,8 +223,8 @@ public class Redirector { * @param input * the file from which input is read. */ - public void setInput(File input) { - setInput((input == null) ? null : new File[] { input }); + public void setInput(final File input) { + setInput((input == null) ? null : new File[] {input}); } /** @@ -232,12 +233,12 @@ public class Redirector { * @param input * the files from which input is read. */ - public void setInput(File[] input) { + public void setInput(final File[] input) { synchronized (inMutex) { if (input == null) { this.input = null; } else { - this.input = (File[]) input.clone(); + this.input = input.clone(); } } } @@ -248,7 +249,7 @@ public class Redirector { * @param inputString * the string which is used as the input source */ - public void setInputString(String inputString) { + public void setInputString(final String inputString) { synchronized (inMutex) { this.inputString = inputString; } @@ -262,7 +263,7 @@ public class Redirector { * true or false. * @since Ant 1.7 */ - public void setLogInputString(boolean logInputString) { + public void setLogInputString(final boolean logInputString) { this.logInputString = logInputString; } @@ -273,7 +274,7 @@ public class Redirector { * the stream from which input will be read * @since Ant 1.6.3 */ - /* public */void setInputStream(InputStream inputStream) { + /* public */void setInputStream(final InputStream inputStream) { synchronized (inMutex) { this.inputStream = inputStream; } @@ -286,8 +287,8 @@ public class Redirector { * @param out * the file to which output stream is written */ - public void setOutput(File out) { - setOutput((out == null) ? null : new File[] { out }); + public void setOutput(final File out) { + setOutput((out == null) ? null : new File[] {out}); } /** @@ -297,12 +298,12 @@ public class Redirector { * @param out * the files to which output stream is written */ - public void setOutput(File[] out) { + public void setOutput(final File[] out) { synchronized (outMutex) { if (out == null) { this.out = null; } else { - this.out = (File[]) out.clone(); + this.out = out.clone(); } } } @@ -313,7 +314,7 @@ public class Redirector { * @param outputEncoding * String. */ - public void setOutputEncoding(String outputEncoding) { + public void setOutputEncoding(final String outputEncoding) { if (outputEncoding == null) { throw new IllegalArgumentException( "outputEncoding must not be null"); @@ -329,7 +330,7 @@ public class Redirector { * @param errorEncoding * String. */ - public void setErrorEncoding(String errorEncoding) { + public void setErrorEncoding(final String errorEncoding) { if (errorEncoding == null) { throw new IllegalArgumentException("errorEncoding must not be null"); } @@ -344,7 +345,7 @@ public class Redirector { * @param inputEncoding * String. */ - public void setInputEncoding(String inputEncoding) { + public void setInputEncoding(final String inputEncoding) { if (inputEncoding == null) { throw new IllegalArgumentException("inputEncoding must not be null"); } @@ -361,7 +362,7 @@ public class Redirector { * if true the standard error is sent to the Ant log system and * not sent to output. */ - public void setLogError(boolean logError) { + public void setLogError(final boolean logError) { synchronized (errMutex) { this.logError = logError; } @@ -375,7 +376,7 @@ public class Redirector { * @param appendProperties * whether to append properties. */ - public void setAppendProperties(boolean appendProperties) { + public void setAppendProperties(final boolean appendProperties) { synchronized (outMutex) { this.appendProperties = appendProperties; } @@ -387,8 +388,8 @@ public class Redirector { * @param error * the file to which error is to be written */ - public void setError(File error) { - setError((error == null) ? null : new File[] { error }); + public void setError(final File error) { + setError((error == null) ? null : new File[] {error}); } /** @@ -397,12 +398,12 @@ public class Redirector { * @param error * the file to which error is to be written */ - public void setError(File[] error) { + public void setError(final File[] error) { synchronized (errMutex) { if (error == null) { this.error = null; } else { - this.error = (File[]) error.clone(); + this.error = error.clone(); } } } @@ -413,7 +414,7 @@ public class Redirector { * @param outputProperty * the name of the property to be set with the task's output. */ - public void setOutputProperty(String outputProperty) { + public void setOutputProperty(final String outputProperty) { if (outputProperty == null || !(outputProperty.equals(this.outputProperty))) { synchronized (outMutex) { @@ -431,7 +432,7 @@ public class Redirector { * if true output and error streams are appended to their * respective files, if specified. */ - public void setAppend(boolean append) { + public void setAppend(final boolean append) { synchronized (outMutex) { appendOut = append; } @@ -449,7 +450,7 @@ public class Redirector { * boolean * @since Ant 1.6.3 */ - public void setAlwaysLog(boolean alwaysLog) { + public void setAlwaysLog(final boolean alwaysLog) { synchronized (outMutex) { alwaysLogOut = alwaysLog; } @@ -465,7 +466,7 @@ public class Redirector { * @param createEmptyFiles * boolean. */ - public void setCreateEmptyFiles(boolean createEmptyFiles) { + public void setCreateEmptyFiles(final boolean createEmptyFiles) { synchronized (outMutex) { createEmptyFilesOut = createEmptyFiles; } @@ -480,7 +481,7 @@ public class Redirector { * @param errorProperty * the name of the property to be set with the error output. */ - public void setErrorProperty(String errorProperty) { + public void setErrorProperty(final String errorProperty) { synchronized (errMutex) { if (errorProperty == null || !(errorProperty.equals(this.errorProperty))) { @@ -496,7 +497,7 @@ public class Redirector { * @param inputFilterChains * Vector containing FilterChain. */ - public void setInputFilterChains(Vector inputFilterChains) { + public void setInputFilterChains(final Vector inputFilterChains) { synchronized (inMutex) { this.inputFilterChains = inputFilterChains; } @@ -508,7 +509,7 @@ public class Redirector { * @param outputFilterChains * Vector containing FilterChain. */ - public void setOutputFilterChains(Vector outputFilterChains) { + public void setOutputFilterChains(final Vector outputFilterChains) { synchronized (outMutex) { this.outputFilterChains = outputFilterChains; } @@ -520,7 +521,7 @@ public class Redirector { * @param errorFilterChains * Vector containing FilterChain. */ - public void setErrorFilterChains(Vector errorFilterChains) { + public void setErrorFilterChains(final Vector errorFilterChains) { synchronized (errMutex) { this.errorFilterChains = errorFilterChains; } @@ -534,7 +535,7 @@ public class Redirector { * the same stream.

* @since 1.9.4 */ - public void setBinaryOutput(boolean b) { + public void setBinaryOutput(final boolean b) { outputIsBinary = b; } @@ -549,13 +550,13 @@ public class Redirector { * @exception IOException * if the value cannot be read form the stream. */ - private void setPropertyFromBAOS(ByteArrayOutputStream baos, - String propertyName) throws IOException { + private void setPropertyFromBAOS(final ByteArrayOutputStream baos, + final String propertyName) throws IOException { - BufferedReader in = new BufferedReader(new StringReader(Execute + final BufferedReader in = new BufferedReader(new StringReader(Execute .toString(baos))); String line = null; - StringBuffer val = new StringBuffer(); + final StringBuffer val = new StringBuffer(); while ((line = in.readLine()) != null) { if (val.length() != 0) { val.append(StringUtils.LINE_SEP); @@ -574,7 +575,7 @@ public class Redirector { synchronized (outMutex) { outStreams(); if (alwaysLogOut || outputStream == null) { - OutputStream outputLog = new LogOutputStream(managingTask, + final OutputStream outputLog = new LogOutputStream(managingTask, Project.MSG_INFO); outputStream = (outputStream == null) ? outputLog : new TeeOutputStream(outputLog, outputStream); @@ -583,7 +584,7 @@ public class Redirector { if ((outputFilterChains != null && outputFilterChains.size() > 0) || !(outputEncoding.equalsIgnoreCase(inputEncoding))) { try { - LeadPipeInputStream snk = new LeadPipeInputStream(); + final LeadPipeInputStream snk = new LeadPipeInputStream(); snk.setManagingComponent(managingTask); InputStream outPumpIn = snk; @@ -593,7 +594,7 @@ public class Redirector { if (outputFilterChains != null && outputFilterChains.size() > 0) { - ChainReaderHelper helper = new ChainReaderHelper(); + final ChainReaderHelper helper = new ChainReaderHelper(); helper.setProject(managingTask.getProject()); helper.setPrimaryReader(reader); helper.setFilterChains(outputFilterChains); @@ -601,12 +602,12 @@ public class Redirector { } outPumpIn = new ReaderInputStream(reader, outputEncoding); - Thread t = new Thread(threadGroup, new StreamPumper( + final Thread t = new Thread(threadGroup, new StreamPumper( outPumpIn, outputStream, true), "output pumper"); t.setPriority(Thread.MAX_PRIORITY); outputStream = new PipedOutputStream(snk); t.start(); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { throw new BuildException("error setting up output stream", eyeOhEx); } @@ -616,7 +617,7 @@ public class Redirector { synchronized (errMutex) { errorStreams(); if (alwaysLogErr || errorStream == null) { - OutputStream errorLog = new LogOutputStream(managingTask, + final OutputStream errorLog = new LogOutputStream(managingTask, Project.MSG_WARN); errorStream = (errorStream == null) ? errorLog : new TeeOutputStream(errorLog, errorStream); @@ -625,7 +626,7 @@ public class Redirector { if ((errorFilterChains != null && errorFilterChains.size() > 0) || !(errorEncoding.equalsIgnoreCase(inputEncoding))) { try { - LeadPipeInputStream snk = new LeadPipeInputStream(); + final LeadPipeInputStream snk = new LeadPipeInputStream(); snk.setManagingComponent(managingTask); InputStream errPumpIn = snk; @@ -635,7 +636,7 @@ public class Redirector { if (errorFilterChains != null && errorFilterChains.size() > 0) { - ChainReaderHelper helper = new ChainReaderHelper(); + final ChainReaderHelper helper = new ChainReaderHelper(); helper.setProject(managingTask.getProject()); helper.setPrimaryReader(reader); helper.setFilterChains(errorFilterChains); @@ -643,12 +644,12 @@ public class Redirector { } errPumpIn = new ReaderInputStream(reader, errorEncoding); - Thread t = new Thread(threadGroup, new StreamPumper( + final Thread t = new Thread(threadGroup, new StreamPumper( errPumpIn, errorStream, true), "error pumper"); t.setPriority(Thread.MAX_PRIORITY); errorStream = new PipedOutputStream(snk); t.start(); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { throw new BuildException("error setting up error stream", eyeOhEx); } @@ -667,13 +668,13 @@ public class Redirector { Project.MSG_VERBOSE); try { inputStream = new ConcatFileInputStream(input); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { throw new BuildException(eyeOhEx); } ((ConcatFileInputStream) inputStream) .setManagingComponent(managingTask); } else if (inputString != null) { - StringBuffer buf = new StringBuffer("Using input "); + final StringBuffer buf = new StringBuffer("Using input "); if (logInputString) { buf.append('"').append(inputString).append('"'); } else { @@ -685,12 +686,12 @@ public class Redirector { if (inputStream != null && inputFilterChains != null && inputFilterChains.size() > 0) { - ChainReaderHelper helper = new ChainReaderHelper(); + final ChainReaderHelper helper = new ChainReaderHelper(); helper.setProject(managingTask.getProject()); try { helper.setPrimaryReader(new InputStreamReader(inputStream, inputEncoding)); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { throw new BuildException("error setting up input stream", eyeOhEx); } @@ -704,7 +705,7 @@ public class Redirector { /** outStreams */ private void outStreams() { if (out != null && out.length > 0) { - String logHead = new StringBuffer("Output ").append( + final String logHead = new StringBuffer("Output ").append( ((appendOut) ? "appended" : "redirected")).append(" to ") .toString(); outputStream = foldFiles(out, logHead, Project.MSG_VERBOSE, @@ -717,7 +718,7 @@ public class Redirector { + outputProperty, Project.MSG_VERBOSE); } // shield it from being closed by a filtering StreamPumper - OutputStream keepAliveOutput = new KeepAliveOutputStream(baos); + final OutputStream keepAliveOutput = new KeepAliveOutputStream(baos); outputStream = (outputStream == null) ? keepAliveOutput : new TeeOutputStream(outputStream, keepAliveOutput); } else { @@ -727,14 +728,14 @@ public class Redirector { private void errorStreams() { if (error != null && error.length > 0) { - String logHead = new StringBuffer("Error ").append( + final String logHead = new StringBuffer("Error ").append( ((appendErr) ? "appended" : "redirected")).append(" to ") .toString(); errorStream = foldFiles(error, logHead, Project.MSG_VERBOSE, appendErr, createEmptyFilesErr); } else if (!(logError || outputStream == null) && errorProperty == null) { - long funnelTimeout = 0L; - OutputStreamFunneler funneler = new OutputStreamFunneler( + final long funnelTimeout = 0L; + final OutputStreamFunneler funneler = new OutputStreamFunneler( outputStream, funnelTimeout); try { outputStream = funneler.getFunnelInstance(); @@ -743,7 +744,7 @@ public class Redirector { outputStream = new LineOrientedOutputStreamRedirector(outputStream); errorStream = new LineOrientedOutputStreamRedirector(errorStream); } - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { throw new BuildException( "error splitting output/error streams", eyeOhEx); } @@ -755,7 +756,7 @@ public class Redirector { + errorProperty, Project.MSG_VERBOSE); } // shield it from being closed by a filtering StreamPumper - OutputStream keepAliveError = new KeepAliveOutputStream(errorBaos); + final OutputStream keepAliveError = new KeepAliveOutputStream(errorBaos); errorStream = (error == null || error.length == 0) ? keepAliveError : new TeeOutputStream(errorStream, keepAliveError); } else { @@ -774,7 +775,7 @@ public class Redirector { */ public ExecuteStreamHandler createHandler() throws BuildException { createStreams(); - boolean nonBlockingRead = input == null && inputString == null; + final boolean nonBlockingRead = input == null && inputString == null; return new PumpStreamHandler(getOutputStream(), getErrorStream(), getInputStream(), nonBlockingRead); } @@ -785,7 +786,7 @@ public class Redirector { * @param output * the data to be output */ - protected void handleOutput(String output) { + protected void handleOutput(final String output) { synchronized (outMutex) { if (outPrintStream == null) { outPrintStream = new PrintStream(outputStream); @@ -809,7 +810,7 @@ public class Redirector { * @exception IOException * if the data cannot be read */ - protected int handleInput(byte[] buffer, int offset, int length) + protected int handleInput(final byte[] buffer, final int offset, final int length) throws IOException { synchronized (inMutex) { if (inputStream == null) { @@ -827,7 +828,7 @@ public class Redirector { * @param output * the data being flushed. */ - protected void handleFlush(String output) { + protected void handleFlush(final String output) { synchronized (outMutex) { if (outPrintStream == null) { outPrintStream = new PrintStream(outputStream); @@ -843,7 +844,7 @@ public class Redirector { * @param output * the error output data. */ - protected void handleErrorOutput(String output) { + protected void handleErrorOutput(final String output) { synchronized (errMutex) { if (errorPrintStream == null) { errorPrintStream = new PrintStream(errorStream); @@ -858,7 +859,7 @@ public class Redirector { * @param output * the error information being flushed. */ - protected void handleErrorFlush(String output) { + protected void handleErrorFlush(final String output) { synchronized (errMutex) { if (errorPrintStream == null) { errorPrintStream = new PrintStream(errorStream); @@ -940,19 +941,19 @@ public class Redirector { try { managingTask.log("waiting for " + threadGroup.activeCount() + " Threads:", Project.MSG_DEBUG); - Thread[] thread = new Thread[threadGroup.activeCount()]; + final Thread[] thread = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(thread); for (int i = 0; i < thread.length && thread[i] != null; i++) { try { managingTask.log(thread[i].toString(), Project.MSG_DEBUG); - } catch (NullPointerException enPeaEx) { + } catch (final NullPointerException enPeaEx) { // Ignore exception } } wait(STREAMPUMPER_WAIT_INTERVAL); - } catch (InterruptedException eyeEx) { - Thread[] thread = new Thread[threadGroup.activeCount()]; + } catch (final InterruptedException eyeEx) { + final Thread[] thread = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(thread); for (int i = 0; i < thread.length && thread[i] != null; i++) { thread[i].interrupt(); @@ -985,7 +986,7 @@ public class Redirector { if (baos != null) { try { baos.close(); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { // Ignore exception } } @@ -994,22 +995,22 @@ public class Redirector { if (errorBaos != null) { try { errorBaos.close(); - } catch (IOException eyeOhEx) { + } catch (final IOException eyeOhEx) { // Ignore exception } } } } - private OutputStream foldFiles(File[] file, String logHead, int loglevel, - boolean append, boolean createEmptyFiles) { - OutputStream result = new LazyFileOutputStream(file[0], append, + private OutputStream foldFiles(final File[] file, final String logHead, final int loglevel, + final boolean append, final boolean createEmptyFiles) { + final OutputStream result = new LazyFileOutputStream(file[0], append, createEmptyFiles); managingTask.log(logHead + file[0], loglevel); - char[] c = new char[logHead.length()]; + final char[] c = new char[logHead.length()]; Arrays.fill(c, ' '); - String indent = new String(c); + final String indent = new String(c); for (int i = 1; i < file.length; i++) { outputStream = new TeeOutputStream(outputStream, diff --git a/src/main/org/apache/tools/ant/taskdefs/Rmic.java b/src/main/org/apache/tools/ant/taskdefs/Rmic.java index f17b47a16..87dde5a57 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Rmic.java +++ b/src/main/org/apache/tools/ant/taskdefs/Rmic.java @@ -39,14 +39,14 @@ import org.apache.tools.ant.util.facade.FacadeTaskHelper; /** *

Runs the rmic compiler against classes.

- * + * *

Rmic can be run on a single class (as specified with the classname * attribute) or a number of classes at once (all classes below base that * are neither _Stub nor _Skel classes). If you want to rmic a single * class and this class is a class nested into another class, you have to * specify the classname in the form Outer$$Inner instead of * Outer.Inner.

- * + * *

It is possible to refine the set of files that are being rmiced. This can * be done with the includes, includesfile, excludes, * excludesfile and defaultexcludes @@ -58,17 +58,17 @@ import org.apache.tools.ant.util.facade.FacadeTaskHelper; * you want to use default exclusions or not. See the section on * directory based tasks, on how the * inclusion/exclusion of files works, and how to write patterns.

- * + * *

This task forms an implicit FileSet and * supports all attributes of <fileset> * (dir becomes base) as well as the nested * <include>, <exclude> and * <patternset> elements.

- * + * *

It is possible to use different compilers. This can be selected * with the "build.rmic" property or the compiler * attribute. There are three choices:

- * + * *
    *
  • sun (the standard compiler of the JDK)
  • *
  • kaffe (the standard compiler of @@ -587,7 +587,8 @@ public class Rmic extends MatchingTask { * @throws org.apache.tools.ant.BuildException * if there's a problem with baseDir or RMIC */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { try { compileList.clear(); diff --git a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java index 8638bebd7..874939b18 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java @@ -90,7 +90,8 @@ public class SQLExec extends JDBCTask { /** The enumerated strings */ public static final String NORMAL = "normal", ROW = "row"; /** @return the enumerated strings */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {NORMAL, ROW}; } } @@ -589,7 +590,8 @@ public class SQLExec extends JDBCTask { * Load the sql file and then execute it * @throws BuildException on error. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { Vector savedTransaction = (Vector) transactions.clone(); String savedSqlCommand = sqlCommand; @@ -850,7 +852,8 @@ public class SQLExec extends JDBCTask { * @param out the place to print results * @throws SQLException on SQL problems. */ - protected void printResults(PrintStream out) throws SQLException { + @Deprecated + protected void printResults(PrintStream out) throws SQLException { ResultSet rs = getStatement().getResultSet(); try { printResults(rs, out); @@ -954,7 +957,8 @@ public class SQLExec extends JDBCTask { *

    returns null if the connection does not connect to the * expected RDBMS.

    */ - protected Connection getConnection() { + @Override + protected Connection getConnection() { if (conn == null) { conn = super.getConnection(); if (!isValidRdbms(conn)) { @@ -981,14 +985,15 @@ public class SQLExec extends JDBCTask { return statement; } - + /** * The action a task should perform on an error, * one of "continue", "stop" and "abort" */ public static class OnError extends EnumeratedAttribute { /** @return the enumerated values */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"continue", "stop", "abort"}; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/SignJar.java b/src/main/org/apache/tools/ant/taskdefs/SignJar.java index 66804de86..7f9b1ee52 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SignJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/SignJar.java @@ -321,7 +321,8 @@ public class SignJar extends AbstractJarSignerTask { * * @throws BuildException on errors */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { //validation logic final boolean hasJar = jar != null; final boolean hasSignedJar = signedjar != null; @@ -514,7 +515,7 @@ public class SignJar extends AbstractJarSignerTask { * is complex, and best explained in the source itself. Essentially if * either file doesnt exist, or the destfile has an out of date timestamp, * then the return value is false.

    - * + * *

    If we are signing ourself, the check {@link #isSigned(File)} is used to * trigger the process.

    * diff --git a/src/main/org/apache/tools/ant/taskdefs/Sleep.java b/src/main/org/apache/tools/ant/taskdefs/Sleep.java index 4e924f9f4..0fe27c5c9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sleep.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sleep.java @@ -26,11 +26,11 @@ import org.apache.tools.ant.Task; * *

    A task for sleeping a short period of time, useful when a * build or deployment process requires an interval between tasks.

    - * + * *

    A negative value can be supplied to any of attributes provided the total sleep time * is positive, pending fundamental changes in physics and JVM * execution times

    - * + * *

    Note that sleep times are always hints to be interpreted by the OS how it feels * small times may either be ignored or rounded up to a minimum timeslice. Note * also that the system clocks often have a fairly low granularity too, which complicates @@ -171,7 +171,8 @@ public class Sleep extends Task { * * @exception BuildException Description of Exception */ - public void execute() + @Override + public void execute() throws BuildException { try { validate(); diff --git a/src/main/org/apache/tools/ant/taskdefs/SubAnt.java b/src/main/org/apache/tools/ant/taskdefs/SubAnt.java index 34b3f21e0..3751b0244 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SubAnt.java +++ b/src/main/org/apache/tools/ant/taskdefs/SubAnt.java @@ -84,7 +84,7 @@ public class SubAnt extends Task { *

    * This function may be overrided by providers of custom ProjectHelper so they can implement easily their sub * launcher. - * + * * @return the name of the default file * @since Ant 1.8.0 */ @@ -98,7 +98,8 @@ public class SubAnt extends Task { * @param output a line of output * @since Ant 1.6.2 */ - public void handleOutput(String output) { + @Override + public void handleOutput(String output) { if (ant != null) { ant.handleOutput(output); } else { @@ -121,7 +122,8 @@ public class SubAnt extends Task { * * @since Ant 1.6.2 */ - public int handleInput(byte[] buffer, int offset, int length) + @Override + public int handleInput(byte[] buffer, int offset, int length) throws IOException { if (ant != null) { return ant.handleInput(buffer, offset, length); @@ -137,7 +139,8 @@ public class SubAnt extends Task { * * @since Ant 1.6.2 */ - public void handleFlush(String output) { + @Override + public void handleFlush(String output) { if (ant != null) { ant.handleFlush(output); } else { @@ -152,7 +155,8 @@ public class SubAnt extends Task { * * @since Ant 1.6.2 */ - public void handleErrorOutput(String output) { + @Override + public void handleErrorOutput(String output) { if (ant != null) { ant.handleErrorOutput(output); } else { @@ -167,7 +171,8 @@ public class SubAnt extends Task { * * @since Ant 1.6.2 */ - public void handleErrorFlush(String output) { + @Override + public void handleErrorFlush(String output) { if (ant != null) { ant.handleErrorFlush(output); } else { @@ -178,7 +183,8 @@ public class SubAnt extends Task { /** * Runs the various sub-builds. */ - public void execute() { + @Override + public void execute() { if (buildpath == null) { throw new BuildException("No buildpath specified"); } diff --git a/src/main/org/apache/tools/ant/taskdefs/Sync.java b/src/main/org/apache/tools/ant/taskdefs/Sync.java index e269cf493..29982af4a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sync.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sync.java @@ -72,7 +72,8 @@ public class Sync extends Task { * @throws BuildException if there is a problem. * @see Task#init() */ - public void init() + @Override + public void init() throws BuildException { // Instantiate it myCopy = new MyCopy(); @@ -97,7 +98,8 @@ public class Sync extends Task { * @throws BuildException if there is an error. * @see Task#execute() */ - public void execute() + @Override + public void execute() throws BuildException { // The destination of the files to copy File toDir = myCopy.getToDir(); @@ -324,7 +326,7 @@ public class Sync extends Task { private int removeEmptyDirectories(Set preservedEmptyDirectories) { int removedCount = 0; for (Iterator iter = preservedEmptyDirectories.iterator(); - iter.hasNext(); ) { + iter.hasNext();) { File f = (File) iter.next(); String[] s = f.list(); if (s == null || s.length == 0) { @@ -399,7 +401,7 @@ public class Sync extends Task { myCopy.add(rc); } else { if (resources == null) { - Restrict r = new Restrict(); + Restrict r = new Restrict(); r.add(new Exists()); r.add(resources = new Resources()); myCopy.add(r); @@ -464,7 +466,8 @@ public class Sync extends Task { * @see Copy#scan(File, File, String[], String[]) */ /** {@inheritDoc} */ - protected void scan(File fromDir, File toDir, String[] files, + @Override + protected void scan(File fromDir, File toDir, String[] files, String[] dirs) { assertTrue("No mapper", mapperElement == null); @@ -482,7 +485,8 @@ public class Sync extends Task { * @see Copy#scan(Resource[], File) */ /** {@inheritDoc} */ - protected Map scan(Resource[] resources, File toDir) { + @Override + protected Map scan(Resource[] resources, File toDir) { assertTrue("No mapper", mapperElement == null); for (int i = 0; i < resources.length; i++) { @@ -512,7 +516,8 @@ public class Sync extends Task { * @return true always. * @since Ant 1.7 */ - protected boolean supportsNonFileResources() { + @Override + protected boolean supportsNonFileResources() { return true; } } @@ -543,7 +548,8 @@ public class Sync extends Task { * @param dir ignored * @throws BuildException always */ - public void setDir(File dir) throws BuildException { + @Override + public void setDir(File dir) throws BuildException { throw new BuildException("preserveintarget doesn't support the dir " + "attribute"); } @@ -579,7 +585,7 @@ public class Sync extends Task { PatternSet ps = mergePatterns(getProject()); fs.appendIncludes(ps.getIncludePatterns(getProject())); fs.appendExcludes(ps.getExcludePatterns(getProject())); - for (Enumeration e = selectorElements(); e.hasMoreElements(); ) { + for (Enumeration e = selectorElements(); e.hasMoreElements();) { fs.appendSelector((FileSelector) e.nextElement()); } fs.setDefaultexcludes(getDefaultexcludes()); diff --git a/src/main/org/apache/tools/ant/taskdefs/War.java b/src/main/org/apache/tools/ant/taskdefs/War.java index 0820627a1..b39c2907f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/War.java +++ b/src/main/org/apache/tools/ant/taskdefs/War.java @@ -33,11 +33,11 @@ import org.apache.tools.zip.ZipOutputStream; * Contains special treatment for files that should end up in the * WEB-INF/lib, WEB-INF/classes or * WEB-INF directories of the Web Application Archive.

    - * + * *

    (The War task is a shortcut for specifying the particular layout of a WAR file. * The same thing can be accomplished by using the prefix and fullpath * attributes of zipfilesets in a Zip or Jar task.)

    - * + * *

    The extended zipfileset element from the zip task * (with attributes prefix, fullpath, and src) * is available in the War task.

    @@ -151,7 +151,8 @@ public class War extends Jar { * @throws IOException on output error * @throws BuildException if invalid configuration */ - protected void initZipOutputStream(ZipOutputStream zOut) + @Override + protected void initZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException { super.initZipOutputStream(zOut); } @@ -171,7 +172,8 @@ public class War extends Jar { * @param mode the Unix permissions to set. * @throws IOException on output error */ - protected void zipFile(File file, ZipOutputStream zOut, String vPath, + @Override + protected void zipFile(File file, ZipOutputStream zOut, String vPath, int mode) throws IOException { // If the file being added is WEB-INF/web.xml, we warn if it's @@ -215,7 +217,8 @@ public class War extends Jar { * Make sure we don't think we already have a web.xml next time this task * gets executed. */ - protected void cleanUp() { + @Override + protected void cleanUp() { if (addedWebXmlFile == null && deploymentDescriptor == null && needxmlfile diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison.java b/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison.java index df22cf2d3..304995c68 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison.java @@ -51,7 +51,7 @@ public interface XSLTLiaison { * @param name the parameter name. * @param expression the parameter value as an expression string. * @throws Exception thrown if any problems happens. - * @see XSLTLiaison4#addParam(java.lang.String, java.lang.Object) + * @see XSLTLiaison4#addParam(java.lang.String, java.lang.Object) * @since Ant 1.3 */ void addParam(String name, String expression) throws Exception; diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison4.java b/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison4.java index efc3f5b3e..5de380b70 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison4.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTLiaison4.java @@ -17,8 +17,6 @@ */ package org.apache.tools.ant.taskdefs; -import javax.xml.transform.Transformer; - /** * Extends Proxy interface for XSLT processors: adds support for XSLT parameters * of various types (not only String) diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java index c5d230913..91ea06264 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java @@ -210,7 +210,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @since Ant 1.8.0 */ private boolean failOnNoResources = true; - + /** * For evaluating template params * @@ -617,7 +617,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { */ public boolean getSuppressWarnings() { return suppressWarnings; - } + } /** * Whether transformation errors should make the build fail. @@ -978,7 +978,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { /** The parameter's value */ private String expression = null; - + /** * Type of the expression. * @see ParamType @@ -1011,7 +1011,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * The parameter value - * can be a primitive type value or an XPath expression. * @param expression the parameter's value/expression. - * @see #setType(java.lang.String) + * @see #setType(java.lang.String) */ public void setExpression(String expression) { this.expression = expression; @@ -1024,7 +1024,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { public void setType(String type) { this.type = type; } - + /** * Get the parameter name * @@ -1113,7 +1113,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { && ph.testUnlessCondition(unlessCond); } } // Param - + /** * Enum for types of the parameter expression. * @@ -1134,7 +1134,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { *

    Default type (if omited) is primitive String. So if the expression is e.g * "true" with no type, in XSLT it will be only a text string, not true * boolean.

    - * + * * @see Param#setType(java.lang.String) * @see Param#setExpression(java.lang.String) * @since Ant 1.9.3 @@ -1151,7 +1151,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { XPATH_NUMBER, XPATH_NODE, XPATH_NODESET; - + public static final Map XPATH_TYPES; static { @@ -1230,11 +1230,12 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { public void init() throws BuildException { super.init(); xmlCatalog.setProject(getProject()); - + xpathFactory = XPathFactory.newInstance(); xpath = xpathFactory.newXPath(); xpath.setXPathVariableResolver(new XPathVariableResolver() { - public Object resolveVariable(QName variableName) { + @Override + public Object resolveVariable(QName variableName) { return getProject().getProperty(variableName.toString()); } }); @@ -1247,7 +1248,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @exception BuildException if the stylesheet cannot be loaded. * @deprecated since Ant 1.7 */ - protected void configureLiaison(File stylesheet) throws BuildException { + @Deprecated + protected void configureLiaison(File stylesheet) throws BuildException { FileResource fr = new FileResource(); fr.setProject(getProject()); fr.setFile(stylesheet); @@ -1314,7 +1316,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { handleTransformationError(ex); } } - + /** * Evaluates parameter expression according to its type. * @@ -1530,7 +1532,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @return null * @throws BuildException never */ - public Object createDynamicElement(String name) throws BuildException { + @Override + public Object createDynamicElement(String name) throws BuildException { return null; } @@ -1541,7 +1544,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @param value the value of the attribute * @throws BuildException on error */ - public void setDynamicAttribute(String name, String value) throws BuildException { + @Override + public void setDynamicAttribute(String name, String value) throws BuildException { // only 'name' and 'value' exist. if ("name".equalsIgnoreCase(name)) { this.name = value; @@ -1576,11 +1580,14 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @since Ant 1.6.2 */ private class StyleMapper implements FileNameMapper { - public void setFrom(String from) { + @Override + public void setFrom(String from) { } - public void setTo(String to) { + @Override + public void setTo(String to) { } - public String[] mapFileName(String xmlFile) { + @Override + public String[] mapFileName(String xmlFile) { int dotPos = xmlFile.lastIndexOf('.'); if (dotPos > 0) { xmlFile = xmlFile.substring(0, dotPos); diff --git a/src/main/org/apache/tools/ant/taskdefs/Zip.java b/src/main/org/apache/tools/ant/taskdefs/Zip.java index 3d05349a4..451016eff 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Zip.java +++ b/src/main/org/apache/tools/ant/taskdefs/Zip.java @@ -105,14 +105,16 @@ public class Zip extends MatchingTask { private static final ResourceSelector MISSING_SELECTOR = new ResourceSelector() { - public boolean isSelected(Resource target) { + @Override + public boolean isSelected(Resource target) { return !target.isExists(); } }; private static final ResourceUtils.ResourceSelectorProvider MISSING_DIR_PROVIDER = new ResourceUtils.ResourceSelectorProvider() { - public ResourceSelector + @Override + public ResourceSelector getTargetSelectorForSource(Resource sr) { return MISSING_SELECTOR; } @@ -237,7 +239,8 @@ public class Zip extends MatchingTask { * Use setDestFile(File) instead. * @ant.attribute ignore="true" */ - public void setZipfile(File zipFile) { + @Deprecated + public void setZipfile(File zipFile) { setDestFile(zipFile); } @@ -250,7 +253,8 @@ public class Zip extends MatchingTask { * Use setDestFile(File) instead. * @ant.attribute ignore="true" */ - public void setFile(File file) { + @Deprecated + public void setFile(File file) { setDestFile(file); } @@ -383,7 +387,8 @@ public class Zip extends MatchingTask { * The string values for the enumerated value * @return the values */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"fail", "skip", "create"}; } } @@ -581,7 +586,8 @@ public class Zip extends MatchingTask { * validate and build * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (doubleFilePass) { skipWriting = true; @@ -628,7 +634,7 @@ public class Zip extends MatchingTask { } final int size = resources.size(); for (int i = 0; i < size; i++) { - ResourceCollection rc = (ResourceCollection) resources.elementAt(i); + ResourceCollection rc = resources.elementAt(i); vfss.addElement(rc); } @@ -702,7 +708,7 @@ public class Zip extends MatchingTask { final int addSize = addedFiles.size(); for (int i = 0; i < addSize; i++) { PatternSet.NameEntry ne = oldFiles.createExclude(); - ne.setName((String) addedFiles.elementAt(i)); + ne.setName(addedFiles.elementAt(i)); } DirectoryScanner ds = oldFiles.getDirectoryScanner(getProject()); @@ -855,7 +861,7 @@ public class Zip extends MatchingTask { for (int i = 0; i < size; i++) { logWhenWriting("Processing groupfileset ", Project.MSG_VERBOSE); - FileSet fs = (FileSet) groupfilesets.elementAt(i); + FileSet fs = groupfilesets.elementAt(i); FileScanner scanner = fs.getDirectoryScanner(getProject()); String[] files = scanner.getIncludedFiles(); File basedir = scanner.getBasedir(); @@ -1249,7 +1255,7 @@ public class Zip extends MatchingTask { ArchiveState as = getNonFileSetResourcesToAdd(rc, zipFile, needsUpdate); - FileSet[] fs = (FileSet[]) filesets.toArray(new FileSet[filesets + FileSet[] fs = filesets.toArray(new FileSet[filesets .size()]); ArchiveState as2 = getResourcesToAdd(fs, zipFile, as.isOutOfDate()); if (!as.isOutOfDate() && as2.isOutOfDate()) { @@ -1285,7 +1291,8 @@ public class Zip extends MatchingTask { * subclasses in several ways). */ private static final ThreadLocal HAVE_NON_FILE_SET_RESOURCES_TO_ADD = new ThreadLocal() { - protected Boolean initialValue() { + @Override + protected Boolean initialValue() { return Boolean.FALSE; } }; @@ -1630,7 +1637,8 @@ public class Zip extends MatchingTask { // make sure directories are in alpha-order - this also // ensures parents come before their children Collections.sort(dirs, new Comparator() { - public int compare(Resource r1, Resource r2) { + @Override + public int compare(Resource r1, Resource r2) { return r1.getName().compareTo(r2.getName()); } }); @@ -1739,7 +1747,7 @@ public class Zip extends MatchingTask { * @since Ant 1.8.0 */ protected final ZipExtraField[] getCurrentExtraFields() { - return (ZipExtraField[]) CURRENT_ZIP_EXTRA.get(); + return CURRENT_ZIP_EXTRA.get(); } /** @@ -2032,7 +2040,8 @@ public class Zip extends MatchingTask { protected Resource[] selectFileResources(Resource[] orig) { return selectResources(orig, new ResourceSelector() { - public boolean isSelected(Resource r) { + @Override + public boolean isSelected(Resource r) { if (!r.isDirectory()) { return true; } else if (doFilesonly) { @@ -2056,7 +2065,8 @@ public class Zip extends MatchingTask { protected Resource[] selectDirectoryResources(Resource[] orig) { return selectResources(orig, new ResourceSelector() { - public boolean isSelected(Resource r) { + @Override + public boolean isSelected(Resource r) { return r.isDirectory(); } }); @@ -2108,7 +2118,8 @@ public class Zip extends MatchingTask { * @see EnumeratedAttribute#getValues() */ /** {@inheritDoc} */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"add", "preserve", "fail"}; } } @@ -2184,7 +2195,8 @@ public class Zip extends MatchingTask { .NOT_ENCODEABLE); } - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {NEVER_KEY, ALWAYS_KEY, N_E_KEY}; } @@ -2242,7 +2254,8 @@ public class Zip extends MatchingTask { MODES.put(A_N_KEY, Zip64Mode.AsNeeded); } - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {NEVER_KEY, ALWAYS_KEY, A_N_KEY}; } diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/AptCompilerAdapter.java b/src/main/org/apache/tools/ant/taskdefs/compilers/AptCompilerAdapter.java index 5ada0d7ea..404ee0d27 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/AptCompilerAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/AptCompilerAdapter.java @@ -32,24 +32,24 @@ import org.apache.tools.ant.types.Path; /** *

    The implementation of the apt compiler for JDK 1.5.

    - * + * *

    As usual, the low level entry points for Java tools are neither documented or * stable; this entry point may change from that of 1.5.0_01-b08 without any * warning at all. The IDE decompile of the tool entry points is as follows:

    *
      * public class Main {
      * public Main() ;
    - * 
    + *
      * public static transient void main(String... strings);
    - * 
    + *
      * public static transient int process(String... strings);
    - * 
    + *
      * public static transient int process(PrintWriter printWriter,
      *      String... strings);
      * public static transient int process(
      *      AnnotationProcessorFactory annotationProcessorFactory,
      *      String... strings);
    - *      
    + *
      * public static transient int process(
      *      AnnotationProcessorFactory annotationProcessorFactory,
      *      PrintWriter printWriter,
    @@ -157,7 +157,8 @@ public class AptCompilerAdapter extends DefaultCompilerAdapter {
          * @return true on success.
          * @throws BuildException if the compilation has problems.
          */
    -    public boolean execute() throws BuildException {
    +    @Override
    +	public boolean execute() throws BuildException {
             attributes.log("Using apt compiler", Project.MSG_VERBOSE);
             //set up the javac options
             Commandline cmd = setupModernJavacCommand();
    diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterExtension.java b/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterExtension.java
    index 010deb03d..038b9cbef 100644
    --- a/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterExtension.java
    +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterExtension.java
    @@ -20,7 +20,7 @@ package org.apache.tools.ant.taskdefs.compilers;
     /**
      * Extension interface for compilers that support source extensions
      * other than .java.
    - * 
    + *
      * @since Ant 1.8.2
      */
     public interface CompilerAdapterExtension {
    @@ -32,7 +32,7 @@ public interface CompilerAdapterExtension {
          * 

    For example, most compiler adapters will return [ "java" ], * but a compiler adapter that can compile both Java and Groovy * source code would return [ "java", "groovy" ].

    - * + * * @return list of source file extensions recognized by this * compiler adapter. */ 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 5b32d1096..6819e5adf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java @@ -97,7 +97,8 @@ public abstract class DefaultCompilerAdapter * * @param attributes a configured Javac task. */ - public void setJavac(Javac attributes) { + @Override + public void setJavac(final Javac attributes) { this.attributes = attributes; src = attributes.getSrcdir(); destDir = attributes.getDestdir(); @@ -135,8 +136,9 @@ public abstract class DefaultCompilerAdapter * but specialized compilers can recognize multiple kinds * of files. */ - public String[] getSupportedFileExtensions() { - return new String[] { "java" }; + @Override + public String[] getSupportedFileExtensions() { + return new String[] {"java"}; } /** @@ -153,7 +155,7 @@ public abstract class DefaultCompilerAdapter * @return the compilation class path */ protected Path getCompileClasspath() { - Path classpath = new Path(project); + final Path classpath = new Path(project); // add dest dir to classpath so that previously compiled and // untouched classes are on classpath @@ -187,7 +189,7 @@ public abstract class DefaultCompilerAdapter * @param cmd the command line * @return the command line */ - protected Commandline setupJavacCommandlineSwitches(Commandline cmd) { + protected Commandline setupJavacCommandlineSwitches(final Commandline cmd) { return setupJavacCommandlineSwitches(cmd, false); } @@ -198,9 +200,9 @@ public abstract class DefaultCompilerAdapter * @param useDebugLevel if true set set the debug level with the -g switch * @return the command line */ - protected Commandline setupJavacCommandlineSwitches(Commandline cmd, - boolean useDebugLevel) { - Path classpath = getCompileClasspath(); + protected Commandline setupJavacCommandlineSwitches(final Commandline cmd, + final boolean useDebugLevel) { + final Path classpath = getCompileClasspath(); // For -sourcepath, use the "sourcepath" value if present. // Otherwise default to the "srcdir" value. Path sourcepath = null; @@ -210,7 +212,7 @@ public abstract class DefaultCompilerAdapter sourcepath = src; } - String memoryParameterPrefix = assumeJava11() ? "-J-" : "-J-X"; + final String memoryParameterPrefix = assumeJava11() ? "-J-" : "-J-X"; if (memoryInitialSize != null) { if (!attributes.isForkedJavac()) { attributes.log("Since fork is false, ignoring " @@ -251,9 +253,9 @@ public abstract class DefaultCompilerAdapter // Just add "sourcepath" to classpath ( for JDK1.1 ) // as well as "bootclasspath" and "extdirs" if (assumeJava11()) { - Path cp = new Path(project); + final Path cp = new Path(project); - Path bp = getBootClassPath(); + final Path bp = getBootClassPath(); if (bp.size() > 0) { cp.append(bp); } @@ -277,7 +279,7 @@ public abstract class DefaultCompilerAdapter cmd.createArgument().setValue(target); } - Path bp = getBootClassPath(); + final Path bp = getBootClassPath(); if (bp.size() > 0) { cmd.createArgument().setValue("-bootclasspath"); cmd.createArgument().setPath(bp); @@ -295,7 +297,7 @@ public abstract class DefaultCompilerAdapter } if (debug) { if (useDebugLevel && !assumeJava11()) { - String debugLevel = attributes.getDebugLevel(); + final String debugLevel = attributes.getDebugLevel(); if (debugLevel != null) { cmd.createArgument().setValue("-g:" + debugLevel); } else { @@ -337,7 +339,7 @@ public abstract class DefaultCompilerAdapter * @param cmd the command line * @return the command line */ - protected Commandline setupModernJavacCommandlineSwitches(Commandline cmd) { + protected Commandline setupModernJavacCommandlineSwitches(final Commandline cmd) { setupJavacCommandlineSwitches(cmd, true); if (!assumeJava13()) { // -source added with JDK 1.4 final String t = attributes.getTarget(); @@ -359,7 +361,7 @@ public abstract class DefaultCompilerAdapter * @return the command line */ protected Commandline setupModernJavacCommand() { - Commandline cmd = new Commandline(); + final Commandline cmd = new Commandline(); setupModernJavacCommandlineSwitches(cmd); logAndAddFilesToCompile(cmd); @@ -380,8 +382,8 @@ public abstract class DefaultCompilerAdapter * @param debugLevelCheck if true set the debug level with the -g switch * @return the command line */ - protected Commandline setupJavacCommand(boolean debugLevelCheck) { - Commandline cmd = new Commandline(); + protected Commandline setupJavacCommand(final boolean debugLevelCheck) { + final Commandline cmd = new Commandline(); setupJavacCommandlineSwitches(cmd, debugLevelCheck); logAndAddFilesToCompile(cmd); return cmd; @@ -392,11 +394,11 @@ public abstract class DefaultCompilerAdapter * "niceSourceList" * @param cmd the command line */ - protected void logAndAddFilesToCompile(Commandline cmd) { + protected void logAndAddFilesToCompile(final Commandline cmd) { attributes.log("Compilation " + cmd.describeArguments(), Project.MSG_VERBOSE); - StringBuffer niceSourceList = new StringBuffer("File"); + final StringBuffer niceSourceList = new StringBuffer("File"); if (compileList.length != 1) { niceSourceList.append("s"); } @@ -405,7 +407,7 @@ public abstract class DefaultCompilerAdapter niceSourceList.append(StringUtils.LINE_SEP); for (int i = 0; i < compileList.length; i++) { - String arg = compileList[i].getAbsolutePath(); + final String arg = compileList[i].getAbsolutePath(); cmd.createArgument().setValue(arg); niceSourceList.append(" "); niceSourceList.append(arg); @@ -424,7 +426,7 @@ public abstract class DefaultCompilerAdapter * system. * @return the exit code of the compilation */ - protected int executeExternalCompile(String[] args, int firstFileName) { + protected int executeExternalCompile(final String[] args, final int firstFileName) { return executeExternalCompile(args, firstFileName, true); } @@ -447,8 +449,8 @@ public abstract class DefaultCompilerAdapter * * @since Ant 1.6 */ - protected int executeExternalCompile(String[] args, int firstFileName, - boolean quoteFiles) { + protected int executeExternalCompile(final String[] args, final int firstFileName, + final boolean quoteFiles) { String[] commandArray = null; File tmpFile = null; @@ -480,7 +482,7 @@ public abstract class DefaultCompilerAdapter commandArray = new String[firstFileName + 1]; System.arraycopy(args, 0, commandArray, 0, firstFileName); commandArray[firstFileName] = "@" + tmpFile; - } catch (IOException e) { + } catch (final IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { @@ -491,7 +493,7 @@ public abstract class DefaultCompilerAdapter } try { - Execute exe = new Execute( + final Execute exe = new Execute( new LogStreamHandler(attributes, Project.MSG_INFO, Project.MSG_WARN)); @@ -505,7 +507,7 @@ public abstract class DefaultCompilerAdapter exe.setCommandline(commandArray); exe.execute(); return exe.getExitValue(); - } catch (IOException e) { + } catch (final IOException e) { throw new BuildException("Error running " + args[0] + " compiler", e, location); } @@ -522,7 +524,8 @@ public abstract class DefaultCompilerAdapter * @deprecated since 1.5.x. * Use org.apache.tools.ant.types.Path#addExtdirs instead. */ - protected void addExtdirsToClasspath(Path classpath) { + @Deprecated + protected void addExtdirsToClasspath(final Path classpath) { classpath.addExtdirs(extdirs); } @@ -530,7 +533,7 @@ public abstract class DefaultCompilerAdapter * Adds the command line arguments specific to the current implementation. * @param cmd the command line to use */ - protected void addCurrentCompilerArgs(Commandline cmd) { + protected void addCurrentCompilerArgs(final Commandline cmd) { cmd.addArguments(getJavac().getCurrentCompilerArgs()); } @@ -619,7 +622,7 @@ public abstract class DefaultCompilerAdapter * Shall we assume command line switches for the given version of Java? * @since Ant 1.8.3 */ - private boolean assumeJavaXY(String javacXY, String javaEnvVersionXY) { + private boolean assumeJavaXY(final String javacXY, final String javaEnvVersionXY) { return javacXY.equals(attributes.getCompilerVersion()) || ("classic".equals(attributes.getCompilerVersion()) && JavaEnvUtils.isJavaVersion(javaEnvVersionXY)) @@ -637,7 +640,7 @@ public abstract class DefaultCompilerAdapter * specified and the system bootclasspath. */ protected Path getBootClassPath() { - Path bp = new Path(project); + final Path bp = new Path(project); if (bootclasspath != null) { bp.append(bootclasspath); } @@ -658,8 +661,8 @@ public abstract class DefaultCompilerAdapter return assumeJava11() ? null : "-g:none"; } - private void setImplicitSourceSwitch(Commandline cmd, - String target, String source) { + private void setImplicitSourceSwitch(final Commandline cmd, + final String target, final String source) { attributes.log("", Project.MSG_WARN); attributes.log(" WARNING", Project.MSG_WARN); attributes.log("", Project.MSG_WARN); @@ -723,7 +726,7 @@ public abstract class DefaultCompilerAdapter *

    support for -source 1.1 and -source 1.2 has been added with * JDK 1.4.2 but isn't present in 1.5.0+

    */ - private String adjustSourceValue(String source) { + private String adjustSourceValue(final String source) { return (source.equals("1.1") || source.equals("1.2")) ? "1.3" : source; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/condition/IsReachable.java b/src/main/org/apache/tools/ant/taskdefs/condition/IsReachable.java index d7206c391..101c78ab5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/condition/IsReachable.java +++ b/src/main/org/apache/tools/ant/taskdefs/condition/IsReachable.java @@ -33,19 +33,19 @@ import org.apache.tools.ant.ProjectComponent; *

    Test for a host being reachable using ICMP "ping" packets & echo operations. * Ping packets are very reliable for assessing reachability in a LAN or WAN, * but they do not get through any well-configured firewall. Echo (port 7) may.

    - * + * *

    This condition turns unknown host exceptions into false conditions. This is * because on a laptop, DNS is one of the first services lost when the network * goes; you are implicitly offline.

    - * + * *

    If a URL is supplied instead of a host, the hostname is extracted and used in * the test--all other parts of the URL are discarded.

    - * + * *

    The test may not work through firewalls; that is, something may be reachable * using a protocol such as HTTP, while the lower level ICMP packets get dropped * on the floor. Similarly, a host may be detected as reachable with ICMP, but not * reachable on other ports (i.e. port 80), because of firewalls.

    - * + * *

    Requires Java 5+ to work properly. On Java 1.4, if a hostname * can be resolved, the destination is assumed to be reachable.

    * @@ -139,7 +139,8 @@ public class IsReachable extends ProjectComponent implements Condition { * @throws org.apache.tools.ant.BuildException * if an error occurs */ - public boolean eval() throws BuildException { + @Override + public boolean eval() throws BuildException { if (empty(host) && empty(url)) { throw new BuildException(ERROR_NO_HOSTNAME); } diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java index dcf4fc63f..0096aadfe 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java @@ -88,11 +88,11 @@ class ChangeLogParser { ArrayList names = new ArrayList(); if (packageName != null) { for (StringTokenizer tok = new StringTokenizer(packageName); - tok.hasMoreTokens(); ) { + tok.hasMoreTokens();) { names.add(tok.nextToken()); } } - for (Iterator iter = modules.iterator(); iter.hasNext(); ) { + for (Iterator iter = modules.iterator(); iter.hasNext();) { AbstractCvsTask.Module m = (AbstractCvsTask.Module) iter.next(); names.add(m.getName()); } 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 38606fe1c..112feb037 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsTagDiff.java @@ -144,7 +144,7 @@ public class CvsTagDiff extends AbstractCvsTask { private File mydestfile; /** - * Used to skip over removed files + * Used to skip over removed files */ private boolean ignoreRemoved = false; @@ -167,7 +167,8 @@ public class CvsTagDiff extends AbstractCvsTask { * The package/module to analyze. * @param p the name of the package to analyse */ - public void setPackage(String p) { + @Override + public void setPackage(String p) { mypackage = p; } @@ -222,7 +223,7 @@ public class CvsTagDiff extends AbstractCvsTask { * @param b the ignore removed indicator. * * @since Ant 1.8.0 - */ + */ public void setIgnoreRemoved(boolean b) { ignoreRemoved = b; } @@ -233,7 +234,8 @@ public class CvsTagDiff extends AbstractCvsTask { * * @exception BuildException if an error occurs */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { // validate the input parameters validate(); diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java index 71b7e6053..f39fff046 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java @@ -80,7 +80,7 @@ public class CommandLauncher { /** * Launches the given command in a new process. - * + * * @param project * The project that the command is part of. * @param cmd @@ -104,7 +104,7 @@ public class CommandLauncher { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * The project that the command is part of. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.java b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.java index dce5d40cf..7a1c87741 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.java @@ -35,7 +35,7 @@ public class CommandLauncherProxy extends CommandLauncher { /** * Launches the given command in a new process. Delegates this * method to the proxied launcher. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.java index df22fb321..e022ade9b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.java @@ -33,7 +33,7 @@ public class Java13CommandLauncher extends CommandLauncher { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.java index 77941768f..02a8e7826 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.java @@ -34,7 +34,7 @@ public class MacCommandLauncher extends CommandLauncherProxy { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/OS2CommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/OS2CommandLauncher.java index 24be3cb5a..75ecaa3da 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/OS2CommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/OS2CommandLauncher.java @@ -37,7 +37,7 @@ public class OS2CommandLauncher extends CommandLauncherProxy { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java index d624d76da..d5b06f745 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java @@ -38,7 +38,7 @@ public class PerlScriptCommandLauncher extends CommandLauncherProxy { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java index ee0a9661b..936f948eb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java @@ -38,7 +38,7 @@ public class ScriptCommandLauncher extends CommandLauncherProxy { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd 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 9d953db66..4c1b3f090 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java @@ -38,7 +38,7 @@ public class VmsCommandLauncher extends Java13CommandLauncher { /** * Launches the given command in a new process. - * + * * @param project * the Ant project. * @param cmd @@ -63,7 +63,7 @@ public class VmsCommandLauncher extends Java13CommandLauncher { * working directory. Note that under Java 1.4.0 and 1.4.1 on VMS * this method only works if workingDir is null or * the logical JAVA$FORK_SUPPORT_CHDIR needs to be set to TRUE. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/WinNTCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/WinNTCommandLauncher.java index aeea46ab7..65abafc3d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/WinNTCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/WinNTCommandLauncher.java @@ -35,7 +35,7 @@ public class WinNTCommandLauncher extends CommandLauncherProxy { /** * Launches the given command in a new process, in the given * working directory. - * + * * @param project * the Ant project. * @param cmd diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java index dec296ac3..13f6b8f20 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java @@ -71,9 +71,9 @@ import org.apache.tools.ant.util.LayoutPreservingProperties; *
* Other parameters are: *
    - *
  • comment
  • - *
  • key
  • - *
  • operation
  • + *
  • comment
  • + *
  • key
  • + *
  • operation
  • *
  • type
  • *
  • value (the final four being eliminated shortly)
  • *
@@ -155,7 +155,8 @@ public class PropertyFile extends Task { * Execute the task. * @throws BuildException on error. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { checkParameters(); readFile(); executeOperation(); @@ -378,7 +379,7 @@ public class PropertyFile extends Task { */ protected void executeOn(Properties props) throws BuildException { checkParameters(); - + if (operation == Operation.DELETE_OPER) { props.remove(key); return; @@ -614,7 +615,8 @@ public class PropertyFile extends Task { public static final int DELETE_OPER = 3; /** {@inheritDoc}. */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"+", "-", "=", "del"}; } @@ -649,7 +651,8 @@ public class PropertyFile extends Task { public static final int STRING_TYPE = 2; /** {@inheritDoc} */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"int", "date", "string"}; } @@ -715,7 +718,8 @@ public class PropertyFile extends Task { } /** {@inheritDoc}. */ - public String[] getValues() { + @Override + public String[] getValues() { return UNITS; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java index 726ceee80..64e552b8d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java @@ -213,7 +213,7 @@ public class ReplaceRegExp extends Task { * want to only replace the first occurrence of a regular expression on * each line, which is not easy to do when processing the file as a whole. * Defaults to false. - * + * * @param byline the byline attribute as a string * @deprecated since 1.6.x. * Use setByLine(boolean). @@ -234,7 +234,7 @@ public class ReplaceRegExp extends Task { * want to only replace the first occurrence of a regular expression on * each line, which is not easy to do when processing the file as a whole. * Defaults to false. - * + * * @param byline the byline attribute */ public void setByLine(boolean byline) { @@ -465,7 +465,8 @@ public class ReplaceRegExp extends Task { * * @throws BuildException is there is a problem in the task execution. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (regex == null) { throw new BuildException("No expression to match."); } 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 9f6c3d79b..111e79bb2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java @@ -143,7 +143,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @param stylesheet a File value * @throws Exception on error */ - public void setStylesheet(File stylesheet) throws Exception { + @Override + public void setStylesheet(File stylesheet) throws Exception { FileResource fr = new FileResource(); fr.setProject(project); fr.setFile(stylesheet); @@ -155,7 +156,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @param stylesheet a {@link org.apache.tools.ant.types.Resource} value * @throws Exception on error */ - public void setStylesheet(Resource stylesheet) throws Exception { + @Override + public void setStylesheet(Resource stylesheet) throws Exception { if (this.stylesheet != null) { // resetting the stylesheet - reset transformer transformer = null; @@ -175,7 +177,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @param outfile the result file * @throws Exception on error */ - public void transform(File infile, File outfile) throws Exception { + @Override + public void transform(File infile, File outfile) throws Exception { if (transformer == null) { createTransformer(); } @@ -504,17 +507,19 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @param name the name of the parameter * @param value the value of the parameter */ - public void addParam(String name, String value) { + @Override + public void addParam(String name, String value) { params.put(name, value); } - + /** * Add a parameter. * @param name the name of the parameter * @param value the value of the parameter * @since Ant 1.9.3 */ - public void addParam(String name, Object value) { + @Override + public void addParam(String name, Object value) { params.put(name, value); } @@ -522,7 +527,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * Set a logger. * @param l a logger. */ - public void setLogger(XSLTLogger l) { + @Override + public void setLogger(XSLTLogger l) { logger = l; } @@ -530,7 +536,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * Log an error. * @param e the exception to log. */ - public void error(TransformerException e) { + @Override + public void error(TransformerException e) { logError(e, "Error"); } @@ -538,7 +545,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * Log a fatal error. * @param e the exception to log. */ - public void fatalError(TransformerException e) { + @Override + public void fatalError(TransformerException e) { logError(e, "Fatal Error"); throw new BuildException("Fatal error during transformation using " + stylesheet + ": " + e.getMessageAndLocation(), e); } @@ -547,7 +555,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * Log a warning. * @param e the exception to log. */ - public void warning(TransformerException e) { + @Override + public void warning(TransformerException e) { if (!suppressWarnings) { logError(e, "Warning"); } @@ -601,7 +610,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @deprecated since 1.5.x. * Use org.apache.tools.ant.util.JAXPUtils#getSystemId instead. */ - protected String getSystemId(File file) { + @Deprecated + protected String getSystemId(File file) { return JAXPUtils.getSystemId(file); } @@ -611,7 +621,8 @@ public class TraXLiaison implements XSLTLiaison4, ErrorListener, XSLTLoggerAware * @param xsltTask the XSLTProcess task instance from which this liasion * is to be configured. */ - public void configure(XSLTProcess xsltTask) { + @Override + public void configure(XSLTProcess xsltTask) { project = xsltTask.getProject(); XSLTProcess.Factory factory = xsltTask.getFactory(); if (factory != null) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java index 54ec522bf..857c48401 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java @@ -43,7 +43,8 @@ public class MethodTypeCPInfo extends ConstantCPInfo { * @exception java.io.IOException if there is a problem reading the entry from * the stream. */ - public void read(DataInputStream cpStream) throws IOException { + @Override + public void read(final DataInputStream cpStream) throws IOException { methodDescriptorIndex = cpStream.readUnsignedShort(); } @@ -54,8 +55,9 @@ public class MethodTypeCPInfo extends ConstantCPInfo { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ - public void resolve(ConstantPool constantPool) { - Utf8CPInfo methodClass + @Override + public void resolve(final ConstantPool constantPool) { + final Utf8CPInfo methodClass = (Utf8CPInfo) constantPool.getEntry(methodDescriptorIndex); methodClass.resolve(constantPool); methodDescriptor = methodClass.getValue(); @@ -66,8 +68,9 @@ public class MethodTypeCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ - public String toString() { - if (! isResolved()) { + @Override + public String toString() { + if (!isResolved()) { return "MethodDescriptorIndex: " + methodDescriptorIndex; } else { return "MethodDescriptor: " + methodDescriptor; 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 7db731d5e..193f32ca5 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 @@ -166,7 +166,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * @param inString the string to use as the suffix. This parameter is * ignored. */ - public void setGenericJarSuffix(String inString) { + @Override + public void setGenericJarSuffix(String inString) { log("Since a generic JAR file is not created during processing, the " + "iPlanet Deployment Tool does not support the " + "\"genericjarsuffix\" attribute. It will be ignored.", @@ -174,7 +175,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ - public void processDescriptor(String descriptorName, SAXParser saxParser) { + @Override + public void processDescriptor(String descriptorName, SAXParser saxParser) { this.descriptorName = descriptorName; this.iasDescriptorName = null; @@ -193,7 +195,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * descriptor * @throws BuildException If the user selections are invalid. */ - protected void checkConfiguration(String descriptorFileName, + @Override + protected void checkConfiguration(String descriptorFileName, SAXParser saxParser) throws BuildException { int startOfName = descriptorFileName.lastIndexOf(File.separatorChar) + 1; @@ -236,7 +239,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * @throws SAXException Any SAX exception, possibly wrapping another * exception */ - protected Hashtable parseEjbFiles(String descriptorFileName, + @Override + protected Hashtable parseEjbFiles(String descriptorFileName, SAXParser saxParser) throws IOException, SAXException { Hashtable files; @@ -257,7 +261,7 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { } if (getConfig().dtdLocations != null) { for (Iterator i = getConfig().dtdLocations.iterator(); - i.hasNext(); ) { + i.hasNext();) { EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); ejbc.registerDTD(dtdLocation.getPublicId(), @@ -308,7 +312,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * the completed JAR file. * @param ddPrefix not used */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { ejbFiles.put(META_DIR + IAS_DD, new File(getConfig().descriptorDir, getIasDescriptorName())); } @@ -322,7 +327,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * * @return File representing the JAR file which will be written. */ - File getVendorOutputJarFile(String baseName) { + @Override + File getVendorOutputJarFile(String baseName) { File jarFile = new File(getDestDir(), baseName + jarSuffix); log("JAR file name: " + jarFile.toString(), Project.MSG_VERBOSE); return jarFile; @@ -335,7 +341,8 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * * @return null. */ - protected String getPublicId() { + @Override + protected String getPublicId() { return null; } 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 caf0b43c9..ed799d331 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 @@ -37,7 +37,6 @@ import java.util.StringTokenizer; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; -import org.apache.tools.ant.BuildException; import org.xml.sax.AttributeList; import org.xml.sax.HandlerBase; import org.xml.sax.InputSource; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java index 3786c66a5..676c70762 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java @@ -113,7 +113,8 @@ public class ExtensionSet * @param reference the reference to which this instance is associated * @exception BuildException if this instance already has been configured. */ - public void setRefid(final Reference reference) + @Override + public void setRefid(final Reference reference) throws BuildException { if (!extensions.isEmpty() || !extensionsFilesets.isEmpty()) { throw tooManyAttributes(); @@ -121,7 +122,8 @@ public class ExtensionSet super.setRefid(reference); } - protected synchronized void dieOnCircularReference(Stack stk, Project p) + @Override + protected synchronized void dieOnCircularReference(Stack stk, Project p) throws BuildException { if (isChecked()) { return; @@ -129,11 +131,11 @@ public class ExtensionSet if (isReference()) { super.dieOnCircularReference(stk, p); } else { - for (Iterator i = extensions.iterator(); i.hasNext(); ) { + for (Iterator i = extensions.iterator(); i.hasNext();) { pushAndInvokeCircularReferenceCheck((ExtensionAdapter) i.next(), stk, p); } - for (Iterator i = extensionsFilesets.iterator(); i.hasNext(); ) { + for (Iterator i = extensionsFilesets.iterator(); i.hasNext();) { pushAndInvokeCircularReferenceCheck((FileSet) i.next(), stk, p); } setChecked(true); @@ -144,7 +146,8 @@ public class ExtensionSet * @see java.lang.Object#toString() * @return the extensions in a string. */ - public String toString() { + @Override + public String toString() { return "ExtensionSet" + Arrays.asList(toExtensions(getProject())); } } 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 4b52689ca..71068e959 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 @@ -48,7 +48,7 @@ public class JUnit4TestMethodAdapter implements Test { /** * Creates a new adapter for the given class and a method within the class. - * + * * @param testClass test class containing the method to be executed * @param methodNames names of the test methods that are to be executed * @exception java.lang.IllegalArgumentException @@ -72,7 +72,7 @@ public class JUnit4TestMethodAdapter implements Test { } } this.testClass = testClass; - this.methodNames = (String[]) methodNames.clone(); + this.methodNames = methodNames.clone(); this.cache = CustomJUnit4TestAdapterCache.getInstance(); // Warning: If 'testClass' is an old-style (pre-JUnit-4) class, @@ -87,7 +87,8 @@ public class JUnit4TestMethodAdapter implements Test { runner = request.getRunner(); } - public int countTestCases() { + @Override + public int countTestCases() { return runner.testCount(); } @@ -103,11 +104,13 @@ public class JUnit4TestMethodAdapter implements Test { return testClass; } - public void run(final TestResult result) { + @Override + public void run(final TestResult result) { runner.run(cache.getNotifier(result)); } - public String toString() { + @Override + public String toString() { String testClassName = testClass.getName(); StringBuilder buf = new StringBuilder(testClassName.length() + 12 * methodNames.length) @@ -144,7 +147,8 @@ public class JUnit4TestMethodAdapter implements Test { this.methodNames = methodNames; } - public boolean shouldRun(Description description) { + @Override + public boolean shouldRun(Description description) { if (methodNames.length == 0) { return false; } @@ -165,10 +169,11 @@ public class JUnit4TestMethodAdapter implements Test { } } } - return false; + return false; } - public String describe() { + @Override + public String describe() { StringBuilder buf = new StringBuilder(40); if (methodNames.length == 0) { buf.append("No methods"); 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 1ecbeba2c..2b41f8e90 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 @@ -364,7 +364,8 @@ public class JUnitTask extends Task { * list the possible values * @return array of allowed values */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {"true", "yes", "false", "no", "on", "off", "withOutAndErr"}; } @@ -455,7 +456,8 @@ public class JUnitTask extends Task { * @deprecated since ant 1.6 * @param sysp environment variable to add */ - public void addSysproperty(Environment.Variable sysp) { + @Deprecated + public void addSysproperty(Environment.Variable sysp) { getCommandline().addSysproperty(sysp); } @@ -703,7 +705,7 @@ public class JUnitTask extends Task { * Whether test listener events shall be generated. * *

Defaults to false.

- * + * *

This value will be overridden by the magic property * ant.junit.enabletestlistenerevents if it has been set.

* @@ -732,7 +734,8 @@ public class JUnitTask extends Task { * * @since Ant 1.4 */ - public void init() { + @Override + public void init() { antRuntimeClasses = new Path(getProject()); splitJUnit = !addClasspathResource("/junit/framework/TestCase.class"); addClasspathEntry("/org/apache/tools/ant/launch/AntMain.class"); @@ -779,7 +782,8 @@ public class JUnitTask extends Task { path.add(extra); } mirrorLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + @Override + public Object run() { return new SplitClassLoader(myLoader, path, getProject(), new String[] { "BriefJUnitResultFormatter", @@ -812,7 +816,8 @@ public class JUnitTask extends Task { * @throws BuildException in case of test failures or errors * @since Ant 1.2 */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { checkMethodLists(); setupJUnitDelegate(); @@ -866,7 +871,8 @@ public class JUnitTask extends Task { this.id = id; } - public void run() { + @Override + public void run() { try { masterTask.oneJunitThread(iterator, id); } catch (BuildException b) { @@ -877,7 +883,7 @@ public class JUnitTask extends Task { private JUnitTask masterTask; private Iterator iterator; - private int id; + private int id; } /* @@ -1436,7 +1442,8 @@ public class JUnitTask extends Task { * @param output output coming from System.out * @since Ant 1.5 */ - protected void handleOutput(String output) { + @Override + protected void handleOutput(String output) { if (output.startsWith(TESTLISTENER_PREFIX)) { log(output, Project.MSG_VERBOSE); } else if (runner != null) { @@ -1465,7 +1472,8 @@ public class JUnitTask extends Task { * * @since Ant 1.6 */ - protected int handleInput(byte[] buffer, int offset, int length) + @Override + protected int handleInput(byte[] buffer, int offset, int length) throws IOException { if (runner != null) { return runner.handleInput(buffer, offset, length); @@ -1482,7 +1490,8 @@ public class JUnitTask extends Task { * @param output output coming from System.out * @since Ant 1.5.2 */ - protected void handleFlush(String output) { + @Override + protected void handleFlush(String output) { if (runner != null) { runner.handleFlush(output); if (showOutput) { @@ -1500,7 +1509,8 @@ public class JUnitTask extends Task { * @param output output coming from System.err * @since Ant 1.5 */ - public void handleErrorOutput(String output) { + @Override + public void handleErrorOutput(String output) { if (runner != null) { runner.handleErrorOutput(output); if (showOutput) { @@ -1519,7 +1529,8 @@ public class JUnitTask extends Task { * @param output coming from System.err * @since Ant 1.5.2 */ - public void handleErrorFlush(String output) { + @Override + public void handleErrorFlush(String output) { if (runner != null) { runner.handleErrorFlush(output); if (showOutput) { @@ -1783,7 +1794,7 @@ public class JUnitTask extends Task { } } - static final String TIMEOUT_MESSAGE = + static final String TIMEOUT_MESSAGE = "Timeout occurred. Please note the time in the report does" + " not reflect the time until the timeout."; @@ -1999,7 +2010,8 @@ public class JUnitTask extends Task { * @param other * @return true if everything is equal */ - public boolean equals(Object other) { + @Override + public boolean equals(Object other) { if (other == null || other.getClass() != ForkedTestConfiguration.class) { return false; @@ -2023,7 +2035,8 @@ public class JUnitTask extends Task { * in the range 0-7. * @return hash code value */ - public int hashCode() { + @Override + public int hashCode() { // CheckStyle:MagicNumber OFF return (filterTrace ? 1 : 0) + (haltOnError ? 2 : 0) @@ -2066,7 +2079,8 @@ public class JUnitTask extends Task { } /** {@inheritDoc}. */ - public String[] getValues() { + @Override + public String[] getValues() { return new String[] {ONCE, PER_TEST, PER_BATCH}; } } @@ -2203,7 +2217,8 @@ public class JUnitTask extends Task { * @param line the line to log. * @param level the logging level to use. */ - protected void processLine(String line, int level) { + @Override + protected void processLine(String line, int level) { if (line.startsWith(TESTLISTENER_PREFIX)) { task.log(line, Project.MSG_VERBOSE); } else { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java index b96a1a7db..86ccad752 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java @@ -55,7 +55,7 @@ public class JUnitTest extends BaseTest implements Cloneable { /** the names of test methods to execute */ private String[] methods = null; - + /** the name of the result file */ private String outfile = null; @@ -110,7 +110,7 @@ public class JUnitTest extends BaseTest implements Cloneable { */ public JUnitTest(String name, boolean haltOnError, boolean haltOnFailure, boolean filtertrace, String[] methods) { - this(name, haltOnError, haltOnFailure, filtertrace, methods, 0); + this(name, haltOnError, haltOnFailure, filtertrace, methods, 0); } /** @@ -527,7 +527,8 @@ public class JUnitTest extends BaseTest implements Cloneable { * @since Ant 1.5 * @return a clone of this test. */ - public Object clone() { + @Override + public Object clone() { try { JUnitTest t = (JUnitTest) super.clone(); t.props = props == null ? null : (Properties) props.clone(); 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 042b05de0..515e65dcf 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 @@ -75,7 +75,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * Holds the registered formatters. */ - private Vector formatters = new Vector(); + private final Vector formatters = new Vector(); /** * Collects TestResults. @@ -138,7 +138,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * The TestSuite we are currently running. */ - private JUnitTest junitTest; + private final JUnitTest junitTest; /** output written during the test */ private PrintStream systemError; @@ -153,7 +153,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private static boolean multipleTests = false; /** ClassLoader passed in in non-forked mode. */ - private ClassLoader loader; + private final ClassLoader loader; /** Do we print TestListener events? */ private boolean logTestListenerEvents = false; @@ -169,7 +169,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** Names of test methods to execute */ private String[] methods = null; - + /** * Constructor for fork=true or when the user hasn't specified a * classpath. @@ -178,8 +178,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param filtertrace whether to filter junit.*.* stack frames out of exceptions * @param haltOnFailure whether to stop the run if failure is found. */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure) { + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure) { this(test, haltOnError, filtertrace, haltOnFailure, false); } @@ -192,9 +192,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param haltOnFailure whether to stop the run if failure is found. * @param showOutput whether to send output to System.out/.err as well as formatters. */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput) { + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput) { this(test, haltOnError, filtertrace, haltOnFailure, showOutput, false); } @@ -209,9 +209,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param logTestListenerEvents whether to print TestListener events. * @since Ant 1.7 */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput, boolean logTestListenerEvents) { + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput, final boolean logTestListenerEvents) { this(test, null, haltOnError, filtertrace, haltOnFailure, showOutput, logTestListenerEvents, null); } @@ -228,9 +228,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param logTestListenerEvents whether to print TestListener events. * @since 1.8.2 */ - public JUnitTestRunner(JUnitTest test, String[] methods, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput, boolean logTestListenerEvents) { + public JUnitTestRunner(final JUnitTest test, final String[] methods, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput, final boolean logTestListenerEvents) { this(test, methods, haltOnError, filtertrace, haltOnFailure, showOutput, logTestListenerEvents, null); } @@ -243,9 +243,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param haltOnFailure whether to stop the run if failure is found. * @param loader the classloader to use running the test. */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - ClassLoader loader) { + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final ClassLoader loader) { this(test, haltOnError, filtertrace, haltOnFailure, false, loader); } @@ -258,9 +258,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param showOutput whether to send output to System.out/.err as well as formatters. * @param loader the classloader to use running the test. */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput, ClassLoader loader) { + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput, final ClassLoader loader) { this(test, haltOnError, filtertrace, haltOnFailure, showOutput, false, loader); } @@ -276,11 +276,11 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param loader the classloader to use running the test. * @since Ant 1.7 */ - public JUnitTestRunner(JUnitTest test, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput, boolean logTestListenerEvents, - ClassLoader loader) { - this(test, null, haltOnError, filtertrace, haltOnFailure, showOutput, + public JUnitTestRunner(final JUnitTest test, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput, final boolean logTestListenerEvents, + final ClassLoader loader) { + this(test, null, haltOnError, filtertrace, haltOnFailure, showOutput, logTestListenerEvents, loader); } @@ -289,10 +289,10 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * Constructor to use when the user has specified a classpath. * @since 1.8.2 */ - public JUnitTestRunner(JUnitTest test, String[] methods, boolean haltOnError, - boolean filtertrace, boolean haltOnFailure, - boolean showOutput, boolean logTestListenerEvents, - ClassLoader loader) { + public JUnitTestRunner(final JUnitTest test, final String[] methods, final boolean haltOnError, + final boolean filtertrace, final boolean haltOnFailure, + final boolean showOutput, final boolean logTestListenerEvents, + final ClassLoader loader) { super(); JUnitTestRunner.filtertrace = filtertrace; // TODO clumsy, should use instance field somehow this.junitTest = test; @@ -310,17 +310,18 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private PrintStream createEmptyStream() { return new PrintStream( new OutputStream() { - public void write(int b) { + @Override + public void write(final int b) { } }); } - private PrintStream createTeePrint(PrintStream ps1, PrintStream ps2) { + private PrintStream createTeePrint(final PrintStream ps1, final PrintStream ps2) { return new PrintStream(new TeeOutputStream(ps1, ps2)); } - private void setupIOStreams(ByteArrayOutputStream o, - ByteArrayOutputStream e) { + private void setupIOStreams(final ByteArrayOutputStream o, + final ByteArrayOutputStream e) { systemOut = new PrintStream(o); systemError = new PrintStream(e); @@ -354,7 +355,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * Run the test. */ - public void run() { + @Override + public void run() { res = new IgnoredTestResult(); res.addListener(wrapListener(this)); final int size = formatters.size(); @@ -362,8 +364,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR res.addListener(wrapListener((TestListener) formatters.elementAt(i))); } - ByteArrayOutputStream errStrm = new ByteArrayOutputStream(); - ByteArrayOutputStream outStrm = new ByteArrayOutputStream(); + final ByteArrayOutputStream errStrm = new ByteArrayOutputStream(); + final ByteArrayOutputStream outStrm = new ByteArrayOutputStream(); setupIOStreams(outStrm, errStrm); @@ -391,7 +393,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR try { // check if there is a suite method suiteMethod = testClass.getMethod("suite", new Class[0]); - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { // no appropriate suite method found. We don't report any // error here since it might be perfectly normal. } @@ -461,14 +463,14 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR useSingleMethodAdapter = true; } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // OK, fall back to JUnit 3. } } junit4 = junit4TestAdapterClass != null; if (junitTest.isSkipNonTests()) { - if (!containsTests( testClass, junit4)) { + if (!containsTests(testClass, junit4)) { return; } } @@ -500,7 +502,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } else if (methods.length == 1) { suite = TestSuite.createTest(testClass, methods[0]); } else { - TestSuite testSuite = new TestSuite(testClass.getName()); + final TestSuite testSuite = new TestSuite(testClass.getName()); for (int i = 0; i < methods.length; i++) { testSuite.addTest( TestSuite.createTest(testClass, methods[i])); @@ -511,12 +513,12 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } - } catch (Throwable e) { + } catch (final Throwable e) { retCode = ERRORS; exception = e; } - long start = System.currentTimeMillis(); + final long start = System.currentTimeMillis(); fireStartTestSuite(); startTestSuiteSuccess = true; @@ -535,7 +537,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } finally { if (junit4 || suite.getClass().getName().equals(JUNIT_4_TEST_ADAPTER)) { - int[] cnts = findJUnit4FailureErrorCount(res); + final int[] cnts = findJUnit4FailureErrorCount(res); junitTest.setCounts(res.runCount() + res.ignoredCount(), cnts[0], cnts[1], res.ignoredCount() + res.skippedCount()); } else { junitTest.setCounts(res.runCount() + res.ignoredCount(), res.failureCount(), @@ -563,12 +565,12 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR String out, err; try { out = new String(outStrm.toByteArray()); - } catch (OutOfMemoryError ex) { + } catch (final OutOfMemoryError ex) { out = "out of memory on output stream"; } try { err = new String(errStrm.toByteArray()); - } catch (OutOfMemoryError ex) { + } catch (final OutOfMemoryError ex) { err = "out of memory on error stream"; } sendOutAndErr(out, err); @@ -584,14 +586,14 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } - private static boolean containsTests(Class testClass, boolean isJUnit4) { + private static boolean containsTests(final Class testClass, final boolean isJUnit4) { Class testAnnotation = null; Class suiteAnnotation = null; Class runWithAnnotation = null; try { testAnnotation = Class.forName("org.junit.Test"); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { if (isJUnit4) { // odd - we think we're JUnit4 but don't support the test annotation. We therefore can't have any tests! return false; @@ -601,12 +603,12 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR try { suiteAnnotation = Class.forName("org.junit.Suite.SuiteClasses"); - } catch(ClassNotFoundException ex) { + } catch(final ClassNotFoundException ex) { // ignore - we don't have this annotation so make sure we don't check for it } try { runWithAnnotation = Class.forName("org.junit.runner.RunWith"); - } catch(ClassNotFoundException ex) { + } catch(final ClassNotFoundException ex) { // also ignore as this annotation doesn't exist so tests can't use it } @@ -617,7 +619,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } // check if we have any inner classes that contain suitable test methods - for (Class innerClass : testClass.getDeclaredClasses()) { + for (final Class innerClass : testClass.getDeclaredClasses()) { if (containsTests(innerClass, isJUnit4) || containsTests(innerClass, !isJUnit4)) { return true; } @@ -645,7 +647,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } - for (Method m : testClass.getMethods()) { + for (final Method m : testClass.getMethods()) { if (isJUnit4) { // check if suspected JUnit4 classes have methods with @Test annotation if (m.getAnnotation(testAnnotation) != null) { @@ -676,7 +678,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @return 2 if errors occurred, 1 if tests failed else 0. */ - public int getRetCode() { + @Override + public int getRetCode() { return retCode; } @@ -686,8 +689,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR *

A new Test is started. * @param t the test. */ - public void startTest(Test t) { - String testName = JUnitVersionHelper.getTestCaseName(t); + @Override + public void startTest(final Test t) { + final String testName = JUnitVersionHelper.getTestCaseName(t); logTestListenerEvent("startTest(" + testName + ")"); } @@ -697,19 +701,20 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR *

A Test is finished. * @param test the test. */ - public void endTest(Test test) { - String testName = JUnitVersionHelper.getTestCaseName(test); + @Override + public void endTest(final Test test) { + final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("endTest(" + testName + ")"); } private void logTestListenerEvent(String msg) { if (logTestListenerEvents) { - PrintStream out = savedOut != null ? savedOut : System.out; + final PrintStream out = savedOut != null ? savedOut : System.out; out.flush(); if (msg == null) { msg = "null"; } - StringTokenizer msgLines = new StringTokenizer(msg, "\r\n", false); + final StringTokenizer msgLines = new StringTokenizer(msg, "\r\n", false); while (msgLines.hasMoreTokens()) { out.println(JUnitTask.TESTLISTENER_PREFIX + msgLines.nextToken()); @@ -725,8 +730,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the exception thrown by the test. */ - public void addFailure(Test test, Throwable t) { - String testName = JUnitVersionHelper.getTestCaseName(test); + public void addFailure(final Test test, final Throwable t) { + final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("addFailure(" + testName + ", " + t.getMessage() + ")"); if (haltOnFailure) { res.stop(); @@ -740,7 +745,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the assertion thrown by the test. */ - public void addFailure(Test test, AssertionFailedError t) { + @Override + public void addFailure(final Test test, final AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -751,8 +757,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the error thrown by the test. */ - public void addError(Test test, Throwable t) { - String testName = JUnitVersionHelper.getTestCaseName(test); + @Override + public void addError(final Test test, final Throwable t) { + final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("addError(" + testName + ", " + t.getMessage() + ")"); if (haltOnError) { res.stop(); @@ -764,7 +771,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @since Ant 1.6 * @param permissions the permissions to use. */ - public void setPermissions(Permissions permissions) { + @Override + public void setPermissions(final Permissions permissions) { perm = permissions; } @@ -772,7 +780,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * Handle a string destined for standard output. * @param output the string to output */ - public void handleOutput(String output) { + @Override + public void handleOutput(final String output) { if (!logTestListenerEvents && output.startsWith(JUnitTask.TESTLISTENER_PREFIX)) { // ignore } else if (systemOut != null) { @@ -791,36 +800,40 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @since Ant 1.6 */ - public int handleInput(byte[] buffer, int offset, int length) + @Override + public int handleInput(final byte[] buffer, final int offset, final int length) throws IOException { return -1; } /** {@inheritDoc}. */ - public void handleErrorOutput(String output) { + @Override + public void handleErrorOutput(final String output) { if (systemError != null) { systemError.print(output); } } /** {@inheritDoc}. */ - public void handleFlush(String output) { + @Override + public void handleFlush(final String output) { if (systemOut != null) { systemOut.print(output); } } /** {@inheritDoc}. */ - public void handleErrorFlush(String output) { + @Override + public void handleErrorFlush(final String output) { if (systemError != null) { systemError.print(output); } } - private void sendOutAndErr(String out, String err) { + private void sendOutAndErr(final String out, final String err) { final int size = formatters.size(); for (int i = 0; i < size; i++) { - JUnitResultFormatter formatter = + final JUnitResultFormatter formatter = ((JUnitResultFormatter) formatters.elementAt(i)); formatter.setSystemOutput(out); @@ -848,12 +861,13 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * Add a formatter. * @param f the formatter to add. */ - public void addFormatter(JUnitResultFormatter f) { + public void addFormatter(final JUnitResultFormatter f) { formatters.addElement(f); } /** {@inheritDoc}. */ - public void addFormatter(JUnitTaskMirror.JUnitResultFormatterMirror f) { + @Override + public void addFormatter(final JUnitTaskMirror.JUnitResultFormatterMirror f) { formatters.addElement(f); } @@ -890,12 +904,12 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param args the command line arguments. * @throws IOException on error. */ - public static void main(String[] args) throws IOException { + public static void main(final String[] args) throws IOException { String[] methods = null; boolean haltError = false; boolean haltFail = false; boolean stackfilter = true; - Properties props = new Properties(); + final Properties props = new Properties(); boolean showOut = false; boolean outputToFormat = true; boolean logFailedTests = true; @@ -916,9 +930,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR for (int i = 1; i < args.length; i++) { if (args[i].startsWith(Constants.METHOD_NAMES)) { try { - String methodsList = args[i].substring(Constants.METHOD_NAMES.length()); + final String methodsList = args[i].substring(Constants.METHOD_NAMES.length()); methods = JUnitTest.parseTestMethodNamesList(methodsList); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { System.err.println("Invalid specification of test method names: " + args[i]); System.exit(ERRORS); } @@ -934,12 +948,12 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } else if (args[i].startsWith(Constants.FORMATTER)) { try { createAndStoreFormatter(args[i].substring(Constants.FORMATTER.length())); - } catch (BuildException be) { + } catch (final BuildException be) { System.err.println(be.getMessage()); System.exit(ERRORS); } } else if (args[i].startsWith(Constants.PROPSFILE)) { - FileInputStream in = new FileInputStream(args[i] + final FileInputStream in = new FileInputStream(args[i] .substring(Constants.PROPSFILE.length())); props.load(in); in.close(); @@ -958,21 +972,21 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR 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()) ); + antThreadID = Integer.parseInt(args[i].substring(Constants.THREADID.length())); } } // Add/overlay system properties on the properties from the Ant project - Hashtable p = System.getProperties(); - for (Enumeration e = p.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); + final Hashtable p = System.getProperties(); + for (final Enumeration e = p.keys(); e.hasMoreElements();) { + final Object key = e.nextElement(); props.put(key, p.get(key)); } int returnCode = SUCCESS; if (multipleTests) { try { - java.io.BufferedReader reader = + final java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(args[0])); String testCaseName; String[] testMethodNames; @@ -981,9 +995,9 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR boolean failureOccurred = false; String line = null; while ((line = reader.readLine()) != null) { - StringTokenizer st = new StringTokenizer(line, ","); - String testListSpec = st.nextToken(); - int colonIndex = testListSpec.indexOf(':'); + final StringTokenizer st = new StringTokenizer(line, ","); + final String testListSpec = st.nextToken(); + final int colonIndex = testListSpec.indexOf(':'); if (colonIndex == -1) { testCaseName = testListSpec; testMethodNames = null; @@ -994,7 +1008,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR .substring(colonIndex + 1) .replace('+', ',')); } - JUnitTest t = new JUnitTest(testCaseName); + final JUnitTest t = new JUnitTest(testCaseName); t.setTodir(new File(st.nextToken())); t.setOutfile(st.nextToken()); t.setProperties(props); @@ -1021,11 +1035,11 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } } - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } else { - JUnitTest t = new JUnitTest(args[0]); + final JUnitTest t = new JUnitTest(args[0]); t.setThread(antThreadID); t.setProperties(props); t.setSkipNonTests(skipNonTests); @@ -1040,43 +1054,52 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private static Vector fromCmdLine = new Vector(); - private static void transferFormatters(JUnitTestRunner runner, - JUnitTest test) { + private static void transferFormatters(final JUnitTestRunner runner, + final JUnitTest test) { runner.addFormatter(new JUnitResultFormatter() { - public void startTestSuite(JUnitTest suite) throws BuildException { + @Override + public void startTestSuite(final JUnitTest suite) throws BuildException { } - public void endTestSuite(JUnitTest suite) throws BuildException { + @Override + public void endTestSuite(final JUnitTest suite) throws BuildException { } - public void setOutput(OutputStream out) { + @Override + public void setOutput(final OutputStream out) { } - public void setSystemOutput(String out) { + @Override + public void setSystemOutput(final String out) { } - public void setSystemError(String err) { + @Override + public void setSystemError(final String err) { } - public void addError(Test arg0, Throwable arg1) { + @Override + public void addError(final Test arg0, final Throwable arg1) { } - public void addFailure(Test arg0, AssertionFailedError arg1) { + @Override + public void addFailure(final Test arg0, final AssertionFailedError arg1) { } - public void endTest(Test arg0) { + @Override + public void endTest(final Test arg0) { } - public void startTest(Test arg0) { + @Override + public void startTest(final Test arg0) { registerTestCase(JUnitVersionHelper.getTestCaseName(arg0)); } }); final int size = fromCmdLine.size(); for (int i = 0; i < size; i++) { - FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i); + final FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i); if (multipleTests && fe.getUseFile()) { - File destFile = + final File destFile = new File(test.getTodir(), test.getOutfile() + fe.getExtension()); fe.setOutfile(destFile); @@ -1088,10 +1111,10 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * Line format is: formatter=(,)? */ - private static void createAndStoreFormatter(String line) + private static void createAndStoreFormatter(final String line) throws BuildException { - FormatterElement fe = new FormatterElement(); - int pos = line.indexOf(','); + final FormatterElement fe = new FormatterElement(); + final int pos = line.indexOf(','); if (pos == -1) { fe.setClassname(line); fe.setUseFile(false); @@ -1101,7 +1124,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR if (!multipleTests) { fe.setOutfile(new File(line.substring(pos + 1))); } else { - int fName = line.indexOf(IGNORED_FILE_NAME); + final int fName = line.indexOf(IGNORED_FILE_NAME); if (fName > -1) { fe.setExtension(line .substring(fName @@ -1118,8 +1141,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param t the exception to filter. * @return the filtered stack trace. */ - public static String getFilteredTrace(Throwable t) { - String trace = StringUtils.getStackTrace(t); + public static String getFilteredTrace(final Throwable t) { + final String trace = StringUtils.getStackTrace(t); return JUnitTestRunner.filterStack(trace); } @@ -1128,14 +1151,14 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param stack the stack trace to filter. * @return the filtered stack. */ - public static String filterStack(String stack) { + public static String filterStack(final String stack) { if (!filtertrace) { return stack; } - StringWriter sw = new StringWriter(); - BufferedWriter pw = new BufferedWriter(sw); - StringReader sr = new StringReader(stack); - BufferedReader br = new BufferedReader(sr); + final StringWriter sw = new StringWriter(); + final BufferedWriter pw = new BufferedWriter(sw); + final StringReader sr = new StringReader(stack); + final BufferedReader br = new BufferedReader(sr); String line; try { @@ -1147,7 +1170,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } firstLine = false; } - } catch (Exception e) { + } catch (final Exception e) { return stack; // return the stack unfiltered } finally { FileUtils.close(pw); @@ -1155,7 +1178,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR return sw.toString(); } - private static boolean filterLine(String line) { + 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) { return true; @@ -1167,11 +1190,11 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * @since Ant 1.6.2 */ - private static int launch(JUnitTest t, String[] methods, boolean haltError, - boolean stackfilter, boolean haltFail, - boolean showOut, boolean outputToFormat, - boolean logTestListenerEvents) { - JUnitTestRunner runner = + private static int launch(final JUnitTest t, final String[] methods, final boolean haltError, + final boolean stackfilter, final boolean haltFail, + final boolean showOut, final boolean outputToFormat, + final boolean logTestListenerEvents) { + final JUnitTestRunner runner = new JUnitTestRunner(t, methods, haltError, stackfilter, haltFail, showOut, logTestListenerEvents, null); runner.forked = true; @@ -1199,7 +1222,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } - private static void registerTestCase(String testCase) { + private static void registerTestCase(final String testCase) { if (crashFile != null) { try { FileWriter out = null; @@ -1210,7 +1233,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } finally { FileUtils.close(out); } - } catch (IOException e) { + } catch (final IOException e) { // ignored. } } @@ -1224,7 +1247,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR */ private TestListenerWrapper wrapListener(final TestListener testListener) { return new TestListenerWrapper(testListener) { - public void addError(Test test, Throwable t) { + @Override + public void addError(final Test test, final Throwable t) { if (junit4 && t instanceof AssertionFailedError) { // JUnit 4 does not distinguish between errors and failures // even in the JUnit 3 adapter. @@ -1235,8 +1259,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // JUnit 4-specific test GUIs will show just "failures". // But Ant's output shows "failures" vs. "errors". // We would prefer to show "failure" for things that logically are. - String msg = t.getMessage(); - AssertionFailedError failure = msg != null + final String msg = t.getMessage(); + final AssertionFailedError failure = msg != null ? new AssertionFailedError(msg) : new AssertionFailedError(); failure.setStackTrace(t.getStackTrace()); testListener.addFailure(test, failure); @@ -1244,20 +1268,23 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR testListener.addError(test, t); } } - public void addFailure(Test test, AssertionFailedError t) { + @Override + public void addFailure(final Test test, final AssertionFailedError t) { testListener.addFailure(test, t); } - public void addFailure(Test test, Throwable t) { // pre-3.4 + public void addFailure(final Test test, final Throwable t) { // pre-3.4 if (t instanceof AssertionFailedError) { testListener.addFailure(test, (AssertionFailedError) t); } else { testListener.addError(test, t); } } - public void endTest(Test test) { + @Override + public void endTest(final Test test) { testListener.endTest(test); } - public void startTest(Test test) { + @Override + public void startTest(final Test test) { testListener.startTest(test); } }; @@ -1268,7 +1295,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * since the adapter claims that all failures are errors. * @since Ant 1.7 */ - private int[] findJUnit4FailureErrorCount(TestResult result) { + private int[] findJUnit4FailureErrorCount(final TestResult result) { int failures = 0; int errors = 0; Enumeration e = result.failures(); @@ -1278,7 +1305,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } e = result.errors(); while (e.hasMoreElements()) { - Throwable t = ((TestFailure) e.nextElement()).thrownException(); + final Throwable t = ((TestFailure) e.nextElement()).thrownException(); if (t instanceof AssertionFailedError || t instanceof AssertionError) { failures++; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java index c32870db8..4d6f9af8b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java @@ -43,7 +43,8 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { * Records the suite's name to later determine the class to invoke * tearDown on. */ - public void startTestSuite(final JUnitTest suite) { + @Override + public void startTestSuite(final JUnitTest suite) { suiteName = suite.getName(); if (suiteName != null && suiteName.endsWith(JUnitTask.NAME_OF_DUMMY_TEST)) { @@ -57,7 +58,8 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { * test we get when a Batch fails and the error is an actual * error generated by Ant. */ - public void addError(final Test fakeTest, final Throwable t) { + @Override + public void addError(final Test fakeTest, final Throwable t) { if (suiteName != null && fakeTest instanceof JUnitTaskMirrorImpl.VmExitErrorTest) { tearDown(); @@ -67,19 +69,26 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { // no need to implement the rest public void addFailure(Test test, Throwable t) {} - public void addFailure(Test test, AssertionFailedError t) {} + @Override + public void addFailure(Test test, AssertionFailedError t) {} - public void startTest(Test test) {} + @Override + public void startTest(Test test) {} - public void endTest(Test test) {} + @Override + public void endTest(Test test) {} - public void endTestSuite(JUnitTest suite) {} - - public void setOutput(OutputStream out) {} + @Override + public void endTestSuite(JUnitTest suite) {} - public void setSystemOutput(String out) {} + @Override + public void setOutput(OutputStream out) {} - public void setSystemError(String err) {} + @Override + public void setSystemOutput(String out) {} + + @Override + public void setSystemError(String err) {} private void tearDown() { try { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java index 3c159f01b..2a93474ce 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java @@ -76,7 +76,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan private Element rootElement; /** * Element for the current test. - * + * * The keying of this map is a bit of a hack: tests are keyed by caseName(className) since * the Test we get for Test-start isn't the same as the Test we get during test-assumption-fail, * so we can't easily match Test objects without manually iterating over all keys and checking @@ -109,17 +109,20 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan } /** {@inheritDoc}. */ - public void setOutput(OutputStream out) { + @Override + public void setOutput(OutputStream out) { this.out = out; } /** {@inheritDoc}. */ - public void setSystemOutput(String out) { + @Override + public void setSystemOutput(String out) { formatOutput(SYSTEM_OUT, out); } /** {@inheritDoc}. */ - public void setSystemError(String out) { + @Override + public void setSystemError(String out) { formatOutput(SYSTEM_ERR, out); } @@ -127,7 +130,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * The whole testsuite started. * @param suite the testsuite. */ - public void startTestSuite(JUnitTest suite) { + @Override + public void startTestSuite(JUnitTest suite) { doc = getDocumentBuilder().newDocument(); rootElement = doc.createElement(TESTSUITE); String n = suite.getName(); @@ -178,7 +182,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param suite the testsuite. * @throws BuildException on error. */ - public void endTestSuite(JUnitTest suite) throws BuildException { + @Override + public void endTestSuite(JUnitTest suite) throws BuildException { rootElement.setAttribute(ATTR_TESTS, "" + suite.runCount()); rootElement.setAttribute(ATTR_FAILURES, "" + suite.failureCount()); rootElement.setAttribute(ATTR_ERRORS, "" + suite.errorCount()); @@ -214,7 +219,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan *

A new Test is started. * @param t the test. */ - public void startTest(Test t) { + @Override + public void startTest(Test t) { testStarts.put(createDescription(t), System.currentTimeMillis()); } @@ -228,7 +234,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan *

A Test is finished. * @param test the test. */ - public void endTest(Test test) { + @Override + public void endTest(Test test) { String testDescription = createDescription(test); // Fix for bug #5637 - if a junit.extensions.TestSetup is @@ -276,7 +283,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param test the test. * @param t the assertion. */ - public void addFailure(Test test, AssertionFailedError t) { + @Override + public void addFailure(Test test, AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -287,7 +295,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param test the test. * @param t the error. */ - public void addError(Test test, Throwable t) { + @Override + public void addError(Test test, Throwable t) { formatError(ERROR, test, t); } @@ -324,7 +333,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan nested.appendChild(doc.createCDATASection(output)); } - public void testIgnored(Test test) { + @Override + public void testIgnored(Test test) { formatSkip(test, JUnitVersionHelper.getIgnoreMessage(test)); if (test != null) { ignoredTests.put(createDescription(test), test); @@ -354,7 +364,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan } - public void testAssumptionFailure(Test test, Throwable failure) { + @Override + public void testAssumptionFailure(Test test, Throwable failure) { formatSkip(test, failure.getMessage()); skippedTests.put(createDescription(test), test); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirror.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirror.java index e01403b12..5d09e6f6f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirror.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirror.java @@ -20,6 +20,5 @@ package org.apache.tools.ant.taskdefs.optional.net; import org.apache.tools.ant.BuildException; public interface FTPTaskMirror { - - public void doFTP() throws BuildException; + void doFTP() throws BuildException; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java index 042155ed1..ff3a94008 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java @@ -71,7 +71,8 @@ public class SplashTask extends Task { * @deprecated since 1.5.x. * Use org.apache.tools.ant.taskdefs.optional.net.SetProxy */ - public void setUseproxy(boolean useProxy) { + @Deprecated + public void setUseproxy(boolean useProxy) { this.useProxy = useProxy; } @@ -81,7 +82,8 @@ public class SplashTask extends Task { * @deprecated since 1.5.x. * Use org.apache.tools.ant.taskdefs.optional.net.SetProxy */ - public void setProxy(String proxy) { + @Deprecated + public void setProxy(String proxy) { this.proxy = proxy; } @@ -91,7 +93,8 @@ public class SplashTask extends Task { * @deprecated since 1.5.x. * Use org.apache.tools.ant.taskdefs.optional.net.SetProxy */ - public void setPort(String port) { + @Deprecated + public void setPort(String port) { this.port = port; } @@ -101,7 +104,8 @@ public class SplashTask extends Task { * @deprecated since 1.5.x. * Use org.apache.tools.ant.taskdefs.optional.net.SetProxy */ - public void setUser(String user) { + @Deprecated + public void setUser(String user) { this.user = user; } @@ -111,7 +115,8 @@ public class SplashTask extends Task { * @deprecated since 1.5.x. * Use org.apache.tools.ant.taskdefs.optional.net.SetProxy */ - public void setPassword(String password) { + @Deprecated + public void setPassword(String password) { this.password = password; } @@ -140,7 +145,7 @@ public class SplashTask extends Task { /** * Sets the display text presented in the splash window. - * optional; defaults to "Building ..." + * optional; defaults to "Building ..." * @param displayText the display text presented the splash window * @since Ant 1.8.0 */ @@ -152,7 +157,8 @@ public class SplashTask extends Task { * Execute the task. * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (splash != null) { splash.setVisible(false); getProject().removeBuildListener(splash); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java index f5455916d..3dea1d8ee 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java @@ -119,13 +119,12 @@ public class Directory { * @return the child directory, or null if not found */ public Directory getChild(File dir) { - for (Iterator i = childDirectories.iterator(); i.hasNext(); ) { + for (Iterator i = childDirectories.iterator(); i.hasNext();) { Directory current = (Directory) i.next(); if (current.getDirectory().equals(dir)) { return current; } } - return null; } @@ -135,7 +134,8 @@ public class Directory { * @param obj the object to compare to * @return true if this object has an equal directory field as the other object */ - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) { if (obj == this) { return true; } @@ -153,7 +153,8 @@ public class Directory { * The hashcode method. * @return the hash code of the directory field */ - public int hashCode() { + @Override + public int hashCode() { return directory.hashCode(); } 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 1a8517bb7..564d07d87 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 @@ -100,7 +100,7 @@ public class SSHExec extends SSHBase { * * @param command The new command value */ - public void setCommand(String command) { + public void setCommand(final String command) { this.command = command; } @@ -109,7 +109,7 @@ public class SSHExec extends SSHBase { * @param f the value to use. * @since Ant 1.7.1 */ - public void setCommandResource(String f) { + public void setCommandResource(final String f) { this.commandResource = new FileResource(new File(f)); } @@ -120,7 +120,7 @@ public class SSHExec extends SSHBase { * * @param timeout The new timeout value in seconds */ - public void setTimeout(long timeout) { + public void setTimeout(final long timeout) { maxwait = timeout; } @@ -129,7 +129,7 @@ public class SSHExec extends SSHBase { * * @param output The file to write to. */ - public void setOutput(File output) { + public void setOutput(final File output) { outputFile = output; } @@ -139,7 +139,7 @@ public class SSHExec extends SSHBase { * @param output The file to write to. * @since Apache Ant 1.9.4 */ - public void setErrorOutput(File output) { + public void setErrorOutput(final File output) { errorFile = output; } @@ -150,7 +150,7 @@ public class SSHExec extends SSHBase { * * @since Ant 1.8.0 */ - public void setInput(File input) { + public void setInput(final File input) { inputFile = input; } @@ -162,7 +162,7 @@ public class SSHExec extends SSHBase { * * @since Ant 1.8.0 */ - public void setInputProperty(String inputProperty) { + public void setInputProperty(final String inputProperty) { this.inputProperty = inputProperty; } @@ -173,7 +173,7 @@ public class SSHExec extends SSHBase { * * @since Ant 1.8.3 */ - public void setInputString(String inputString) { + public void setInputString(final String inputString) { this.inputString = inputString; } @@ -184,7 +184,7 @@ public class SSHExec extends SSHBase { * * @param append True to append to an existing file, false to overwrite. */ - public void setAppend(boolean append) { + public void setAppend(final boolean append) { this.append = append; } @@ -196,7 +196,7 @@ public class SSHExec extends SSHBase { * @param append True to append to an existing file, false to overwrite. * @since Apache Ant 1.9.4 */ - public void setErrAppend(boolean appenderr) { + public void setErrAppend(final boolean appenderr) { this.appenderr = appenderr; } @@ -206,7 +206,7 @@ public class SSHExec extends SSHBase { * @param property The name of the property in which the command output * will be stored. */ - public void setOutputproperty(String property) { + public void setOutputproperty(final String property) { outputProperty = property; } @@ -217,7 +217,7 @@ public class SSHExec extends SSHBase { * will be stored. * @since Apache Ant 1.9.4 */ - public void setErrorproperty (String property) { + public void setErrorproperty (final String property) { errorProperty = property; } @@ -228,7 +228,7 @@ public class SSHExec extends SSHBase { * will be stored. * @since Apache Ant 1.9.4 */ - public void setResultproperty(String property) { + public void setResultproperty(final String property) { resultProperty = property; } @@ -236,17 +236,17 @@ public class SSHExec extends SSHBase { * Whether a pseudo-tty should be allocated. * @since Apache Ant 1.8.3 */ - public void setUsePty(boolean b) { + public void setUsePty(final boolean b) { usePty = b; } /** * If set, input will be taken from System.in - * + * * @param useSystemIn True to use System.in as InputStream, false otherwise * @since Apache Ant 1.9.4 */ - public void setUseSystemIn(boolean useSystemIn) { + public void setUseSystemIn(final boolean useSystemIn) { this.useSystemIn = useSystemIn; } @@ -255,7 +255,7 @@ public class SSHExec extends SSHBase { * If suppressSystemOut is false, normal behavior * @since Ant 1.9.0 */ - public void setSuppressSystemOut(boolean suppressSystemOut) { + public void setSuppressSystemOut(final boolean suppressSystemOut) { this.suppressSystemOut = suppressSystemOut; } @@ -264,7 +264,7 @@ public class SSHExec extends SSHBase { * If suppressSystemErr is false, normal behavior * @since Ant 1.9.4 */ - public void setSuppressSystemErr(boolean suppressSystemErr) { + public void setSuppressSystemErr(final boolean suppressSystemErr) { this.suppressSystemErr = suppressSystemErr; } @@ -273,7 +273,8 @@ public class SSHExec extends SSHBase { * * @exception BuildException Most likely a network error or bad parameter. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (getHost() == null) { throw new BuildException("Host is required."); @@ -289,7 +290,7 @@ public class SSHExec extends SSHBase { throw new BuildException("Command or commandResource is required."); } - int numberOfInputs = (inputFile != null ? 1 : 0) + final int numberOfInputs = (inputFile != null ? 1 : 0) + (inputProperty != null ? 1 : 0) + (inputString != null ? 1 : 0); if (numberOfInputs > 1) { @@ -304,7 +305,7 @@ public class SSHExec extends SSHBase { } Session session = null; - StringBuffer output = new StringBuffer(); + final StringBuffer output = new StringBuffer(); try { session = openSession(); /* called once */ @@ -313,7 +314,7 @@ public class SSHExec extends SSHBase { executeCommand(session, command, output); } else { // read command resource and execute for each command try { - BufferedReader br = new BufferedReader( + final BufferedReader br = new BufferedReader( new InputStreamReader(commandResource.getInputStream())); String cmd; while ((cmd = br.readLine()) != null) { @@ -323,7 +324,7 @@ public class SSHExec extends SSHBase { output.append("\n"); } FileUtils.close(br); - } catch (IOException e) { + } catch (final IOException e) { if (getFailonerror()) { throw new BuildException(e); } else { @@ -332,7 +333,7 @@ public class SSHExec extends SSHBase { } } } - } catch (JSchException e) { + } catch (final JSchException e) { if (getFailonerror()) { throw new BuildException(e); } else { @@ -348,18 +349,18 @@ public class SSHExec extends SSHBase { } } - private void executeCommand(Session session, String cmd, StringBuffer sb) + private void executeCommand(final Session session, final String cmd, final StringBuffer sb) throws BuildException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream errout = new ByteArrayOutputStream(); - OutputStream teeErr = suppressSystemErr ? errout : new TeeOutputStream(errout, KeepAliveOutputStream.wrapSystemErr()); - OutputStream tee = suppressSystemOut ? out : new TeeOutputStream(out, KeepAliveOutputStream.wrapSystemOut()); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final ByteArrayOutputStream errout = new ByteArrayOutputStream(); + final OutputStream teeErr = suppressSystemErr ? errout : new TeeOutputStream(errout, KeepAliveOutputStream.wrapSystemErr()); + final OutputStream tee = suppressSystemOut ? out : new TeeOutputStream(out, KeepAliveOutputStream.wrapSystemOut()); - InputStream istream = null ; + InputStream istream = null; if (inputFile != null) { try { - istream = new FileInputStream(inputFile) ; - } catch (IOException e) { + istream = new FileInputStream(inputFile); + } catch (final IOException e) { // because we checked the existence before, this one // shouldn't happen What if the file exists, but there // are no read permissions? @@ -368,9 +369,9 @@ public class SSHExec extends SSHBase { } } if (inputProperty != null) { - String inputData = getProject().getProperty(inputProperty) ; + final String inputData = getProject().getProperty(inputProperty); if (inputData != null) { - istream = new ByteArrayInputStream(inputData.getBytes()) ; + istream = new ByteArrayInputStream(inputData.getBytes()); } } if (inputString != null) { @@ -398,14 +399,15 @@ public class SSHExec extends SSHBase { // wait for it to finish thread = new Thread() { - public void run() { + @Override + public void run() { while (!channel.isClosed()) { if (thread == null) { return; } try { sleep(RETRY_INTERVAL); - } catch (Exception e) { + } catch (final Exception e) { // ignored } } @@ -438,13 +440,13 @@ public class SSHExec extends SSHBase { } // this is the wrong test if the remote OS is OpenVMS, // but there doesn't seem to be a way to detect it. - int ec = channel.getExitStatus(); + final int ec = channel.getExitStatus(); // set resultproperty if (resultProperty != null) { getProject().setNewProperty(resultProperty, Integer.toString(ec)); } if (ec != 0) { - String msg = "Remote command failed with exit status " + ec; + final String msg = "Remote command failed with exit status " + ec; if (getFailonerror()) { throw new BuildException(msg); } else { @@ -452,9 +454,9 @@ public class SSHExec extends SSHBase { } } } - } catch (BuildException e) { + } catch (final BuildException e) { throw e; - } catch (JSchException e) { + } catch (final JSchException e) { if (e.getMessage().indexOf("session is down") >= 0) { if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE, e); @@ -469,7 +471,7 @@ public class SSHExec extends SSHBase { Project.MSG_ERR); } } - } catch (Exception e) { + } catch (final Exception e) { if (getFailonerror()) { throw new BuildException(e); } else { @@ -490,13 +492,13 @@ public class SSHExec extends SSHBase { * @param append if true, append to existing file, else overwrite * @exception Exception most likely an IOException */ - private void writeToFile(String from, boolean append, File to) + private void writeToFile(final String from, final boolean append, final File to) throws IOException { FileWriter out = null; try { out = new FileWriter(to.getAbsolutePath(), append); - StringReader in = new StringReader(from); - char[] buffer = new char[BUFFER_SIZE]; + final StringReader in = new StringReader(from); + final char[] buffer = new char[BUFFER_SIZE]; int bytesRead; while (true) { bytesRead = in.read(buffer); 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 c70813f6b..b39aa6b70 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 @@ -130,7 +130,8 @@ public class SSHSession extends SSHBase { * @exception BuildException if one of the nested tasks fails, or * network error or bad parameter. */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (getHost() == null) { throw new BuildException("Host is required."); } @@ -277,13 +278,13 @@ public class SSHSession extends SSHBase { return lport; } public String getLHost() { - if (lhost == null) { + if (lhost == null) { throw new BuildException("lhost is required for RemoteTunnel."); } return lhost; } public int getRPort() { - if (rport == 0) { + if (rport == 0) { throw new BuildException("rport is required for RemoteTunnel."); } return rport; @@ -315,7 +316,8 @@ public class SSHSession extends SSHBase { * * @param task an unknown element. */ - public void addTask(Task task) { + @Override + public void addTask(Task task) { nested.add(task); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java index 62b4245ae..74cd2c865 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java @@ -123,7 +123,7 @@ public class Scp extends SSHBase { */ public void setPreservelastmodified(boolean yesOrNo) { this.preserveLastModified = yesOrNo; - } + } /** * Similiar to {@link #setTodir setTodir} but explicitly states @@ -145,7 +145,7 @@ public class Scp extends SSHBase { + "following: user:password@host:/path" + " - the :password part is optional"); } - } + } /** * Changes the file name to the given name while receiving it, @@ -196,7 +196,8 @@ public class Scp extends SSHBase { * Initialize this task. * @throws BuildException on error */ - public void init() throws BuildException { + @Override + public void init() throws BuildException { super.init(); this.toUri = null; this.fromUri = null; @@ -207,7 +208,8 @@ public class Scp extends SSHBase { * Execute this task. * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { if (toUri == null) { throw exactlyOne(TO_ATTRS); } @@ -362,7 +364,7 @@ public class Scp extends SSHBase { // no password, will require keyfile setUsername(uri.substring(0, indexOfAt)); } else { - throw new BuildException("no username was given. Can't authenticate."); + throw new BuildException("no username was given. Can't authenticate."); } if (getUserInfo().getPassword() == null diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java index 4369028f0..cc5205934 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java @@ -129,7 +129,8 @@ public class Symlink extends DispatchTask { * Initialize the task. * @throws BuildException on error. */ - public void init() throws BuildException { + @Override + public void init() throws BuildException { super.init(); setDefaults(); } @@ -138,7 +139,8 @@ public class Symlink extends DispatchTask { * The standard method for executing any task. * @throws BuildException on error. */ - public synchronized void execute() throws BuildException { + @Override + public synchronized void execute() throws BuildException { if (executing) { throw new BuildException( "Infinite recursion detected in Symlink.execute()"); @@ -325,7 +327,8 @@ public class Symlink extends DispatchTask { * * @param action The action to perform. */ - public void setAction(String action) { + @Override + public void setAction(String action) { super.setAction(action); } @@ -383,7 +386,8 @@ public class Symlink extends DispatchTask { * org.apache.tools.ant.util.SymbolicLinkUtils#deleteSymbolicLink * instead */ - public static void deleteSymlink(String path) + @Deprecated + public static void deleteSymlink(String path) throws IOException, FileNotFoundException { SYMLINK_UTILS.deleteSymbolicLink(new File(path), null); } @@ -403,7 +407,7 @@ public class Symlink extends DispatchTask { * an exception.

* *

Since Ant 1.8.0 this method will try to delete the File object if - * it reports it wouldn't exist (as symlinks pointing nowhere usually do). + * it reports it wouldn't exist (as symlinks pointing nowhere usually do). * Prior version would throw a FileNotFoundException in that case.

* * @param linkfil A File object of the symlink to delete. @@ -416,7 +420,8 @@ public class Symlink extends DispatchTask { * org.apache.tools.ant.util.SymbolicLinkUtils#deleteSymbolicLink * instead */ - public static void deleteSymlink(File linkfil) + @Deprecated + public static void deleteSymlink(File linkfil) throws IOException { SYMLINK_UTILS.deleteSymbolicLink(linkfil, null); } diff --git a/src/main/org/apache/tools/ant/types/FilterChain.java b/src/main/org/apache/tools/ant/types/FilterChain.java index 06e889961..a848ce71c 100644 --- a/src/main/org/apache/tools/ant/types/FilterChain.java +++ b/src/main/org/apache/tools/ant/types/FilterChain.java @@ -374,7 +374,8 @@ public class FilterChain extends DataType * @param r the reference to which this instance is associated * @exception BuildException if this instance already has been configured. */ - public void setRefid(Reference r) throws BuildException { + @Override + public void setRefid(Reference r) throws BuildException { if (!filterReaders.isEmpty()) { throw tooManyAttributes(); } @@ -396,7 +397,8 @@ public class FilterChain extends DataType filterReaders.addElement(filter); } - protected synchronized void dieOnCircularReference(Stack stk, Project p) + @Override + protected synchronized void dieOnCircularReference(Stack stk, Project p) throws BuildException { if (isChecked()) { return; @@ -404,7 +406,7 @@ public class FilterChain extends DataType if (isReference()) { super.dieOnCircularReference(stk, p); } else { - for (Iterator i = filterReaders.iterator(); i.hasNext(); ) { + for (Iterator i = filterReaders.iterator(); i.hasNext();) { Object o = i.next(); 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 761deaad4..b853dd1e8 100644 --- a/src/main/org/apache/tools/ant/types/FilterSet.java +++ b/src/main/org/apache/tools/ant/types/FilterSet.java @@ -164,7 +164,8 @@ public class FilterSet extends DataType implements Cloneable { //inherit doc /** {@inheritDoc}. */ - public String[] getValues() { + @Override + public String[] getValues() { return VALUES; } } @@ -229,7 +230,7 @@ public class FilterSet extends DataType implements Cloneable { readingFiles = true; final int size = filtersFiles.size(); for (int i = 0; i < size; i++) { - readFiltersFromFile((File) filtersFiles.get(i)); + readFiltersFromFile(filtersFiles.get(i)); } filtersFiles.clear(); readingFiles = false; @@ -243,7 +244,7 @@ public class FilterSet extends DataType implements Cloneable { * @return the filterset from the reference. */ protected FilterSet getRef() { - return (FilterSet) getCheckedRef(FilterSet.class, "filterset"); + return getCheckedRef(FilterSet.class, "filterset"); } /** @@ -461,7 +462,7 @@ public class FilterSet extends DataType implements Cloneable { /** * Adds the properties provided by the specified PropertySet to this filterset. - * + * * @param propertySet the propertyset to be added to this propertyset */ public synchronized void addConfiguredPropertySet(PropertySet propertySet) { @@ -492,9 +493,10 @@ public class FilterSet extends DataType implements Cloneable { * * @throws BuildException if the clone cannot be performed. */ - public synchronized Object clone() throws BuildException { + @Override + public synchronized Object clone() throws BuildException { if (isReference()) { - return ((FilterSet) getRef()).clone(); + return getRef().clone(); } try { FilterSet fs = (FilterSet) super.clone(); @@ -621,7 +623,7 @@ public class FilterSet extends DataType implements Cloneable { } else if (duplicateToken) { // should always be the case... if (passedTokens.size() > 0) { - value = (String) passedTokens.remove(passedTokens.size() - 1); + value = passedTokens.remove(passedTokens.size() - 1); if (passedTokens.size() == 0) { value = beginToken + value + endToken; duplicateToken = false; diff --git a/src/main/org/apache/tools/ant/types/Permissions.java b/src/main/org/apache/tools/ant/types/Permissions.java index 2ee0cf2e1..103633862 100644 --- a/src/main/org/apache/tools/ant/types/Permissions.java +++ b/src/main/org/apache/tools/ant/types/Permissions.java @@ -44,12 +44,12 @@ import org.apache.tools.ant.ExitException; */ public class Permissions { - private List grantedPermissions = new LinkedList(); - private List revokedPermissions = new LinkedList(); + private final List grantedPermissions = new LinkedList(); + private final List revokedPermissions = new LinkedList(); private java.security.Permissions granted = null; private SecurityManager origSm = null; private boolean active = false; - private boolean delegateToOldSM; + private final boolean delegateToOldSM; // Mandatory constructor for permission object. private static final Class[] PARAMS = {String.class, String.class}; @@ -68,7 +68,7 @@ public class Permissions { * will be used if the permission has not been explicitly granted or revoked * in this instance. */ - public Permissions(boolean delegateToOldSM) { + public Permissions(final boolean delegateToOldSM) { this.delegateToOldSM = delegateToOldSM; } @@ -76,7 +76,7 @@ public class Permissions { * Adds a permission to be granted. * @param perm The Permissions.Permission to be granted. */ - public void addConfiguredGrant(Permissions.Permission perm) { + public void addConfiguredGrant(final Permissions.Permission perm) { grantedPermissions.add(perm); } @@ -84,7 +84,7 @@ public class Permissions { * Adds a permission to be revoked. * @param perm The Permissions.Permission to be revoked */ - public void addConfiguredRevoke(Permissions.Permission perm) { + public void addConfiguredRevoke(final Permissions.Permission perm) { revokedPermissions.add(perm); } @@ -107,17 +107,17 @@ public class Permissions { */ private void init() throws BuildException { granted = new java.security.Permissions(); - for (Permissions.Permission p : revokedPermissions) { + for (final Permissions.Permission p : revokedPermissions) { if (p.getClassName() == null) { throw new BuildException("Revoked permission " + p + " does not contain a class."); } } - for (Permissions.Permission p : grantedPermissions) { + for (final Permissions.Permission p : grantedPermissions) { if (p.getClassName() == null) { throw new BuildException("Granted permission " + p + " does not contain a class."); } else { - java.security.Permission perm = createPermission(p); + final java.security.Permission perm = createPermission(p); granted.add(perm); } } @@ -146,17 +146,17 @@ public class Permissions { } private java.security.Permission createPermission( - Permissions.Permission permission) { + final Permissions.Permission permission) { try { // First add explicitly already resolved permissions will not be // resolved when added as unresolved permission. - Class clazz = Class.forName( + final Class clazz = Class.forName( permission.getClassName()).asSubclass(java.security.Permission.class); - String name = permission.getName(); - String actions = permission.getActions(); - Constructor ctr = clazz.getConstructor(PARAMS); - return ctr.newInstance(new Object[] { name, actions }); - } catch (Exception e) { + final String name = permission.getName(); + final String actions = permission.getActions(); + final Constructor ctr = clazz.getConstructor(PARAMS); + return ctr.newInstance(new Object[] {name, actions}); + } catch (final Exception e) { // Let the UnresolvedPermission handle it. return new UnresolvedPermission(permission.getClassName(), permission.getName(), permission.getActions(), null); @@ -185,11 +185,12 @@ public class Permissions { * Overridden from java.lang.SecurityManager * @param status The exit status requested. */ - public void checkExit(int status) { - java.security.Permission perm = new java.lang.RuntimePermission("exitVM", null); + @Override + public void checkExit(final int status) { + final java.security.Permission perm = new java.lang.RuntimePermission("exitVM", null); try { checkPermission(perm); - } catch (SecurityException e) { + } catch (final SecurityException e) { throw new ExitException(e.getMessage(), status); } } @@ -200,7 +201,8 @@ public class Permissions { * * @param perm The permission requested. */ - public void checkPermission(java.security.Permission perm) { + @Override + public void checkPermission(final java.security.Permission perm) { if (active) { if (delegateToOldSM && !perm.getName().equals("exitVM")) { boolean permOK = false; @@ -228,8 +230,8 @@ public class Permissions { * throws an exception if this permission is revoked * @param perm the permission being checked */ - private void checkRevoked(java.security.Permission perm) { - for (Permissions.Permission revoked : revokedPermissions) { + private void checkRevoked(final java.security.Permission perm) { + for (final Permissions.Permission revoked : revokedPermissions) { if (revoked.matches(perm)) { throw new SecurityException("Permission " + perm + " was revoked."); } @@ -248,7 +250,7 @@ public class Permissions { * Set the class, mandatory. * @param aClass The class name of the permission. */ - public void setClass(String aClass) { + public void setClass(final String aClass) { className = aClass.trim(); } @@ -264,7 +266,7 @@ public class Permissions { * Set the name of the permission. * @param aName The name of the permission. */ - public void setName(String aName) { + public void setName(final String aName) { name = aName.trim(); } @@ -280,7 +282,7 @@ public class Permissions { * Set the actions. * @param actions The actions of the permission. */ - public void setActions(String actions) { + public void setActions(final String actions) { actionString = actions; if (actions.length() > 0) { this.actions = parseActions(actions); @@ -299,7 +301,7 @@ public class Permissions { * Learn whether the permission matches in case of a revoked permission. * @param perm The permission to check against. */ - boolean matches(java.security.Permission perm) { + boolean matches(final java.security.Permission perm) { if (!className.equals(perm.getClass().getName())) { return false; } @@ -315,8 +317,8 @@ public class Permissions { } } if (actions != null) { - Set as = parseActions(perm.getActions()); - int size = as.size(); + final Set as = parseActions(perm.getActions()); + final int size = as.size(); as.removeAll(actions); if (as.size() == size) { // None of the actions revoked, so all allowed. @@ -330,11 +332,11 @@ public class Permissions { * Parses the actions into a set of separate strings. * @param actions The actions to be parsed. */ - private Set parseActions(String actions) { - Set result = new HashSet(); - StringTokenizer tk = new StringTokenizer(actions, ","); + private Set parseActions(final String actions) { + final Set result = new HashSet(); + final StringTokenizer tk = new StringTokenizer(actions, ","); while (tk.hasMoreTokens()) { - String item = tk.nextToken().trim(); + final String item = tk.nextToken().trim(); if (!item.equals("")) { result.add(item); } @@ -346,7 +348,8 @@ public class Permissions { * Get a string description of the permissions. * @return string description of the permissions. */ - public String toString() { + @Override + public String toString() { return ("Permission: " + className + " (\"" + name + "\", \"" + actions + "\")"); } } diff --git a/src/main/org/apache/tools/ant/types/ResourceCollection.java b/src/main/org/apache/tools/ant/types/ResourceCollection.java index 85a5e43f7..0101d706f 100644 --- a/src/main/org/apache/tools/ant/types/ResourceCollection.java +++ b/src/main/org/apache/tools/ant/types/ResourceCollection.java @@ -19,8 +19,6 @@ package org.apache.tools.ant.types; import java.util.Iterator; -import org.apache.tools.ant.types.resources.FileProvider; - /** * Interface describing a collection of Resources. * @since Ant 1.7 diff --git a/src/main/org/apache/tools/ant/types/mappers/CutDirsMapper.java b/src/main/org/apache/tools/ant/types/mappers/CutDirsMapper.java index e1ab5fafa..3c2fcbfb2 100644 --- a/src/main/org/apache/tools/ant/types/mappers/CutDirsMapper.java +++ b/src/main/org/apache/tools/ant/types/mappers/CutDirsMapper.java @@ -38,7 +38,7 @@ public class CutDirsMapper implements FileNameMapper { /** * The number of leading directories to cut. */ - public void setDirs(int dirs) { + public void setDirs(final int dirs) { this.dirs = dirs; } @@ -46,23 +46,26 @@ public class CutDirsMapper implements FileNameMapper { * Empty implementation. * @param ignore ignored. */ - public void setFrom(String ignore) { + @Override + public void setFrom(final String ignore) { } /** * Empty implementation. * @param ignore ignored. */ - public void setTo(String ignore) { + @Override + public void setTo(final String ignore) { } /** {@inheritDoc}. */ - public String[] mapFileName(final String sourceFileName) { + @Override + public String[] mapFileName(final String sourceFileName) { if (dirs <= 0) { throw new BuildException("dirs must be set to a positive number"); } - char fileSep = File.separatorChar; - String fileSepCorrected = + final char fileSep = File.separatorChar; + final String fileSepCorrected = sourceFileName.replace('/', fileSep).replace('\\', fileSep); int nthMatch = fileSepCorrected.indexOf(fileSep); for (int n = 1; nthMatch > -1 && n < dirs; n++) { @@ -71,6 +74,6 @@ public class CutDirsMapper implements FileNameMapper { if (nthMatch == -1) { return null; } - return new String[] { sourceFileName.substring(nthMatch + 1) }; + return new String[] {sourceFileName.substring(nthMatch + 1)}; } } diff --git a/src/main/org/apache/tools/ant/types/resources/Archives.java b/src/main/org/apache/tools/ant/types/resources/Archives.java index 0f45437df..943cfd114 100644 --- a/src/main/org/apache/tools/ant/types/resources/Archives.java +++ b/src/main/org/apache/tools/ant/types/resources/Archives.java @@ -72,13 +72,14 @@ public class Archives extends DataType /** * Sums the sizes of nested archives. */ - public int size() { + @Override + public int size() { if (isReference()) { return ((Archives) getCheckedRef()).size(); } dieOnCircularReference(); int total = 0; - for (Iterator i = grabArchives(); i.hasNext(); ) { + for (Iterator i = grabArchives(); i.hasNext();) { total += i.next().size(); } return total; @@ -87,13 +88,14 @@ public class Archives extends DataType /** * Merges the nested collections. */ - public Iterator iterator() { + @Override + public Iterator iterator() { if (isReference()) { return ((Archives) getCheckedRef()).iterator(); } dieOnCircularReference(); List l = new LinkedList(); - for (Iterator i = grabArchives(); i.hasNext(); ) { + for (Iterator i = grabArchives(); i.hasNext();) { l.addAll(CollectionUtils .asCollection(i.next().iterator())); } @@ -103,7 +105,8 @@ public class Archives extends DataType /** * @return false */ - public boolean isFilesystemOnly() { + @Override + public boolean isFilesystemOnly() { if (isReference()) { return ((Archives) getCheckedRef()).isFilesystemOnly(); } @@ -115,7 +118,8 @@ public class Archives extends DataType * Overrides the base version. * @param r the Reference to set. */ - public void setRefid(Reference r) { + @Override + public void setRefid(Reference r) { if (zips.getResourceCollections().size() > 0 || tars.getResourceCollections().size() > 0) { throw tooManyAttributes(); @@ -128,7 +132,8 @@ public class Archives extends DataType * well. * @return a cloned instance. */ - public Object clone() { + @Override + public Object clone() { try { Archives a = (Archives) super.clone(); a.zips = (Union) zips.clone(); @@ -174,7 +179,8 @@ public class Archives extends DataType * @param p the project to use to dereference the references. * @throws BuildException on error. */ - protected synchronized void dieOnCircularReference(Stack stk, Project p) + @Override + protected synchronized void dieOnCircularReference(Stack stk, Project p) throws BuildException { if (isChecked()) { return; diff --git a/src/main/org/apache/tools/ant/types/resources/ContentTransformingResource.java b/src/main/org/apache/tools/ant/types/resources/ContentTransformingResource.java index 4921e34aa..b4d6de0f5 100644 --- a/src/main/org/apache/tools/ant/types/resources/ContentTransformingResource.java +++ b/src/main/org/apache/tools/ant/types/resources/ContentTransformingResource.java @@ -55,7 +55,8 @@ public abstract class ContentTransformingResource extends ResourceDecorator { * @return the size, as a long, 0 if the Resource does not exist (for * compatibility with java.io.File), or UNKNOWN_SIZE if not known. */ - public long getSize() { + @Override + public long getSize() { if (isExists()) { InputStream in = null; try { @@ -86,7 +87,8 @@ public abstract class ContentTransformingResource extends ResourceDecorator { * @throws UnsupportedOperationException if InputStreams are not * supported for this Resource type. */ - public InputStream getInputStream() throws IOException { + @Override + public InputStream getInputStream() throws IOException { InputStream in = getResource().getInputStream(); if (in != null) { in = wrapStream(in); @@ -102,7 +104,8 @@ public abstract class ContentTransformingResource extends ResourceDecorator { * @throws UnsupportedOperationException if OutputStreams are not * supported for this Resource type. */ - public OutputStream getOutputStream() throws IOException { + @Override + public OutputStream getOutputStream() throws IOException { OutputStream out = getResource().getOutputStream(); if (out != null) { out = wrapStream(out); @@ -113,14 +116,16 @@ public abstract class ContentTransformingResource extends ResourceDecorator { /** * Suppress FileProvider, re-implement Appendable */ - public T as(Class clazz) { + @Override + public T as(Class clazz) { if (Appendable.class.isAssignableFrom(clazz)) { if (isAppendSupported()) { final Appendable a = getResource().as(Appendable.class); if (a != null) { return clazz.cast(new Appendable() { - public OutputStream getAppendOutputStream() + @Override + public OutputStream getAppendOutputStream() throws IOException { OutputStream out = a.getAppendOutputStream(); if (out != null) { @@ -134,7 +139,7 @@ public abstract class ContentTransformingResource extends ResourceDecorator { return null; } - return FileProvider.class.isAssignableFrom(clazz) + return FileProvider.class.isAssignableFrom(clazz) ? null : getResource().as(clazz); } @@ -148,7 +153,7 @@ public abstract class ContentTransformingResource extends ResourceDecorator { */ protected boolean isAppendSupported() { return false; - } + } /** * Get a content-filtering/transforming InputStream. diff --git a/src/main/org/apache/tools/ant/types/resources/LazyResourceCollectionWrapper.java b/src/main/org/apache/tools/ant/types/resources/LazyResourceCollectionWrapper.java index a66098d76..4bb72b936 100644 --- a/src/main/org/apache/tools/ant/types/resources/LazyResourceCollectionWrapper.java +++ b/src/main/org/apache/tools/ant/types/resources/LazyResourceCollectionWrapper.java @@ -36,7 +36,8 @@ public class LazyResourceCollectionWrapper extends private FilteringIterator filteringIterator; - protected Iterator createIterator() { + @Override + protected Iterator createIterator() { Iterator iterator; if (isCache()) { if (filteringIterator == null) { @@ -51,7 +52,8 @@ public class LazyResourceCollectionWrapper extends return iterator; } - protected int getSize() { + @Override + protected int getSize() { // to compute the size, just iterate: the iterator will take care of // caching Iterator it = createIterator(); @@ -66,7 +68,7 @@ public class LazyResourceCollectionWrapper extends /** * Specify if the resource should be filtered or not. This function should * be overrided in order to define the filtering algorithm - * + * * @param r resource considered for filtration * @return whether the resource should be filtered or not */ @@ -86,7 +88,8 @@ public class LazyResourceCollectionWrapper extends this.it = it; } - public boolean hasNext() { + @Override + public boolean hasNext() { if (ended) { return false; } @@ -103,7 +106,8 @@ public class LazyResourceCollectionWrapper extends return true; } - public Resource next() { + @Override + public Resource next() { if (!hasNext()) { throw new UnsupportedOperationException(); } @@ -112,7 +116,8 @@ public class LazyResourceCollectionWrapper extends return r; } - public void remove() { + @Override + public void remove() { throw new UnsupportedOperationException(); } } @@ -129,7 +134,7 @@ public class LazyResourceCollectionWrapper extends /** * Default constructor - * + * * @param it * the iterator which will provide the resources to put in * cache @@ -138,7 +143,8 @@ public class LazyResourceCollectionWrapper extends this.it = it; } - public boolean hasNext() { + @Override + public boolean hasNext() { synchronized (cachedResources) { // have we already cached the next entry ? if (cachedResources.size() > cusrsor) { @@ -155,7 +161,8 @@ public class LazyResourceCollectionWrapper extends return true; } - public Resource next() { + @Override + public Resource next() { // first check that we have some to deliver if (!hasNext()) { throw new NoSuchElementException(); @@ -167,7 +174,8 @@ public class LazyResourceCollectionWrapper extends } } - public void remove() { + @Override + public void remove() { throw new UnsupportedOperationException(); } } diff --git a/src/main/org/apache/tools/ant/types/resources/MappedResource.java b/src/main/org/apache/tools/ant/types/resources/MappedResource.java index bffc9a8f8..8b193c4d6 100644 --- a/src/main/org/apache/tools/ant/types/resources/MappedResource.java +++ b/src/main/org/apache/tools/ant/types/resources/MappedResource.java @@ -46,7 +46,8 @@ public class MappedResource extends ResourceDecorator { /** * Maps the name. */ - public String getName() { + @Override + public String getName() { String name = getResource().getName(); if (isReference()) { return name; @@ -59,7 +60,8 @@ public class MappedResource extends ResourceDecorator { * Not really supported since mapper is never null. * @param r reference to set */ - public void setRefid(Reference r) { + @Override + public void setRefid(Reference r) { if (mapper != null) { throw noChildrenAllowed(); } @@ -70,8 +72,9 @@ public class MappedResource extends ResourceDecorator { * Suppress FileProvider * @param clazz the type to implement */ - public T as(Class clazz) { - return FileProvider.class.isAssignableFrom(clazz) + @Override + public T as(Class clazz) { + return FileProvider.class.isAssignableFrom(clazz) ? null : getResource().as(clazz); } @@ -79,7 +82,8 @@ public class MappedResource extends ResourceDecorator { * Get the hash code for this Resource. * @since Ant 1.8.1 */ - public int hashCode() { + @Override + public int hashCode() { String n = getName(); return n == null ? super.hashCode() : n.hashCode(); } @@ -89,7 +93,8 @@ public class MappedResource extends ResourceDecorator { * resource itself. * @since Ant 1.8.1 */ - public boolean equals(Object other) { + @Override + public boolean equals(Object other) { if (other == null || !other.getClass().equals(getClass())) { return false; } @@ -100,7 +105,8 @@ public class MappedResource extends ResourceDecorator { && getResource().equals(m.getResource()); } - public String toString() { + @Override + public String toString() { if (isReference()) { return getCheckedRef().toString(); } diff --git a/src/main/org/apache/tools/ant/types/resources/MultiRootFileSet.java b/src/main/org/apache/tools/ant/types/resources/MultiRootFileSet.java index 21349bc70..8c025784c 100644 --- a/src/main/org/apache/tools/ant/types/resources/MultiRootFileSet.java +++ b/src/main/org/apache/tools/ant/types/resources/MultiRootFileSet.java @@ -43,7 +43,8 @@ public class MultiRootFileSet extends AbstractFileSet private List baseDirs = new ArrayList(); private Union union; - public void setDir(File dir) { + @Override + public void setDir(File dir) { throw new BuildException(getDataTypeName() + " doesn't support the dir attribute"); } @@ -96,7 +97,8 @@ public class MultiRootFileSet extends AbstractFileSet baseDirs.add(r.getFile()); } - public void setRefid(Reference r) { + @Override + public void setRefid(Reference r) { if (!baseDirs.isEmpty()) { throw tooManyAttributes(); } @@ -108,7 +110,8 @@ public class MultiRootFileSet extends AbstractFileSet * as this one. * @return the cloned MultiRootFileSet. */ - public Object clone() { + @Override + public Object clone() { if (isReference()) { return ((MultiRootFileSet) getRef(getProject())).clone(); } else { @@ -123,7 +126,8 @@ public class MultiRootFileSet extends AbstractFileSet * Fulfill the ResourceCollection contract. * @return an Iterator of Resources. */ - public Iterator iterator() { + @Override + public Iterator iterator() { if (isReference()) { return ((MultiRootFileSet) getRef(getProject())).iterator(); } @@ -134,7 +138,8 @@ public class MultiRootFileSet extends AbstractFileSet * Fulfill the ResourceCollection contract. * @return number of elements as int. */ - public int size() { + @Override + public int size() { if (isReference()) { return ((MultiRootFileSet) getRef(getProject())).size(); } @@ -145,7 +150,8 @@ public class MultiRootFileSet extends AbstractFileSet * Always returns true. * @return true indicating that all elements will be FileResources. */ - public boolean isFilesystemOnly() { + @Override + public boolean isFilesystemOnly() { return true; } @@ -154,7 +160,8 @@ public class MultiRootFileSet extends AbstractFileSet * * @return a String of included directories. */ - public String toString() { + @Override + public String toString() { if (isReference()) { return ((MultiRootFileSet) getRef(getProject())).toString(); } @@ -190,18 +197,20 @@ public class MultiRootFileSet extends AbstractFileSet implements ResourceCollection { private final SetType type; - + private Worker(MultiRootFileSet fs, SetType type, File dir) { super(fs); this.type = type; setDir(dir); } - public boolean isFilesystemOnly() { + @Override + public boolean isFilesystemOnly() { return true; } - public Iterator iterator() { + @Override + public Iterator iterator() { DirectoryScanner ds = getDirectoryScanner(getProject()); String[] names = type == SetType.file ? ds.getIncludedFiles() @@ -217,7 +226,8 @@ public class MultiRootFileSet extends AbstractFileSet names); } - public int size() { + @Override + public int size() { DirectoryScanner ds = getDirectoryScanner(getProject()); int count = type == SetType.file ? ds.getIncludedFilesCount() diff --git a/src/main/org/apache/tools/ant/types/resources/selectors/Type.java b/src/main/org/apache/tools/ant/types/resources/selectors/Type.java index 6c8cd7a12..c35c18f88 100644 --- a/src/main/org/apache/tools/ant/types/resources/selectors/Type.java +++ b/src/main/org/apache/tools/ant/types/resources/selectors/Type.java @@ -44,7 +44,7 @@ public class Type implements ResourceSelector { * Implements the type attribute. */ public static class FileDir extends EnumeratedAttribute { - private static final String[] VALUES = new String[] { FILE_ATTR, DIR_ATTR, ANY_ATTR }; + private static final String[] VALUES = new String[] {FILE_ATTR, DIR_ATTR, ANY_ATTR}; /** * Default constructor. @@ -56,7 +56,7 @@ public class Type implements ResourceSelector { * Convenience constructor. * @param value the String EnumeratedAttribute value. */ - public FileDir(String value) { + public FileDir(final String value) { setValue(value); } @@ -64,7 +64,8 @@ public class Type implements ResourceSelector { * Return the possible values. * @return a String array. */ - public String[] getValues() { + @Override + public String[] getValues() { return VALUES; } } @@ -81,7 +82,7 @@ public class Type implements ResourceSelector { * Convenience constructor. * @param fd the FileDir type. */ - public Type(FileDir fd) { + public Type(final FileDir fd) { setType(fd); } @@ -89,7 +90,7 @@ public class Type implements ResourceSelector { * Set type; file|dir. * @param fd a FileDir object. */ - public void setType(FileDir fd) { + public void setType(final FileDir fd) { type = fd; } @@ -98,11 +99,12 @@ public class Type implements ResourceSelector { * @param r the Resource to check. * @return whether the Resource was selected. */ - public boolean isSelected(Resource r) { + @Override + public boolean isSelected(final Resource r) { if (type == null) { throw new BuildException("The type attribute is required."); } - int i = type.getIndex(); + final int i = type.getIndex(); return i == 2 || (r.isDirectory() ? i == 1 : i == 0); } diff --git a/src/main/org/apache/tools/ant/types/selectors/MappingSelector.java b/src/main/org/apache/tools/ant/types/selectors/MappingSelector.java index 63e7a4493..85e478c6c 100644 --- a/src/main/org/apache/tools/ant/types/selectors/MappingSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/MappingSelector.java @@ -88,12 +88,13 @@ public abstract class MappingSelector extends BaseSelector { } this.map = fileNameMapper; } - + /** * Checks to make sure all settings are kosher. In this case, it * means that the dest attribute has been set and we have a mapper. */ - public void verifySettings() { + @Override + public void verifySettings() { if (targetdir == null) { setError("The targetdir attribute is required."); } @@ -118,7 +119,8 @@ public abstract class MappingSelector extends BaseSelector { * @param file is a java.io.File object the selector can use * @return whether the file should be selected or not */ - public boolean isSelected(File basedir, String filename, File file) { + @Override + public boolean isSelected(File basedir, String filename, File file) { // throw BuildException on error validate(); diff --git a/src/main/org/apache/tools/ant/types/selectors/PresentSelector.java b/src/main/org/apache/tools/ant/types/selectors/PresentSelector.java index f9efce397..9887dcab8 100644 --- a/src/main/org/apache/tools/ant/types/selectors/PresentSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/PresentSelector.java @@ -51,8 +51,9 @@ public class PresentSelector extends BaseSelector { /** * @return a string describing this object */ - public String toString() { - StringBuilder buf = new StringBuilder("{presentselector targetdir: "); + @Override + public String toString() { + final StringBuilder buf = new StringBuilder("{presentselector targetdir: "); if (targetdir == null) { buf.append("NOT YET SET"); } else { @@ -79,7 +80,7 @@ public class PresentSelector extends BaseSelector { * * @param targetdir the directory to scan looking for matching files. */ - public void setTargetdir(File targetdir) { + public void setTargetdir(final File targetdir) { this.targetdir = targetdir; } @@ -102,7 +103,7 @@ public class PresentSelector extends BaseSelector { * @throws BuildException if more than one mapper defined * @since Ant 1.8.0 */ - public void addConfigured(FileNameMapper fileNameMapper) { + public void addConfigured(final FileNameMapper fileNameMapper) { if (map != null || mapperElement != null) { throw new BuildException("Cannot define more than one mapper"); } @@ -121,7 +122,7 @@ public class PresentSelector extends BaseSelector { * @param fp An attribute set to either srconlyboth. */ - public void setPresent(FilePresence fp) { + public void setPresent(final FilePresence fp) { if (fp.getIndex() == 0) { destmustexist = false; } @@ -131,7 +132,8 @@ public class PresentSelector extends BaseSelector { * Checks to make sure all settings are kosher. In this case, it * means that the targetdir attribute has been set and we have a mapper. */ - public void verifySettings() { + @Override + public void verifySettings() { if (targetdir == null) { setError("The targetdir attribute is required."); } @@ -156,13 +158,14 @@ public class PresentSelector extends BaseSelector { * @param file is a java.io.File object the selector can use * @return whether the file should be selected or not */ - public boolean isSelected(File basedir, String filename, File file) { + @Override + public boolean isSelected(final File basedir, final String filename, final File file) { // throw BuildException on error validate(); // Determine file whose existence is to be checked - String[] destfiles = map.mapFileName(filename); + final String[] destfiles = map.mapFileName(filename); // If filename does not match the To attribute of the mapper // then filter it out of the files we are considering if (destfiles == null) { @@ -173,8 +176,8 @@ public class PresentSelector extends BaseSelector { throw new BuildException("Invalid destination file results for " + targetdir + " with filename " + filename); } - String destname = destfiles[0]; - File destfile = FileUtils.getFileUtils().resolveFile(targetdir, destname); + final String destname = destfiles[0]; + final File destfile = FileUtils.getFileUtils().resolveFile(targetdir, destname); return destfile.exists() == destmustexist; } @@ -186,8 +189,9 @@ public class PresentSelector extends BaseSelector { /** * @return the values as an array of strings */ - public String[] getValues() { - return new String[] { "srconly", "both" }; + @Override + public String[] getValues() { + return new String[] {"srconly", "both"}; } } 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 db70d0c27..cdc3790e9 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java +++ b/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java @@ -50,14 +50,14 @@ public class TokenizedPath { private final String[] tokenizedPath; /** - * Initialize the TokenizedPath by parsing it. + * Initialize the TokenizedPath by parsing it. * @param path The path to tokenize. Must not be * null. */ public TokenizedPath(String path) { this(path, SelectorUtils.tokenizePathAsArray(path)); } - + /** * Creates a new path as a child of another path. * @@ -86,10 +86,11 @@ public class TokenizedPath { /** * @return The original path String */ - public String toString() { + @Override + public String toString() { return path; } - + /** * The depth (or length) of a path. */ @@ -160,12 +161,14 @@ public class TokenizedPath { /** * true if the original paths are equal. */ - public boolean equals(Object o) { + @Override + public boolean equals(Object o) { return o instanceof TokenizedPath && path.equals(((TokenizedPath) o).path); } - public int hashCode() { + @Override + public int hashCode() { return path.hashCode(); } @@ -213,7 +216,7 @@ public class TokenizedPath { * this path. */ public TokenizedPattern toPattern() { - return new TokenizedPattern(path, tokenizedPath); + return new TokenizedPattern(path, tokenizedPath); } } diff --git a/src/main/org/apache/tools/ant/util/DOMElementWriter.java b/src/main/org/apache/tools/ant/util/DOMElementWriter.java index ea1f7f353..14cbaee2b 100644 --- a/src/main/org/apache/tools/ant/util/DOMElementWriter.java +++ b/src/main/org/apache/tools/ant/util/DOMElementWriter.java @@ -521,7 +521,7 @@ public class DOMElementWriter { while (prevEnd < len) { final int end = (cdataEndPos < 0 ? len : cdataEndPos); // Write out stretches of legal characters in the range [prevEnd, end). - for (int prevLegalCharPos = prevEnd; prevLegalCharPos < end; /*empty*/) { + for (int prevLegalCharPos = prevEnd; prevLegalCharPos < end;/*empty*/) { int illegalCharPos; for (illegalCharPos = prevLegalCharPos; true; ++illegalCharPos) { if (illegalCharPos >= end diff --git a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java index 9da26e010..9ed62c3c5 100644 --- a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java +++ b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java @@ -211,7 +211,7 @@ public final class JavaEnvUtils { * Searching for changes (grep -r -i -n "@since 1.9" .) in the sources gave * only one hit: a new constant in the class SourceVersion. * So we have to check that ... - * + * * @throws Exception if we can't load the class or don't find the new constant. * This is the behavior when searching for new features on older versions. * @since Ant 1.9.4 diff --git a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java index bdfcb4090..9308292c0 100644 --- a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java +++ b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java @@ -109,7 +109,7 @@ public class LayoutPreservingProperties extends Properties { * Create a new, empty, Properties collection, with the specified defaults. * @param defaults the default property values */ - public LayoutPreservingProperties(Properties defaults) { + public LayoutPreservingProperties(final Properties defaults) { super(defaults); } @@ -134,27 +134,30 @@ public class LayoutPreservingProperties extends Properties { * removed when a property is removed; false * otherwise */ - public void setRemoveComments(boolean val) { + public void setRemoveComments(final boolean val) { removeComments = val; } - public void load(InputStream inStream) throws IOException { - String s = readLines(inStream); - byte[] ba = s.getBytes(ResourceUtils.ISO_8859_1); - ByteArrayInputStream bais = new ByteArrayInputStream(ba); + @Override + public void load(final InputStream inStream) throws IOException { + final String s = readLines(inStream); + final byte[] ba = s.getBytes(ResourceUtils.ISO_8859_1); + final ByteArrayInputStream bais = new ByteArrayInputStream(ba); super.load(bais); } - public Object put(Object key, Object value) throws NullPointerException { - Object obj = super.put(key, value); + @Override + public Object put(final Object key, final Object value) throws NullPointerException { + final Object obj = super.put(key, value); // the above call will have failed if key or value are null innerSetProperty(key.toString(), value.toString()); return obj; } - public Object setProperty(String key, String value) + @Override + public Object setProperty(final String key, final String value) throws NullPointerException { - Object obj = super.setProperty(key, value); + final Object obj = super.setProperty(key, value); // the above call will have failed if key or value are null innerSetProperty(key, value); return obj; @@ -172,27 +175,29 @@ public class LayoutPreservingProperties extends Properties { value = escapeValue(value); if (keyedPairLines.containsKey(key)) { - Integer i = (Integer) keyedPairLines.get(key); - Pair p = (Pair) logicalLines.get(i.intValue()); + final Integer i = (Integer) keyedPairLines.get(key); + final Pair p = (Pair) logicalLines.get(i.intValue()); p.setValue(value); } else { key = escapeName(key); - Pair p = new Pair(key, value); + final Pair p = new Pair(key, value); p.setNew(true); keyedPairLines.put(key, new Integer(logicalLines.size())); logicalLines.add(p); } } - public void clear() { + @Override + public void clear() { super.clear(); keyedPairLines.clear(); logicalLines.clear(); } - public Object remove(Object key) { - Object obj = super.remove(key); - Integer i = (Integer) keyedPairLines.remove(key); + @Override + public Object remove(final Object key) { + final Object obj = super.remove(key); + final Integer i = (Integer) keyedPairLines.remove(key); if (null != i) { if (removeComments) { removeCommentsEndingAt(i.intValue()); @@ -202,16 +207,17 @@ public class LayoutPreservingProperties extends Properties { return obj; } - public Object clone() { - LayoutPreservingProperties dolly = + @Override + public Object clone() { + final LayoutPreservingProperties dolly = (LayoutPreservingProperties) super.clone(); dolly.keyedPairLines = (HashMap) this.keyedPairLines.clone(); dolly.logicalLines = (ArrayList) this.logicalLines.clone(); final int size = dolly.logicalLines.size(); for (int j = 0; j < size; j++) { - LogicalLine line = (LogicalLine) dolly.logicalLines.get(j); + final LogicalLine line = (LogicalLine) dolly.logicalLines.get(j); if (line instanceof Pair) { - Pair p = (Pair) line; + final Pair p = (Pair) line; dolly.logicalLines.set(j, p.clone()); } // no reason to clone other lines are they are immutable @@ -224,11 +230,11 @@ public class LayoutPreservingProperties extends Properties { * stream. * @param out the stream to write to */ - public void listLines(PrintStream out) { + public void listLines(final PrintStream out) { out.println("-- logical lines --"); - Iterator i = logicalLines.iterator(); + final Iterator i = logicalLines.iterator(); while (i.hasNext()) { - LogicalLine line = (LogicalLine) i.next(); + final LogicalLine line = (LogicalLine) i.next(); if (line instanceof Blank) { out.println("blank: \"" + line + "\""); } else if (line instanceof Comment) { @@ -243,17 +249,18 @@ public class LayoutPreservingProperties extends Properties { * Save the properties to a file. * @param dest the file to write to */ - public void saveAs(File dest) throws IOException { - FileOutputStream fos = new FileOutputStream(dest); + public void saveAs(final File dest) throws IOException { + final FileOutputStream fos = new FileOutputStream(dest); store(fos, null); fos.close(); } - public void store(OutputStream out, String header) throws IOException { - OutputStreamWriter osw = new OutputStreamWriter(out, ResourceUtils.ISO_8859_1); + @Override + public void store(final OutputStream out, final String header) throws IOException { + final OutputStreamWriter osw = new OutputStreamWriter(out, ResourceUtils.ISO_8859_1); int skipLines = 0; - int totalLines = logicalLines.size(); + final int totalLines = logicalLines.size(); if (header != null) { osw.write("#" + header + LS); @@ -274,16 +281,16 @@ public class LayoutPreservingProperties extends Properties { .get(skipLines) .toString().substring(1)); skipLines++; - } catch (java.text.ParseException pe) { + } catch (final java.text.ParseException pe) { // not an existing date comment } } osw.write("#" + DateUtils.getDateForHeader() + LS); boolean writtenSep = false; - for (Iterator i = logicalLines.subList(skipLines, totalLines).iterator(); - i.hasNext(); ) { - LogicalLine line = (LogicalLine) i.next(); + for (final Iterator i = logicalLines.subList(skipLines, totalLines).iterator(); + i.hasNext();) { + final LogicalLine line = (LogicalLine) i.next(); if (line instanceof Pair) { if (((Pair)line).isNew()) { if (!writtenSep) { @@ -306,9 +313,9 @@ public class LayoutPreservingProperties extends Properties { * file. * @param is the stream from which to read the data */ - private String readLines(InputStream is) throws IOException { - InputStreamReader isr = new InputStreamReader(is, ResourceUtils.ISO_8859_1); - PushbackReader pbr = new PushbackReader(isr, 1); + private String readLines(final InputStream is) throws IOException { + final InputStreamReader isr = new InputStreamReader(is, ResourceUtils.ISO_8859_1); + final PushbackReader pbr = new PushbackReader(isr, 1); if (logicalLines.size() > 0) { // we add a blank line for spacing @@ -316,12 +323,12 @@ public class LayoutPreservingProperties extends Properties { } String s = readFirstLine(pbr); - BufferedReader br = new BufferedReader(pbr); + final BufferedReader br = new BufferedReader(pbr); boolean continuation = false; boolean comment = false; - StringBuffer fileBuffer = new StringBuffer(); - StringBuffer logicalLineBuffer = new StringBuffer(); + final StringBuffer fileBuffer = new StringBuffer(); + final StringBuffer logicalLineBuffer = new StringBuffer(); while (s != null) { fileBuffer.append(s).append(LS); @@ -349,7 +356,7 @@ public class LayoutPreservingProperties extends Properties { line = new Blank(); } else { line = new Pair(logicalLineBuffer.toString()); - String key = unescape(((Pair)line).getName()); + final String key = unescape(((Pair)line).getName()); if (keyedPairLines.containsKey(key)) { // this key is already present, so we remove it and add // the new one @@ -376,8 +383,8 @@ public class LayoutPreservingProperties extends Properties { * * @since Ant 1.8.2 */ - private String readFirstLine(PushbackReader r) throws IOException { - StringBuffer sb = new StringBuffer(80); + private String readFirstLine(final PushbackReader r) throws IOException { + final StringBuffer sb = new StringBuffer(80); int ch = r.read(); boolean hasCR = false; // when reaching EOF before the first EOL, assume native line @@ -413,14 +420,14 @@ public class LayoutPreservingProperties extends Properties { * @return true if the line is to be continued, * false otherwise */ - private boolean requiresContinuation(String s) { - char[] ca = s.toCharArray(); + private boolean requiresContinuation(final String s) { + final char[] ca = s.toCharArray(); int i = ca.length - 1; while (i > 0 && ca[i] == '\\') { i--; } // trailing backslashes - int tb = ca.length - i - 1; + final int tb = ca.length - i - 1; return tb % 2 == 1; } @@ -431,7 +438,7 @@ public class LayoutPreservingProperties extends Properties { * @param s the string to unescape (coming from the source file) * @return the unescaped string */ - private String unescape(String s) { + private String unescape(final String s) { /* * The following combinations are converted: * \n newline @@ -444,10 +451,10 @@ public class LayoutPreservingProperties extends Properties { * \b becomes 'b'. */ - char[] ch = new char[s.length() + 1]; + final char[] ch = new char[s.length() + 1]; s.getChars(0, s.length(), ch, 0); ch[s.length()] = '\n'; - StringBuffer buffy = new StringBuffer(s.length()); + final StringBuffer buffy = new StringBuffer(s.length()); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (c == '\n') { @@ -485,8 +492,8 @@ public class LayoutPreservingProperties extends Properties { * @param ch the character array containing the unicode character code * @return the character extracted */ - private char unescapeUnicode(char[] ch, int i) { - String s = new String(ch, i, 4); + private char unescapeUnicode(final char[] ch, final int i) { + final String s = new String(ch, i, 4); return (char) Integer.parseInt(s, 16); } @@ -497,7 +504,7 @@ public class LayoutPreservingProperties extends Properties { * @param s the string to escape * @return the escaped string */ - private String escapeValue(String s) { + private String escapeValue(final String s) { return escape(s, false); } @@ -510,7 +517,7 @@ public class LayoutPreservingProperties extends Properties { * @param s the string to escape * @return the escaped string */ - private String escapeName(String s) { + private String escapeName(final String s) { return escape(s, true); } @@ -524,19 +531,19 @@ public class LayoutPreservingProperties extends Properties { * leading whitespace * @return the escaped string */ - private String escape(String s, boolean escapeAllSpaces) { + private String escape(final String s, final boolean escapeAllSpaces) { if (s == null) { return null; } - char[] ch = new char[s.length()]; + final char[] ch = new char[s.length()]; s.getChars(0, s.length(), ch, 0); - String forEscaping = "\t\f\r\n\\:=#!"; - String escaped = "tfrn\\:=#!"; - StringBuffer buffy = new StringBuffer(s.length()); + final String forEscaping = "\t\f\r\n\\:=#!"; + final String escaped = "tfrn\\:=#!"; + final StringBuffer buffy = new StringBuffer(s.length()); boolean leadingSpace = true; for (int i = 0; i < ch.length; i++) { - char c = ch[i]; + final char c = ch[i]; if (c == ' ') { if (escapeAllSpaces || leadingSpace) { buffy.append("\\"); @@ -544,7 +551,7 @@ public class LayoutPreservingProperties extends Properties { } else { leadingSpace = false; } - int p = forEscaping.indexOf(c); + final int p = forEscaping.indexOf(c); if (p != -1) { buffy.append("\\").append(escaped.substring(p,p+1)); } else if (c < 0x0020 || c > 0x007e) { @@ -562,7 +569,7 @@ public class LayoutPreservingProperties extends Properties { * @param ch the character to encode * @return the unicode escape sequence */ - private String escapeUnicode(char ch) { + private String escapeUnicode(final char ch) { return "\\" + UnicodeUtil.EscapeUnicode(ch); } @@ -580,7 +587,7 @@ public class LayoutPreservingProperties extends Properties { * B1. */ - int end = pos - 1; + final int end = pos - 1; // step pos back until it hits something non-blank for (pos = end; pos > 0; pos--) { @@ -603,7 +610,7 @@ public class LayoutPreservingProperties extends Properties { } // now we want to delete from pos+1 to end - for (pos++ ;pos <= end; pos++) { + for (pos++; pos <= end; pos++) { logicalLines.set(pos, null); } } @@ -611,18 +618,19 @@ public class LayoutPreservingProperties extends Properties { /** * A logical line of the properties input stream. */ - private static abstract class LogicalLine { + private abstract static class LogicalLine { private String text; - public LogicalLine(String text) { + public LogicalLine(final String text) { this.text = text; } - public void setText(String text) { + public void setText(final String text) { this.text = text; } - public String toString() { + @Override + public String toString() { return text; } } @@ -640,7 +648,7 @@ public class LayoutPreservingProperties extends Properties { * A comment line of the input stream. */ private class Comment extends LogicalLine { - public Comment(String text) { + public Comment(final String text) { super(text); } } @@ -655,12 +663,12 @@ public class LayoutPreservingProperties extends Properties { private String value; private boolean added; - public Pair(String text) { + public Pair(final String text) { super(text); parsePair(text); } - public Pair(String name, String value) { + public Pair(final String name, final String value) { this(name + "=" + value); } @@ -672,7 +680,7 @@ public class LayoutPreservingProperties extends Properties { return value; } - public void setValue(String value) { + public void setValue(final String value) { this.value = value; setText(name + "=" + value); } @@ -681,24 +689,25 @@ public class LayoutPreservingProperties extends Properties { return added; } - public void setNew(boolean val) { + public void setNew(final boolean val) { added = val; } - public Object clone() { + @Override + public Object clone() { Object dolly = null; try { dolly = super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // should be fine e.printStackTrace(); } return dolly; } - private void parsePair(String text) { + private void parsePair(final String text) { // need to find first non-escaped '=', ':', '\t' or ' '. - int pos = findFirstSeparator(text); + final int pos = findFirstSeparator(text); if (pos == -1) { // trim leading whitespace only name = text; @@ -711,7 +720,7 @@ public class LayoutPreservingProperties extends Properties { name = stripStart(name, " \t\f"); } - private String stripStart(String s, String chars) { + private String stripStart(final String s, final String chars) { if (s == null) { return null; } @@ -745,14 +754,14 @@ public class LayoutPreservingProperties extends Properties { return indexOfAny(s, " :=\t"); } - private int indexOfAny(String s, String chars) { + private int indexOfAny(final String s, final String chars) { if (s == null || chars == null) { return -1; } int p = s.length() + 1; for (int i = 0; i < chars.length(); i++) { - int x = s.indexOf(chars.charAt(i)); + final int x = s.indexOf(chars.charAt(i)); if (x != -1 && x < p) { p = x; } diff --git a/src/main/org/apache/tools/ant/util/LineOrientedOutputStream.java b/src/main/org/apache/tools/ant/util/LineOrientedOutputStream.java index 3c0df4d9e..7630f590d 100644 --- a/src/main/org/apache/tools/ant/util/LineOrientedOutputStream.java +++ b/src/main/org/apache/tools/ant/util/LineOrientedOutputStream.java @@ -50,7 +50,8 @@ public abstract class LineOrientedOutputStream extends OutputStream { * @param cc data to log (byte). * @throws IOException if there is an error. */ - public final void write(int cc) throws IOException { + @Override + public final void write(int cc) throws IOException { final byte c = (byte) cc; if ((c == LF) || (c == CR)) { if (!skip) { @@ -66,7 +67,8 @@ public abstract class LineOrientedOutputStream extends OutputStream { * Flush this log stream * @throws IOException if there is an error. */ - public void flush() throws IOException { + @Override + public void flush() throws IOException { } /** @@ -111,7 +113,8 @@ public abstract class LineOrientedOutputStream extends OutputStream { * Writes all remaining * @throws IOException if there is an error. */ - public void close() throws IOException { + @Override + public void close() throws IOException { if (buffer.size() > 0) { processBuffer(); } @@ -127,7 +130,8 @@ public abstract class LineOrientedOutputStream extends OutputStream { * * @throws IOException if the data cannot be written into the stream. */ - public final void write(byte[] b, int off, int len) throws IOException { + @Override + public final void write(byte[] b, int off, int len) throws IOException { // find the line breaks and pass other chars through in blocks int offset = off; int blockStartOffset = offset; diff --git a/src/main/org/apache/tools/ant/util/LineOrientedOutputStreamRedirector.java b/src/main/org/apache/tools/ant/util/LineOrientedOutputStreamRedirector.java index 6ce302de2..a4e6d8e64 100644 --- a/src/main/org/apache/tools/ant/util/LineOrientedOutputStreamRedirector.java +++ b/src/main/org/apache/tools/ant/util/LineOrientedOutputStreamRedirector.java @@ -26,12 +26,12 @@ import java.io.OutputStream; * If the source stream doesn't end with a end of line, one will be added. This * is particularly useful in combination with the OutputStreamFunneler so each * funneled stream get its line. - * + * * @since Ant 1.8.3 */ public class LineOrientedOutputStreamRedirector - extends - LineOrientedOutputStream { + extends LineOrientedOutputStream { + private OutputStream stream; // these should be in the ASCII range and hopefully are single bytes @@ -42,22 +42,26 @@ public class LineOrientedOutputStreamRedirector public LineOrientedOutputStreamRedirector(OutputStream stream) { this.stream = stream; } - - protected void processLine(byte[] b) throws IOException { + + @Override + protected void processLine(byte[] b) throws IOException { stream.write(b); stream.write(EOL); } - - protected void processLine(String line) throws IOException { + + @Override + protected void processLine(String line) throws IOException { stream.write((line + System.getProperty("line.separator")).getBytes()); } - - public void close() throws IOException { + + @Override + public void close() throws IOException { super.close(); stream.close(); } - public void flush() throws IOException { + @Override + public void flush() throws IOException { super.flush(); stream.flush(); } diff --git a/src/main/org/apache/tools/ant/util/ResourceUtils.java b/src/main/org/apache/tools/ant/util/ResourceUtils.java index 50c34c253..891447cee 100644 --- a/src/main/org/apache/tools/ant/util/ResourceUtils.java +++ b/src/main/org/apache/tools/ant/util/ResourceUtils.java @@ -88,10 +88,10 @@ public class ResourceUtils { * copied or processed, because the targets are out of date or do * not exist. */ - public static Resource[] selectOutOfDateSources(ProjectComponent logTo, - Resource[] source, - FileNameMapper mapper, - ResourceFactory targets) { + public static Resource[] selectOutOfDateSources(final ProjectComponent logTo, + final Resource[] source, + final FileNameMapper mapper, + final ResourceFactory targets) { return selectOutOfDateSources(logTo, source, mapper, targets, FILE_UTILS.getFileTimestampGranularity()); } @@ -113,14 +113,14 @@ public class ResourceUtils { * not exist. * @since Ant 1.6.2 */ - public static Resource[] selectOutOfDateSources(ProjectComponent logTo, - Resource[] source, - FileNameMapper mapper, - ResourceFactory targets, - long granularity) { - Union u = new Union(); + public static Resource[] selectOutOfDateSources(final ProjectComponent logTo, + final Resource[] source, + final FileNameMapper mapper, + final ResourceFactory targets, + final long granularity) { + final Union u = new Union(); u.addAll(Arrays.asList(source)); - ResourceCollection rc + final ResourceCollection rc = selectOutOfDateSources(logTo, u, mapper, targets, granularity); return rc.size() == 0 ? new Resource[0] : ((Union) rc).listResources(); } @@ -137,18 +137,20 @@ public class ResourceUtils { * @return ResourceCollection. * @since Ant 1.7 */ - public static ResourceCollection selectOutOfDateSources(ProjectComponent logTo, - ResourceCollection source, - FileNameMapper mapper, - ResourceFactory targets, + public static ResourceCollection selectOutOfDateSources(final ProjectComponent logTo, + final ResourceCollection source, + final FileNameMapper mapper, + final ResourceFactory targets, final long granularity) { logFuture(logTo, source, granularity); - ResourceSelectorProvider p = + final ResourceSelectorProvider p = new ResourceSelectorProvider() { - public ResourceSelector + @Override + public ResourceSelector getTargetSelectorForSource(final Resource sr) { return new ResourceSelector() { - public boolean isSelected(Resource target) { + @Override + public boolean isSelected(final Resource target) { /* Extra I/O, probably wasted: if (target.isDirectory()) { return false; @@ -166,7 +168,7 @@ public class ResourceUtils { /** * Tells which sources should be reprocessed because the given * selector selects at least one target. - * + * * @param logTo where to send (more or less) interesting output. * @param source ResourceCollection. * @param mapper filename mapper indicating how to find the target Resources. @@ -177,19 +179,19 @@ public class ResourceUtils { * @return ResourceCollection. * @since Ant 1.8.0 */ - public static ResourceCollection selectSources(ProjectComponent logTo, + public static ResourceCollection selectSources(final ProjectComponent logTo, ResourceCollection source, - FileNameMapper mapper, - ResourceFactory targets, - ResourceSelectorProvider selector) { + final FileNameMapper mapper, + final ResourceFactory targets, + final ResourceSelectorProvider selector) { if (source.size() == 0) { logTo.log("No sources found.", Project.MSG_VERBOSE); return Resources.NONE; } source = Union.getInstance(source); - Union result = new Union(); - for (Resource sr : source) { + final Union result = new Union(); + for (final Resource sr : source) { String srName = sr.getName(); srName = srName == null ? srName : srName.replace('/', File.separatorChar); @@ -197,7 +199,7 @@ public class ResourceUtils { String[] targetnames = null; try { targetnames = mapper.mapFileName(srName); - } catch (Exception e) { + } catch (final Exception e) { logTo.log("Caught " + e + " mapping resource " + sr, Project.MSG_VERBOSE); } @@ -211,18 +213,18 @@ public class ResourceUtils { targetnames[i] = "(no name)"; } } - Union targetColl = new Union(); + final Union targetColl = new Union(); for (int i = 0; i < targetnames.length; i++) { targetColl.add(targets.getResource( targetnames[i].replace(File.separatorChar, '/'))); } //find the out-of-date targets: - Restrict r = new Restrict(); + final Restrict r = new Restrict(); r.add(selector.getTargetSelectorForSource(sr)); r.add(targetColl); if (r.size() > 0) { result.add(sr); - Resource t = r.iterator().next(); + final Resource t = r.iterator().next(); logTo.log(sr.getName() + " added as " + t.getName() + (t.isExists() ? " is outdated." : " doesn\'t exist."), Project.MSG_VERBOSE); @@ -250,7 +252,7 @@ public class ResourceUtils { * * @since Ant 1.7 */ - public static void copyResource(Resource source, Resource dest) throws IOException { + public static void copyResource(final Resource source, final Resource dest) throws IOException { copyResource(source, dest, null); } @@ -268,7 +270,7 @@ public class ResourceUtils { * * @since Ant 1.7 */ - public static void copyResource(Resource source, Resource dest, Project project) + public static void copyResource(final Resource source, final Resource dest, final Project project) throws IOException { copyResource(source, dest, null, null, false, false, null, null, project); @@ -301,11 +303,11 @@ public class ResourceUtils { * * @since Ant 1.7 */ - public static void copyResource(Resource source, Resource dest, - FilterSetCollection filters, Vector filterChains, - boolean overwrite, boolean preserveLastModified, - String inputEncoding, String outputEncoding, - Project project) + public static void copyResource(final Resource source, final Resource dest, + final FilterSetCollection filters, final Vector filterChains, + final boolean overwrite, final boolean preserveLastModified, + final String inputEncoding, final String outputEncoding, + final Project project) throws IOException { copyResource(source, dest, filters, filterChains, overwrite, preserveLastModified, false, inputEncoding, outputEncoding, project); } @@ -338,12 +340,12 @@ public class ResourceUtils { * * @since Ant 1.8 */ - public static void copyResource(Resource source, Resource dest, - FilterSetCollection filters, Vector filterChains, - boolean overwrite, boolean preserveLastModified, - boolean append, - String inputEncoding, String outputEncoding, - Project project) + public static void copyResource(final Resource source, final Resource dest, + final FilterSetCollection filters, final Vector filterChains, + final boolean overwrite, final boolean preserveLastModified, + final boolean append, + final String inputEncoding, final String outputEncoding, + final Project project) throws IOException { copyResource(source, dest, filters, filterChains, overwrite, preserveLastModified, append, inputEncoding, @@ -378,12 +380,12 @@ public class ResourceUtils { * * @since Ant 1.8.2 */ - public static void copyResource(Resource source, Resource dest, - FilterSetCollection filters, Vector filterChains, - boolean overwrite, boolean preserveLastModified, - boolean append, - String inputEncoding, String outputEncoding, - Project project, boolean force) + public static void copyResource(final Resource source, final Resource dest, + final FilterSetCollection filters, final Vector filterChains, + final boolean overwrite, final boolean preserveLastModified, + final boolean append, + final String inputEncoding, final String outputEncoding, + final Project project, final boolean force) throws IOException { if (!(overwrite || SelectorUtils.isOutOfDate(source, dest, FileUtils.getFileUtils() .getFileTimestampGranularity()))) { @@ -429,12 +431,12 @@ public class ResourceUtils { boolean copied = false; if (source.as(FileProvider.class) != null && destFile != null && !append) { - File sourceFile = + final File sourceFile = source.as(FileProvider.class).getFile(); try { copyUsingFileChannels(sourceFile, destFile); copied = true; - } catch (IOException ex) { + } catch (final IOException ex) { project.log("Attempt to copy " + sourceFile + " to " + destFile + " using NIO Channels" + " failed due to '" + ex.getMessage() @@ -447,7 +449,7 @@ public class ResourceUtils { } } if (preserveLastModified) { - Touchable t = dest.as(Touchable.class); + final Touchable t = dest.as(Touchable.class); if (t != null) { setLastModified(t, source.getLastModified()); } @@ -464,7 +466,7 @@ public class ResourceUtils { * if this is -1, the current time is used. * @since Ant 1.7 */ - public static void setLastModified(Touchable t, long time) { + public static void setLastModified(final Touchable t, final long time) { t.touch((time < 0) ? System.currentTimeMillis() : time); } @@ -481,7 +483,7 @@ public class ResourceUtils { * @throws IOException if the Resources cannot be read. * @since Ant 1.7 */ - public static boolean contentEquals(Resource r1, Resource r2, boolean text) throws IOException { + public static boolean contentEquals(final Resource r1, final Resource r2, final boolean text) throws IOException { if (r1.isExists() != r2.isExists()) { return false; } @@ -499,8 +501,8 @@ public class ResourceUtils { return true; } if (!text) { - long s1 = r1.getSize(); - long s2 = r2.getSize(); + final long s1 = r1.getSize(); + final long s2 = r2.getSize(); if (s1 != Resource.UNKNOWN_SIZE && s2 != Resource.UNKNOWN_SIZE && s1 != s2) { return false; @@ -522,20 +524,20 @@ public class ResourceUtils { * @throws IOException if the Resources cannot be read. * @since Ant 1.7 */ - public static int compareContent(Resource r1, Resource r2, boolean text) throws IOException { + public static int compareContent(final Resource r1, final Resource r2, final boolean text) throws IOException { if (r1.equals(r2)) { return 0; } - boolean e1 = r1.isExists(); - boolean e2 = r2.isExists(); + final boolean e1 = r1.isExists(); + final boolean e2 = r2.isExists(); if (!(e1 || e2)) { return 0; } if (e1 != e2) { return e1 ? 1 : -1; } - boolean d1 = r1.isDirectory(); - boolean d2 = r2.isDirectory(); + final boolean d1 = r1.isDirectory(); + final boolean d2 = r2.isDirectory(); if (d1 && d2) { return 0; } @@ -554,11 +556,11 @@ public class ResourceUtils { * FileResource with fileProvider's file. * @since Ant 1.8 */ - public static FileResource asFileResource(FileProvider fileProvider) { + public static FileResource asFileResource(final FileProvider fileProvider) { if (fileProvider instanceof FileResource || fileProvider == null) { return (FileResource) fileProvider; } - FileResource result = new FileResource(fileProvider.getFile()); + final FileResource result = new FileResource(fileProvider.getFile()); result.setProject(Project.getProject(fileProvider)); return result; } @@ -578,7 +580,7 @@ public class ResourceUtils { * @throws IOException if the Resources cannot be read. * @since Ant 1.7 */ - private static int binaryCompare(Resource r1, Resource r2) throws IOException { + private static int binaryCompare(final Resource r1, final Resource r2) throws IOException { InputStream in1 = null; InputStream in2 = null; try { @@ -586,7 +588,7 @@ public class ResourceUtils { in2 = new BufferedInputStream(r2.getInputStream()); for (int b1 = in1.read(); b1 != -1; b1 = in1.read()) { - int b2 = in2.read(); + final int b2 = in2.read(); if (b1 != b2) { return b1 > b2 ? 1 : -1; } @@ -608,7 +610,7 @@ public class ResourceUtils { * @throws IOException if the Resources cannot be read. * @since Ant 1.7 */ - private static int textCompare(Resource r1, Resource r2) throws IOException { + private static int textCompare(final Resource r1, final Resource r2) throws IOException { BufferedReader in1 = null; BufferedReader in2 = null; try { @@ -617,7 +619,7 @@ public class ResourceUtils { String expected = in1.readLine(); while (expected != null) { - String actual = in2.readLine(); + final String actual = in2.readLine(); if (!expected.equals(actual)) { if (actual == null) { return 1; @@ -640,27 +642,27 @@ public class ResourceUtils { * @param granularity the timestamp granularity to use. * @since Ant 1.7 */ - private static void logFuture(ProjectComponent logTo, - ResourceCollection rc, long granularity) { - long now = System.currentTimeMillis() + granularity; - Date sel = new Date(); + private static void logFuture(final ProjectComponent logTo, + final ResourceCollection rc, final long granularity) { + final long now = System.currentTimeMillis() + granularity; + final Date sel = new Date(); sel.setMillis(now); sel.setWhen(TimeComparison.AFTER); - Restrict future = new Restrict(); + final Restrict future = new Restrict(); future.add(sel); future.add(rc); - for (Resource r : future) { + for (final Resource r : future) { logTo.log("Warning: " + r.getName() + " modified in the future.", Project.MSG_WARN); } } - private static void copyWithFilterSets(Resource source, Resource dest, - FilterSetCollection filters, - Vector filterChains, - boolean filterChainsAvailable, - boolean append, String inputEncoding, - String outputEncoding, - Project project) + private static void copyWithFilterSets(final Resource source, final Resource dest, + final FilterSetCollection filters, + final Vector filterChains, + final boolean filterChainsAvailable, + final boolean append, final String inputEncoding, + final String outputEncoding, + final Project project) throws IOException { BufferedReader in = null; BufferedWriter out = null; @@ -673,7 +675,7 @@ public class ResourceUtils { inputEncoding); } in = new BufferedReader(isr); - OutputStream os = getOutputStream(dest, append, project); + final OutputStream os = getOutputStream(dest, append, project); OutputStreamWriter osw; if (outputEncoding == null) { osw = new OutputStreamWriter(os); @@ -682,15 +684,15 @@ public class ResourceUtils { } out = new BufferedWriter(osw); if (filterChainsAvailable) { - ChainReaderHelper crh = new ChainReaderHelper(); + final ChainReaderHelper crh = new ChainReaderHelper(); crh.setBufferSize(FileUtils.BUF_SIZE); crh.setPrimaryReader(in); crh.setFilterChains(filterChains); crh.setProject(project); - Reader rdr = crh.getAssembledReader(); + final Reader rdr = crh.getAssembledReader(); in = new BufferedReader(rdr); } - LineTokenizer lineTokenizer = new LineTokenizer(); + final LineTokenizer lineTokenizer = new LineTokenizer(); lineTokenizer.setIncludeDelims(true); String newline = null; String line = lineTokenizer.getToken(in); @@ -711,14 +713,14 @@ public class ResourceUtils { } } - private static void copyWithFilterChainsOrTranscoding(Resource source, - Resource dest, - Vector filterChains, - boolean filterChainsAvailable, - boolean append, - String inputEncoding, - String outputEncoding, - Project project) + private static void copyWithFilterChainsOrTranscoding(final Resource source, + final Resource dest, + final Vector filterChains, + final boolean filterChainsAvailable, + final boolean append, + final String inputEncoding, + final String outputEncoding, + final Project project) throws IOException { BufferedReader in = null; BufferedWriter out = null; @@ -731,7 +733,7 @@ public class ResourceUtils { inputEncoding); } in = new BufferedReader(isr); - OutputStream os = getOutputStream(dest, append, project); + final OutputStream os = getOutputStream(dest, append, project); OutputStreamWriter osw; if (outputEncoding == null) { osw = new OutputStreamWriter(os); @@ -740,17 +742,17 @@ public class ResourceUtils { } out = new BufferedWriter(osw); if (filterChainsAvailable) { - ChainReaderHelper crh = new ChainReaderHelper(); + final ChainReaderHelper crh = new ChainReaderHelper(); crh.setBufferSize(FileUtils.BUF_SIZE); crh.setPrimaryReader(in); crh.setFilterChains(filterChains); crh.setProject(project); - Reader rdr = crh.getAssembledReader(); + final Reader rdr = crh.getAssembledReader(); in = new BufferedReader(rdr); } - char[] buffer = new char[FileUtils.BUF_SIZE]; + final char[] buffer = new char[FileUtils.BUF_SIZE]; while (true) { - int nRead = in.read(buffer, 0, buffer.length); + final int nRead = in.read(buffer, 0, buffer.length); if (nRead == -1) { break; } @@ -762,11 +764,11 @@ public class ResourceUtils { } } - private static void copyUsingFileChannels(File sourceFile, - File destFile) + private static void copyUsingFileChannels(final File sourceFile, + final File destFile) throws IOException { - File parent = destFile.getParentFile(); + final File parent = destFile.getParentFile(); if (parent != null && !parent.isDirectory() && !(parent.mkdirs() || parent.isDirectory())) { throw new IOException("failed to create the parent directory" @@ -781,14 +783,14 @@ public class ResourceUtils { try { in = new FileInputStream(sourceFile); out = new FileOutputStream(destFile); - + srcChannel = in.getChannel(); destChannel = out.getChannel(); - + long position = 0; - long count = srcChannel.size(); + final long count = srcChannel.size(); while (position < count) { - long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); + final long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } @@ -800,8 +802,8 @@ public class ResourceUtils { } } - private static void copyUsingStreams(Resource source, Resource dest, - boolean append, Project project) + private static void copyUsingStreams(final Resource source, final Resource dest, + final boolean append, final Project project) throws IOException { InputStream in = null; OutputStream out = null; @@ -809,7 +811,7 @@ public class ResourceUtils { in = source.getInputStream(); out = getOutputStream(dest, append, project); - byte[] buffer = new byte[FileUtils.BUF_SIZE]; + final byte[] buffer = new byte[FileUtils.BUF_SIZE]; int count = 0; do { out.write(buffer, 0, count); @@ -821,10 +823,10 @@ public class ResourceUtils { } } - private static OutputStream getOutputStream(Resource resource, boolean append, Project project) + private static OutputStream getOutputStream(final Resource resource, final boolean append, final Project project) throws IOException { if (append) { - Appendable a = resource.as(Appendable.class); + final Appendable a = resource.as(Appendable.class); if (a != null) { return a.getAppendOutputStream(); } @@ -834,7 +836,7 @@ public class ResourceUtils { return resource.getOutputStream(); } - public static interface ResourceSelectorProvider { + public interface ResourceSelectorProvider { ResourceSelector getTargetSelectorForSource(Resource source); } @@ -842,7 +844,9 @@ public class ResourceUtils { * @since Ant 1.9.4 */ public static class ReadOnlyTargetFileException extends IOException { - public ReadOnlyTargetFileException(File destFile) { + private static final long serialVersionUID = 1L; + + public ReadOnlyTargetFileException(final File destFile) { super("can't write to read-only destination file " + destFile); } } diff --git a/src/main/org/apache/tools/ant/util/SymbolicLinkUtils.java b/src/main/org/apache/tools/ant/util/SymbolicLinkUtils.java index d6c7353a4..36024ec15 100644 --- a/src/main/org/apache/tools/ant/util/SymbolicLinkUtils.java +++ b/src/main/org/apache/tools/ant/util/SymbolicLinkUtils.java @@ -171,13 +171,14 @@ public class SymbolicLinkUtils { * @return true if the file is a broken symbolic link. * @throws IOException on error. */ - public boolean isDanglingSymbolicLink(File parent, String name) + public boolean isDanglingSymbolicLink(File parent, String name) throws IOException { File f = new File(parent, name); if (!f.exists()) { final String localName = f.getName(); String[] c = parent.list(new FilenameFilter() { - public boolean accept(File d, String n) { + @Override + public boolean accept(File d, String n) { return localName.equals(n); } }); diff --git a/src/main/org/apache/tools/ant/util/UnicodeUtil.java b/src/main/org/apache/tools/ant/util/UnicodeUtil.java index f4d52aaf5..bb64f73e2 100644 --- a/src/main/org/apache/tools/ant/util/UnicodeUtil.java +++ b/src/main/org/apache/tools/ant/util/UnicodeUtil.java @@ -41,6 +41,6 @@ public class UnicodeUtil { - s.length() + i, s.charAt(i)); } - return unicodeBuf; + return unicodeBuf; } } diff --git a/src/main/org/apache/tools/tar/TarConstants.java b/src/main/org/apache/tools/tar/TarConstants.java index 2944a4055..06d0faca9 100644 --- a/src/main/org/apache/tools/tar/TarConstants.java +++ b/src/main/org/apache/tools/tar/TarConstants.java @@ -67,7 +67,7 @@ public interface TarConstants { * be expressed in octal char notation (that's 7 sevens, octal). */ long MAXID = 07777777L; - + /** * The length of the checksum field in a header buffer. */ @@ -80,7 +80,7 @@ public interface TarConstants { int SIZELEN = 12; /** - * The maximum size of a file in a tar archive + * The maximum size of a file in a tar archive * which can be expressed in octal char notation (that's 11 sevens, octal). */ long MAXSIZE = 077777777777L; @@ -127,67 +127,67 @@ public interface TarConstants { /** * Length of the prefix field. - * + * */ int PREFIXLEN = 155; /** * The length of the access time field in an old GNU header buffer. - * + * */ int ATIMELEN_GNU = 12; /** * The length of the created time field in an old GNU header buffer. - * + * */ int CTIMELEN_GNU = 12; /** - * The length of the multivolume start offset field in an old GNU header buffer. - * + * The length of the multivolume start offset field in an old GNU header buffer. + * */ int OFFSETLEN_GNU = 12; /** - * The length of the long names field in an old GNU header buffer. - * + * The length of the long names field in an old GNU header buffer. + * */ int LONGNAMESLEN_GNU = 4; /** - * The length of the padding field in an old GNU header buffer. - * + * The length of the padding field in an old GNU header buffer. + * */ int PAD2LEN_GNU = 1; /** - * The sum of the length of all sparse headers in an old GNU header buffer. - * + * The sum of the length of all sparse headers in an old GNU header buffer. + * */ int SPARSELEN_GNU = 96; /** - * The length of the is extension field in an old GNU header buffer. - * + * The length of the is extension field in an old GNU header buffer. + * */ int ISEXTENDEDLEN_GNU = 1; /** - * The length of the real size field in an old GNU header buffer. - * + * The length of the real size field in an old GNU header buffer. + * */ int REALSIZELEN_GNU = 12; /** - * The sum of the length of all sparse headers in a sparse header buffer. - * + * The sum of the length of all sparse headers in a sparse header buffer. + * */ int SPARSELEN_GNU_SPARSE = 504; /** - * The length of the is extension field in a sparse header buffer. - * + * The length of the is extension field in a sparse header buffer. + * */ int ISEXTENDEDLEN_GNU_SPARSE = 1; diff --git a/src/main/org/apache/tools/tar/TarInputStream.java b/src/main/org/apache/tools/tar/TarInputStream.java index 154f14e2e..651f206bd 100644 --- a/src/main/org/apache/tools/tar/TarInputStream.java +++ b/src/main/org/apache/tools/tar/TarInputStream.java @@ -506,10 +506,10 @@ public class TarInputStream extends FilterInputStream { /** * Adds the sparse chunks from the current entry to the sparse chunks, * including any additional sparse entries following the current entry. - * - * @throws IOException on error - * - * @todo Sparse files get not yet really processed. + * + * @throws IOException on error + * + * @todo Sparse files get not yet really processed. */ private void readGNUSparse() throws IOException { /* we do not really process sparse files yet @@ -543,7 +543,7 @@ public class TarInputStream extends FilterInputStream { @Override public int read() throws IOException { int num = read(oneBuf, 0, 1); - return num == -1 ? -1 : ((int) oneBuf[0]) & BYTE_MASK; + return num == -1 ? -1 : (oneBuf[0]) & BYTE_MASK; } /** diff --git a/src/main/org/apache/tools/tar/TarOutputStream.java b/src/main/org/apache/tools/tar/TarOutputStream.java index e90576f38..6babde7de 100644 --- a/src/main/org/apache/tools/tar/TarOutputStream.java +++ b/src/main/org/apache/tools/tar/TarOutputStream.java @@ -206,11 +206,11 @@ public class TarOutputStream extends FilterOutputStream { /** * Ends the TAR archive without closing the underlying OutputStream. - * + * * An archive consists of a series of file entries terminated by an - * end-of-archive entry, which consists of two 512 blocks of zero bytes. + * end-of-archive entry, which consists of two 512 blocks of zero bytes. * POSIX.1 requires two EOF records, like some other implementations. - * + * * @throws IOException on error */ public void finish() throws IOException { @@ -377,7 +377,8 @@ public class TarOutputStream extends FilterOutputStream { * @param wBuf The buffer to write to the archive. * @throws IOException on error */ - public void write(byte[] wBuf) throws IOException { + @Override + public void write(byte[] wBuf) throws IOException { write(wBuf, 0, wBuf.length); } diff --git a/src/main/org/apache/tools/tar/TarUtils.java b/src/main/org/apache/tools/tar/TarUtils.java index c05744160..d6d662304 100644 --- a/src/main/org/apache/tools/tar/TarUtils.java +++ b/src/main/org/apache/tools/tar/TarUtils.java @@ -46,9 +46,11 @@ public class TarUtils { * Encapsulates the algorithms used up to Ant 1.8 as ZipEncoding. */ static final ZipEncoding FALLBACK_ENCODING = new ZipEncoding() { - public boolean canEncode(String name) { return true; } + @Override + public boolean canEncode(String name) { return true; } - public ByteBuffer encode(String name) { + @Override + public ByteBuffer encode(String name) { final int length = name.length(); byte[] buf = new byte[length]; @@ -59,7 +61,8 @@ public class TarUtils { return ByteBuffer.wrap(buf); } - public String decode(byte[] buffer) { + @Override + public String decode(byte[] buffer) { final int length = buffer.length; StringBuilder result = new StringBuilder(length); @@ -146,7 +149,7 @@ public class TarUtils { return result; } - /** + /** * Compute the value contained in a byte buffer. If the most * significant bit of the first byte in the buffer is set, this * bit is ignored and the rest of the buffer is interpreted as a @@ -303,7 +306,7 @@ public class TarUtils { /** * Copy a name into a buffer. * Copies characters from the name into the buffer - * starting at the specified offset. + * starting at the specified offset. * If the buffer is longer than the name, the buffer * is filled with trailing NULs. * If the name is longer than the buffer, @@ -332,7 +335,7 @@ public class TarUtils { /** * Copy a name into a buffer. * Copies characters from the name into the buffer - * starting at the specified offset. + * starting at the specified offset. * If the buffer is longer than the name, the buffer * is filled with trailing NULs. * If the name is longer than the buffer, @@ -367,7 +370,7 @@ public class TarUtils { /** * Fill buffer with unsigned octal number, padded with leading zeroes. - * + * * @param value number to convert to octal - treated as unsigned * @param buffer destination buffer * @param offset starting offset in buffer @@ -405,7 +408,7 @@ public class TarUtils { * Uses {@link #formatUnsignedOctalString} to format * the value as an octal string with leading zeros. * The converted number is followed by space and NUL - * + * * @param value The value to write * @param buf The buffer to receive the output * @param offset The starting offset into the buffer @@ -426,11 +429,11 @@ public class TarUtils { /** * Write an octal long integer into a buffer. - * + * * Uses {@link #formatUnsignedOctalString} to format * the value as an octal string with leading zeros. * The converted number is followed by a space. - * + * * @param value The value to write as octal * @param buf The destinationbuffer. * @param offset The starting offset into the buffer. @@ -451,11 +454,11 @@ public class TarUtils { /** * Write an long integer into a buffer as an octal string if this * will fit, or as a binary number otherwise. - * + * * Uses {@link #formatUnsignedOctalString} to format * the value as an octal string with leading zeros. * The converted number is followed by a space. - * + * * @param value The value to write into the buffer. * @param buf The destination buffer. * @param offset The starting offset into the buffer. @@ -488,7 +491,7 @@ public class TarUtils { final int offset, final int length, final boolean negative) { final int bits = (length - 1) * 8; - final long max = 1l << bits; + final long max = 1L << bits; long val = Math.abs(value); if (val >= max) { throw new IllegalArgumentException("Value " + value + @@ -522,7 +525,7 @@ public class TarUtils { /** * Writes an octal value into a buffer. - * + * * Uses {@link #formatUnsignedOctalString} to format * the value as an octal string with leading zeros. * The converted number is followed by NUL and then space. diff --git a/src/main/org/apache/tools/zip/AbstractUnicodeExtraField.java b/src/main/org/apache/tools/zip/AbstractUnicodeExtraField.java index 0a7eec2f7..731d2612e 100644 --- a/src/main/org/apache/tools/zip/AbstractUnicodeExtraField.java +++ b/src/main/org/apache/tools/zip/AbstractUnicodeExtraField.java @@ -36,7 +36,7 @@ public abstract class AbstractUnicodeExtraField implements ZipExtraField { /** * Assemble as unicode extension from the name/comment and * encoding of the original zip entry. - * + * * @param text The file name or comment. * @param bytes The encoded of the filename or comment in the zip * file. @@ -62,7 +62,7 @@ public abstract class AbstractUnicodeExtraField implements ZipExtraField { /** * Assemble as unicode extension from the name/comment and * encoding of the original zip entry. - * + * * @param text The file name or comment. * @param bytes The encoded of the filename or comment in the zip * file. @@ -128,7 +128,8 @@ public abstract class AbstractUnicodeExtraField implements ZipExtraField { } /** {@inheritDoc} */ - public byte[] getCentralDirectoryData() { + @Override + public byte[] getCentralDirectoryData() { if (data == null) { this.assembleData(); } @@ -141,7 +142,8 @@ public abstract class AbstractUnicodeExtraField implements ZipExtraField { } /** {@inheritDoc} */ - public ZipShort getCentralDirectoryLength() { + @Override + public ZipShort getCentralDirectoryLength() { if (data == null) { assembleData(); } @@ -149,17 +151,20 @@ public abstract class AbstractUnicodeExtraField implements ZipExtraField { } /** {@inheritDoc} */ - public byte[] getLocalFileDataData() { + @Override + public byte[] getLocalFileDataData() { return getCentralDirectoryData(); } /** {@inheritDoc} */ - public ZipShort getLocalFileDataLength() { + @Override + public ZipShort getLocalFileDataLength() { return getCentralDirectoryLength(); } /** {@inheritDoc} */ - public void parseFromLocalFileData(byte[] buffer, int offset, int length) + @Override + public void parseFromLocalFileData(byte[] buffer, int offset, int length) throws ZipException { if (length < 5) { diff --git a/src/main/org/apache/tools/zip/FallbackZipEncoding.java b/src/main/org/apache/tools/zip/FallbackZipEncoding.java index facc63e70..545d6c717 100644 --- a/src/main/org/apache/tools/zip/FallbackZipEncoding.java +++ b/src/main/org/apache/tools/zip/FallbackZipEncoding.java @@ -29,14 +29,14 @@ import java.nio.ByteBuffer; * utf-8, because java.io encodes unmappable character as question * marks leading to unreadable ZIP entries on some operating * systems.

- * + * *

Furthermore this implementation is unable to tell whether a * given name can be safely encoded or not.

- * + * *

This implementation acts as a last resort implementation, when * neither {@link Simple8BitZipEnoding} nor {@link NioZipEncoding} is * available.

- * + * *

The methods of this class are reentrant.

*/ class FallbackZipEncoding implements ZipEncoding { @@ -52,7 +52,7 @@ class FallbackZipEncoding implements ZipEncoding { /** * Construct a fallback zip encoding, which uses the given charset. - * + * * @param charset The name of the charset or {@code null} for * the platform's default character set. */ @@ -64,7 +64,8 @@ class FallbackZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#canEncode(java.lang.String) */ - public boolean canEncode(String name) { + @Override + public boolean canEncode(String name) { return true; } @@ -72,7 +73,8 @@ class FallbackZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#encode(java.lang.String) */ - public ByteBuffer encode(String name) throws IOException { + @Override + public ByteBuffer encode(String name) throws IOException { if (this.charset == null) { // i.e. use default charset, see no-args constructor return ByteBuffer.wrap(name.getBytes()); } else { @@ -84,7 +86,8 @@ class FallbackZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#decode(byte[]) */ - public String decode(byte[] data) throws IOException { + @Override + public String decode(byte[] data) throws IOException { if (this.charset == null) { // i.e. use default charset, see no-args constructor return new String(data); } else { diff --git a/src/main/org/apache/tools/zip/GeneralPurposeBit.java b/src/main/org/apache/tools/zip/GeneralPurposeBit.java index 1e92103aa..eaafc2c5c 100644 --- a/src/main/org/apache/tools/zip/GeneralPurposeBit.java +++ b/src/main/org/apache/tools/zip/GeneralPurposeBit.java @@ -122,7 +122,7 @@ public final class GeneralPurposeBit { * Encodes the set bits in a form suitable for ZIP archives. */ public byte[] encode() { - return + return ZipShort.getBytes((dataDescriptorFlag ? DATA_DESCRIPTOR_FLAG : 0) | (languageEncodingFlag ? UFT8_NAMES_FLAG : 0) diff --git a/src/main/org/apache/tools/zip/NioZipEncoding.java b/src/main/org/apache/tools/zip/NioZipEncoding.java index e2274e522..cc5e40bd6 100644 --- a/src/main/org/apache/tools/zip/NioZipEncoding.java +++ b/src/main/org/apache/tools/zip/NioZipEncoding.java @@ -34,7 +34,7 @@ import java.nio.charset.CodingErrorAction; *

This implementation works for all cases under java-1.5 or * later. However, in java-1.4, some charsets don't have a java.nio * implementation, most notably the default ZIP encoding Cp437.

- * + * *

The methods of this class are reentrant.

*/ class NioZipEncoding implements ZipEncoding { @@ -43,7 +43,7 @@ class NioZipEncoding implements ZipEncoding { /** * Construct an NIO based zip encoding, which wraps the given * charset. - * + * * @param charset The NIO charset to wrap. */ public NioZipEncoding(Charset charset) { @@ -54,7 +54,8 @@ class NioZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#canEncode(java.lang.String) */ - public boolean canEncode(String name) { + @Override + public boolean canEncode(String name) { CharsetEncoder enc = this.charset.newEncoder(); enc.onMalformedInput(CodingErrorAction.REPORT); enc.onUnmappableCharacter(CodingErrorAction.REPORT); @@ -66,7 +67,8 @@ class NioZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#encode(java.lang.String) */ - public ByteBuffer encode(String name) { + @Override + public ByteBuffer encode(String name) { CharsetEncoder enc = this.charset.newEncoder(); enc.onMalformedInput(CodingErrorAction.REPORT); @@ -113,7 +115,8 @@ class NioZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#decode(byte[]) */ - public String decode(byte[] data) throws IOException { + @Override + public String decode(byte[] data) throws IOException { return this.charset.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) diff --git a/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java b/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java index 5bff47293..4db24b8dc 100644 --- a/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java +++ b/src/main/org/apache/tools/zip/Simple8BitZipEncoding.java @@ -28,7 +28,7 @@ import java.util.List; /** * This ZipEncoding implementation implements a simple 8bit character * set, which mets the following restrictions: - * + * *
    *
  • Characters 0x0000 to 0x007f are encoded as the corresponding * byte values 0x00 to 0x7f.
  • @@ -36,11 +36,11 @@ import java.util.List; * character in the range 0x0080 to 0x7fff. (No support for * UTF-16 surrogates) *
- * + * *

These restrictions most notably apply to the most prominent * omissions of java-1.4's {@link java.nio.charset.Charset Charset} * implementation, Cp437 and Cp850.

- * + * *

The methods of this class are reentrant.

*/ class Simple8BitZipEncoding implements ZipEncoding { @@ -58,7 +58,8 @@ class Simple8BitZipEncoding implements ZipEncoding { this.unicode = unicode; } - public int compareTo(Simple8BitChar a) { + @Override + public int compareTo(Simple8BitChar a) { return this.unicode - a.unicode; } @@ -117,7 +118,7 @@ class Simple8BitZipEncoding implements ZipEncoding { /** * Return the character code for a given encoded byte. - * + * * @param b The byte to decode. * @return The associated character value. */ @@ -147,12 +148,12 @@ class Simple8BitZipEncoding implements ZipEncoding { /** * Pushes the encoded form of the given character to the given byte buffer. - * + * * @param bb The byte buffer to write to. * @param c The character to encode. * @return Whether the given unicode character is covered by this encoding. * If {@code false} is returned, nothing is pushed to the - * byte buffer. + * byte buffer. */ public boolean pushEncodedChar(ByteBuffer bb, char c) { @@ -215,7 +216,8 @@ class Simple8BitZipEncoding implements ZipEncoding { * @see * org.apache.tools.zip.ZipEncoding#canEncode(java.lang.String) */ - public boolean canEncode(String name) { + @Override + public boolean canEncode(String name) { for (int i=0;ibytes. @@ -54,7 +54,7 @@ public class UnicodeCommentExtraField extends AbstractUnicodeExtraField { /** * Assemble as unicode comment extension from the comment given as * text as well as the bytes actually written to the archive. - * + * * @param comment The file comment * @param bytes the bytes actually written to the archive */ @@ -63,7 +63,8 @@ public class UnicodeCommentExtraField extends AbstractUnicodeExtraField { } /** {@inheritDoc} */ - public ZipShort getHeaderId() { + @Override + public ZipShort getHeaderId() { return UCOM_ID; } diff --git a/src/main/org/apache/tools/zip/UnicodePathExtraField.java b/src/main/org/apache/tools/zip/UnicodePathExtraField.java index 4fb87723b..2f6e0c280 100644 --- a/src/main/org/apache/tools/zip/UnicodePathExtraField.java +++ b/src/main/org/apache/tools/zip/UnicodePathExtraField.java @@ -21,7 +21,7 @@ package org.apache.tools.zip; /** * Info-ZIP Unicode Path Extra Field (0x7075): * - *

Stores the UTF-8 version of the file name field as stored in the + *

Stores the UTF-8 version of the file name field as stored in the * local header and central directory header.

* *

See {@link @@ -32,13 +32,13 @@ public class UnicodePathExtraField extends AbstractUnicodeExtraField { public static final ZipShort UPATH_ID = new ZipShort(0x7075); - public UnicodePathExtraField () { + public UnicodePathExtraField () { } /** * Assemble as unicode path extension from the name given as * text as well as the encoded bytes actually written to the archive. - * + * * @param text The file name * @param bytes the bytes actually written to the archive * @param off The offset of the encoded filename in bytes. @@ -52,7 +52,7 @@ public class UnicodePathExtraField extends AbstractUnicodeExtraField { /** * Assemble as unicode path extension from the name given as * text as well as the encoded bytes actually written to the archive. - * + * * @param name The file name * @param bytes the bytes actually written to the archive */ @@ -61,7 +61,8 @@ public class UnicodePathExtraField extends AbstractUnicodeExtraField { } /** {@inheritDoc} */ - public ZipShort getHeaderId() { + @Override + public ZipShort getHeaderId() { return UPATH_ID; } } diff --git a/src/main/org/apache/tools/zip/ZipEncoding.java b/src/main/org/apache/tools/zip/ZipEncoding.java index 08524735a..72653834c 100644 --- a/src/main/org/apache/tools/zip/ZipEncoding.java +++ b/src/main/org/apache/tools/zip/ZipEncoding.java @@ -30,14 +30,14 @@ import java.nio.ByteBuffer; * {@link java.nio.charset.Charset Charset} and one implementation, * which copes with simple 8 bit charsets, because java-1.4 did not * support Cp437 in java.nio.

- * + * *

The main reason for defining an own encoding layer comes from * the problems with {@link java.lang.String#getBytes(String) * String.getBytes}, which encodes unknown characters as ASCII * quotation marks ('?'). Quotation marks are per definition an * invalid filename on some operating systems like Windows, which * leads to ignored ZIP entries.

- * + * *

All implementations should implement this interface in a * reentrant way.

*/ @@ -45,7 +45,7 @@ public interface ZipEncoding { /** * Check, whether the given string may be losslessly encoded using this * encoding. - * + * * @param name A filename or ZIP comment. * @return Whether the given name may be encoded with out any losses. */ @@ -54,15 +54,15 @@ public interface ZipEncoding { /** * Encode a filename or a comment to a byte array suitable for * storing it to a serialized zip entry. - * + * *

Examples for CP 437 (in pseudo-notation, right hand side is * C-style notation):

*
      *  encode("\u20AC_for_Dollar.txt") = "%U20AC_for_Dollar.txt"
      *  encode("\u00D6lf\u00E4sser.txt") = "\231lf\204sser.txt"
      * 
- * - * @param name A filename or ZIP comment. + * + * @param name A filename or ZIP comment. * @return A byte buffer with a backing array containing the * encoded name. Unmappable characters or malformed * character sequences are mapped to a sequence of utf-16 @@ -71,14 +71,14 @@ public interface ZipEncoding { * beginning of the encoded result, the byte buffer has a * backing array and the limit of the byte buffer points * to the end of the encoded result. - * @throws IOException + * @throws IOException */ ByteBuffer encode(String name) throws IOException; /** * @param data The byte values to decode. * @return The decoded string. - * @throws IOException + * @throws IOException */ String decode(byte [] data) throws IOException; } diff --git a/src/main/org/apache/tools/zip/ZipEncodingHelper.java b/src/main/org/apache/tools/zip/ZipEncodingHelper.java index b32f902b3..4d3dab957 100644 --- a/src/main/org/apache/tools/zip/ZipEncodingHelper.java +++ b/src/main/org/apache/tools/zip/ZipEncodingHelper.java @@ -26,7 +26,7 @@ import java.util.HashMap; import java.util.Map; /** - * Static helper functions for robustly encoding filenames in zip files. + * Static helper functions for robustly encoding filenames in zip files. */ public abstract class ZipEncodingHelper { @@ -42,12 +42,12 @@ public abstract class ZipEncodingHelper { /** * Instantiate a simple encoding holder. - * + * * @param highChars The characters for byte codes 128 to 255. - * + * * @see Simple8BitZipEncoding#Simple8BitZipEncoding(char[]) */ - SimpleEncodingHolder(char [] highChars) { + SimpleEncodingHolder(final char [] highChars) { this.highChars = highChars; } @@ -66,34 +66,34 @@ public abstract class ZipEncodingHelper { private static final Map simpleEncodings; static { - Map se = + final Map se = new HashMap(); - char[] cp437_high_chars = - new char[] { 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, - 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, - 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, - 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, - 0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, - 0x20a7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, - 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, - 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, - 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, - 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, - 0x255d, 0x255c, 0x255b, 0x2510, 0x2514, 0x2534, - 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, - 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, - 0x256c, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, - 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, - 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, - 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, - 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, - 0x221e, 0x03c6, 0x03b5, 0x2229, 0x2261, 0x00b1, - 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, - 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, - 0x25a0, 0x00a0 }; - - SimpleEncodingHolder cp437 = new SimpleEncodingHolder(cp437_high_chars); + final char[] cp437_high_chars = + new char[] {0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, + 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, + 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, + 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, + 0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, + 0x20a7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, + 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, + 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, + 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, + 0x255d, 0x255c, 0x255b, 0x2510, 0x2514, 0x2534, + 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, + 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, + 0x256c, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, + 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, + 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, + 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, + 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, + 0x221e, 0x03c6, 0x03b5, 0x2229, 0x2261, 0x00b1, + 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, + 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, + 0x25a0, 0x00a0}; + + final SimpleEncodingHolder cp437 = new SimpleEncodingHolder(cp437_high_chars); se.put("CP437", cp437); se.put("Cp437", cp437); @@ -101,31 +101,31 @@ public abstract class ZipEncodingHelper { se.put("IBM437", cp437); se.put("ibm437", cp437); - char[] cp850_high_chars = - new char[] { 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, - 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, - 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, - 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, - 0x00ff, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, - 0x00d7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, - 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x00ae, - 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, - 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00c1, - 0x00c2, 0x00c0, 0x00a9, 0x2563, 0x2551, 0x2557, - 0x255d, 0x00a2, 0x00a5, 0x2510, 0x2514, 0x2534, - 0x252c, 0x251c, 0x2500, 0x253c, 0x00e3, 0x00c3, - 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, - 0x256c, 0x00a4, 0x00f0, 0x00d0, 0x00ca, 0x00cb, - 0x00c8, 0x0131, 0x00cd, 0x00ce, 0x00cf, 0x2518, - 0x250c, 0x2588, 0x2584, 0x00a6, 0x00cc, 0x2580, - 0x00d3, 0x00df, 0x00d4, 0x00d2, 0x00f5, 0x00d5, - 0x00b5, 0x00fe, 0x00de, 0x00da, 0x00db, 0x00d9, - 0x00fd, 0x00dd, 0x00af, 0x00b4, 0x00ad, 0x00b1, - 0x2017, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x00b8, - 0x00b0, 0x00a8, 0x00b7, 0x00b9, 0x00b3, 0x00b2, - 0x25a0, 0x00a0 }; - - SimpleEncodingHolder cp850 = new SimpleEncodingHolder(cp850_high_chars); + final char[] cp850_high_chars = + new char[] {0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, + 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, + 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, + 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, + 0x00ff, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, + 0x00d7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, + 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x00ae, + 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00c1, + 0x00c2, 0x00c0, 0x00a9, 0x2563, 0x2551, 0x2557, + 0x255d, 0x00a2, 0x00a5, 0x2510, 0x2514, 0x2534, + 0x252c, 0x251c, 0x2500, 0x253c, 0x00e3, 0x00c3, + 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, + 0x256c, 0x00a4, 0x00f0, 0x00d0, 0x00ca, 0x00cb, + 0x00c8, 0x0131, 0x00cd, 0x00ce, 0x00cf, 0x2518, + 0x250c, 0x2588, 0x2584, 0x00a6, 0x00cc, 0x2580, + 0x00d3, 0x00df, 0x00d4, 0x00d2, 0x00f5, 0x00d5, + 0x00b5, 0x00fe, 0x00de, 0x00da, 0x00db, 0x00d9, + 0x00fd, 0x00dd, 0x00af, 0x00b4, 0x00ad, 0x00b1, + 0x2017, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x00b8, + 0x00b0, 0x00a8, 0x00b7, 0x00b9, 0x00b3, 0x00b2, + 0x25a0, 0x00a0}; + + final SimpleEncodingHolder cp850 = new SimpleEncodingHolder(cp850_high_chars); se.put("CP850", cp850); se.put("Cp850", cp850); @@ -137,8 +137,8 @@ public abstract class ZipEncodingHelper { /** * Grow a byte buffer, so it has a minimal capacity or at least - * the double capacity of the original buffer - * + * the double capacity of the original buffer + * * @param b The original buffer. * @param newCapacity The minimal requested new capacity. * @return A byte buffer r with @@ -147,18 +147,18 @@ public abstract class ZipEncodingHelper { * of r. * */ - static ByteBuffer growBuffer(ByteBuffer b, int newCapacity) { + static ByteBuffer growBuffer(final ByteBuffer b, final int newCapacity) { b.limit(b.position()); b.rewind(); - int c2 = b.capacity() * 2; - ByteBuffer on = ByteBuffer.allocate(c2 < newCapacity ? newCapacity : c2); + final int c2 = b.capacity() * 2; + final ByteBuffer on = ByteBuffer.allocate(c2 < newCapacity ? newCapacity : c2); on.put(b); return on; } - + /** * The hexadecimal digits 0,...,9,A,...,F encoded as * ASCII bytes. @@ -172,11 +172,11 @@ public abstract class ZipEncodingHelper { /** * Append %Uxxxx to the given byte buffer. * The caller must assure, that bb.remaining()>=6. - * + * * @param bb The byte buffer to write to. * @param c The character to write. */ - static void appendSurrogate(ByteBuffer bb, char c) { + static void appendSurrogate(final ByteBuffer bb, final char c) { bb.put((byte) '%'); bb.put((byte) 'U'); @@ -205,13 +205,13 @@ public abstract class ZipEncodingHelper { /** * Instantiates a zip encoding. - * + * * @param name The name of the zip encoding. Specify {@code null} for * the platform's default encoding. * @return A zip encoding for the given encoding name. */ - public static ZipEncoding getZipEncoding(String name) { - + public static ZipEncoding getZipEncoding(final String name) { + // fallback encoding is good enough for utf-8. if (isUTF8(name)) { return UTF8_ZIP_ENCODING; @@ -221,7 +221,7 @@ public abstract class ZipEncodingHelper { return new FallbackZipEncoding(); } - SimpleEncodingHolder h = simpleEncodings.get(name); + final SimpleEncodingHolder h = simpleEncodings.get(name); if (h!=null) { return h.getEncoding(); @@ -229,10 +229,10 @@ public abstract class ZipEncodingHelper { try { - Charset cs = Charset.forName(name); + final Charset cs = Charset.forName(name); return new NioZipEncoding(cs); - } catch (UnsupportedCharsetException e) { + } catch (final UnsupportedCharsetException e) { return new FallbackZipEncoding(name); } } diff --git a/src/main/org/apache/tools/zip/ZipEntry.java b/src/main/org/apache/tools/zip/ZipEntry.java index 7d52a9694..bbcf1aeb5 100644 --- a/src/main/org/apache/tools/zip/ZipEntry.java +++ b/src/main/org/apache/tools/zip/ZipEntry.java @@ -90,7 +90,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param name the name of the entry * @since 1.1 */ - public ZipEntry(String name) { + public ZipEntry(final String name) { super(name); setName(name); } @@ -105,10 +105,10 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @since 1.1 * @throws ZipException on error */ - public ZipEntry(java.util.zip.ZipEntry entry) throws ZipException { + public ZipEntry(final java.util.zip.ZipEntry entry) throws ZipException { super(entry); setName(entry.getName()); - byte[] extra = entry.getExtra(); + final byte[] extra = entry.getExtra(); if (extra != null) { setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils @@ -131,7 +131,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @throws ZipException on error * @since 1.1 */ - public ZipEntry(ZipEntry entry) throws ZipException { + public ZipEntry(final ZipEntry entry) throws ZipException { this((java.util.zip.ZipEntry) entry); setInternalAttributes(entry.getInternalAttributes()); setExternalAttributes(entry.getExternalAttributes()); @@ -154,8 +154,8 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * potential trailing forward slash will be stripped from the * entry name.

*/ - public ZipEntry(File inputFile, String entryName) { - this(inputFile.isDirectory() && !entryName.endsWith("/") ? + public ZipEntry(final File inputFile, final String entryName) { + this(inputFile.isDirectory() && !entryName.endsWith("/") ? entryName + "/" : entryName); if (inputFile.isFile()){ setSize(inputFile.length()); @@ -171,7 +171,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { */ @Override public Object clone() { - ZipEntry e = (ZipEntry) super.clone(); + final ZipEntry e = (ZipEntry) super.clone(); e.setInternalAttributes(getInternalAttributes()); e.setExternalAttributes(getExternalAttributes()); @@ -196,7 +196,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param method compression method */ @Override - public void setMethod(int method) { + public void setMethod(final int method) { if (method < 0) { throw new IllegalArgumentException( "ZIP compression method can not be negative: " + method); @@ -219,7 +219,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param value an int value * @since 1.1 */ - public void setInternalAttributes(int value) { + public void setInternalAttributes(final int value) { internalAttributes = value; } @@ -237,7 +237,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param value an long value * @since 1.1 */ - public void setExternalAttributes(long value) { + public void setExternalAttributes(final long value) { externalAttributes = value; } @@ -247,7 +247,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param mode an int value * @since Ant 1.5.2 */ - public void setUnixMode(int mode) { + public void setUnixMode(final int mode) { // CheckStyle:MagicNumberCheck OFF - no point setExternalAttributes((mode << SHORT_SHIFT) // MS-DOS read-only attribute @@ -286,7 +286,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param platform an int value - 0 is FAT, 3 is UNIX * @since 1.9 */ - protected void setPlatform(int platform) { + protected void setPlatform(final int platform) { this.platform = platform; } @@ -295,9 +295,9 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param fields an array of extra fields * @since 1.1 */ - public void setExtraFields(ZipExtraField[] fields) { + public void setExtraFields(final ZipExtraField[] fields) { extraFields = new LinkedHashMap(); - for (ZipExtraField field : fields) { + for (final ZipExtraField field : fields) { if (field instanceof UnparseableExtraFieldData) { unparseableExtra = (UnparseableExtraFieldData) field; } else { @@ -323,13 +323,13 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @return an array of the extra fields * @since 1.1 */ - public ZipExtraField[] getExtraFields(boolean includeUnparseable) { + public ZipExtraField[] getExtraFields(final boolean includeUnparseable) { if (extraFields == null) { return !includeUnparseable || unparseableExtra == null ? new ZipExtraField[0] - : new ZipExtraField[] { unparseableExtra }; + : new ZipExtraField[] {unparseableExtra}; } - List result = + final List result = new ArrayList(extraFields.values()); if (includeUnparseable && unparseableExtra != null) { result.add(unparseableExtra); @@ -346,7 +346,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param ze an extra field * @since 1.1 */ - public void addExtraField(ZipExtraField ze) { + public void addExtraField(final ZipExtraField ze) { if (ze instanceof UnparseableExtraFieldData) { unparseableExtra = (UnparseableExtraFieldData) ze; } else { @@ -366,11 +366,11 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param ze an extra field * @since 1.1 */ - public void addAsFirstExtraField(ZipExtraField ze) { + public void addAsFirstExtraField(final ZipExtraField ze) { if (ze instanceof UnparseableExtraFieldData) { unparseableExtra = (UnparseableExtraFieldData) ze; } else { - LinkedHashMap copy = extraFields; + final LinkedHashMap copy = extraFields; extraFields = new LinkedHashMap(); extraFields.put(ze.getHeaderId(), ze); if (copy != null) { @@ -386,7 +386,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param type the type of extra field to remove * @since 1.1 */ - public void removeExtraField(ZipShort type) { + public void removeExtraField(final ZipShort type) { if (extraFields == null) { throw new java.util.NoSuchElementException(); } @@ -412,7 +412,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * * @return null if no such field exists. */ - public ZipExtraField getExtraField(ZipShort type) { + public ZipExtraField getExtraField(final ZipShort type) { if (extraFields != null) { return extraFields.get(type); } @@ -438,13 +438,13 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @throws RuntimeException on error */ @Override - public void setExtra(byte[] extra) throws RuntimeException { + public void setExtra(final byte[] extra) throws RuntimeException { try { - ZipExtraField[] local = + final ZipExtraField[] local = ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ); mergeExtraFields(local, true); - } catch (ZipException e) { + } catch (final ZipException e) { // actually this is not be possible as of Ant 1.8.1 throw new RuntimeException("Error parsing extra fields for entry: " + getName() + " - " + e.getMessage(), e); @@ -466,13 +466,13 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { /** * Sets the central directory part of extra fields. */ - public void setCentralDirectoryExtra(byte[] b) { + public void setCentralDirectoryExtra(final byte[] b) { try { - ZipExtraField[] central = + final ZipExtraField[] central = ExtraFieldUtils.parse(b, false, ExtraFieldUtils.UnparseableExtraField.READ); mergeExtraFields(central, false); - } catch (ZipException e) { + } catch (final ZipException e) { throw new RuntimeException(e.getMessage(), e); } } @@ -483,7 +483,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @since 1.1 */ public byte[] getLocalFileDataExtra() { - byte[] extra = getExtra(); + final byte[] extra = getExtra(); return extra != null ? extra : EMPTY; } @@ -506,7 +506,8 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * Use setCompressedSize directly. * @since 1.2 */ - public void setComprSize(long size) { + @Deprecated + public void setComprSize(final long size) { setCompressedSize(size); } @@ -558,7 +559,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * than 0 */ @Override - public void setSize(long size) { + public void setSize(final long size) { if (size < 0) { throw new IllegalArgumentException("invalid entry size"); } @@ -573,7 +574,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param rawName the bytes originally read as name from the * archive */ - protected void setName(String name, byte[] rawName) { + protected void setName(final String name, final byte[] rawName) { setName(name); this.rawName = rawName; } @@ -587,7 +588,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { */ public byte[] getRawName() { if (rawName != null) { - byte[] b = new byte[rawName.length]; + final byte[] b = new byte[rawName.length]; System.arraycopy(rawName, 0, b, 0, rawName.length); return b; } @@ -619,7 +620,7 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { /** * The "general purpose bit" field. */ - public void setGeneralPurposeBit(GeneralPurposeBit b) { + public void setGeneralPurposeBit(final GeneralPurposeBit b) { gpb = b; } @@ -631,12 +632,12 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @param f the extra fields to merge * @param local whether the new fields originate from local data */ - private void mergeExtraFields(ZipExtraField[] f, boolean local) + private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException { if (extraFields == null) { setExtraFields(f); } else { - for (ZipExtraField element : f) { + for (final ZipExtraField element : f) { ZipExtraField existing; if (element instanceof UnparseableExtraFieldData) { existing = unparseableExtra; @@ -649,10 +650,10 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { if (local || !(existing instanceof CentralDirectoryParsingZipExtraField)) { - byte[] b = element.getLocalFileDataData(); + final byte[] b = element.getLocalFileDataData(); existing.parseFromLocalFileData(b, 0, b.length); } else { - byte[] b = element.getCentralDirectoryData(); + final byte[] b = element.getCentralDirectoryData(); ((CentralDirectoryParsingZipExtraField) existing) .parseFromCentralDirectoryData(b, 0, b.length); } @@ -671,16 +672,16 @@ public class ZipEntry extends java.util.zip.ZipEntry implements Cloneable { * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } - ZipEntry other = (ZipEntry) obj; - String myName = getName(); - String otherName = other.getName(); + final ZipEntry other = (ZipEntry) obj; + final String myName = getName(); + final String otherName = other.getName(); if (myName == null) { if (otherName != null) { return false; diff --git a/src/main/org/apache/tools/zip/ZipFile.java b/src/main/org/apache/tools/zip/ZipFile.java index 560314d3c..05efb33e0 100644 --- a/src/main/org/apache/tools/zip/ZipFile.java +++ b/src/main/org/apache/tools/zip/ZipFile.java @@ -815,7 +815,7 @@ public class ZipFile { /** * Skips the given number of bytes or throws an EOFException if * skipping failed. - */ + */ private void skipBytes(final int count) throws IOException { int totalSkipped = 0; while (totalSkipped < count) { @@ -852,7 +852,7 @@ public class ZipFile { private void resolveLocalFileHeaderData(Map entriesWithoutUTF8Flag) throws IOException { - for (Iterator it = entries.iterator(); it.hasNext(); ) { + for (Iterator it = entries.iterator(); it.hasNext();) { // entries is filled in populateFromCentralDirectory and // never modified Entry ze = (Entry) it.next(); @@ -992,7 +992,8 @@ public class ZipFile { */ private final Comparator OFFSET_COMPARATOR = new Comparator() { - public int compare(ZipEntry e1, ZipEntry e2) { + @Override + public int compare(ZipEntry e1, ZipEntry e2) { if (e1 == e2) { return 0; } diff --git a/src/main/org/apache/tools/zip/ZipOutputStream.java b/src/main/org/apache/tools/zip/ZipOutputStream.java index a04eae62d..2ac61c511 100644 --- a/src/main/org/apache/tools/zip/ZipOutputStream.java +++ b/src/main/org/apache/tools/zip/ZipOutputStream.java @@ -78,7 +78,7 @@ public class ZipOutputStream extends FilterOutputStream { */ private boolean finished = false; - /* + /* * Apparently Deflater.setInput gets slowed down a lot on Sun JVMs * when it gets handed a really big buffer. See * https://issues.apache.org/bugzilla/show_bug.cgi?id=45396 @@ -268,7 +268,7 @@ public class ZipOutputStream extends FilterOutputStream { * whether to use the general purpose bit flag when writing UTF-8 * filenames or not. */ - private boolean useUTF8Flag = true; + private boolean useUTF8Flag = true; /** * Whether to encode non-encodable file names as UTF-8. @@ -421,7 +421,7 @@ public class ZipOutputStream extends FilterOutputStream { * this mode is not valid when the output stream is not seekable * and the uncompressed size is unknown when {@link * #putNextEntry} is called.

- * + * *

If no entry inside the resulting archive requires Zip64 * extensions then {@link Zip64Mode#Never Never} will create the * smallest archive. {@link Zip64Mode#AsNeeded AsNeeded} will @@ -477,7 +477,7 @@ public class ZipOutputStream extends FilterOutputStream { * @since 1.1 * @throws IOException on error * @throws Zip64RequiredException if the entry's uncompressed or - * compressed size exceeds 4 GByte and {@link #setUseZip64} + * compressed size exceeds 4 GByte and {@link #setUseZip64} * is {@link Zip64Mode#Never}. */ public void closeEntry() throws IOException { @@ -625,9 +625,9 @@ public class ZipOutputStream extends FilterOutputStream { } /** - * {@inheritDoc} + * {@inheritDoc} * @throws Zip64RequiredException if the entry's uncompressed or - * compressed size is known to exceed 4 GByte and {@link #setUseZip64} + * compressed size is known to exceed 4 GByte and {@link #setUseZip64} * is {@link Zip64Mode#Never}. */ public void putNextEntry(ZipEntry archiveEntry) throws IOException { @@ -1089,7 +1089,7 @@ public class ZipOutputStream extends FilterOutputStream { // version made by // CheckStyle:MagicNumber OFF - writeOut(ZipShort.getBytes((ze.getPlatform() << 8) | + writeOut(ZipShort.getBytes((ze.getPlatform() << 8) | (!hasUsedZip64 ? DATA_DESCRIPTOR_MIN_VERSION : ZIP64_MIN_VERSION))); written += SHORT; @@ -1251,7 +1251,8 @@ public class ZipOutputStream extends FilterOutputStream { * @since 1.1 * @deprecated use ZipUtil#toDosTime */ - protected static ZipLong toDosTime(Date time) { + @Deprecated + protected static ZipLong toDosTime(Date time) { return ZipUtil.toDosTime(time); } @@ -1264,7 +1265,8 @@ public class ZipOutputStream extends FilterOutputStream { * @since 1.26 * @deprecated use ZipUtil#toDosTime */ - protected static byte[] toDosTime(long t) { + @Deprecated + protected static byte[] toDosTime(long t) { return ZipUtil.toDosTime(t); } @@ -1396,7 +1398,8 @@ public class ZipOutputStream extends FilterOutputStream { * @since 1.34 * @deprecated use ZipUtil#adjustToLong */ - protected static long adjustToLong(int i) { + @Deprecated + protected static long adjustToLong(int i) { return ZipUtil.adjustToLong(i); } diff --git a/src/main/org/apache/tools/zip/ZipUtil.java b/src/main/org/apache/tools/zip/ZipUtil.java index af5459039..f07e1eee5 100644 --- a/src/main/org/apache/tools/zip/ZipUtil.java +++ b/src/main/org/apache/tools/zip/ZipUtil.java @@ -147,7 +147,7 @@ public abstract class ZipUtil { *

If the field is null or the CRCs don't match, return null * instead.

*/ - private static + private static String getUnicodeStringIfOriginalMatches(AbstractUnicodeExtraField f, byte[] orig) { if (f != null) {