From 3d706ab8188a674936880b6f4530b0cf3991758b Mon Sep 17 00:00:00 2001 From: Matthew Jason Benson Date: Mon, 20 Aug 2012 17:49:13 +0000 Subject: [PATCH] java 5 updates git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@1375137 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/tools/ant/AntClassLoader.java | 130 +++++------ .../apache/tools/ant/AntTypeDefinition.java | 32 +-- .../org/apache/tools/ant/BuildException.java | 3 +- .../org/apache/tools/ant/ComponentHelper.java | 220 +++++++----------- .../apache/tools/ant/DemuxOutputStream.java | 3 +- .../org/apache/tools/ant/Diagnostics.java | 12 +- .../apache/tools/ant/DirectoryScanner.java | 93 ++++---- .../apache/tools/ant/IntrospectionHelper.java | 160 ++++++------- src/main/org/apache/tools/ant/Location.java | 1 + src/main/org/apache/tools/ant/Main.java | 121 +++++----- src/main/org/apache/tools/ant/Project.java | 146 ++++++------ .../org/apache/tools/ant/ProjectHelper.java | 54 ++--- .../tools/ant/ProjectHelperRepository.java | 78 +++---- .../org/apache/tools/ant/PropertyHelper.java | 102 ++++---- .../apache/tools/ant/RuntimeConfigurable.java | 25 +- src/main/org/apache/tools/ant/Target.java | 32 ++- src/main/org/apache/tools/ant/Task.java | 5 +- .../org/apache/tools/ant/TaskAdapter.java | 4 +- .../org/apache/tools/ant/TypeAdapter.java | 2 +- .../org/apache/tools/ant/UnknownElement.java | 26 +-- .../ant/UnsupportedAttributeException.java | 1 + .../ant/UnsupportedElementException.java | 1 + src/main/org/apache/tools/ant/XmlLogger.java | 27 +-- .../tools/ant/property/LocalProperties.java | 4 +- .../apache/tools/ant/taskdefs/MacroDef.java | 16 +- .../org/apache/tools/ant/types/FilterSet.java | 44 ++-- .../tools/ant/util/CollectionUtils.java | 64 +++-- .../apache/tools/ant/util/JavaEnvUtils.java | 6 +- .../org/apache/tools/ant/util/VectorSet.java | 68 +++--- 29 files changed, 683 insertions(+), 797 deletions(-) diff --git a/src/main/org/apache/tools/ant/AntClassLoader.java b/src/main/org/apache/tools/ant/AntClassLoader.java index 06ec892f4..2c0a05693 100644 --- a/src/main/org/apache/tools/ant/AntClassLoader.java +++ b/src/main/org/apache/tools/ant/AntClassLoader.java @@ -80,7 +80,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * @see AntClassLoader#findResources(String) * @see java.lang.ClassLoader#getResources(String) */ - private class ResourceEnumeration implements Enumeration { + private class ResourceEnumeration implements Enumeration { /** * The name of the resource being searched for. */ @@ -126,7 +126,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @return the next resource in the enumeration */ - public Object nextElement() { + public URL nextElement() { URL ret = this.nextResource; if (ret == null) { throw new NoSuchElementException(); @@ -171,7 +171,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 Vector pathComponents = new VectorSet(); /** * The project to which this class loader belongs. @@ -189,14 +189,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 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 Vector loaderPackages = new Vector(); /** * Whether or not this classloader will ignore the base @@ -214,10 +214,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { /** * A hashtable of zip files opened by the classloader (File to JarFile). */ - private Hashtable jarFiles = new Hashtable(); + 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 @@ -535,16 +535,16 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * separated by the path separator for the system. */ public String getClasspath() { - StringBuffer sb = new StringBuffer(); + final StringBuilder sb = new StringBuilder(); boolean firstPass = true; - Enumeration componentEnum = pathComponents.elements(); + Enumeration componentEnum = pathComponents.elements(); while (componentEnum.hasMoreElements()) { if (!firstPass) { sb.append(System.getProperty("path.separator")); } else { firstPass = false; } - sb.append(((File) componentEnum.nextElement()).getAbsolutePath()); + sb.append(componentEnum.nextElement().getAbsolutePath()); } return sb.toString(); } @@ -572,13 +572,13 @@ 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) { + public static void initializeClass(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 // at the same time not running a valid constructor. - final Constructor[] cons = theClass.getDeclaredConstructors(); + final Constructor[] cons = theClass.getDeclaredConstructors(); //At least one constructor is guaranteed to be there, but check anyway. if (cons != null) { if (cons.length > 0 && cons[0] != null) { @@ -646,10 +646,10 @@ 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(String classname) throws ClassNotFoundException { log("force loading " + classname, Project.MSG_DEBUG); - Class theClass = findLoadedClass(classname); + Class theClass = findLoadedClass(classname); if (theClass == null) { theClass = findClass(classname); @@ -673,10 +673,10 @@ 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(String classname) throws ClassNotFoundException { log("force system loading " + classname, Project.MSG_DEBUG); - Class theClass = findLoadedClass(classname); + Class theClass = findLoadedClass(classname); if (theClass == null) { theClass = findBaseClass(classname); @@ -739,9 +739,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { // find the class we want. InputStream stream = null; - Enumeration e = pathComponents.elements(); + Enumeration e = pathComponents.elements(); while (e.hasMoreElements() && stream == null) { - File pathComponent = (File) e.nextElement(); + File pathComponent = e.nextElement(); stream = getResourceStream(pathComponent, name); } return stream; @@ -828,15 +828,15 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { boolean useParentFirst = parentFirst; - for (Enumeration e = systemPackages.elements(); e.hasMoreElements();) { - String packageName = (String) e.nextElement(); + for (Enumeration e = systemPackages.elements(); e.hasMoreElements();) { + String packageName = e.nextElement(); if (resourceName.startsWith(packageName)) { useParentFirst = true; break; } } - for (Enumeration e = loaderPackages.elements(); e.hasMoreElements();) { - String packageName = (String) e.nextElement(); + for (Enumeration e = loaderPackages.elements(); e.hasMoreElements();) { + String packageName = e.nextElement(); if (resourceName.startsWith(packageName)) { useParentFirst = false; break; @@ -881,9 +881,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(); + Enumeration e = pathComponents.elements(); while (e.hasMoreElements() && url == null) { - File pathComponent = (File) e.nextElement(); + File pathComponent = e.nextElement(); url = getResourceURL(pathComponent, name); if (url != null) { log("Resource " + name + " loaded from ant loader", Project.MSG_DEBUG); @@ -917,7 +917,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * * @since Ant 1.8.0 */ - public Enumeration/**/ getNamedResources(String name) + public Enumeration getNamedResources(String name) throws IOException { return findResources(name, false); } @@ -931,7 +931,7 @@ 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 { + protected Enumeration findResources(String name) throws IOException { return findResources(name, true); } @@ -947,11 +947,11 @@ 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, + protected Enumeration findResources(String name, boolean parentHasBeenSearched) throws IOException { - Enumeration/**/ mine = new ResourceEnumeration(name); - Enumeration/**/ base; + Enumeration mine = new ResourceEnumeration(name); + Enumeration base; if (parent != null && (!parentHasBeenSearched || parent != getParent())) { // Delegate to the parent: base = parent.getResources(name); @@ -961,7 +961,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { } else { // ClassLoader.this.parent is already delegated to for example from // ClassLoader.getResources, no need: - base = new CollectionUtils.EmptyEnumeration(); + base = new CollectionUtils.EmptyEnumeration(); } if (isParentFirst(name)) { // Normal case. @@ -1049,13 +1049,13 @@ 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) + protected synchronized Class loadClass(String classname, boolean resolve) throws ClassNotFoundException { // 'sync' is needed - otherwise 2 threads can load the same class // twice, resulting in LinkageError: duplicated class definition. // findLoadedClass avoids that, but without sync it won't work. - Class theClass = findLoadedClass(classname); + Class theClass = findLoadedClass(classname); if (theClass != null) { return theClass; } @@ -1113,7 +1113,7 @@ 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(File container, byte[] classData, String classname) throws IOException { definePackage(container, classname); ProtectionDomain currentPd = Project.class.getProtectionDomain(); @@ -1286,7 +1286,7 @@ 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(InputStream stream, String classname, File container) throws IOException, SecurityException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = -1; @@ -1310,7 +1310,7 @@ 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 { + public Class findClass(String name) throws ClassNotFoundException { log("Finding class " + name, Project.MSG_DEBUG); return findClassInComponents(name); } @@ -1337,35 +1337,33 @@ 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(String name) throws ClassNotFoundException { // we need to search the components of the path to see if // we can find the class we want. - InputStream stream = null; String classFilename = getClassFilename(name); - try { - Enumeration e = pathComponents.elements(); - while (e.hasMoreElements()) { - File pathComponent = (File) e.nextElement(); - try { - stream = getResourceStream(pathComponent, classFilename); - if (stream != null) { - log("Loaded from " + pathComponent + " " - + classFilename, Project.MSG_DEBUG); - return getClassFromStream(stream, name, pathComponent); - } - } catch (SecurityException se) { - throw se; - } catch (IOException ioe) { - // ioe.printStackTrace(); - log("Exception reading component " + pathComponent + " (reason: " - + ioe.getMessage() + ")", Project.MSG_VERBOSE); + Enumeration e = pathComponents.elements(); + while (e.hasMoreElements()) { + File pathComponent = (File) e.nextElement(); + InputStream stream = null; + try { + stream = getResourceStream(pathComponent, classFilename); + if (stream != null) { + log("Loaded from " + pathComponent + " " + + classFilename, Project.MSG_DEBUG); + return getClassFromStream(stream, name, pathComponent); } + } catch (SecurityException se) { + throw se; + } catch (IOException ioe) { + // ioe.printStackTrace(); + log("Exception reading component " + pathComponent + " (reason: " + + ioe.getMessage() + ")", Project.MSG_VERBOSE); + } finally { + FileUtils.close(stream); } - throw new ClassNotFoundException(name); - } finally { - FileUtils.close(stream); } + throw new ClassNotFoundException(name); } /** @@ -1383,7 +1381,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(String name) throws ClassNotFoundException { return parent == null ? findSystemClass(name) : parent.loadClass(name); } @@ -1392,15 +1390,15 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * files are closed. */ public synchronized void cleanup() { - for (Enumeration e = jarFiles.elements(); e.hasMoreElements();) { - JarFile jarFile = (JarFile) e.nextElement(); + for (Enumeration e = jarFiles.elements(); e.hasMoreElements();) { + JarFile jarFile = e.nextElement(); try { jarFile.close(); } catch (IOException ioe) { // ignore } } - jarFiles = new Hashtable(); + jarFiles = new Hashtable(); if (project != null) { project.removeBuildListener(this); } @@ -1512,10 +1510,10 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { * here */ public void addJavaLibraries() { - Vector packages = JavaEnvUtils.getJrePackages(); - Enumeration e = packages.elements(); + Vector packages = JavaEnvUtils.getJrePackages(); + Enumeration e = packages.elements(); while (e.hasMoreElements()) { - String packageName = (String) e.nextElement(); + String packageName = e.nextElement(); addSystemPackageRoot(packageName); } } @@ -1528,8 +1526,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { return "AntClassLoader[" + getClasspath() + "]"; } - private static Class subClassToLoad = null; - private static final Class[] CONSTRUCTOR_ARGS = new Class[] { + private static Class subClassToLoad = null; + private static final Class[] CONSTRUCTOR_ARGS = new Class[] { ClassLoader.class, Project.class, Path.class, Boolean.TYPE }; diff --git a/src/main/org/apache/tools/ant/AntTypeDefinition.java b/src/main/org/apache/tools/ant/AntTypeDefinition.java index 1abd47a72..f0fe85cc1 100644 --- a/src/main/org/apache/tools/ant/AntTypeDefinition.java +++ b/src/main/org/apache/tools/ant/AntTypeDefinition.java @@ -33,9 +33,9 @@ import java.lang.reflect.Constructor; */ public class AntTypeDefinition { private String name; - private Class clazz; - private Class adapterClass; - private Class adaptToClass; + private Class clazz; + private Class adapterClass; + private Class adaptToClass; private String className; private ClassLoader classLoader; private boolean restrict = false; @@ -77,7 +77,7 @@ public class AntTypeDefinition { * As a side-effect may set the classloader and classname. * @param clazz the class of this definition. */ - public void setClass(Class clazz) { + public void setClass(Class clazz) { this.clazz = clazz; if (clazz == null) { return; @@ -109,7 +109,7 @@ public class AntTypeDefinition { * required. * @param adapterClass the adapterClass. */ - public void setAdapterClass(Class adapterClass) { + public void setAdapterClass(Class adapterClass) { this.adapterClass = adapterClass; } @@ -118,7 +118,7 @@ public class AntTypeDefinition { * @param adaptToClass the assignable class. */ - public void setAdaptToClass(Class adaptToClass) { + public void setAdaptToClass(Class adaptToClass) { this.adaptToClass = adaptToClass; } @@ -148,9 +148,9 @@ public class AntTypeDefinition { * @param project the current project. * @return the exposed class - may return null if unable to load the class */ - public Class getExposedClass(Project project) { + public Class getExposedClass(Project project) { if (adaptToClass != null) { - Class z = getTypeClass(project); + Class z = getTypeClass(project); if (z == null || adaptToClass.isAssignableFrom(z)) { return z; } @@ -163,7 +163,7 @@ public class AntTypeDefinition { * @param project the current project. * @return the type of the definition. */ - public Class getTypeClass(Project project) { + public Class getTypeClass(Project project) { try { return innerGetTypeClass(); } catch (NoClassDefFoundError ncdfe) { @@ -184,7 +184,7 @@ public class AntTypeDefinition { * @throws NoClassDefFoundError if the there is an error * finding the class. */ - public Class innerGetTypeClass() throws ClassNotFoundException { + public Class innerGetTypeClass() throws ClassNotFoundException { if (clazz != null) { return clazz; } @@ -212,7 +212,7 @@ public class AntTypeDefinition { * @return the component as an Object. */ private Object icreate(Project project) { - Class c = getTypeClass(project); + Class c = getTypeClass(project); if (c == null) { return null; } @@ -269,7 +269,7 @@ public class AntTypeDefinition { * and invoke it. * @return the instantiated Object. */ - private Object createAndSet(Project project, Class c) { + private Object createAndSet(Project project, Class c) { try { Object o = innerCreateAndSet(c, project); return o; @@ -307,12 +307,12 @@ public class AntTypeDefinition { * @throws IllegalAccessException cannot access the object. * @throws InvocationTargetException error in invocation. */ - public Object innerCreateAndSet(Class newclass, Project project) + public T innerCreateAndSet(Class newclass, Project project) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor ctor = null; + Constructor ctor; boolean noArg = false; // DataType can have a "no arg" constructor or take a single // Project argument. @@ -325,7 +325,7 @@ public class AntTypeDefinition { noArg = false; } //now we instantiate - Object o = ctor.newInstance( + T o = ctor.newInstance( ((noArg) ? new Object[0] : new Object[] {project})); //set up project references. @@ -382,7 +382,7 @@ public class AntTypeDefinition { .equals(((AntClassLoader) newLoader).getClasspath())); } - private String extractClassname(Class c) { + private String extractClassname(Class c) { return (c == null) ? "" : c.getClass().getName(); } } diff --git a/src/main/org/apache/tools/ant/BuildException.java b/src/main/org/apache/tools/ant/BuildException.java index 1a47af847..34c16051f 100644 --- a/src/main/org/apache/tools/ant/BuildException.java +++ b/src/main/org/apache/tools/ant/BuildException.java @@ -54,8 +54,7 @@ public class BuildException extends RuntimeException { * May be null. */ public BuildException(String message, Throwable cause) { - super(message); - initCause(cause); + super(message, cause); } /** diff --git a/src/main/org/apache/tools/ant/ComponentHelper.java b/src/main/org/apache/tools/ant/ComponentHelper.java index f6001ffda..c5823d1b8 100644 --- a/src/main/org/apache/tools/ant/ComponentHelper.java +++ b/src/main/org/apache/tools/ant/ComponentHelper.java @@ -17,28 +17,28 @@ */ package org.apache.tools.ant; -import java.lang.reflect.Modifier; -import java.lang.reflect.InvocationTargetException; -import java.io.InputStream; -import java.io.IOException; import java.io.File; -import java.io.StringWriter; +import java.io.IOException; +import java.io.InputStream; import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.Enumeration; -import java.util.Hashtable; +import java.util.HashMap; import java.util.HashSet; +import java.util.Hashtable; import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import org.apache.tools.ant.taskdefs.Typedef; -import org.apache.tools.ant.taskdefs.Definer; import org.apache.tools.ant.launch.Launcher; +import org.apache.tools.ant.taskdefs.Definer; +import org.apache.tools.ant.taskdefs.Typedef; import org.apache.tools.ant.util.FileUtils; /** @@ -59,31 +59,31 @@ import org.apache.tools.ant.util.FileUtils; */ public class ComponentHelper { /** Map of component name to lists of restricted definitions */ - private Map restrictedDefinitions = new HashMap(); + private Map> restrictedDefinitions = new HashMap>(); /** Map from component name to anttypedefinition */ - private AntTypeTable antTypeTable; + private final Hashtable antTypeTable = new Hashtable(); /** Map of tasks generated from antTypeTable */ - private final Hashtable taskClassDefinitions = new Hashtable(); + private final Hashtable> taskClassDefinitions = new Hashtable>(); /** flag to rebuild taskClassDefinitions */ private boolean rebuildTaskClassDefinitions = true; /** Map of types generated from antTypeTable */ - private final Hashtable typeClassDefinitions = new Hashtable(); + private final Hashtable> typeClassDefinitions = new Hashtable>(); /** flag to rebuild typeClassDefinitions */ private boolean rebuildTypeClassDefinitions = true; /** Set of namespaces that have been checked for antlibs */ - private final HashSet checkedNamespaces = new HashSet(); + private final HashSet checkedNamespaces = new HashSet(); /** * Stack of antlib contexts used to resolve definitions while * processing antlib */ - private Stack antLibStack = new Stack(); + private Stack antLibStack = new Stack(); /** current antlib uri */ private String antLibCurrentUri = null; @@ -189,38 +189,37 @@ public class ComponentHelper { */ public void setProject(Project project) { this.project = project; - antTypeTable = new AntTypeTable(project); +// antTypeTable = new Hashtable(project); } /** * @return A copy of the CheckedNamespace. */ - private synchronized Set getCheckedNamespace() { - return (Set) checkedNamespaces.clone(); + private synchronized Set getCheckedNamespace() { + @SuppressWarnings("unchecked") + final Set result = (Set) checkedNamespaces.clone(); + return result; } /** * @return A deep copy of the restrictredDefinition */ - private Map getRestrictedDefinition() { - Map result = new HashMap(); + private Map> getRestrictedDefinition() { + final Map> result = new HashMap>(); synchronized (restrictedDefinitions) { - for(Iterator i = restrictedDefinitions.entrySet().iterator(); - i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - List entryVal = (List) entry.getValue(); + for (Map.Entry> entry : restrictedDefinitions.entrySet()) { + List entryVal = entry.getValue(); synchronized (entryVal) { //copy the entryVal - entryVal = new ArrayList(entryVal); + entryVal = new ArrayList (entryVal); } - Object entryKey = entry.getKey(); - result.put(entryKey, entryVal); + result.put(entry.getKey(), entryVal); } } return result; } - + /** * Used with creating child projects. Each child * project inherits the component definitions @@ -229,19 +228,19 @@ public class ComponentHelper { */ public void initSubProject(ComponentHelper helper) { // add the types of the parent project - AntTypeTable typeTable = (AntTypeTable) helper.antTypeTable.clone(); - synchronized (antTypeTable) { - for (Iterator i = typeTable.values().iterator(); i.hasNext();) { - AntTypeDefinition def = (AntTypeDefinition) i.next(); + @SuppressWarnings("unchecked") + final Hashtable typeTable = (Hashtable) helper.antTypeTable.clone(); + synchronized (antTypeTable) { + for (AntTypeDefinition def : typeTable.values()) { antTypeTable.put(def.getName(), def); } } // add the parsed namespaces of the parent project - Set inheritedCheckedNamespace = helper.getCheckedNamespace(); + Set inheritedCheckedNamespace = helper.getCheckedNamespace(); synchronized (this) { checkedNamespaces.addAll(inheritedCheckedNamespace); } - Map inheritedRestrictedDef = helper.getRestrictedDefinition(); + Map> inheritedRestrictedDef = helper.getRestrictedDefinition(); synchronized (restrictedDefinitions) { restrictedDefinitions.putAll(inheritedRestrictedDef); } @@ -294,7 +293,7 @@ public class ComponentHelper { * name is prefixed with the namespace uri and ":". * @return the class if found or null if not. */ - public Class getComponentClass(String componentName) { + public Class getComponentClass(String componentName) { AntTypeDefinition def = getDefinition(componentName); return def == null ? null : def.getExposedClass(project); } @@ -306,7 +305,7 @@ public class ComponentHelper { */ public AntTypeDefinition getDefinition(String componentName) { checkNamespace(componentName); - return antTypeTable.getDefinition(componentName); + return antTypeTable.get(componentName); } /** @@ -337,7 +336,7 @@ public class ComponentHelper { * * @see #checkTaskClass(Class) */ - public void addTaskDefinition(String taskName, Class taskClass) { + public void addTaskDefinition(String taskName, Class taskClass) { checkTaskClass(taskClass); AntTypeDefinition def = new AntTypeDefinition(); def.setName(taskName); @@ -361,7 +360,7 @@ public class ComponentHelper { * task. An error level message is logged before * this exception is thrown. */ - public void checkTaskClass(final Class taskClass) throws BuildException { + public void checkTaskClass(final Class taskClass) throws BuildException { if (!Modifier.isPublic(taskClass.getModifiers())) { final String message = taskClass + " is not public"; project.log(message, Project.MSG_ERR); @@ -388,25 +387,24 @@ public class ComponentHelper { /** * Returns the current task definition hashtable. The returned hashtable is - * "live" and so should not be modified. Also, the returned table may be + * "live" and so should not be modified. Also, the returned table may be * modified asynchronously. * * @return a map of from task name to implementing class * (String to Class). */ - public Hashtable getTaskDefinitions() { + public Hashtable> getTaskDefinitions() { synchronized (taskClassDefinitions) { synchronized (antTypeTable) { if (rebuildTaskClassDefinitions) { taskClassDefinitions.clear(); - for (Iterator i = antTypeTable.keySet().iterator(); i.hasNext();) { - String name = (String) i.next(); - Class clazz = antTypeTable.getExposedClass(name); + for (Map.Entry e : antTypeTable.entrySet()) { + final Class clazz = e.getValue().getExposedClass(project); if (clazz == null) { continue; } if (Task.class.isAssignableFrom(clazz)) { - taskClassDefinitions.put(name, antTypeTable.getTypeClass(name)); + taskClassDefinitions.put(e.getKey(), e.getValue().getTypeClass(project)); } } rebuildTaskClassDefinitions = false; @@ -423,19 +421,18 @@ public class ComponentHelper { * @return a map of from type name to implementing class * (String to Class). */ - public Hashtable getDataTypeDefinitions() { + public Hashtable> getDataTypeDefinitions() { synchronized (typeClassDefinitions) { synchronized (antTypeTable) { if (rebuildTypeClassDefinitions) { typeClassDefinitions.clear(); - for (Iterator i = antTypeTable.keySet().iterator(); i.hasNext();) { - String name = (String) i.next(); - Class clazz = antTypeTable.getExposedClass(name); + for (Map.Entry e : antTypeTable.entrySet()) { + final Class clazz = e.getValue().getExposedClass(project); if (clazz == null) { continue; } - if (!(Task.class.isAssignableFrom(clazz))) { - typeClassDefinitions.put(name, antTypeTable.getTypeClass(name)); + if (!Task.class.isAssignableFrom(clazz)) { + typeClassDefinitions.put(e.getKey(), e.getValue().getTypeClass(project)); } } rebuildTypeClassDefinitions = false; @@ -447,16 +444,16 @@ public class ComponentHelper { /** * This returns a list of restricted definitions for a name. - * The returned List is "live" and so should not be modified. - * Also, the returned list may be modified asynchronously. + * The returned List is "live" and so should not be modified. + * Also, the returned list may be modified asynchronously. * Any access must be guarded with a lock on the list itself. - * + * * @param componentName the name to use. * @return the list of restricted definitions for a particular name. */ - public List getRestrictedDefinitions(String componentName) { + public List getRestrictedDefinitions(String componentName) { synchronized (restrictedDefinitions) { - return (List) restrictedDefinitions.get(componentName); + return restrictedDefinitions.get(componentName); } } @@ -473,8 +470,8 @@ public class ComponentHelper { * @param typeClass The full name of the class implementing the datatype. * Must not be null. */ - public void addDataTypeDefinition(String typeName, Class typeClass) { - AntTypeDefinition def = new AntTypeDefinition(); + public void addDataTypeDefinition(String typeName, Class typeClass) { + final AntTypeDefinition def = new AntTypeDefinition(); def.setName(typeName); def.setClass(typeClass); updateDataTypeDefinition(def); @@ -499,10 +496,10 @@ public class ComponentHelper { * Returns the current datatype definition hashtable. The returned * hashtable is "live" and so should not be modified. * - * @return a map of from datatype name to implementing class - * (String to Class). + * @return a map of from datatype name to datatype definition + * (String to {@link AntTypeDefinition}). */ - public Hashtable getAntTypeTable() { + public Hashtable getAntTypeTable() { return antTypeTable; } @@ -544,7 +541,7 @@ public class ComponentHelper { * creation fails. */ private Task createNewTask(String taskType) throws BuildException { - Class c = getComponentClass(taskType); + Class c = getComponentClass(taskType); if (c == null || !(Task.class.isAssignableFrom(c))) { return null; } @@ -614,11 +611,10 @@ public class ComponentHelper { // PR: I do not know what to do if the object class // has multiple defines // but this is for logging only... - Class elementClass = o.getClass(); + Class elementClass = o.getClass(); String elementClassname = elementClass.getName(); synchronized (antTypeTable) { - for (Iterator i = antTypeTable.values().iterator(); i.hasNext();) { - AntTypeDefinition def = (AntTypeDefinition) i.next(); + for (AntTypeDefinition def : antTypeTable.values()) { if (elementClassname.equals(def.getClassName()) && (elementClass == def.getExposedClass(project))) { String name = def.getName(); @@ -647,7 +643,7 @@ public class ComponentHelper { .getElementName(o, brief); } - private static String getUnmappedElementName(Class c, boolean brief) { + private static String getUnmappedElementName(Class c, boolean brief) { if (brief) { String name = c.getName(); return name.substring(name.lastIndexOf('.') + 1); @@ -684,19 +680,19 @@ public class ComponentHelper { */ private void updateRestrictedDefinition(AntTypeDefinition def) { String name = def.getName(); - List list = null; + List list = null; synchronized (restrictedDefinitions) { - list = (List) restrictedDefinitions.get(name); + list = restrictedDefinitions.get(name); if (list == null) { - list = new ArrayList(); + list = new ArrayList(); restrictedDefinitions.put(name, list); } } // Check if the classname is already present and remove it // if it is synchronized (list) { - for (Iterator i = list.iterator(); i.hasNext();) { - AntTypeDefinition current = (AntTypeDefinition) i.next(); + for (Iterator i = list.iterator(); i.hasNext();) { + AntTypeDefinition current = i.next(); if (current.getClassName().equals(def.getClassName())) { i.remove(); break; @@ -716,12 +712,12 @@ public class ComponentHelper { synchronized (antTypeTable) { rebuildTaskClassDefinitions = true; rebuildTypeClassDefinitions = true; - AntTypeDefinition old = antTypeTable.getDefinition(name); + final AntTypeDefinition old = antTypeTable.get(name); if (old != null) { if (sameDefinition(def, old)) { return; } - Class oldClass = antTypeTable.getExposedClass(name); + Class oldClass = old.getExposedClass(project); boolean isTask = oldClass != null && Task.class.isAssignableFrom(oldClass); project.log("Trying to override old definition of " + (isTask ? "task " : "datatype ") + name, (def.similarDefinition(old, @@ -762,7 +758,7 @@ public class ComponentHelper { private void initTasks() { ClassLoader classLoader = getClassLoader(null); Properties props = getDefaultDefinitions(false); - Enumeration e = props.propertyNames(); + Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String className = props.getProperty(name); @@ -825,7 +821,7 @@ public class ComponentHelper { private void initTypes() { ClassLoader classLoader = getClassLoader(null); Properties props = getDefaultDefinitions(true); - Enumeration e = props.propertyNames(); + Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String className = props.getProperty(name); @@ -936,7 +932,7 @@ public class ComponentHelper { optional |= classname.startsWith("org.apache.tools.ant.types.optional"); //start with instantiating the class. - Class clazz = null; + Class clazz = null; try { clazz = def.innerGetTypeClass(); } catch (ClassNotFoundException e) { @@ -1028,12 +1024,11 @@ public class ComponentHelper { out.println("Action: Check that any /" + " declarations have taken place."); if (uri.length() > 0) { - List matches = antTypeTable.findMatches(uri); + final List matches = findTypeMatches(uri); if (matches.size() > 0) { out.println(); out.println("The definitions in the namespace " + uri + " are:"); - for (Iterator it = matches.iterator(); it.hasNext();) { - AntTypeDefinition def = (AntTypeDefinition) it.next(); + for (AntTypeDefinition def : matches) { String local = ProjectHelper.extractNameFromComponentName(def.getName()); out.println(" " + local); } @@ -1086,63 +1081,20 @@ public class ComponentHelper { } /** - * Map that contains the component definitions. + * Create a list of all definitions that match a prefix, usually the URI + * of a library + * @param prefix prefix to match off + * @return the (possibly empty) list of definitions */ - private static class AntTypeTable extends Hashtable { - private static final long serialVersionUID = -3060442320477772028L; - private Project project; - - AntTypeTable(Project project) { - this.project = project; - } - - AntTypeDefinition getDefinition(String key) { - return (AntTypeDefinition) (super.get(key)); - } - - public Object get(Object key) { - return getTypeClass((String) key); - } - - Class getTypeClass(String name) { - AntTypeDefinition def = getDefinition(name); - return (def == null) ? null : def.getTypeClass(project); - } - - Class getExposedClass(String name) { - AntTypeDefinition def = getDefinition(name); - return def == null ? null : def.getExposedClass(project); - } - - public synchronized boolean contains(Object clazz) { - boolean found = false; - if (clazz instanceof Class) { - for (Iterator i = values().iterator(); i.hasNext() && !found;) { - found = (((AntTypeDefinition) (i.next())).getExposedClass(project) == clazz); - } - } - return found; - } - - public boolean containsValue(Object value) { - return contains(value); - } - - /** - * Create a list of all definitions that match a prefix, usually the URI - * of a library - * @param prefix prefix to match off - * @return the (possibly empty) list of definitions - */ - public synchronized List/**/ findMatches(String prefix) { - ArrayList matches = new ArrayList(); - for (Iterator i = values().iterator(); i.hasNext();) { - AntTypeDefinition def = (AntTypeDefinition) (i.next()); + private List findTypeMatches(String prefix) { + final List result = new ArrayList(); + synchronized (antTypeTable) { + for (AntTypeDefinition def : antTypeTable.values()) { if (def.getName().startsWith(prefix)) { - matches.add(def); + result.add(def); } } - return matches; } + return result; } } diff --git a/src/main/org/apache/tools/ant/DemuxOutputStream.java b/src/main/org/apache/tools/ant/DemuxOutputStream.java index 7ad7f946c..cd5a7e9d6 100644 --- a/src/main/org/apache/tools/ant/DemuxOutputStream.java +++ b/src/main/org/apache/tools/ant/DemuxOutputStream.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.OutputStream; import java.util.WeakHashMap; + /** * Logs content written by a thread and forwards the buffers onto the * project object which will forward the content to the appropriate @@ -62,7 +63,7 @@ public class DemuxOutputStream extends OutputStream { private static final int LF = 0x0a; /** Mapping from thread to buffer (Thread to BufferInfo). */ - private WeakHashMap buffers = new WeakHashMap(); + private WeakHashMap buffers = new WeakHashMap(); /** * The project to send output to. diff --git a/src/main/org/apache/tools/ant/Diagnostics.java b/src/main/org/apache/tools/ant/Diagnostics.java index 5e03d8b6a..e5cac0200 100644 --- a/src/main/org/apache/tools/ant/Diagnostics.java +++ b/src/main/org/apache/tools/ant/Diagnostics.java @@ -145,7 +145,7 @@ public final class Diagnostics { * @return null if there is no package or implementation version. * '?.?' for JDK 1.0 or 1.1. */ - private static String getImplementationVersion(Class clazz) { + private static String getImplementationVersion(Class clazz) { return clazz.getPackage().getImplementationVersion(); } @@ -154,7 +154,7 @@ public final class Diagnostics { * @param clazz the class to get the information from. * @since Ant 1.8.0 */ - private static URL getClassLocation(Class clazz) { + private static URL getClassLocation(Class clazz) { if (clazz.getProtectionDomain().getCodeSource() == null) { return null; } @@ -364,7 +364,7 @@ public final class Diagnostics { out.println("Access to System.getProperties() blocked " + "by a security manager"); return; } - for (Enumeration keys = sysprops.propertyNames(); + for (Enumeration keys = sysprops.propertyNames(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); String value = getProperty(key); @@ -455,7 +455,7 @@ public final class Diagnostics { private static void doReportWhich(PrintStream out) { Throwable error = null; try { - Class which = Class.forName("org.apache.env.Which"); + Class which = Class.forName("org.apache.env.Which"); Method method = which.getMethod( "main", new Class[] {String[].class}); method.invoke(null, new Object[]{new String[]{}}); @@ -491,7 +491,7 @@ public final class Diagnostics { Properties props = new Properties(); try { props.load(is); - for (Enumeration keys = props.keys(); keys.hasMoreElements();) { + for (Enumeration keys = props.keys(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); String classname = props.getProperty(key); try { @@ -696,7 +696,7 @@ public final class Diagnostics { printProperty(out, ProxySetup.USE_SYSTEM_PROXIES); final String proxyDiagClassname = "org.apache.tools.ant.util.java15.ProxyDiagnostics"; try { - Class proxyDiagClass = Class.forName(proxyDiagClassname); + Class proxyDiagClass = Class.forName(proxyDiagClassname); Object instance = proxyDiagClass.newInstance(); out.println("Java1.5+ proxy settings:"); out.println(instance.toString()); diff --git a/src/main/org/apache/tools/ant/DirectoryScanner.java b/src/main/org/apache/tools/ant/DirectoryScanner.java index 006bef62d..92d97dec0 100644 --- a/src/main/org/apache/tools/ant/DirectoryScanner.java +++ b/src/main/org/apache/tools/ant/DirectoryScanner.java @@ -216,7 +216,7 @@ public class DirectoryScanner * * @see #addDefaultExcludes() */ - private static final Set defaultExcludes = new HashSet(); + private static final Set defaultExcludes = new HashSet(); static { resetDefaultExcludes(); } @@ -239,43 +239,43 @@ public class DirectoryScanner * The files which matched at least one include and no excludes * and were selected. */ - protected Vector filesIncluded; + protected Vector filesIncluded; /** The files which did not match any includes or selectors. */ - protected Vector filesNotIncluded; + protected Vector filesNotIncluded; /** * The files which matched at least one include and at least * one exclude. */ - protected Vector filesExcluded; + protected Vector filesExcluded; /** * The directories which matched at least one include and no excludes * and were selected. */ - protected Vector dirsIncluded; + protected Vector dirsIncluded; /** The directories which were found and did not match any includes. */ - protected Vector dirsNotIncluded; + protected Vector dirsNotIncluded; /** * The directories which matched at least one include and at least one * exclude. */ - protected Vector dirsExcluded; + protected Vector dirsExcluded; /** * The files which matched at least one include and no excludes and * which a selector discarded. */ - protected Vector filesDeselected; + protected Vector filesDeselected; /** * The directories which matched at least one include and no excludes * but which a selector discarded. */ - protected Vector dirsDeselected; + protected Vector dirsDeselected; /** Whether or not our results were built by a slow scan. */ protected boolean haveSlowResults = false; @@ -309,7 +309,7 @@ public class DirectoryScanner * * @since Ant 1.6 */ - private Set scannedDirs = new HashSet(); + private Set scannedDirs = new HashSet(); /** * Map of all include patterns that are full file names and don't @@ -326,7 +326,7 @@ public class DirectoryScanner * * @since Ant 1.8.0 */ - private Map includeNonPatterns = new HashMap(); + private Map includeNonPatterns = new HashMap(); /** * Map of all exclude patterns that are full file names and don't @@ -343,7 +343,7 @@ public class DirectoryScanner * * @since Ant 1.8.0 */ - private Map excludeNonPatterns = new HashMap(); + private Map excludeNonPatterns = new HashMap(); /** * Array of all include patterns that contain wildcards. @@ -422,7 +422,7 @@ public class DirectoryScanner * * @since Ant 1.8.0 */ - private Set/**/ notFollowedSymlinks = new HashSet(); + private Set notFollowedSymlinks = new HashSet(); /** * Sole constructor. @@ -929,7 +929,7 @@ public class DirectoryScanner */ private void checkIncludePatterns() { ensureNonPatternSetsReady(); - Map newroots = new HashMap(); + Map newroots = new HashMap(); // put in the newroots map the include patterns without // wildcard tokens @@ -940,12 +940,10 @@ public class DirectoryScanner pattern); } } - for (Iterator iter = includeNonPatterns.entrySet().iterator(); - iter.hasNext(); ) { - Map.Entry entry = (Map.Entry) iter.next(); - String pattern = (String) entry.getKey(); + for (Map.Entry entry : includeNonPatterns.entrySet()) { + String pattern = entry.getKey(); if (!shouldSkipPattern(pattern)) { - newroots.put((TokenizedPath) entry.getValue(), pattern); + newroots.put(entry.getValue(), pattern); } } @@ -954,10 +952,6 @@ public class DirectoryScanner // we are going to scan everything anyway scandir(basedir, "", true); } else { - // only scan directories that can include matched files or - // directories - Iterator it = newroots.entrySet().iterator(); - File canonBase = null; if (basedir != null) { try { @@ -966,9 +960,10 @@ public class DirectoryScanner throw new BuildException(ex); } } - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - TokenizedPath currentPath = (TokenizedPath) entry.getKey(); + // only scan directories that can include matched files or + // directories + for (Map.Entry entry : newroots.entrySet()) { + TokenizedPath currentPath = entry.getKey(); String currentelement = currentPath.toString(); if (basedir == null && !FileUtils.isAbsolutePath(currentelement)) { @@ -1069,14 +1064,14 @@ public class DirectoryScanner * Clear the result caches for a scan. */ protected synchronized void clearResults() { - filesIncluded = new VectorSet(); - filesNotIncluded = new VectorSet(); - filesExcluded = new VectorSet(); - filesDeselected = new VectorSet(); - dirsIncluded = new VectorSet(); - dirsNotIncluded = new VectorSet(); - dirsExcluded = new VectorSet(); - dirsDeselected = new VectorSet(); + filesIncluded = new VectorSet(); + filesNotIncluded = new VectorSet(); + filesExcluded = new VectorSet(); + filesDeselected = new VectorSet(); + dirsIncluded = new VectorSet(); + dirsNotIncluded = new VectorSet(); + dirsExcluded = new VectorSet(); + dirsDeselected = new VectorSet(); everythingIncluded = (basedir != null); scannedDirs.clear(); notFollowedSymlinks.clear(); @@ -1208,11 +1203,11 @@ public class DirectoryScanner + dir.getAbsolutePath() + "'"); } } - scandir(dir, path, fast, newfiles, new LinkedList()); + scandir(dir, path, fast, newfiles, new LinkedList()); } private void scandir(File dir, TokenizedPath path, boolean fast, - String[] newfiles, LinkedList directoryNamesFollowed) { + String[] newfiles, LinkedList directoryNamesFollowed) { String vpath = path.toString(); if (vpath.length() > 0 && !vpath.endsWith(File.separator)) { vpath += File.separator; @@ -1223,7 +1218,7 @@ public class DirectoryScanner return; } if (!followSymlinks) { - ArrayList noLinks = new ArrayList(); + ArrayList noLinks = new ArrayList(); for (int i = 0; i < newfiles.length; i++) { try { if (SYMLINK_UTILS.isSymbolicLink(dir, newfiles[i])) { @@ -1327,7 +1322,7 @@ public class DirectoryScanner private void accountForIncludedDir(TokenizedPath name, File file, boolean fast, String[] children, - LinkedList directoryNamesFollowed) { + LinkedList directoryNamesFollowed) { processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected); if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) { scandir(file, name, fast, children, directoryNamesFollowed); @@ -1335,8 +1330,8 @@ public class DirectoryScanner } private void processIncluded(TokenizedPath path, - File file, Vector inc, Vector exc, - Vector des) { + File file, Vector inc, Vector exc, + Vector des) { String name = path.toString(); if (inc.contains(name) || exc.contains(name) || des.contains(name)) { return; @@ -1416,10 +1411,10 @@ public class DirectoryScanner return true; } } - for (Iterator iter = includeNonPatterns.values().iterator(); + for (Iterator iter = includeNonPatterns.values().iterator(); iter.hasNext(); ) { if (couldHoldIncluded(tokenizedName, - ((TokenizedPath) iter.next()).toPattern())) { + iter.next().toPattern())) { return true; } } @@ -1788,7 +1783,7 @@ public class DirectoryScanner * Set is live and should not be modified. * @return the Set of relative directory names that have been scanned. */ - /* package-private */ Set getScannedDirs() { + /* package-private */ Set getScannedDirs() { return scannedDirs; } @@ -1827,8 +1822,8 @@ public class DirectoryScanner * @param patterns String[] of patterns. * @since Ant 1.8.0 */ - private TokenizedPattern[] fillNonPatternSet(Map map, String[] patterns) { - ArrayList al = new ArrayList(patterns.length); + private TokenizedPattern[] fillNonPatternSet(Map map, String[] patterns) { + ArrayList al = new ArrayList(patterns.length); for (int i = 0; i < patterns.length; i++) { if (!SelectorUtils.hasWildcards(patterns[i])) { String s = isCaseSensitive() @@ -1853,23 +1848,21 @@ public class DirectoryScanner * @since Ant 1.8.0 */ private boolean causesIllegalSymlinkLoop(String dirName, File parent, - LinkedList directoryNamesFollowed) { + LinkedList directoryNamesFollowed) { try { if (directoryNamesFollowed.size() >= maxLevelsOfSymlinks && CollectionUtils.frequency(directoryNamesFollowed, dirName) >= maxLevelsOfSymlinks && SYMLINK_UTILS.isSymbolicLink(parent, dirName)) { - ArrayList files = new ArrayList(); + ArrayList files = new ArrayList(); File f = FILE_UTILS.resolveFile(parent, dirName); String target = f.getCanonicalPath(); files.add(target); String relPath = ""; - for (Iterator i = directoryNamesFollowed.iterator(); - i.hasNext(); ) { + for (String dir : directoryNamesFollowed) { relPath += "../"; - String dir = (String) i.next(); if (dirName.equals(dir)) { f = FILE_UTILS.resolveFile(parent, relPath + dir); files.add(f.getCanonicalPath()); diff --git a/src/main/org/apache/tools/ant/IntrospectionHelper.java b/src/main/org/apache/tools/ant/IntrospectionHelper.java index ed34ed3e9..ae334b92c 100644 --- a/src/main/org/apache/tools/ant/IntrospectionHelper.java +++ b/src/main/org/apache/tools/ant/IntrospectionHelper.java @@ -28,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; + import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileProvider; @@ -62,7 +63,7 @@ public final class IntrospectionHelper { /** * Helper instances we've already created (Class.getName() to IntrospectionHelper). */ - private static final Map HELPERS = new Hashtable(); + private static final Map HELPERS = new Hashtable(); /** * Map from primitive types to wrapper classes for use in @@ -70,13 +71,13 @@ public final class IntrospectionHelper { * and boolean are in here even though they get special treatment * - this way we only need to test for the wrapper class. */ - private static final Map PRIMITIVE_TYPE_MAP = new HashMap(8); + private static final Map, Class> PRIMITIVE_TYPE_MAP = new HashMap, Class>(8); // Set up PRIMITIVE_TYPE_MAP static { - Class[] primitives = {Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, + 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, + 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]); @@ -90,30 +91,30 @@ public final class IntrospectionHelper { * Map from attribute names to attribute types * (String to Class). */ - private final Hashtable attributeTypes = new Hashtable(); + private final Hashtable> attributeTypes = new Hashtable>(); /** * Map from attribute names to attribute setter methods * (String to AttributeSetter). */ - private final Hashtable attributeSetters = new Hashtable(); + private final Hashtable attributeSetters = new Hashtable(); /** * Map from attribute names to nested types * (String to Class). */ - private final Hashtable nestedTypes = new Hashtable(); + private final Hashtable> nestedTypes = new Hashtable>(); /** * Map from attribute names to methods to create nested types * (String to NestedCreator). */ - private final Hashtable nestedCreators = new Hashtable(); + private final Hashtable nestedCreators = new Hashtable(); /** * Vector of methods matching add[Configured](Class) pattern. */ - private final List addTypeMethods = new ArrayList(); + private final List addTypeMethods = new ArrayList(); /** * The method to invoke to add PCDATA. @@ -123,7 +124,7 @@ public final class IntrospectionHelper { /** * The class introspected by this instance. */ - private final Class bean; + private final Class bean; /** * Sole constructor, which is private to ensure that all @@ -175,15 +176,15 @@ public final class IntrospectionHelper { * * @see #getHelper(Class) */ - private IntrospectionHelper(final Class bean) { + private IntrospectionHelper(final Class bean) { this.bean = bean; 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(); + Class returnType = m.getReturnType(); + Class[] args = m.getParameterTypes(); // check of add[Configured](Class) pattern if (args.length == 1 && java.lang.Void.TYPE.equals(returnType) @@ -254,11 +255,11 @@ public final class IntrospectionHelper { && !java.lang.String.class.equals(args[0]) && !args[0].isArray() && !args[0].isPrimitive()) { try { - Constructor constructor = null; + Constructor constructor = null; try { - constructor = args[0].getConstructor(new Class[] {}); + constructor = args[0].getConstructor(); } catch (NoSuchMethodException ex) { - constructor = args[0].getConstructor(new Class[] {Project.class}); + constructor = args[0].getConstructor(Project.class); } String propName = getPropertyName(name, "addConfigured"); nestedTypes.put(propName, args[0]); @@ -272,11 +273,11 @@ public final class IntrospectionHelper { && !java.lang.String.class.equals(args[0]) && !args[0].isArray() && !args[0].isPrimitive()) { try { - Constructor constructor = null; + Constructor constructor = null; try { - constructor = args[0].getConstructor(new Class[] {}); + constructor = args[0].getConstructor(); } catch (NoSuchMethodException ex) { - constructor = args[0].getConstructor(new Class[] {Project.class}); + constructor = args[0].getConstructor(Project.class); } String propName = getPropertyName(name, "add"); if (nestedTypes.get(propName) != null) { @@ -306,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(String name, Class type) { if ("setLocation".equals(name) && org.apache.tools.ant.Location.class.equals(type)) { return true; } @@ -325,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(Class c) { return getHelper(null, c); } @@ -342,8 +343,8 @@ public final class IntrospectionHelper { * * @return a helper for the specified class */ - public static IntrospectionHelper getHelper(Project p, Class c) { - IntrospectionHelper ih = (IntrospectionHelper) HELPERS.get(c.getName()); + public static IntrospectionHelper getHelper(Project p, 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 if (ih == null || ih.bean != c) { @@ -392,7 +393,7 @@ public final class IntrospectionHelper { if (element instanceof DynamicObjectAttribute) { DynamicObjectAttribute dc = (DynamicObjectAttribute) element; dc.setDynamicAttribute(attributeName.toLowerCase(Locale.ENGLISH), value); - return; + return; } if (element instanceof DynamicAttribute) { DynamicAttribute dc = (DynamicAttribute) element; @@ -830,8 +831,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 = (Class) nestedTypes.get(elementName); + public Class getElementType(String elementName) throws BuildException { + Class nt = nestedTypes.get(elementName); if (nt == null) { throw new UnsupportedElementException("Class " + bean.getName() + " doesn't support the nested \"" @@ -852,8 +853,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 = (Class) attributeTypes.get(attributeName); + public Class getAttributeType(String attributeName) throws BuildException { + Class at = attributeTypes.get(attributeName); if (at == null) { throw new UnsupportedAttributeException("Class " + bean.getName() + " doesn't support the \"" @@ -938,7 +939,7 @@ public final class IntrospectionHelper { * @return an enumeration of the names of the attributes supported by the introspected class. * @see #getAttributeMap */ - public Enumeration getAttributes() { + public Enumeration getAttributes() { return attributeSetters.keys(); } @@ -949,9 +950,9 @@ public final class IntrospectionHelper { * unmodifiable map. Can be empty, but never null. * @since Ant 1.6.3 */ - public Map getAttributeMap() { + public Map> getAttributeMap() { return attributeTypes.isEmpty() - ? Collections.EMPTY_MAP : Collections.unmodifiableMap(attributeTypes); + ? Collections.> emptyMap() : Collections.unmodifiableMap(attributeTypes); } /** @@ -962,7 +963,7 @@ public final class IntrospectionHelper { * by the introspected class. * @see #getNestedElementMap */ - public Enumeration getNestedElements() { + public Enumeration getNestedElements() { return nestedTypes.keys(); } @@ -974,9 +975,9 @@ public final class IntrospectionHelper { * unmodifiable map. Can be empty, but never null. * @since Ant 1.6.3 */ - public Map getNestedElementMap() { + public Map> getNestedElementMap() { return nestedTypes.isEmpty() - ? Collections.EMPTY_MAP : Collections.unmodifiableMap(nestedTypes); + ? Collections.> emptyMap() : Collections.unmodifiableMap(nestedTypes); } /** @@ -996,9 +997,9 @@ public final class IntrospectionHelper { * always appear first. Can be empty, but never null. * @since Ant 1.6.3 */ - public List getExtensionPoints() { + public List getExtensionPoints() { return addTypeMethods.isEmpty() - ? Collections.EMPTY_LIST : Collections.unmodifiableList(addTypeMethods); + ? Collections. emptyList() : Collections.unmodifiableList(addTypeMethods); } /** @@ -1035,12 +1036,12 @@ public final class IntrospectionHelper { * if no appropriate conversion is available. */ private AttributeSetter createAttributeSetter(final Method m, - Class arg, + Class arg, final String attrName) { // use wrappers for primitive classes, e.g. int and // Integer are treated identically - final Class reflectedArg = PRIMITIVE_TYPE_MAP.containsKey(arg) - ? (Class) PRIMITIVE_TYPE_MAP.get(arg) : arg; + final Class reflectedArg = PRIMITIVE_TYPE_MAP.containsKey(arg) + ? PRIMITIVE_TYPE_MAP.get(arg) : arg; // Object.class - it gets handled differently by AttributeSetter if (java.lang.Object.class == reflectedArg) { @@ -1163,15 +1164,15 @@ public final class IntrospectionHelper { // This is used (deliberately) for all primitives/wrappers other than // char, boolean, and long. boolean includeProject; - Constructor c; + Constructor c; try { // First try with Project. - c = reflectedArg.getConstructor(new Class[] {Project.class, String.class}); + c = reflectedArg.getConstructor(Project.class, String.class); includeProject = true; } catch (NoSuchMethodException nme) { // OK, try without. try { - c = reflectedArg.getConstructor(new Class[] {String.class}); + c = reflectedArg.getConstructor(String.class); includeProject = false; } catch (NoSuchMethodException nme2) { // Well, no matching constructor. @@ -1179,7 +1180,7 @@ public final class IntrospectionHelper { } } final boolean finalIncludeProject = includeProject; - final Constructor finalConstructor = c; + final Constructor finalConstructor = c; return new AttributeSetter(m, arg) { public void set(Project p, Object parent, String value) @@ -1212,40 +1213,25 @@ public final class IntrospectionHelper { } private AttributeSetter getEnumSetter( - final Class reflectedArg, final Method m, Class arg) { - Class enumClass = null; - try { - enumClass = Class.forName("java.lang.Enum"); - } catch (ClassNotFoundException e) { - //ignore - } - if (enumClass != null && enumClass.isAssignableFrom(reflectedArg)) { + final Class reflectedArg, final Method m, Class arg) { + if (reflectedArg.isEnum()) { return new AttributeSetter(m, arg) { public void set(Project p, Object parent, String value) throws InvocationTargetException, IllegalAccessException, BuildException { + Enum setValue; try { - m.invoke( - parent, new Object[] { - reflectedArg.getMethod( - "valueOf", new Class[] {String.class}). - invoke(null, new Object[] {value})}); - } catch (InvocationTargetException x) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + Enum enumValue = Enum.valueOf((Class) reflectedArg, + value); + setValue = enumValue; + } catch (IllegalArgumentException e) { //there is specific logic here for the value // being out of the allowed set of enumerations. - if (x.getTargetException() instanceof IllegalArgumentException) { - throw new BuildException( - "'" + value + "' is not a permitted value for " + throw new BuildException("'" + value + "' is not a permitted value for " + reflectedArg.getName()); - } - //only if the exception is not an IllegalArgument do we - // request the - //BuildException via extractBuildException(): - throw extractBuildException(x); - } catch (Exception x) { - //any other failure of invoke() to work. - throw new BuildException(x); } + m.invoke(parent, setValue); } }; } @@ -1433,10 +1419,10 @@ public final class IntrospectionHelper { static final int ADD = 1; static final int ADD_CONFIGURED = 2; - private Constructor constructor; + private Constructor constructor; private int behavior; // ADD or ADD_CONFIGURED - AddNestedCreator(Method m, Constructor c, int behavior) { + AddNestedCreator(Method m, Constructor c, int behavior) { super(m); this.constructor = c; this.behavior = behavior; @@ -1481,15 +1467,15 @@ public final class IntrospectionHelper { */ 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 Class type; + protected AttributeSetter(Method m, Class type) { method = m; this.type = type; } void setObject(Project p, Object parent, Object value) throws InvocationTargetException, IllegalAccessException, BuildException { if (type != null) { - Class useType = type; + Class useType = type; if (type.isPrimitive()) { if (value == null) { throw new BuildException( @@ -1497,7 +1483,7 @@ public final class IntrospectionHelper { + getPropertyName(method.getName(), "set") + " to null on " + parent); } - useType = (Class) PRIMITIVE_TYPE_MAP.get(type); + useType = PRIMITIVE_TYPE_MAP.get(type); } if (value == null || useType.isInstance(value)) { method.invoke(parent, new Object[] {value}); @@ -1589,7 +1575,7 @@ public final class IntrospectionHelper { * @param method the Method to insert. */ private void insertAddTypeMethod(Method method) { - Class argClass = method.getParameterTypes()[0]; + Class argClass = method.getParameterTypes()[0]; final int size = addTypeMethods.size(); for (int c = 0; c < size; ++c) { Method current = (Method) addTypeMethods.get(c); @@ -1615,17 +1601,17 @@ 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(Class paramClass, List methods) { if (paramClass == null) { return null; } - Class matchedClass = null; + Class matchedClass = null; Method matchedMethod = null; final int size = methods.size(); for (int i = 0; i < size; ++i) { - Method method = (Method) methods.get(i); - Class methodClass = method.getParameterTypes()[0]; + Method method = methods.get(i); + Class methodClass = method.getParameterTypes()[0]; if (methodClass.isAssignableFrom(paramClass)) { if (matchedClass == null) { matchedClass = methodClass; @@ -1661,19 +1647,19 @@ public final class IntrospectionHelper { * */ private AntTypeDefinition findRestrictedDefinition( - ComponentHelper helper, String componentName, List methods) { + ComponentHelper helper, String componentName, List methods) { AntTypeDefinition definition = null; - Class matchedDefinitionClass = null; + Class matchedDefinitionClass = null; - List definitions = helper.getRestrictedDefinitions(componentName); + 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 = (AntTypeDefinition) definitions.get(i); - Class exposedClass = d.getExposedClass(helper.getProject()); + AntTypeDefinition d = definitions.get(i); + Class exposedClass = d.getExposedClass(helper.getProject()); if (exposedClass == null) { continue; } @@ -1695,7 +1681,7 @@ public final class IntrospectionHelper { } private MethodAndObject createRestricted( - ComponentHelper helper, String elementName, List addTypeMethods) { + ComponentHelper helper, String elementName, List addTypeMethods) { Project project = helper.getProject(); @@ -1723,8 +1709,8 @@ public final class IntrospectionHelper { } private MethodAndObject createTopLevel( - ComponentHelper helper, String elementName, List methods) { - Class clazz = helper.getComponentClass(elementName); + ComponentHelper helper, String elementName, List methods) { + Class clazz = helper.getComponentClass(elementName); if (clazz == null) { return null; } diff --git a/src/main/org/apache/tools/ant/Location.java b/src/main/org/apache/tools/ant/Location.java index 75f3ea38b..25318694e 100644 --- a/src/main/org/apache/tools/ant/Location.java +++ b/src/main/org/apache/tools/ant/Location.java @@ -29,6 +29,7 @@ import org.xml.sax.Locator; * */ public class Location implements Serializable { + private static final long serialVersionUID = 1L; /** Name of the file. */ private final String fileName; diff --git a/src/main/org/apache/tools/ant/Main.java b/src/main/org/apache/tools/ant/Main.java index fa826006a..27260b408 100644 --- a/src/main/org/apache/tools/ant/Main.java +++ b/src/main/org/apache/tools/ant/Main.java @@ -24,11 +24,14 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; +import java.util.Arrays; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Vector; @@ -58,18 +61,12 @@ import org.apache.tools.ant.util.ProxySetup; public class Main implements AntMain { /** - * A Set of args are are handled by the launcher and should + * A Set of args that are handled by the launcher and should * not be seen by Main. */ - private static final Set LAUNCH_COMMANDS = new HashSet(); - static { - LAUNCH_COMMANDS.add("-lib"); - LAUNCH_COMMANDS.add("-cp"); - LAUNCH_COMMANDS.add("-noclasspath"); - LAUNCH_COMMANDS.add("--noclasspath"); - LAUNCH_COMMANDS.add("-nouserlib"); - LAUNCH_COMMANDS.add("-main"); - } + private static final Set LAUNCH_COMMANDS = Collections + .unmodifiableSet(new HashSet(Arrays.asList("-lib", "-cp", "-noclasspath", + "--noclasspath", "-nouserlib", "-main"))); /** The default build file name. {@value} */ public static final String DEFAULT_BUILD_FILENAME = "build.xml"; @@ -87,16 +84,16 @@ public class Main implements AntMain { private static PrintStream err = System.err; /** The build targets. */ - private Vector targets = new Vector(); + private Vector targets = new Vector(); /** Set of properties that can be used by tasks. */ private Properties definedProps = new Properties(); /** Names of classes to add as listeners to project. */ - private Vector listeners = new Vector(1); + private Vector listeners = new Vector(1); /** File names of property files to load on startup. */ - private Vector propertyFiles = new Vector(1); + private Vector propertyFiles = new Vector(1); /** Indicates whether this build is to support interactive input */ private boolean allowInput = true; @@ -154,15 +151,15 @@ public class Main implements AntMain { * proxy flag: default is false */ private boolean proxy = false; - - + + private static final GetProperty NOPROPERTIES = new GetProperty(){ public Object getProperty(String aName) { // No existing property takes precedence return null; }}; - - + + /** @@ -219,7 +216,7 @@ public class Main implements AntMain { } if (additionalUserProperties != null) { - for (Enumeration e = additionalUserProperties.keys(); + for (Enumeration e = additionalUserProperties.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); String property = additionalUserProperties.getProperty(key); @@ -438,9 +435,9 @@ public class Main implements AntMain { } } else { // no search file specified: so search an existing default file - Iterator it = ProjectHelperRepository.getInstance().getHelpers(); + Iterator it = ProjectHelperRepository.getInstance().getHelpers(); do { - ProjectHelper helper = (ProjectHelper) it.next(); + ProjectHelper helper = it.next(); searchForThis = helper.getDefaultBuildFile(); if (msgOutputLevel >= Project.MSG_VERBOSE) { System.out.println("Searching the default build file: " + searchForThis); @@ -453,9 +450,9 @@ public class Main implements AntMain { } } else { // no build file specified: so search an existing default file - Iterator it = ProjectHelperRepository.getInstance().getHelpers(); + Iterator it = ProjectHelperRepository.getInstance().getHelpers(); do { - ProjectHelper helper = (ProjectHelper) it.next(); + ProjectHelper helper = it.next(); buildFile = new File(helper.getDefaultBuildFile()); if (msgOutputLevel >= Project.MSG_VERBOSE) { System.out.println("Trying the default build file: " + buildFile); @@ -628,11 +625,7 @@ public class Main implements AntMain { /** Load the property files specified by -propertyfile */ private void loadPropertyFiles() { - for (int propertyFileIndex = 0; - propertyFileIndex < propertyFiles.size(); - propertyFileIndex++) { - String filename - = (String) propertyFiles.elementAt(propertyFileIndex); + for (String filename : propertyFiles) { Properties props = new Properties(); FileInputStream fis = null; try { @@ -646,7 +639,7 @@ public class Main implements AntMain { } // ensure that -D properties take precedence - Enumeration propertyNames = props.propertyNames(); + Enumeration propertyNames = props.propertyNames(); while (propertyNames.hasMoreElements()) { String name = (String) propertyNames.nextElement(); if (definedProps.getProperty(name) == null) { @@ -846,21 +839,20 @@ public class Main implements AntMain { } private void setProperties(final Project project) { - + project.init(); - + // resolve properties PropertyHelper propertyHelper = (PropertyHelper) PropertyHelper .getPropertyHelper(project); - HashMap props = new HashMap(definedProps); - + HashMap props = new HashMap(definedProps); + ResolvePropertyMap resolver = new ResolvePropertyMap(project, NOPROPERTIES, propertyHelper.getExpanders()); resolver.resolveAllProperties(props, null, false); // set user-define properties - for (Iterator e = props.entrySet().iterator(); e.hasNext(); ) { - Map.Entry ent = (Map.Entry) e.next(); + for (Entry ent : props.entrySet()) { String arg = (String) ent.getKey(); Object value = ent.getValue(); project.setUserProperty(arg, String.valueOf(value)); @@ -1076,17 +1068,15 @@ 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 (Iterator i = targets.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - String name = (String) entry.getKey(); - Target target = (Target) entry.getValue(); - Target otherTarget = - (Target) locationMap.get(target.getLocation()); + 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()); // Place this entry in the location map if // a) location is not in the map - // b) location is in map, but it's name is longer + // b) location is in map, but its name is longer // (an imported target will have a name. prefix) if (otherTarget == null || otherTarget.getName().length() > name.length()) { @@ -1094,9 +1084,8 @@ public class Main implements AntMain { target.getLocation(), target); // Smallest name wins } } - Map ret = new HashMap(); - for (Iterator i = locationMap.values().iterator(); i.hasNext();) { - Target target = (Target) i.next(); + Map ret = new HashMap(); + for (Target target : locationMap.values()) { ret.put(target.getName(), target); } return ret; @@ -1115,25 +1104,21 @@ public class Main implements AntMain { boolean printDependencies) { // find the target with the longest name int maxLength = 0; - Map ptargets = removeDuplicateTargets(project.getTargets()); - String targetName; - String targetDescription; - Target currentTarget; + 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 (Iterator i = ptargets.values().iterator(); i.hasNext();) { - currentTarget = (Target) i.next(); - targetName = currentTarget.getName(); + 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(); if (targetName.equals("")) { continue; } - targetDescription = currentTarget.getDescription(); + String targetDescription = currentTarget.getDescription(); // maintain a sorted list of targets if (targetDescription == null) { int pos = findTargetPosition(subNames, targetName); @@ -1182,11 +1167,11 @@ 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(Vector names, String name) { final int size = names.size(); int res = size; for (int i = 0; i < size && res == size; i++) { - if (name.compareTo((String) names.elementAt(i)) < 0) { + if (name.compareTo(names.elementAt(i)) < 0) { res = i; } } @@ -1216,8 +1201,8 @@ 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, + private static void printTargets(Project project, Vector names, + Vector descriptions, Vector> dependencies, String heading, int maxlen) { // now, start printing the targets and their descriptions @@ -1227,7 +1212,7 @@ public class Main implements AntMain { while (spaces.length() <= maxlen) { spaces += spaces; } - StringBuffer msg = new StringBuffer(); + StringBuilder msg = new StringBuilder(); msg.append(heading + lSep + lSep); final int size = names.size(); for (int i = 0; i < size; i++) { @@ -1235,12 +1220,12 @@ public class Main implements AntMain { msg.append(names.elementAt(i)); if (descriptions != null) { msg.append( - spaces.substring(0, maxlen - ((String) names.elementAt(i)).length() + 2)); + spaces.substring(0, maxlen - names.elementAt(i).length() + 2)); msg.append(descriptions.elementAt(i)); } msg.append(lSep); if (!dependencies.isEmpty()) { - Enumeration deps = (Enumeration) dependencies.elementAt(i); + Enumeration deps = dependencies.elementAt(i); if (deps.hasMoreElements()) { msg.append(" depends on: "); while (deps.hasMoreElements()) { @@ -1249,7 +1234,7 @@ public class Main implements AntMain { msg.append(", "); } } - msg.append(lSep); + msg.append(lSep); } } } diff --git a/src/main/org/apache/tools/ant/Project.java b/src/main/org/apache/tools/ant/Project.java index 27f5f3289..78eeb760c 100644 --- a/src/main/org/apache/tools/ant/Project.java +++ b/src/main/org/apache/tools/ant/Project.java @@ -135,19 +135,16 @@ public class Project implements ResourceFactory { /** Map of references within the project (paths etc) (String to Object). */ - private Hashtable references = new AntRefTable(); + private Hashtable references = new AntRefTable(); /** Map of id references - used for indicating broken build files */ - private HashMap idReferences = new HashMap(); - - /** the parent project for old id resolution (if inheritreferences is set) */ - private Project parentIdProject = null; + private 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 Hashtable targets = new Hashtable(); /** Set of global filters. */ private FilterSet globalFilterSet = new FilterSet(); { @@ -174,8 +171,8 @@ public class Project implements ResourceFactory { /** for each thread, record whether it is currently executing messageLogged */ - private final ThreadLocal isLoggingMessage = new ThreadLocal() { - protected Object initialValue() { + private final ThreadLocal isLoggingMessage = new ThreadLocal() { + protected Boolean initialValue() { return Boolean.FALSE; } }; @@ -187,12 +184,12 @@ public class Project implements ResourceFactory { private ClassLoader coreLoader = null; /** Records the latest task to be executed on a thread. */ - private final Map/**/ threadTasks = - Collections.synchronizedMap(new WeakHashMap()); + private final Map threadTasks = + Collections.synchronizedMap(new WeakHashMap()); /** Records the latest task to be executed on a thread group. */ - private final Map/**/ threadGroupTasks - = Collections.synchronizedMap(new WeakHashMap()); + private final Map threadGroupTasks + = Collections.synchronizedMap(new WeakHashMap()); /** * Called to handle any input requests. @@ -427,12 +424,12 @@ public class Project implements ResourceFactory { /** * Return a copy of the list of build listeners for the project. - * + * * @return a list of build listeners for the project */ - public Vector getBuildListeners() { + public Vector getBuildListeners() { synchronized (listenersLock) { - Vector r = new Vector(listeners.length); + Vector r = new Vector(listeners.length); for (int i = 0; i < listeners.length; i++) { r.add(listeners[i]); } @@ -644,7 +641,7 @@ public class Project implements ResourceFactory { * @return a hashtable containing all properties * (including user properties). */ - public Hashtable getProperties() { + public Hashtable getProperties() { return PropertyHelper.getPropertyHelper(this).getProperties(); } @@ -652,7 +649,7 @@ public class Project implements ResourceFactory { * Return a copy of the user property hashtable. * @return a hashtable containing just the user properties. */ - public Hashtable getUserProperties() { + public Hashtable getUserProperties() { return PropertyHelper.getPropertyHelper(this).getUserProperties(); } @@ -661,7 +658,7 @@ public class Project implements ResourceFactory { * @return a hashtable containing just the inherited properties. * @since Ant 1.8.0 */ - public Hashtable getInheritedProperties() { + public Hashtable getInheritedProperties() { return PropertyHelper.getPropertyHelper(this).getInheritedProperties(); } @@ -811,7 +808,7 @@ public class Project implements ResourceFactory { * @see #getGlobalFilterSet() * @see FilterSet#getFilterHash() */ - public Hashtable getFilters() { + public Hashtable getFilters() { // we need to build the hashtable dynamically return globalFilterSet.getFilterHash(); } @@ -936,7 +933,7 @@ public class Project implements ResourceFactory { */ public void setSystemProperties() { Properties systemP = System.getProperties(); - Enumeration e = systemP.propertyNames(); + Enumeration e = systemP.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); String value = systemP.getProperty(propertyName); @@ -966,7 +963,7 @@ public class Project implements ResourceFactory { * * @see #checkTaskClass(Class) */ - public void addTaskDefinition(String taskName, Class taskClass) + public void addTaskDefinition(String taskName, Class taskClass) throws BuildException { ComponentHelper.getComponentHelper(this).addTaskDefinition(taskName, taskClass); @@ -984,7 +981,7 @@ public class Project implements ResourceFactory { * task. An error level message is logged before * this exception is thrown. */ - public void checkTaskClass(final Class taskClass) throws BuildException { + public void checkTaskClass(final Class taskClass) throws BuildException { ComponentHelper.getComponentHelper(this).checkTaskClass(taskClass); if (!Modifier.isPublic(taskClass.getModifiers())) { @@ -998,7 +995,7 @@ public class Project implements ResourceFactory { throw new BuildException(message); } try { - taskClass.getConstructor((Class[]) null); + taskClass.getConstructor(); // don't have to check for public, since // getConstructor finds public constructors only. } catch (NoSuchMethodException e) { @@ -1023,7 +1020,7 @@ public class Project implements ResourceFactory { * @return a map of from task name to implementing class * (String to Class). */ - public Hashtable getTaskDefinitions() { + public Hashtable> getTaskDefinitions() { return ComponentHelper.getComponentHelper(this).getTaskDefinitions(); } @@ -1036,8 +1033,8 @@ public class Project implements ResourceFactory { * * @since Ant 1.8.1 */ - public Map getCopyOfTaskDefinitions() { - return new HashMap(getTaskDefinitions()); + public Map> getCopyOfTaskDefinitions() { + return new HashMap>(getTaskDefinitions()); } /** @@ -1053,7 +1050,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(String typeName, Class typeClass) { ComponentHelper.getComponentHelper(this).addDataTypeDefinition(typeName, typeClass); } @@ -1065,7 +1062,7 @@ public class Project implements ResourceFactory { * @return a map of from datatype name to implementing class * (String to Class). */ - public Hashtable getDataTypeDefinitions() { + public Hashtable> getDataTypeDefinitions() { return ComponentHelper.getComponentHelper(this).getDataTypeDefinitions(); } @@ -1078,8 +1075,8 @@ public class Project implements ResourceFactory { * * @since Ant 1.8.1 */ - public Map getCopyOfDataTypeDefinitions() { - return new HashMap(getDataTypeDefinitions()); + public Map> getCopyOfDataTypeDefinitions() { + return new HashMap>(getDataTypeDefinitions()); } /** @@ -1148,7 +1145,7 @@ public class Project implements ResourceFactory { * is "live" and so should not be modified. * @return a map from name to target (String to Target). */ - public Hashtable getTargets() { + public Hashtable getTargets() { return targets; } @@ -1158,8 +1155,8 @@ public class Project implements ResourceFactory { * @return a map from name to target (String to Target). * @since Ant 1.8.1 */ - public Map getCopyOfTargets() { - return new HashMap(targets); + public Map getCopyOfTargets() { + return new HashMap(targets); } /** @@ -1245,11 +1242,10 @@ public class Project implements ResourceFactory { * * @exception BuildException if the build failed. */ - public void executeTargets(Vector names) throws BuildException { + public void executeTargets(Vector names) throws BuildException { setUserProperty(MagicNames.PROJECT_INVOKED_TARGETS, CollectionUtils.flattenToString(names)); - getExecutor().executeTargets(this, - (String[]) (names.toArray(new String[names.size()]))); + getExecutor().executeTargets(this, names.toArray(new String[names.size()])); } /** @@ -1373,17 +1369,15 @@ public class Project implements ResourceFactory { * @param sortedTargets the aforementioned Vector. * @throws BuildException on error. */ - public void executeSortedTargets(Vector sortedTargets) + public void executeSortedTargets(Vector sortedTargets) throws BuildException { - Set succeededTargets = new HashSet(); + Set succeededTargets = new HashSet(); BuildException buildException = null; // first build exception - for (Enumeration iter = sortedTargets.elements(); - iter.hasMoreElements();) { - Target curtarget = (Target) iter.nextElement(); + for (Target curtarget : sortedTargets) { boolean canExecute = true; - for (Enumeration depIter = curtarget.getDependencies(); + for (Enumeration depIter = curtarget.getDependencies(); depIter.hasMoreElements();) { - String dependencyName = ((String) depIter.nextElement()); + String dependencyName = depIter.nextElement(); if (!succeededTargets.contains(dependencyName)) { canExecute = false; log(curtarget, @@ -1756,7 +1750,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(String root, Hashtable targetTable) throws BuildException { return topoSort(new String[] {root}, targetTable, true); } @@ -1778,7 +1772,7 @@ 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, + public final Vector topoSort(String root, Hashtable targetTable, boolean returnAll) throws BuildException { return topoSort(new String[] {root}, targetTable, returnAll); } @@ -1800,11 +1794,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, + public final Vector topoSort(String[] root, Hashtable targetTable, boolean returnAll) throws BuildException { - Vector ret = new VectorSet(); - Hashtable state = new Hashtable(); - Stack visiting = new Stack(); + Vector ret = new VectorSet(); + Hashtable state = new Hashtable(); + 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). @@ -1831,10 +1825,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 = (String) en.nextElement(); - String st = (String) state.get(curTarget); + Vector complete = (returnAll) ? ret : new Vector(ret); + for (Enumeration en = targetTable.keys(); en.hasMoreElements();) { + String curTarget = en.nextElement(); + String st = state.get(curTarget); if (st == null) { tsort(curTarget, targetTable, state, visiting, complete); } else if (st == VISITING) { @@ -1886,34 +1880,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(String root, Hashtable targetTable, + Hashtable state, Stack visiting, + Vector ret) throws BuildException { state.put(root, VISITING); visiting.push(root); - Target target = (Target) targetTable.get(root); + Target target = targetTable.get(root); // Make sure we exist if (target == null) { - StringBuffer sb = new StringBuffer("Target \""); + 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 = (String) visiting.peek(); + 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 = (String) en.nextElement(); - String m = (String) state.get(cur); + for (Enumeration en = target.getDependencies(); en.hasMoreElements();) { + String cur = en.nextElement(); + String m = state.get(cur); if (m == null) { // Not been visited tsort(cur, targetTable, state, visiting, ret); @@ -1922,7 +1916,7 @@ public class Project implements ResourceFactory { throw makeCircularException(cur, visiting); } } - String p = (String) visiting.pop(); + String p = visiting.pop(); if (root != p) { throw new RuntimeException("Unexpected internal error: expected to " + "pop " + root + " but got " + p); @@ -1940,16 +1934,16 @@ public class Project implements ResourceFactory { * * @return a BuildException detailing the specified circular dependency. */ - private static BuildException makeCircularException(String end, Stack stk) { - StringBuffer sb = new StringBuffer("Circular dependency: "); + private static BuildException makeCircularException(String end, Stack stk) { + final StringBuilder sb = new StringBuilder("Circular dependency: "); sb.append(end); String c; do { - c = (String) stk.pop(); + c = stk.pop(); sb.append(" <- "); sb.append(c); } while (!c.equals(end)); - return new BuildException(new String(sb)); + return new BuildException(sb.toString()); } /** @@ -1957,7 +1951,6 @@ public class Project implements ResourceFactory { * @param parent the parent project of this project. */ public void inheritIDReferences(Project parent) { - parentIdProject = parent; } /** @@ -1996,7 +1989,7 @@ public class Project implements ResourceFactory { * * @return a map of the references in the project (String to Object). */ - public Hashtable getReferences() { + public Hashtable getReferences() { return references; } @@ -2018,8 +2011,8 @@ public class Project implements ResourceFactory { * * @since Ant 1.8.1 */ - public Map getCopyOfReferences() { - return new HashMap(references); + public Map getCopyOfReferences() { + return new HashMap(references); } /** @@ -2031,8 +2024,9 @@ public class Project implements ResourceFactory { * @return the reference with the specified ID, or null if * there is no such reference in the project. */ - public Object getReference(String key) { - Object ret = references.get(key); + public T getReference(String key) { + @SuppressWarnings("unchecked") + final T ret = (T) references.get(key); if (ret != null) { return ret; } @@ -2046,7 +2040,7 @@ public class Project implements ResourceFactory { //ignore } } - return ret; + return null; } /** @@ -2397,7 +2391,8 @@ public class Project implements ResourceFactory { // Should move to a separate public class - and have API to add // listeners, etc. - private static class AntRefTable extends Hashtable { + private static class AntRefTable extends Hashtable { + private static final long serialVersionUID = 1L; AntRefTable() { super(); @@ -2426,7 +2421,6 @@ public class Project implements ResourceFactory { * @return mapped value. */ public Object get(Object key) { - //System.out.println("AntRefTable.get " + key); Object o = getReal(key); if (o instanceof UnknownElement) { // Make sure that diff --git a/src/main/org/apache/tools/ant/ProjectHelper.java b/src/main/org/apache/tools/ant/ProjectHelper.java index d1bc4daff..a3a88b889 100644 --- a/src/main/org/apache/tools/ant/ProjectHelper.java +++ b/src/main/org/apache/tools/ant/ProjectHelper.java @@ -87,7 +87,7 @@ public class ProjectHelper { * targets that want to extend missing extension-points. *

* This class behaves like a Java 1.5 Enum class. - * + * * @since 1.8.2 */ public final static class OnMissingExtensionPoint { @@ -143,8 +143,8 @@ public class ProjectHelper { // The following properties are required by import ( and other tasks // that read build files using ProjectHelper ). - private Vector importStack = new Vector(); - private List extensionStack = new LinkedList(); + private Vector importStack = new Vector(); + private List extensionStack = new LinkedList(); /** * Import stack. @@ -153,7 +153,7 @@ public class ProjectHelper { * * @return the stack of import source objects. */ - public Vector getImportStack() { + public Vector getImportStack() { return importStack; } @@ -170,11 +170,7 @@ public class ProjectHelper { return extensionStack; } - private final static ThreadLocal targetPrefix = new ThreadLocal() { - protected Object initialValue() { - return (String) null; - } - }; + private final static ThreadLocal targetPrefix = new ThreadLocal(); /** * The prefix to prepend to imported target names. @@ -186,7 +182,7 @@ public class ProjectHelper { * @since Ant 1.8.0 */ public static String getCurrentTargetPrefix() { - return (String) targetPrefix.get(); + return targetPrefix.get(); } /** @@ -198,8 +194,8 @@ public class ProjectHelper { targetPrefix.set(prefix); } - private final static ThreadLocal prefixSeparator = new ThreadLocal() { - protected Object initialValue() { + private final static ThreadLocal prefixSeparator = new ThreadLocal() { + protected String initialValue() { return "."; } }; @@ -212,7 +208,7 @@ public class ProjectHelper { * @since Ant 1.8.0 */ public static String getCurrentPrefixSeparator() { - return (String) prefixSeparator.get(); + return prefixSeparator.get(); } /** @@ -224,8 +220,8 @@ public class ProjectHelper { prefixSeparator.set(sep); } - private final static ThreadLocal inIncludeMode = new ThreadLocal() { - protected Object initialValue() { + private final static ThreadLocal inIncludeMode = new ThreadLocal() { + protected Boolean initialValue() { return Boolean.FALSE; } }; @@ -246,7 +242,7 @@ public class ProjectHelper { * @since Ant 1.8.0 */ public static boolean isInIncludeMode() { - return inIncludeMode.get() == Boolean.TRUE; + return Boolean.TRUE.equals(inIncludeMode.get()); } /** @@ -256,7 +252,7 @@ public class ProjectHelper { * @since Ant 1.8.0 */ public static void setInIncludeMode(boolean includeMode) { - inIncludeMode.set(includeMode ? Boolean.TRUE : Boolean.FALSE); + inIncludeMode.set(Boolean.valueOf(includeMode)); } // -------------------- Parse method -------------------- @@ -280,7 +276,7 @@ public class ProjectHelper { /** * Get the first project helper found in the classpath - * + * * @return an project helper, never null * @see org.apache.tools.ant.ProjectHelperRepository#getHelpers() */ @@ -436,7 +432,7 @@ public class ProjectHelper { * @param value The string to be scanned for property references. * May be null, in which case this * method returns immediately with no effect. - * @param keys Mapping (String to String) of property names to their + * @param keys Mapping (String to Object) of property names to their * values. Must not be null. * * @exception BuildException if the string contains an opening @@ -447,7 +443,7 @@ public class ProjectHelper { * @deprecated since 1.6.x. * Use PropertyHelper. */ - public static String replaceProperties(Project project, String value, Hashtable keys) + public static String replaceProperties(Project project, String value, Hashtable keys) throws BuildException { PropertyHelper ph = PropertyHelper.getPropertyHelper(project); return ph.replaceProperties(null, value, keys); @@ -474,7 +470,7 @@ public class ProjectHelper { * @exception BuildException if the string contains an opening * ${ without a closing } */ - public static void parsePropertyString(String value, Vector fragments, Vector propertyRefs) + public static void parsePropertyString(String value, Vector fragments, Vector propertyRefs) throws BuildException { PropertyHelper.parsePropertyStringDefault(value, fragments, propertyRefs); } @@ -587,7 +583,7 @@ public class ProjectHelper { /** * Check if the helper supports the kind of file. Some basic check on the * extension's file should be done here. - * + * * @param buildFile * the file expected to be parsed (never null) * @return true if the helper supports it @@ -599,7 +595,7 @@ public class ProjectHelper { /** * The file name of the build script to be parsed if none specified on the command line - * + * * @return the name of the default file (never null) * @since Ant 1.8.0 */ @@ -618,7 +614,7 @@ public class ProjectHelper { * This should be invoked by each concrete implementation of ProjectHelper * when the root "buildfile" and all imported/included buildfile are loaded. *

- * + * * @param project The project containing the target. Must not be * null. * @exception BuildException if OnMissingExtensionPoint.FAIL and @@ -638,11 +634,11 @@ public class ProjectHelper { String prefixAndSep = extensionInfo.length > 3 ? extensionInfo[3] : null; // find the target we're extending - Hashtable projectTargets = project.getTargets(); + Hashtable projectTargets = project.getTargets(); Target extPoint = null; if (prefixAndSep == null) { // no prefix - not from an imported/included build file - extPoint = (Target) projectTargets.get(extPointName); + extPoint = projectTargets.get(extPointName); } else { // we have a prefix, which means we came from an include/import @@ -652,9 +648,9 @@ public class ProjectHelper { // which prefix should be tested before testing the non-prefix // root name. - extPoint = (Target) projectTargets.get(prefixAndSep + extPointName); + extPoint = projectTargets.get(prefixAndSep + extPointName); if (extPoint == null) { - extPoint = (Target) projectTargets.get(extPointName); + extPoint = projectTargets.get(extPointName); } } @@ -666,7 +662,7 @@ public class ProjectHelper { if (missingBehaviour == OnMissingExtensionPoint.FAIL) { throw new BuildException(message); } else if (missingBehaviour == OnMissingExtensionPoint.WARN) { - Target t = (Target) projectTargets.get(targetName); + Target t = projectTargets.get(targetName); project.log(t, "Warning: " + message, Project.MSG_WARN); } } else { diff --git a/src/main/org/apache/tools/ant/ProjectHelperRepository.java b/src/main/org/apache/tools/ant/ProjectHelperRepository.java index c13cf44b2..f83c97326 100644 --- a/src/main/org/apache/tools/ant/ProjectHelperRepository.java +++ b/src/main/org/apache/tools/ant/ProjectHelperRepository.java @@ -34,9 +34,9 @@ import org.apache.tools.ant.util.LoaderUtils; /** * Repository of {@link ProjectHelper} found in the classpath or via * some System properties. - * + * *

See the ProjectHelper documentation in the manual.

- * + * * @since Ant 1.8.0 */ public class ProjectHelperRepository { @@ -52,17 +52,13 @@ public class ProjectHelperRepository { private static ProjectHelperRepository instance = new ProjectHelperRepository(); - private List/* */ helpers = new ArrayList(); - - private static final Class[] NO_CLASS = new Class[0]; - private static final Object[] NO_OBJECT = new Object[0]; + private List> helpers = new ArrayList>(); - private static Constructor PROJECTHELPER2_CONSTRUCTOR; + private static Constructor PROJECTHELPER2_CONSTRUCTOR; static { try { - PROJECTHELPER2_CONSTRUCTOR = ProjectHelper2.class - .getConstructor(NO_CLASS); + PROJECTHELPER2_CONSTRUCTOR = ProjectHelper2.class.getConstructor(); } catch (Exception e) { // ProjectHelper2 must be available throw new RuntimeException(e); @@ -79,7 +75,7 @@ public class ProjectHelperRepository { private void collectProjectHelpers() { // First, try the system property - Constructor projectHelper = getProjectHelperBySystemProperty(); + Constructor projectHelper = getProjectHelperBySystemProperty(); registerProjectHelper(projectHelper); // A JDK1.3 'service' ( like in JAXP ). That will plug a helper @@ -87,10 +83,10 @@ public class ProjectHelperRepository { try { ClassLoader classLoader = LoaderUtils.getContextClassLoader(); if (classLoader != null) { - Enumeration resources = + Enumeration resources = classLoader.getResources(ProjectHelper.SERVICE_ID); while (resources.hasMoreElements()) { - URL resource = (URL) resources.nextElement(); + URL resource = resources.nextElement(); projectHelper = getProjectHelperByService(resource.openStream()); registerProjectHelper(projectHelper); @@ -119,7 +115,7 @@ public class ProjectHelperRepository { *

* The helper will be added after all the already registered helpers, but * before the default one (ProjectHelper2) - * + * * @param helperClassName * the fully qualified name of the helper * @throws BuildException @@ -137,23 +133,23 @@ public class ProjectHelperRepository { *

* The helper will be added after all the already registered helpers, but * before the default one (ProjectHelper2) - * + * * @param helperClass * the class of the helper * @throws BuildException * if there is no constructor with no argument * @since Ant 1.8.2 */ - public void registerProjectHelper(Class helperClass) throws BuildException { + public void registerProjectHelper(Class helperClass) throws BuildException { try { - registerProjectHelper(helperClass.getConstructor(NO_CLASS)); + registerProjectHelper(helperClass.getConstructor()); } catch (NoSuchMethodException e) { throw new BuildException("Couldn't find no-arg constructor in " + helperClass.getName()); } } - private void registerProjectHelper(Constructor helperConstructor) { + private void registerProjectHelper(Constructor helperConstructor) { if (helperConstructor == null) { return; } @@ -164,7 +160,7 @@ public class ProjectHelperRepository { helpers.add(helperConstructor); } - private Constructor getProjectHelperBySystemProperty() { + private Constructor getProjectHelperBySystemProperty() { String helperClass = System.getProperty(ProjectHelper.HELPER_PROPERTY); try { if (helperClass != null) { @@ -182,7 +178,7 @@ public class ProjectHelperRepository { return null; } - private Constructor getProjectHelperByService(InputStream is) { + private Constructor getProjectHelperByService(InputStream is) { try { // This code is needed by EBCDIC and other strange systems. // It's a fix for bugs reported in xerces @@ -214,21 +210,21 @@ public class ProjectHelperRepository { * Get the constructor with not argument of an helper from its class name. * It'll first try the thread class loader, then Class.forName() will load * from the same loader that loaded this class. - * + * * @param helperClass * The name of the class to create an instance of. Must not be * null. - * + * * @return the constructor of the specified class. - * + * * @exception BuildException * if the class cannot be found or if a constructor with no * argument cannot be found. */ - private Constructor getHelperConstructor(String helperClass) throws BuildException { + private Constructor getHelperConstructor(String helperClass) throws BuildException { ClassLoader classLoader = LoaderUtils.getContextClassLoader(); try { - Class clazz = null; + Class clazz = null; if (classLoader != null) { try { clazz = classLoader.loadClass(helperClass); @@ -239,7 +235,7 @@ public class ProjectHelperRepository { if (clazz == null) { clazz = Class.forName(helperClass); } - return clazz.getConstructor(NO_CLASS); + return clazz.asSubclass(ProjectHelper.class).getConstructor(); } catch (Exception e) { throw new BuildException(e); } @@ -248,13 +244,12 @@ public class ProjectHelperRepository { /** * Get the helper that will be able to parse the specified build file. The helper * will be chosen among the ones found in the classpath - * + * * @return the first ProjectHelper that fit the requirement (never null). */ public ProjectHelper getProjectHelperForBuildFile(Resource buildFile) throws BuildException { - Iterator it = getHelpers(); - while (it.hasNext()) { - ProjectHelper helper = (ProjectHelper) it.next(); + for (Iterator it = getHelpers(); it.hasNext();) { + ProjectHelper helper = it.next(); if (helper.canParseBuildFile(buildFile)) { if (DEBUG) { System.out.println("ProjectHelper " @@ -272,13 +267,12 @@ public class ProjectHelperRepository { /** * Get the helper that will be able to parse the specified antlib. The helper * will be chosen among the ones found in the classpath - * + * * @return the first ProjectHelper that fit the requirement (never null). */ public ProjectHelper getProjectHelperForAntlib(Resource antlib) throws BuildException { - Iterator it = getHelpers(); - while (it.hasNext()) { - ProjectHelper helper = (ProjectHelper) it.next(); + for (Iterator it = getHelpers(); it.hasNext();) { + ProjectHelper helper = it.next(); if (helper.canParseAntlibDescriptor(antlib)) { if (DEBUG) { System.out.println("ProjectHelper " @@ -297,18 +291,18 @@ public class ProjectHelperRepository { * Get an iterator on the list of project helpers configured. The iterator * will always return at least one element as there will always be the * default project helper configured. - * + * * @return an iterator of {@link ProjectHelper} */ - public Iterator getHelpers() { + public Iterator getHelpers() { return new ConstructingIterator(helpers.iterator()); } - private static class ConstructingIterator implements Iterator { - private final Iterator nested; + private static class ConstructingIterator implements Iterator { + private final Iterator> nested; private boolean empty = false; - ConstructingIterator(Iterator nested) { + ConstructingIterator(Iterator> nested) { this.nested = nested; } @@ -316,17 +310,17 @@ public class ProjectHelperRepository { return nested.hasNext() || !empty; } - public Object next() { - Constructor c; + public ProjectHelper next() { + Constructor c; if (nested.hasNext()) { - c = (Constructor) nested.next(); + c = nested.next(); } else { // last but not least, ant default project helper empty = true; c = PROJECTHELPER2_CONSTRUCTOR; } try { - return c.newInstance(NO_OBJECT); + return c.newInstance(); } catch (Exception e) { throw new BuildException("Failed to invoke no-arg constructor" + " on " + c.getName()); diff --git a/src/main/org/apache/tools/ant/PropertyHelper.java b/src/main/org/apache/tools/ant/PropertyHelper.java index 924bdfdab..62022c175 100644 --- a/src/main/org/apache/tools/ant/PropertyHelper.java +++ b/src/main/org/apache/tools/ant/PropertyHelper.java @@ -19,21 +19,20 @@ package org.apache.tools.ant; import java.text.ParsePosition; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; +import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; -import java.util.Enumeration; -import java.util.Collection; -import org.apache.tools.ant.property.NullReturn; import org.apache.tools.ant.property.GetProperty; +import org.apache.tools.ant.property.NullReturn; import org.apache.tools.ant.property.ParseNextProperty; -import org.apache.tools.ant.property.PropertyExpander; import org.apache.tools.ant.property.ParseProperties; +import org.apache.tools.ant.property.PropertyExpander; /* ISSUES: - ns param. It could be used to provide "namespaces" for properties, which @@ -248,24 +247,24 @@ public class PropertyHelper implements GetProperty { private Project project; private PropertyHelper next; - private Hashtable delegates = new Hashtable(); + private final Hashtable, List> delegates = new Hashtable, List>(); /** Project properties map (usually String to String). */ - private Hashtable properties = new Hashtable(); + private Hashtable properties = new Hashtable(); /** * Map of "user" properties (as created in the Ant task, for example). * Note that these key/value pairs are also always put into the * project properties, so only the project properties need to be queried. */ - private Hashtable userProperties = new Hashtable(); + private Hashtable userProperties = new Hashtable(); /** * Map of inherited "user" properties - that are those "user" * properties that have been created by tasks and not been set * from the command line or a GUI tool. */ - private Hashtable inheritedProperties = new Hashtable(); + private Hashtable inheritedProperties = new Hashtable(); /** * Default constructor. @@ -414,7 +413,7 @@ public class PropertyHelper implements GetProperty { * @since Ant 1.8.0 * @return the expanders. */ - public Collection getExpanders() { + public Collection getExpanders() { return getDelegates(PropertyExpander.class); } @@ -519,8 +518,8 @@ public class PropertyHelper implements GetProperty { * } * @deprecated use the other mechanisms of this class instead */ - public void parsePropertyString(String value, Vector fragments, - Vector propertyRefs) throws BuildException { + public void parsePropertyString(String value, Vector fragments, + Vector propertyRefs) throws BuildException { parsePropertyStringDefault(value, fragments, propertyRefs); } @@ -535,7 +534,7 @@ public class PropertyHelper implements GetProperty { * @param value The string to be scanned for property references. * May be null, in which case this * method returns immediately with no effect. - * @param keys Mapping (String to String) of property names to their + * @param keys Mapping (String to Object) of property names to their * values. If null, only project properties will * be used. * @@ -545,7 +544,8 @@ public class PropertyHelper implements GetProperty { * @return the original string with the properties replaced, or * null if the original string is null. */ - public String replaceProperties(String ns, String value, Hashtable keys) throws BuildException { + //TODO deprecate? Recall why no longer using ns/keys params + public String replaceProperties(String ns, String value, Hashtable keys) throws BuildException { return replaceProperties(value); } @@ -629,8 +629,7 @@ public class PropertyHelper implements GetProperty { * @return true if the property is set. */ public boolean setProperty(String name, Object value, boolean verbose) { - for (Iterator iter = getDelegates(PropertySetter.class).iterator(); iter.hasNext();) { - PropertySetter setter = (PropertySetter) iter.next(); + for (PropertySetter setter : getDelegates(PropertySetter.class)) { if (setter.set(name, value, this)) { return true; } @@ -691,9 +690,7 @@ public class PropertyHelper implements GetProperty { * @since Ant 1.8.0 */ public void setNewProperty(String name, Object value) { - for (Iterator iter = getDelegates(PropertySetter.class).iterator(); - iter.hasNext();) { - PropertySetter setter = (PropertySetter) iter.next(); + for (PropertySetter setter : getDelegates(PropertySetter.class)) { if (setter.setNew(name, value, this)) { return; } @@ -841,14 +838,12 @@ public class PropertyHelper implements GetProperty { if (name == null) { return null; } - for (Iterator iter = getDelegates(PropertyEvaluator.class).iterator(); iter.hasNext();) { - Object o = ((PropertyEvaluator) iter.next()).evaluate(name, this); - if (o != null) { - if (o instanceof NullReturn) { - return null; - } - return o; + for (PropertyEvaluator evaluator : getDelegates(PropertyEvaluator.class)) { + final Object o = evaluator.evaluate(name, this); + if (o == null) { + continue; } + return o instanceof NullReturn ? null : o; } return properties.get(name); } @@ -901,10 +896,10 @@ public class PropertyHelper implements GetProperty { * * @return a hashtable containing all properties (including user properties). */ - public Hashtable getProperties() { + public Hashtable getProperties() { //avoid concurrent modification: synchronized (properties) { - return new Hashtable(properties); + return new Hashtable(properties); } // There is a better way to save the context. This shouldn't // delegate to next, it's for backward compatibility only. @@ -918,10 +913,10 @@ public class PropertyHelper implements GetProperty { * * @return a hashtable containing just the user properties */ - public Hashtable getUserProperties() { + public Hashtable getUserProperties() { //avoid concurrent modification: synchronized (userProperties) { - return new Hashtable(userProperties); + return new Hashtable(userProperties); } } @@ -933,10 +928,10 @@ public class PropertyHelper implements GetProperty { * * @return a hashtable containing just the inherited properties */ - public Hashtable getInheritedProperties() { + public Hashtable getInheritedProperties() { //avoid concurrent modification: synchronized (inheritedProperties) { - return new Hashtable(inheritedProperties); + return new Hashtable(inheritedProperties); } } @@ -944,7 +939,7 @@ public class PropertyHelper implements GetProperty { * special back door for subclasses, internal access to the hashtables * @return the live hashtable of all properties */ - protected Hashtable getInternalProperties() { + protected Hashtable getInternalProperties() { return properties; } @@ -953,7 +948,7 @@ public class PropertyHelper implements GetProperty { * * @return the live hashtable of user properties */ - protected Hashtable getInternalUserProperties() { + protected Hashtable getInternalUserProperties() { return userProperties; } @@ -962,7 +957,7 @@ public class PropertyHelper implements GetProperty { * * @return the live hashtable inherited properties */ - protected Hashtable getInternalInheritedProperties() { + protected Hashtable getInternalInheritedProperties() { return inheritedProperties; } @@ -984,7 +979,7 @@ public class PropertyHelper implements GetProperty { public void copyInheritedProperties(Project other) { //avoid concurrent modification: synchronized (inheritedProperties) { - Enumeration e = inheritedProperties.keys(); + Enumeration e = inheritedProperties.keys(); while (e.hasMoreElements()) { String arg = e.nextElement().toString(); if (other.getUserProperty(arg) != null) { @@ -1014,7 +1009,7 @@ public class PropertyHelper implements GetProperty { public void copyUserProperties(Project other) { //avoid concurrent modification: synchronized (userProperties) { - Enumeration e = userProperties.keys(); + Enumeration e = userProperties.keys(); while (e.hasMoreElements()) { Object arg = e.nextElement(); if (inheritedProperties.containsKey(arg)) { @@ -1035,7 +1030,7 @@ public class PropertyHelper implements GetProperty { * Default parsing method. It is here only to support backward compatibility * for the static ProjectHelper.parsePropertyString(). */ - static void parsePropertyStringDefault(String value, Vector fragments, Vector propertyRefs) + static void parsePropertyStringDefault(String value, Vector fragments, Vector propertyRefs) throws BuildException { int prev = 0; int pos; @@ -1097,13 +1092,13 @@ public class PropertyHelper implements GetProperty { */ public void add(Delegate delegate) { synchronized (delegates) { - for (Iterator iter = getDelegateInterfaces(delegate).iterator(); iter.hasNext();) { - Object key = iter.next(); - List list = (List) delegates.get(key); + for (Class key : getDelegateInterfaces(delegate)) { + List list = delegates.get(key); if (list == null) { - list = new ArrayList(); + list = new ArrayList(); } else { - list = new ArrayList(list); + //copy on write, top priority + list = new ArrayList(list); list.remove(delegate); } list.add(0, delegate); @@ -1114,15 +1109,16 @@ public class PropertyHelper implements GetProperty { /** * Get the Collection of delegates of the specified type. - * + * * @param type * delegate type. * @return Collection. * @since Ant 1.8.0 */ - protected List getDelegates(Class type) { - List r = (List) delegates.get(type); - return r == null ? Collections.EMPTY_LIST : r; + protected List getDelegates(Class type) { + @SuppressWarnings("unchecked") + final List result = (List) delegates.get(type); + return result == null ? Collections. emptyList() : result; } /** @@ -1131,14 +1127,16 @@ public class PropertyHelper implements GetProperty { * @return Set * @since Ant 1.8.0 */ - protected static Set getDelegateInterfaces(Delegate d) { - HashSet result = new HashSet(); - Class c = d.getClass(); + protected static Set> getDelegateInterfaces(Delegate d) { + final HashSet> result = new HashSet>(); + Class c = d.getClass(); while (c != null) { - Class[] ifs = c.getInterfaces(); + Class[] ifs = c.getInterfaces(); for (int i = 0; i < ifs.length; i++) { if (Delegate.class.isAssignableFrom(ifs[i])) { - result.add(ifs[i]); + @SuppressWarnings("unchecked") + final Class delegateInterface = (Class) ifs[i]; + result.add(delegateInterface); } } c = c.getSuperclass(); diff --git a/src/main/org/apache/tools/ant/RuntimeConfigurable.java b/src/main/org/apache/tools/ant/RuntimeConfigurable.java index d3502d6e3..f8fb44b36 100644 --- a/src/main/org/apache/tools/ant/RuntimeConfigurable.java +++ b/src/main/org/apache/tools/ant/RuntimeConfigurable.java @@ -25,11 +25,10 @@ import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; -import java.util.Iterator; import java.util.Map.Entry; import org.apache.tools.ant.util.CollectionUtils; -import org.apache.tools.ant.taskdefs.MacroDef; +import org.apache.tools.ant.taskdefs.MacroDef.Attribute; import org.apache.tools.ant.taskdefs.MacroInstance; import org.xml.sax.AttributeList; import org.xml.sax.helpers.AttributeListImpl; @@ -59,9 +58,6 @@ public class RuntimeConfigurable implements Serializable { */ private transient Object wrappedObject = null; - /** the creator used to make the wrapped object */ - private transient IntrospectionHelper.Creator creator; - /** * XML attributes for the element. * @deprecated since 1.6.x @@ -70,7 +66,7 @@ public class RuntimeConfigurable implements Serializable { /** Attribute names and values. While the XML spec doesn't require * preserving the order ( AFAIK ), some ant tests do rely on the - * exact order. + * exact order. * The only exception to this order is the treatment of * refid. A number of datatypes check if refid is set * when other attributes are set. This check will not @@ -124,7 +120,6 @@ public class RuntimeConfigurable implements Serializable { * @param creator the creator object. */ synchronized void setCreator(IntrospectionHelper.Creator creator) { - this.creator = creator; } /** @@ -250,7 +245,7 @@ public class RuntimeConfigurable implements Serializable { * Must not be null. */ public synchronized void addChild(RuntimeConfigurable child) { - children = (children == null) ? new ArrayList() : children; + children = (children == null) ? new ArrayList() : children; children.add(child); } @@ -263,7 +258,7 @@ public class RuntimeConfigurable implements Serializable { * list. */ synchronized RuntimeConfigurable getChild(int index) { - return (RuntimeConfigurable) children.get(index); + return children.get(index); } /** @@ -271,8 +266,8 @@ public class RuntimeConfigurable implements Serializable { * @return an enumeration of the child wrappers. * @since Ant 1.6 */ - public synchronized Enumeration getChildren() { - return (children == null) ? new CollectionUtils.EmptyEnumeration() + public synchronized Enumeration getChildren() { + return (children == null) ? new CollectionUtils.EmptyEnumeration() : Collections.enumeration(children); } @@ -405,8 +400,7 @@ public class RuntimeConfigurable implements Serializable { attrValue = PropertyHelper.getPropertyHelper(p).parseProperties(value.toString()); } if (target instanceof MacroInstance) { - for (Iterator attrs = ((MacroInstance) target).getMacroDef().getAttributes().iterator(); attrs.hasNext();) { - MacroDef.Attribute attr = (MacroDef.Attribute) attrs.next(); + for (Attribute attr : ((MacroInstance) target).getMacroDef().getAttributes()) { if (attr.getName().equals(name)) { if (!attr.isDoubleExpanding()) { attrValue = value; @@ -469,8 +463,7 @@ public class RuntimeConfigurable implements Serializable { public void applyPreSet(RuntimeConfigurable r) { // Attributes if (r.attributeMap != null) { - for (Iterator i = r.attributeMap.keySet().iterator(); i.hasNext();) { - String name = (String) i.next(); + for (String name : r.attributeMap.keySet()) { if (attributeMap == null || attributeMap.get(name) == null) { setAttribute(name, (String) r.attributeMap.get(name)); } @@ -482,7 +475,7 @@ public class RuntimeConfigurable implements Serializable { // Children (this is a shadow of UnknownElement#children) if (r.children != null) { - List newChildren = new ArrayList(); + List newChildren = new ArrayList(); newChildren.addAll(r.children); if (children != null) { newChildren.addAll(children); diff --git a/src/main/org/apache/tools/ant/Target.java b/src/main/org/apache/tools/ant/Target.java index 35b40f8f7..796b7e189 100644 --- a/src/main/org/apache/tools/ant/Target.java +++ b/src/main/org/apache/tools/ant/Target.java @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; @@ -53,10 +52,10 @@ public class Target implements TaskContainer { private Condition unlessCondition; /** List of targets this target is dependent on. */ - private List/**/ dependencies = null; + private List dependencies = null; /** Children of this target (tasks and data types). */ - private List children = new ArrayList(); + private List children = new ArrayList(); /** Since Ant 1.6.2 */ private Location location = Location.UNKNOWN_LOCATION; @@ -138,9 +137,8 @@ public class Target implements TaskContainer { * depends on. Must not be null. */ public void setDepends(String depS) { - for (Iterator iter = parseDepends(depS, getName(), "depends").iterator(); - iter.hasNext(); ) { - addDependency((String) iter.next()); + for (String dep : parseDepends(depS, getName(), "depends")) { + addDependency(dep); } } @@ -227,15 +225,13 @@ public class Target implements TaskContainer { * @return an array of the tasks currently within this target */ public Task[] getTasks() { - List tasks = new ArrayList(children.size()); - Iterator it = children.iterator(); - while (it.hasNext()) { - Object o = it.next(); + List tasks = new ArrayList(children.size()); + for (Object o : children) { if (o instanceof Task) { - tasks.add(o); + tasks.add((Task) o); } } - return (Task[]) tasks.toArray(new Task[tasks.size()]); + return tasks.toArray(new Task[tasks.size()]); } /** @@ -246,7 +242,7 @@ public class Target implements TaskContainer { */ public void addDependency(String dependency) { if (dependencies == null) { - dependencies = new ArrayList(2); + dependencies = new ArrayList(2); } dependencies.add(dependency); } @@ -256,9 +252,9 @@ public class Target implements TaskContainer { * * @return an enumeration of the dependencies of this target (enumeration of String) */ - public Enumeration getDependencies() { + public Enumeration getDependencies() { return Collections - .enumeration(dependencies == null ? Collections.EMPTY_LIST : dependencies); + .enumeration(dependencies == null ? Collections. emptyList() : dependencies); } /** @@ -269,7 +265,7 @@ public class Target implements TaskContainer { */ public boolean dependsOn(String other) { Project p = getProject(); - Hashtable t = p == null ? null : p.getTargets(); + Hashtable t = p == null ? null : p.getTargets(); return p != null && p.topoSort(getName(), t, false).contains(t.get(other)); } @@ -304,7 +300,7 @@ public class Target implements TaskContainer { /** * Same as {@link #setIf(String)} but requires a {@link Condition} instance - * + * * @since 1.9 */ public void setIf(Condition condition) { @@ -351,7 +347,7 @@ public class Target implements TaskContainer { /** * Same as {@link #setUnless(String)} but requires a {@link Condition} instance - * + * * @since 1.9 */ public void setUnless(Condition condition) { diff --git a/src/main/org/apache/tools/ant/Task.java b/src/main/org/apache/tools/ant/Task.java index 0a203cf34..099f716e8 100644 --- a/src/main/org/apache/tools/ant/Task.java +++ b/src/main/org/apache/tools/ant/Task.java @@ -427,10 +427,9 @@ public abstract class Task extends ProjectComponent { */ private void replaceChildren(RuntimeConfigurable wrapper, UnknownElement parentElement) { - Enumeration e = wrapper.getChildren(); + Enumeration e = wrapper.getChildren(); while (e.hasMoreElements()) { - RuntimeConfigurable childWrapper = - (RuntimeConfigurable) e.nextElement(); + RuntimeConfigurable childWrapper = e.nextElement(); UnknownElement childElement = new UnknownElement(childWrapper.getElementTag()); parentElement.addChild(childElement); diff --git a/src/main/org/apache/tools/ant/TaskAdapter.java b/src/main/org/apache/tools/ant/TaskAdapter.java index c73d4363a..e5d07e12c 100644 --- a/src/main/org/apache/tools/ant/TaskAdapter.java +++ b/src/main/org/apache/tools/ant/TaskAdapter.java @@ -74,7 +74,7 @@ public class TaskAdapter extends Task implements TypeAdapter { * * @see Project#checkTaskClass(Class) */ - public static void checkTaskClass(final Class taskClass, + public static void checkTaskClass(final Class taskClass, final Project project) { if (!Dispatchable.class.isAssignableFrom(taskClass)) { // don't have to check for interface, since then @@ -109,7 +109,7 @@ public class TaskAdapter extends Task implements TypeAdapter { * The class must have a public no-arg "execute()" method. * @param proxyClass the class to check. */ - public void checkProxyClass(Class proxyClass) { + public void checkProxyClass(Class proxyClass) { checkTaskClass(proxyClass, getProject()); } diff --git a/src/main/org/apache/tools/ant/TypeAdapter.java b/src/main/org/apache/tools/ant/TypeAdapter.java index c9d4a28f3..b8520fce2 100644 --- a/src/main/org/apache/tools/ant/TypeAdapter.java +++ b/src/main/org/apache/tools/ant/TypeAdapter.java @@ -62,5 +62,5 @@ public interface TypeAdapter { * * @param proxyClass the class to be checked. */ - void checkProxyClass(Class proxyClass); + void checkProxyClass(Class proxyClass); } diff --git a/src/main/org/apache/tools/ant/UnknownElement.java b/src/main/org/apache/tools/ant/UnknownElement.java index bd525368c..c3df2e29f 100644 --- a/src/main/org/apache/tools/ant/UnknownElement.java +++ b/src/main/org/apache/tools/ant/UnknownElement.java @@ -59,7 +59,7 @@ public class UnknownElement extends Task { /** * List of child elements (UnknownElements). */ - private List/**/ children = null; + private List children = null; /** Specifies if a predefined definition has been done */ private boolean presetDefed = false; @@ -77,7 +77,7 @@ public class UnknownElement extends Task { /** * @return the list of nested UnknownElements for this UnknownElement. */ - public List getChildren() { + public List getChildren() { return children; } @@ -309,7 +309,7 @@ public class UnknownElement extends Task { */ public void addChild(UnknownElement child) { if (children == null) { - children = new ArrayList(); + children = new ArrayList(); } children.add(child); } @@ -336,15 +336,15 @@ public class UnknownElement extends Task { } String parentUri = getNamespace(); - Class parentClass = parent.getClass(); + Class parentClass = parent.getClass(); IntrospectionHelper ih = IntrospectionHelper.getHelper(getProject(), parentClass); if (children != null) { - Iterator it = children.iterator(); + Iterator it = children.iterator(); for (int i = 0; it.hasNext(); i++) { RuntimeConfigurable childWrapper = parentWrapper.getChild(i); - UnknownElement child = (UnknownElement) it.next(); + UnknownElement child = it.next(); try { if (!handleChild( parentUri, ih, parent, child, childWrapper)) { @@ -390,7 +390,7 @@ public class UnknownElement extends Task { // Do the runtime getWrapper().applyPreSet(u.getWrapper()); if (u.children != null) { - List newChildren = new ArrayList(); + List newChildren = new ArrayList(); newChildren.addAll(u.children); if (children != null) { newChildren.addAll(children); @@ -668,16 +668,14 @@ public class UnknownElement extends Task { RuntimeConfigurable copyRC = new RuntimeConfigurable( ret, getTaskName()); copyRC.setPolyType(getWrapper().getPolyType()); - Map m = getWrapper().getAttributeMap(); - for (Iterator i = m.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - copyRC.setAttribute( - (String) entry.getKey(), (String) entry.getValue()); + Map m = getWrapper().getAttributeMap(); + for (Map.Entry entry : m.entrySet()) { + copyRC.setAttribute(entry.getKey(), (String) entry.getValue()); } copyRC.addText(getWrapper().getText().toString()); - for (Enumeration e = getWrapper().getChildren(); e.hasMoreElements();) { - RuntimeConfigurable r = (RuntimeConfigurable) e.nextElement(); + for (Enumeration e = getWrapper().getChildren(); e.hasMoreElements();) { + RuntimeConfigurable r = e.nextElement(); UnknownElement ueChild = (UnknownElement) r.getProxy(); UnknownElement copyChild = ueChild.copy(newProject); copyRC.addChild(copyChild.getWrapper()); diff --git a/src/main/org/apache/tools/ant/UnsupportedAttributeException.java b/src/main/org/apache/tools/ant/UnsupportedAttributeException.java index 09205998a..1fd9ce51a 100644 --- a/src/main/org/apache/tools/ant/UnsupportedAttributeException.java +++ b/src/main/org/apache/tools/ant/UnsupportedAttributeException.java @@ -23,6 +23,7 @@ package org.apache.tools.ant; * @since Ant 1.6.3 */ public class UnsupportedAttributeException extends BuildException { + private static final long serialVersionUID = 1L; private final String attribute; diff --git a/src/main/org/apache/tools/ant/UnsupportedElementException.java b/src/main/org/apache/tools/ant/UnsupportedElementException.java index 8ec49ffce..2a38120c4 100644 --- a/src/main/org/apache/tools/ant/UnsupportedElementException.java +++ b/src/main/org/apache/tools/ant/UnsupportedElementException.java @@ -32,6 +32,7 @@ package org.apache.tools.ant; * @since Ant 1.6.3 */ public class UnsupportedElementException extends BuildException { + private static final long serialVersionUID = 1L; private final String element; diff --git a/src/main/org/apache/tools/ant/XmlLogger.java b/src/main/org/apache/tools/ant/XmlLogger.java index b2a86c584..b99882186 100644 --- a/src/main/org/apache/tools/ant/XmlLogger.java +++ b/src/main/org/apache/tools/ant/XmlLogger.java @@ -28,6 +28,7 @@ import java.util.Stack; import java.util.Enumeration; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; + import org.apache.tools.ant.util.DOMElementWriter; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.StringUtils; @@ -106,16 +107,16 @@ public class XmlLogger implements BuildLogger { private Document doc = builder.newDocument(); /** Mapping for when tasks started (Task to TimedElement). */ - private Hashtable tasks = new Hashtable(); + private Hashtable tasks = new Hashtable(); - /** Mapping for when targets started (Task to TimedElement). */ - private Hashtable targets = new Hashtable(); + /** Mapping for when targets started (Target to TimedElement). */ + private Hashtable targets = new Hashtable(); /** * Mapping of threads to stacks of elements * (Thread to Stack of TimedElement). */ - private Hashtable threadStacks = new Hashtable(); + private Hashtable> threadStacks = new Hashtable>(); /** * When the build started. @@ -210,10 +211,10 @@ public class XmlLogger implements BuildLogger { * Returns the stack of timed elements for the current thread. * @return the stack of timed elements for the current thread */ - private Stack getStack() { - Stack threadStack = (Stack) threadStacks.get(Thread.currentThread()); + private Stack getStack() { + Stack threadStack = threadStacks.get(Thread.currentThread()); if (threadStack == null) { - threadStack = new Stack(); + threadStack = new Stack(); threadStacks.put(Thread.currentThread(), threadStack); } /* For debugging purposes uncomment: @@ -256,9 +257,9 @@ public class XmlLogger implements BuildLogger { targetElement.element.setAttribute(TIME_ATTR, DefaultLogger.formatTime(totalTime)); TimedElement parentElement = null; - Stack threadStack = getStack(); + Stack threadStack = getStack(); if (!threadStack.empty()) { - TimedElement poppedStack = (TimedElement) threadStack.pop(); + TimedElement poppedStack = threadStack.pop(); if (poppedStack != targetElement) { throw new RuntimeException("Mismatch - popped element = " + poppedStack + " finished target element = " + targetElement); @@ -326,9 +327,9 @@ public class XmlLogger implements BuildLogger { } else { synchronizedAppend(targetElement.element, taskElement.element); } - Stack threadStack = getStack(); + Stack threadStack = getStack(); if (!threadStack.empty()) { - TimedElement poppedStack = (TimedElement) threadStack.pop(); + TimedElement poppedStack = threadStack.pop(); if (poppedStack != taskElement) { throw new RuntimeException("Mismatch - popped element = " + poppedStack + " finished task element = " + taskElement); @@ -348,8 +349,8 @@ public class XmlLogger implements BuildLogger { if (element != null) { return element; } - for (Enumeration e = tasks.keys(); e.hasMoreElements();) { - Task key = (Task) e.nextElement(); + for (Enumeration e = tasks.keys(); e.hasMoreElements();) { + Task key = e.nextElement(); if (key instanceof UnknownElement) { if (((UnknownElement) key).getTask() == task) { return (TimedElement) tasks.get(key); diff --git a/src/main/org/apache/tools/ant/property/LocalProperties.java b/src/main/org/apache/tools/ant/property/LocalProperties.java index e36a1dff0..fb2fa9c0a 100644 --- a/src/main/org/apache/tools/ant/property/LocalProperties.java +++ b/src/main/org/apache/tools/ant/property/LocalProperties.java @@ -26,7 +26,7 @@ import org.apache.tools.ant.MagicNames; * @since Ant 1.8.0 */ public class LocalProperties - extends InheritableThreadLocal + extends InheritableThreadLocal implements PropertyHelper.PropertyEvaluator, PropertyHelper.PropertySetter { @@ -62,7 +62,7 @@ public class LocalProperties * Get the initial value. * @return a new localproperties stack. */ - protected synchronized Object initialValue() { + protected synchronized LocalPropertyStack initialValue() { return new LocalPropertyStack(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java index 9a057655e..7666bad68 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java +++ b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Locale; import java.util.HashMap; -import java.util.Iterator; import org.apache.tools.ant.AntTypeDefinition; import org.apache.tools.ant.BuildException; @@ -45,8 +44,8 @@ public class MacroDef extends AntlibDefinition { private NestedSequential nestedSequential; private String name; private boolean backTrace = true; - private List attributes = new ArrayList(); - private Map elements = new HashMap(); + private List attributes = new ArrayList(); + private Map elements = new HashMap(); private String textName = null; private Text text = null; private boolean hasImplicitElement = false; @@ -74,8 +73,7 @@ public class MacroDef extends AntlibDefinition { "the text nested element needed a \"name\" attribute"); } // Check if used by attributes - for (Iterator i = attributes.iterator(); i.hasNext();) { - Attribute attribute = (Attribute) i.next(); + for (Attribute attribute : attributes) { if (text.getName().equals(attribute.getName())) { throw new BuildException( "the name \"" + text.getName() @@ -134,7 +132,7 @@ public class MacroDef extends AntlibDefinition { * This is a simple task container. */ public static class NestedSequential implements TaskContainer { - private List nested = new ArrayList(); + private List nested = new ArrayList(); /** * Add a task or type to the container. @@ -148,7 +146,7 @@ public class MacroDef extends AntlibDefinition { /** * @return the list of unknown elements */ - public List getNested() { + public List getNested() { return nested; } @@ -201,7 +199,7 @@ public class MacroDef extends AntlibDefinition { * * @return the nested Attributes */ - public List getAttributes() { + public List getAttributes() { return attributes; } @@ -211,7 +209,7 @@ public class MacroDef extends AntlibDefinition { * @return the map nested elements, keyed by element name, with * {@link TemplateElement} values. */ - public Map getElements() { + public Map getElements() { return elements; } diff --git a/src/main/org/apache/tools/ant/types/FilterSet.java b/src/main/org/apache/tools/ant/types/FilterSet.java index 6faa7e94e..64ca40825 100644 --- a/src/main/org/apache/tools/ant/types/FilterSet.java +++ b/src/main/org/apache/tools/ant/types/FilterSet.java @@ -177,13 +177,13 @@ public class FilterSet extends DataType implements Cloneable { private String endOfToken = DEFAULT_TOKEN_END; /** Contains a list of parsed tokens */ - private Vector passedTokens; + private Vector passedTokens; /** if a duplicate token is found, this is set to true */ private boolean duplicateToken = false; private boolean recurse = true; - private Hashtable filterHash = null; - private Vector filtersFiles = new Vector(); + private Hashtable filterHash = null; + private Vector filtersFiles = new Vector(); private OnMissing onMissingFiltersFile = OnMissing.FAIL; private boolean readingFiles = false; @@ -192,7 +192,7 @@ public class FilterSet extends DataType implements Cloneable { /** * List of ordered filters and filter files. */ - private Vector filters = new Vector(); + private Vector filters = new Vector(); /** * Default constructor. @@ -207,7 +207,9 @@ public class FilterSet extends DataType implements Cloneable { */ protected FilterSet(FilterSet filterset) { super(); - this.filters = (Vector) filterset.getFilters().clone(); + @SuppressWarnings("unchecked") + Vector clone = (Vector) filterset.getFilters().clone(); + this.filters = clone; } /** @@ -215,7 +217,7 @@ public class FilterSet extends DataType implements Cloneable { * * @return a Vector of Filter instances. */ - protected synchronized Vector getFilters() { + protected synchronized Vector getFilters() { if (isReference()) { return getRef().getFilters(); } @@ -247,15 +249,15 @@ public class FilterSet extends DataType implements Cloneable { * * @return The hash of the tokens and values for quick lookup. */ - public synchronized Hashtable getFilterHash() { + public synchronized Hashtable getFilterHash() { if (isReference()) { return getRef().getFilterHash(); } dieOnCircularReference(); if (filterHash == null) { - filterHash = new Hashtable(getFilters().size()); - for (Enumeration e = getFilters().elements(); e.hasMoreElements();) { - Filter filter = (Filter) e.nextElement(); + filterHash = new Hashtable(getFilters().size()); + for (Enumeration e = getFilters().elements(); e.hasMoreElements();) { + Filter filter = e.nextElement(); filterHash.put(filter.getToken(), filter.getValue()); } } @@ -368,8 +370,8 @@ public class FilterSet extends DataType implements Cloneable { in = new FileInputStream(filtersFile); props.load(in); - Enumeration e = props.propertyNames(); - Vector filts = getFilters(); + Enumeration e = props.propertyNames(); + Vector filts = getFilters(); while (e.hasMoreElements()) { String strPropName = (String) e.nextElement(); String strValue = props.getProperty(strPropName); @@ -450,8 +452,8 @@ public class FilterSet extends DataType implements Cloneable { if (isReference()) { throw noChildrenAllowed(); } - for (Enumeration e = filterSet.getFilters().elements(); e.hasMoreElements();) { - addFilter((Filter) e.nextElement()); + for (Filter filter : filterSet.getFilters()) { + addFilter(filter); } } @@ -477,7 +479,9 @@ public class FilterSet extends DataType implements Cloneable { } try { FilterSet fs = (FilterSet) super.clone(); - fs.filters = (Vector) getFilters().clone(); + @SuppressWarnings("unchecked") + Vector clonedFilters = (Vector) getFilters().clone(); + fs.filters = clonedFilters; fs.setProject(getProject()); return fs; } catch (CloneNotSupportedException e) { @@ -515,9 +519,9 @@ public class FilterSet extends DataType implements Cloneable { int index = line.indexOf(beginToken); if (index > -1) { - Hashtable tokens = getFilterHash(); + Hashtable tokens = getFilterHash(); try { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); int i = 0; String token = null; String value = null; @@ -533,7 +537,7 @@ public class FilterSet extends DataType implements Cloneable { = line.substring(index + beginToken.length(), endIndex); b.append(line.substring(i, index)); if (tokens.containsKey(token)) { - value = (String) tokens.get(token); + value = tokens.get(token); if (recurse && !value.equals(token)) { // we have another token, let's parse it. value = replaceTokens(value, token); @@ -577,7 +581,7 @@ public class FilterSet extends DataType implements Cloneable { String beginToken = getBeginToken(); String endToken = getEndToken(); if (recurseDepth == 0) { - passedTokens = new VectorSet(); + passedTokens = new VectorSet(); } recurseDepth++; if (passedTokens.contains(parent) && !duplicateToken) { @@ -605,7 +609,7 @@ public class FilterSet extends DataType implements Cloneable { } } } else if (passedTokens.size() > 0) { - // remove last seen token when crawling out of recursion + // remove last seen token when crawling out of recursion passedTokens.remove(passedTokens.size() - 1); } recurseDepth--; diff --git a/src/main/org/apache/tools/ant/util/CollectionUtils.java b/src/main/org/apache/tools/ant/util/CollectionUtils.java index e2e78f748..65735ae7e 100644 --- a/src/main/org/apache/tools/ant/util/CollectionUtils.java +++ b/src/main/org/apache/tools/ant/util/CollectionUtils.java @@ -39,8 +39,9 @@ public class CollectionUtils { /** * Collections.emptyList() is Java5+. */ - public static final List EMPTY_LIST = - Collections.unmodifiableList(new ArrayList(0)); + @SuppressWarnings("rawtypes") + @Deprecated + public static final List EMPTY_LIST = Collections.EMPTY_LIST; /** * Please use Vector.equals() or List.equals(). @@ -50,7 +51,7 @@ public class CollectionUtils { * @since Ant 1.5 * @deprecated since 1.6.x. */ - public static boolean equals(Vector v1, Vector v2) { + public static boolean equals(Vector v1, Vector v2) { if (v1 == v2) { return true; } @@ -73,7 +74,7 @@ public class CollectionUtils { * @since Ant 1.5 * @deprecated since 1.6.x. */ - public static boolean equals(Dictionary d1, Dictionary d2) { + public static boolean equals(Dictionary d1, Dictionary d2) { if (d1 == d2) { return true; } @@ -86,7 +87,7 @@ public class CollectionUtils { return false; } - Enumeration e1 = d1.keys(); + Enumeration e1 = d1.keys(); while (e1.hasMoreElements()) { Object key = e1.nextElement(); Object value1 = d1.get(key); @@ -108,16 +109,13 @@ public class CollectionUtils { * * @since Ant 1.8.0 */ - public static String flattenToString(Collection c) { - Iterator iter = c.iterator(); - boolean first = true; - StringBuffer sb = new StringBuffer(); - while (iter.hasNext()) { - if (!first) { + public static String flattenToString(Collection c) { + final StringBuilder sb = new StringBuilder(); + for (Object o : c) { + if (sb.length() != 0) { sb.append(","); } - sb.append(String.valueOf(iter.next())); - first = false; + sb.append(o); } return sb.toString(); } @@ -129,9 +127,9 @@ public class CollectionUtils { * @since Ant 1.6 * @deprecated since 1.6.x. */ - public static void putAll(Dictionary m1, Dictionary m2) { - for (Enumeration it = m2.keys(); it.hasMoreElements();) { - Object key = it.nextElement(); + public static void putAll(Dictionary m1, Dictionary m2) { + for (Enumeration it = m2.keys(); it.hasMoreElements();) { + K key = it.nextElement(); m1.put(key, m2.get(key)); } } @@ -140,7 +138,7 @@ public class CollectionUtils { * An empty enumeration. * @since Ant 1.6 */ - public static final class EmptyEnumeration implements Enumeration { + public static final class EmptyEnumeration implements Enumeration { /** Constructor for the EmptyEnumeration */ public EmptyEnumeration() { } @@ -156,7 +154,7 @@ public class CollectionUtils { * @return nothing. * @throws NoSuchElementException always. */ - public Object nextElement() throws NoSuchElementException { + public E nextElement() throws NoSuchElementException { throw new NoSuchElementException(); } } @@ -169,8 +167,8 @@ public class CollectionUtils { * @return an enumeration representing e1 followed by e2. * @since Ant 1.6.3 */ - public static Enumeration append(Enumeration e1, Enumeration e2) { - return new CompoundEnumeration(e1, e2); + public static Enumeration append(Enumeration e1, Enumeration e2) { + return new CompoundEnumeration(e1, e2); } /** @@ -178,12 +176,12 @@ public class CollectionUtils { * @param iter the Iterator to adapt. * @return an Enumeration. */ - public static Enumeration asEnumeration(final Iterator iter) { - return new Enumeration() { + public static Enumeration asEnumeration(final Iterator iter) { + return new Enumeration() { public boolean hasMoreElements() { return iter.hasNext(); } - public Object nextElement() { + public E nextElement() { return iter.next(); } }; @@ -194,12 +192,12 @@ public class CollectionUtils { * @param e the Enumeration to adapt. * @return an Iterator. */ - public static Iterator asIterator(final Enumeration e) { - return new Iterator() { + public static Iterator asIterator(final Enumeration e) { + return new Iterator() { public boolean hasNext() { return e.hasMoreElements(); } - public Object next() { + public E next() { return e.nextElement(); } public void remove() { @@ -221,11 +219,11 @@ public class CollectionUtils { return l; } - private static final class CompoundEnumeration implements Enumeration { + private static final class CompoundEnumeration implements Enumeration { - private final Enumeration e1, e2; + private final Enumeration e1, e2; - public CompoundEnumeration(Enumeration e1, Enumeration e2) { + public CompoundEnumeration(Enumeration e1, Enumeration e2) { this.e1 = e1; this.e2 = e2; } @@ -234,7 +232,7 @@ public class CollectionUtils { return e1.hasMoreElements() || e2.hasMoreElements(); } - public Object nextElement() throws NoSuchElementException { + public E nextElement() throws NoSuchElementException { if (e1.hasMoreElements()) { return e1.nextElement(); } else { @@ -250,11 +248,11 @@ public class CollectionUtils { * * @since Ant 1.8.0 */ - public static int frequency(Collection c, Object o) { + public static int frequency(Collection c, Object o) { // same as Collections.frequency introduced with JDK 1.5 int freq = 0; if (c != null) { - for (Iterator i = c.iterator(); i.hasNext(); ) { + for (Iterator i = c.iterator(); i.hasNext(); ) { Object test = i.next(); if (o == null ? test == null : o.equals(test)) { freq++; @@ -263,5 +261,5 @@ public class CollectionUtils { } return freq; } - + } diff --git a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java index 08cc22cc4..eb416688d 100644 --- a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java +++ b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java @@ -108,7 +108,7 @@ public final class JavaEnvUtils { private static boolean harmonyDetected; /** array of packages in the runtime */ - private static Vector jrePackages; + private static Vector jrePackages; static { @@ -376,7 +376,7 @@ public final class JavaEnvUtils { */ private static void buildJrePackages() { - jrePackages = new Vector(); + jrePackages = new Vector(); switch(javaVersionNumber) { case VERSION_1_8: case VERSION_1_7: @@ -479,7 +479,7 @@ public final class JavaEnvUtils { * that platforms runtime jar(s) * @return list of packages. */ - public static Vector getJrePackages() { + public static Vector getJrePackages() { if (jrePackages == null) { buildJrePackages(); } diff --git a/src/main/org/apache/tools/ant/util/VectorSet.java b/src/main/org/apache/tools/ant/util/VectorSet.java index 3d46da934..66fdb972a 100644 --- a/src/main/org/apache/tools/ant/util/VectorSet.java +++ b/src/main/org/apache/tools/ant/util/VectorSet.java @@ -19,7 +19,6 @@ package org.apache.tools.ant.util; import java.util.Collection; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import java.util.Vector; @@ -38,8 +37,10 @@ import java.util.Vector; * * @since Ant 1.8.0 */ -public final class VectorSet extends Vector { - private final HashSet set = new HashSet(); +public final class VectorSet extends Vector { + private static final long serialVersionUID = 1L; + + private final HashSet set = new HashSet(); public VectorSet() { super(); } @@ -49,15 +50,15 @@ public final class VectorSet extends Vector { super(initialCapacity, capacityIncrement); } - public VectorSet(Collection c) { + public VectorSet(Collection c) { if (c != null) { - for (Iterator i = c.iterator(); i.hasNext(); ) { - add(i.next()); + for (E e : c) { + add(e); } } } - public synchronized boolean add(Object o) { + public synchronized boolean add(E o) { if (!set.contains(o)) { doAdd(size(), o); return true; @@ -69,11 +70,11 @@ public final class VectorSet extends Vector { * This implementation may not add the element at the given index * if it is already contained in the collection. */ - public void add(int index, Object o) { + public void add(int index, E o) { doAdd(index, o); } - private synchronized void doAdd(int index, Object o) { + private synchronized void doAdd(int index, E o) { // Vector.add seems to delegate to insertElementAt, but this // is not documented so we may better implement it ourselves if (set.add(o)) { @@ -88,14 +89,14 @@ public final class VectorSet extends Vector { } } - public synchronized void addElement(Object o) { + public synchronized void addElement(E o) { doAdd(size(), o); } - public synchronized boolean addAll(Collection c) { + public synchronized boolean addAll(Collection c) { boolean changed = false; - for (Iterator i = c.iterator(); i.hasNext(); ) { - changed |= add(i.next()); + for (E e : c) { + changed |= add(e); } return changed; } @@ -104,12 +105,11 @@ public final class VectorSet extends Vector { * This implementation may not add all elements at the given index * if any of them are already contained in the collection. */ - public synchronized boolean addAll(int index, Collection c) { + public synchronized boolean addAll(int index, Collection c) { boolean changed = false; - for (Iterator i = c.iterator(); i.hasNext(); ) { - Object o = i.next(); - if (!set.contains(o)) { - doAdd(index++, o); + for (E e : c) { + if (!set.contains(e)) { + doAdd(index++, e); changed = true; } } @@ -122,7 +122,8 @@ public final class VectorSet extends Vector { } public Object clone() { - VectorSet vs = (VectorSet) super.clone(); + @SuppressWarnings("unchecked") + final VectorSet vs = (VectorSet) super.clone(); vs.set.addAll(set); return vs; } @@ -131,16 +132,16 @@ public final class VectorSet extends Vector { return set.contains(o); } - public synchronized boolean containsAll(Collection c) { + public synchronized boolean containsAll(Collection c) { return set.containsAll(c); } - public void insertElementAt(Object o, int index) { + public void insertElementAt(E o, int index) { doAdd(index, o); } - public synchronized Object remove(int index) { - Object o = get(index); + public synchronized E remove(int index) { + E o = get(index); remove(o); return o; } @@ -164,10 +165,10 @@ public final class VectorSet extends Vector { return false; } - public synchronized boolean removeAll(Collection c) { + public synchronized boolean removeAll(Collection c) { boolean changed = false; - for (Iterator i = c.iterator(); i.hasNext(); ) { - changed |= remove(i.next()); + for (Object o : c) { + changed |= remove(o); } return changed; } @@ -191,13 +192,12 @@ public final class VectorSet extends Vector { } } - public synchronized boolean retainAll(Collection c) { + public synchronized boolean retainAll(Collection c) { if (!(c instanceof Set)) { - c = new HashSet(c); + c = new HashSet(c); } - LinkedList l = new LinkedList(); - for (Iterator i = iterator(); i.hasNext(); ) { - Object o = i.next(); + LinkedList l = new LinkedList(); + for (E o : this) { if (!c.contains(o)) { l.addLast(o); } @@ -209,8 +209,8 @@ public final class VectorSet extends Vector { return false; } - public synchronized Object set(int index, Object o) { - Object orig = get(index); + public synchronized E set(int index, E o) { + E orig = get(index); if (set.add(o)) { elementData[index] = o; set.remove(orig); @@ -223,7 +223,7 @@ public final class VectorSet extends Vector { return orig; } - public void setElementAt(Object o, int index) { + public void setElementAt(E o, int index) { set(index, o); }