http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Parallel.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Parallel.java b/src/main/org/apache/tools/ant/taskdefs/Parallel.java index 469ba41..b3d400b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Parallel.java +++ b/src/main/org/apache/tools/ant/taskdefs/Parallel.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs; import java.util.ArrayList; -import java.util.Enumeration; import java.util.List; import java.util.Vector; @@ -56,7 +55,7 @@ public class Parallel extends Task /** Class which holds a list of tasks to execute */ public static class TaskList implements TaskContainer { /** Collection holding the nested tasks */ - private List tasks = new ArrayList(); + private List<Task> tasks = new ArrayList<>(); /** * Add a nested task to execute parallel (asynchron). @@ -64,13 +63,14 @@ public class Parallel extends Task * @param nestedTask Nested task to be executed in parallel. * must not be null. */ + @Override public void addTask(Task nestedTask) { tasks.add(nestedTask); } } /** Collection holding the nested tasks */ - private Vector nestedTasks = new Vector(); + private Vector<Task> nestedTasks = new Vector<>(); /** Semaphore to notify of completed threads */ private final Object semaphore = new Object(); @@ -150,6 +150,7 @@ public class Parallel extends Task * Add a nested task to execute in parallel. * @param nestedTask Nested task to be executed in parallel */ + @Override public void addTask(Task nestedTask) { nestedTasks.addElement(nestedTask); } @@ -195,13 +196,12 @@ public class Parallel extends Task this.timeout = timeout; } - - /** * Execute the parallel tasks * * @exception BuildException if any of the threads failed. */ + @Override public void execute() throws BuildException { updateThreadCounts(); if (numThreads == 0) { @@ -224,8 +224,8 @@ public class Parallel extends Task if (runnables == null) { return; } - for (int i = 0; i < runnables.length; ++i) { - Throwable t = runnables[i].getException(); + for (TaskRunnable runnable : runnables) { + Throwable t = runnable.getException(); if (t != null) { numExceptions++; if (firstException == null) { @@ -255,28 +255,21 @@ public class Parallel extends Task * @exception BuildException if any of the threads failed. */ private void spinThreads() throws BuildException { - final int numTasks = nestedTasks.size(); - TaskRunnable[] runnables = new TaskRunnable[numTasks]; stillRunning = true; timedOut = false; boolean interrupted = false; - int threadNumber = 0; - for (Enumeration e = nestedTasks.elements(); e.hasMoreElements(); - threadNumber++) { - Task nestedTask = (Task) e.nextElement(); - runnables[threadNumber] - = new TaskRunnable(nestedTask); - } + TaskRunnable[] runnables = nestedTasks.stream().map(TaskRunnable::new) + .toArray(TaskRunnable[]::new); + final int numTasks = nestedTasks.size(); final int maxRunning = numTasks < numThreads ? numTasks : numThreads; - TaskRunnable[] running = new TaskRunnable[maxRunning]; - threadNumber = 0; + TaskRunnable[] running = new TaskRunnable[maxRunning]; ThreadGroup group = new ThreadGroup("parallel"); TaskRunnable[] daemons = null; - if (daemonTasks != null && daemonTasks.tasks.size() != 0) { + if (!(daemonTasks == null || daemonTasks.tasks.isEmpty())) { daemons = new TaskRunnable[daemonTasks.tasks.size()]; } @@ -292,7 +285,7 @@ public class Parallel extends Task // start any daemon threads if (daemons != null) { for (int i = 0; i < daemons.length; ++i) { - daemons[i] = new TaskRunnable((Task) daemonTasks.tasks.get(i)); + daemons[i] = new TaskRunnable(daemonTasks.tasks.get(i)); Thread daemonThread = new Thread(group, daemons[i]); daemonThread.setDaemon(true); daemonThread.start(); @@ -301,6 +294,7 @@ public class Parallel extends Task // now run main threads in limited numbers... // start initial batch of threads + int threadNumber = 0; for (int i = 0; i < maxRunning; ++i) { running[i] = runnables[threadNumber++]; Thread thread = new Thread(group, running[i]); @@ -310,6 +304,7 @@ public class Parallel extends Task if (timeout != 0) { // start the timeout thread Thread timeoutThread = new Thread() { + @Override public synchronized void run() { try { final long start = System.currentTimeMillis(); @@ -393,17 +388,16 @@ public class Parallel extends Task if (numExceptions == 1) { if (firstException instanceof BuildException) { throw (BuildException) firstException; - } else { - throw new BuildException(firstException); } - } else if (numExceptions > 1) { + throw new BuildException(firstException); + } + if (numExceptions > 1) { if (firstExitStatus == null) { throw new BuildException(exceptionMessage.toString(), firstLocation); - } else { - throw new ExitStatusException(exceptionMessage.toString(), - firstExitStatus, firstLocation); } + throw new ExitStatusException(exceptionMessage.toString(), + firstExitStatus, firstLocation); } } @@ -453,6 +447,7 @@ public class Parallel extends Task * Executes the task within a thread and takes care about * Exceptions raised within the task. */ + @Override public void run() { try { LocalProperties.get(getProject()).copy();
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Patch.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Patch.java b/src/main/org/apache/tools/ant/taskdefs/Patch.java index 96ab082..3d9d099 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Patch.java +++ b/src/main/org/apache/tools/ant/taskdefs/Patch.java @@ -165,12 +165,13 @@ public class Patch extends Task { * execute patch * @throws BuildException when it all goes a bit pear shaped */ + @Override public void execute() throws BuildException { if (!havePatchfile) { throw new BuildException("patchfile argument is required", getLocation()); } - Commandline toExecute = (Commandline) cmd.clone(); + Commandline toExecute = cmd.clone(); toExecute.setExecutable(PATCH); if (originalFile != null) { @@ -182,18 +183,14 @@ public class Patch extends Task { null); exe.setCommandline(toExecute.getCommandline()); - if (directory != null) { - if (directory.exists() && directory.isDirectory()) { - exe.setWorkingDirectory(directory); - } else if (!directory.isDirectory()) { + if (directory == null) { + exe.setWorkingDirectory(getProject().getBaseDir()); + } else { + if (!directory.isDirectory()) { throw new BuildException(directory + " is not a directory.", getLocation()); - } else { - throw new BuildException("directory " + directory - + " doesn\'t exist", getLocation()); } - } else { - exe.setWorkingDirectory(getProject().getBaseDir()); + exe.setWorkingDirectory(directory); } log(toExecute.describeCommand(), Project.MSG_VERBOSE); @@ -204,9 +201,8 @@ public class Patch extends Task { + returncode; if (failOnError) { throw new BuildException(msg); - } else { - log(msg, Project.MSG_ERR); } + log(msg, Project.MSG_ERR); } } catch (IOException e) { throw new BuildException(e, getLocation()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/PathConvert.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/PathConvert.java b/src/main/org/apache/tools/ant/taskdefs/PathConvert.java index abbc5fd..3adb05e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/PathConvert.java +++ b/src/main/org/apache/tools/ant/taskdefs/PathConvert.java @@ -19,7 +19,6 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; @@ -81,7 +80,7 @@ public class PathConvert extends Task { /** * Path prefix map */ - private Vector prefixMap = new Vector(); + private List<MapEntry> prefixMap = new Vector<>(); /** * User override on path sep char */ @@ -97,12 +96,6 @@ public class PathConvert extends Task { private boolean preserveDuplicates; /** - * Construct a new instance of the PathConvert task. - */ - public PathConvert() { - } - - /** * Helper class, holds the nested <map> values. Elements will look like * this: <map from="d:" to="/foo"/> * @@ -142,8 +135,8 @@ public class PathConvert extends Task { */ public String apply(String elem) { if (from == null || to == null) { - throw new BuildException("Both 'from' and 'to' must be set " - + "in a map entry"); + throw new BuildException( + "Both 'from' and 'to' must be set in a map entry"); } // If we're on windows, then do the comparison ignoring case // and treat the two directory characters the same @@ -170,7 +163,8 @@ public class PathConvert extends Task { */ @Override public String[] getValues() { - return new String[]{"windows", "unix", "netware", "os/2", "tandem"}; + return new String[] { "windows", "unix", "netware", "os/2", + "tandem" }; } } @@ -213,7 +207,7 @@ public class PathConvert extends Task { */ public MapEntry createMap() { MapEntry entry = new MapEntry(); - prefixMap.addElement(entry); + prefixMap.add(entry); return entry; } @@ -251,7 +245,7 @@ public class PathConvert extends Task { // validateSetup code, the same assumptions can be made as // with windows - that ; is the path separator - targetWindows = !targetOS.equals("unix") && !targetOS.equals("tandem"); + targetWindows = !"unix".equals(targetOS) && !"tandem".equals(targetOS); } /** @@ -293,7 +287,6 @@ public class PathConvert extends Task { pathSep = sep; } - /** * Set the default directory separator string; * defaults to current JVM {@link java.io.File#separator File.separator}. @@ -344,8 +337,9 @@ public class PathConvert extends Task { if (isReference()) { Object o = refid.getReferencedObject(getProject()); if (!(o instanceof ResourceCollection)) { - throw new BuildException("refid '" + refid.getRefId() - + "' does not refer to a resource collection."); + throw new BuildException( + "refid '%s' does not refer to a resource collection.", + refid.getRefId()); } getPath().add((ResourceCollection) o); } @@ -361,10 +355,10 @@ public class PathConvert extends Task { // case-insensitive. String fromDirSep = onWindows ? "\\" : "/"; - StringBuffer rslt = new StringBuffer(); + StringBuilder rslt = new StringBuilder(); ResourceCollection resources = isPreserveDuplicates() ? (ResourceCollection) path : new Union(path); - List ret = new ArrayList(); + List<String> ret = new ArrayList<>(); FileNameMapper mapperImpl = mapper == null ? new IdentityMapper() : mapper.getImplementation(); for (Resource r : resources) { String[] mapped = mapperImpl.mapFileName(String.valueOf(r)); @@ -373,8 +367,8 @@ public class PathConvert extends Task { } } boolean first = true; - for (Iterator mappedIter = ret.iterator(); mappedIter.hasNext();) { - String elem = mapElement((String) mappedIter.next()); // Apply the path prefix map + for (String string : ret) { + String elem = mapElement(string); // Apply the path prefix map // Now convert the path and file separator characters from the // current os to the target os. @@ -418,25 +412,17 @@ public class PathConvert extends Task { * @return String Updated element. */ private String mapElement(String elem) { + // Iterate over the map entries and apply each one. + // Stop when one of the entries actually changes the element. - int size = prefixMap.size(); + for (MapEntry entry : prefixMap) { + String newElem = entry.apply(elem); - if (size != 0) { + // Note I'm using "!=" to see if we got a new object back from + // the apply method. - // Iterate over the map entries and apply each one. - // Stop when one of the entries actually changes the element. - - for (int i = 0; i < size; i++) { - MapEntry entry = (MapEntry) prefixMap.elementAt(i); - String newElem = entry.apply(elem); - - // Note I'm using "!=" to see if we got a new object back from - // the apply method. - - if (newElem != elem) { - elem = newElem; - break; // We applied one, so we're done - } + if (newElem != elem) { + return newElem; } } return elem; @@ -503,9 +489,8 @@ public class PathConvert extends Task { * @return BuildException. */ private BuildException noChildrenAllowed() { - return new BuildException("You must not specify nested " - + "elements when using the refid attribute."); + return new BuildException( + "You must not specify nested elements when using the refid attribute."); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/PreSetDef.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/PreSetDef.java b/src/main/org/apache/tools/ant/taskdefs/PreSetDef.java index fe57704..b343919 100644 --- a/src/main/org/apache/tools/ant/taskdefs/PreSetDef.java +++ b/src/main/org/apache/tools/ant/taskdefs/PreSetDef.java @@ -56,6 +56,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * Add a nested task to predefine attributes and elements on. * @param nestedTask Nested task/type to extend. */ + @Override public void addTask(Task nestedTask) { if (this.nestedTask != null) { throw new BuildException("Only one nested element allowed"); @@ -71,6 +72,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { /** * Make a new definition. */ + @Override public void execute() { if (nestedTask == null) { throw new BuildException("Missing nested element"); @@ -89,7 +91,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { AntTypeDefinition def = helper.getDefinition(componentName); if (def == null) { throw new BuildException( - "Unable to find typedef " + componentName); + "Unable to find typedef %s", componentName); } PreSetDefinition newDef = new PreSetDefinition(def, nestedTask); @@ -129,7 +131,8 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * * @param clazz a <code>Class</code> value. */ - public void setClass(Class clazz) { + @Override + public void setClass(Class<?> clazz) { throw new BuildException("Not supported"); } @@ -138,6 +141,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * * @param className a <code>String</code> value. */ + @Override public void setClassName(String className) { throw new BuildException("Not supported"); } @@ -146,6 +150,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * Get the classname of the definition. * @return the name of the class of this definition. */ + @Override public String getClassName() { return parent.getClassName(); } @@ -155,7 +160,8 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * NOT Supported * @param adapterClass the adapterClass. */ - public void setAdapterClass(Class adapterClass) { + @Override + public void setAdapterClass(Class<?> adapterClass) { throw new BuildException("Not supported"); } @@ -164,7 +170,8 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * NOT SUPPORTED * @param adaptToClass the assignable class. */ - public void setAdaptToClass(Class adaptToClass) { + @Override + public void setAdaptToClass(Class<?> adaptToClass) { throw new BuildException("Not supported"); } @@ -174,6 +181,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * NOT SUPPORTED * @param classLoader the classLoader. */ + @Override public void setClassLoader(ClassLoader classLoader) { throw new BuildException("Not supported"); } @@ -182,6 +190,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * Get the classloader for this definition. * @return the classloader for this definition. */ + @Override public ClassLoader getClassLoader() { return parent.getClassLoader(); } @@ -191,7 +200,8 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * @param project the current project. * @return the exposed class. */ - public Class getExposedClass(Project project) { + @Override + public Class<?> getExposedClass(Project project) { return parent.getExposedClass(project); } @@ -200,7 +210,8 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * @param project the current project. * @return the type of the definition. */ - public Class getTypeClass(Project project) { + @Override + public Class<?> getTypeClass(Project project) { return parent.getTypeClass(project); } @@ -209,6 +220,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * Check if the attributes are correct. * @param project the current project. */ + @Override public void checkClass(Project project) { parent.checkClass(project); } @@ -240,6 +252,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * @param project the current project. * @return this object. */ + @Override public Object create(Project project) { return this; } @@ -251,6 +264,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * @param project the current project. * @return true if the definitions are the same. */ + @Override public boolean sameDefinition(AntTypeDefinition other, Project project) { return (other != null && other.getClass() == getClass() && parent != null && parent.sameDefinition(((PreSetDefinition) other).parent, project) @@ -264,6 +278,7 @@ public class PreSetDef extends AntlibDefinition implements TaskContainer { * @param project the current project. * @return true if the definitions are similar. */ + @Override public boolean similarDefinition( AntTypeDefinition other, Project project) { return (other != null && other.getClass().getName().equals( http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java b/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java index bc3ff49..acc69a0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java +++ b/src/main/org/apache/tools/ant/taskdefs/ProcessDestroyer.java @@ -21,7 +21,7 @@ package org.apache.tools.ant.taskdefs; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; -import java.util.Iterator; +import java.util.Set; /** * Destroys all registered <code>Process</code>es when the VM exits. @@ -30,7 +30,8 @@ import java.util.Iterator; */ class ProcessDestroyer implements Runnable { private static final int THREAD_DIE_TIMEOUT = 20000; - private HashSet processes = new HashSet(); + + private Set<Process> processes = new HashSet<>(); // methods to register and unregister shutdown hooks private Method addShutdownHookMethod; private Method removeShutdownHookMethod; @@ -49,6 +50,7 @@ class ProcessDestroyer implements Runnable { public ProcessDestroyerImpl() { super("ProcessDestroyer Shutdown Hook"); } + @Override public void run() { if (shouldDestroy) { ProcessDestroyer.this.run(); @@ -74,12 +76,11 @@ class ProcessDestroyer implements Runnable { try { // check to see if the shutdown hook methods exists // (support pre-JDK 1.3 and Non-Sun VMs) - Class[] paramTypes = {Thread.class}; addShutdownHookMethod = - Runtime.class.getMethod("addShutdownHook", paramTypes); + Runtime.class.getMethod("addShutdownHook", Thread.class); removeShutdownHookMethod = - Runtime.class.getMethod("removeShutdownHook", paramTypes); + Runtime.class.getMethod("removeShutdownHook", Thread.class); // wait to add shutdown hook as needed } catch (NoSuchMethodException e) { // it just won't be added as a shutdown hook... :( @@ -95,9 +96,8 @@ class ProcessDestroyer implements Runnable { private void addShutdownHook() { if (addShutdownHookMethod != null && !running) { destroyProcessThread = new ProcessDestroyerImpl(); - Object[] args = {destroyProcessThread}; try { - addShutdownHookMethod.invoke(Runtime.getRuntime(), args); + addShutdownHookMethod.invoke(Runtime.getRuntime(), destroyProcessThread); added = true; } catch (IllegalAccessException e) { e.printStackTrace(); //NOSONAR @@ -119,13 +119,9 @@ class ProcessDestroyer implements Runnable { */ private void removeShutdownHook() { if (removeShutdownHookMethod != null && added && !running) { - Object[] args = {destroyProcessThread}; try { - Boolean removed = - (Boolean) removeShutdownHookMethod.invoke( - Runtime.getRuntime(), - args); - if (!removed.booleanValue()) { + if (!Boolean.TRUE.equals(removeShutdownHookMethod + .invoke(Runtime.getRuntime(), destroyProcessThread))) { System.err.println("Could not remove shutdown hook"); } } catch (IllegalAccessException e) { @@ -180,7 +176,7 @@ class ProcessDestroyer implements Runnable { public boolean add(Process process) { synchronized (processes) { // if this list is empty, register the shutdown hook - if (processes.size() == 0) { + if (processes.isEmpty()) { addShutdownHook(); } return processes.add(process); @@ -198,7 +194,7 @@ class ProcessDestroyer implements Runnable { public boolean remove(Process process) { synchronized (processes) { boolean processRemoved = processes.remove(process); - if (processRemoved && processes.size() == 0) { + if (processRemoved && processes.isEmpty()) { removeShutdownHook(); } return processRemoved; @@ -208,13 +204,11 @@ class ProcessDestroyer implements Runnable { /** * Invoked by the VM when it is exiting. */ + @Override public void run() { synchronized (processes) { running = true; - Iterator e = processes.iterator(); - while (e.hasNext()) { - ((Process) e.next()).destroy(); - } + processes.forEach(Process::destroy); } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java b/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java index 8f348a7..726913f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ProjectHelperTask.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.apache.tools.ant.BuildException; @@ -33,7 +32,7 @@ import org.apache.tools.ant.Task; */ public class ProjectHelperTask extends Task { - private List projectHelpers = new ArrayList(); + private List<ProjectHelper> projectHelpers = new ArrayList<>(); public synchronized void addConfigured(ProjectHelper projectHelper) { this.projectHelpers.add(projectHelper); @@ -41,10 +40,7 @@ public class ProjectHelperTask extends Task { @Override public void execute() throws BuildException { - ProjectHelperRepository repo = ProjectHelperRepository.getInstance(); - for (Iterator it = projectHelpers.iterator(); it.hasNext();) { - ProjectHelper helper = (ProjectHelper) it.next(); - repo.registerProjectHelper(helper.getClass()); - } + projectHelpers.stream().map(ProjectHelper::getClass).forEach( + ProjectHelperRepository.getInstance()::registerProjectHelper); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Property.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Property.java b/src/main/org/apache/tools/ant/taskdefs/Property.java index c8f33be..ebe73de 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Property.java +++ b/src/main/org/apache/tools/ant/taskdefs/Property.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; @@ -218,9 +217,8 @@ public class Property extends Task { msg = currentValue + msg; } internalSetValue(msg); - } else if (msg.trim().length() > 0) { - throw new BuildException("can't combine nested text with value" - + " attribute"); + } else if (!msg.trim().isEmpty()) { + throw new BuildException("can't combine nested text with value attribute"); } } @@ -460,27 +458,31 @@ public class Property extends Task { if (name != null) { if (untypedValue == null && ref == null) { - throw new BuildException("You must specify value, location or " - + "refid with the name attribute", - getLocation()); + throw new BuildException( + "You must specify value, location or refid with the name attribute", + getLocation()); } } else { - if (url == null && file == null && resource == null && env == null) { - throw new BuildException("You must specify url, file, resource or " - + "environment when not using the " - + "name attribute", getLocation()); + if (url == null && file == null && resource == null + && env == null) { + throw new BuildException( + "You must specify url, file, resource or environment when not using the name attribute", + getLocation()); } } if (url == null && file == null && resource == null && prefix != null) { - throw new BuildException("Prefix is only valid when loading from " - + "a url, file or resource", getLocation()); + throw new BuildException( + "Prefix is only valid when loading from a url, file or resource", + getLocation()); } if (name != null && untypedValue != null) { if (relative) { try { - File from = untypedValue instanceof File ? (File)untypedValue : new File(untypedValue.toString()); + File from = + untypedValue instanceof File ? (File) untypedValue + : new File(untypedValue.toString()); File to = basedir != null ? basedir : getProject().getBaseDir(); String relPath = FileUtils.getRelativePath(to, from); relPath = relPath.replace('/', File.separatorChar); @@ -575,12 +577,8 @@ public class Property extends Task { log("Loading " + file.getAbsolutePath(), Project.MSG_VERBOSE); try { if (file.exists()) { - InputStream fis = null; - try { - fis = Files.newInputStream(file.toPath()); + try (InputStream fis = Files.newInputStream(file.toPath())) { loadProperties(props, fis, file.getName().endsWith(".xml")); - } finally { - FileUtils.close(fis); } addProperties(props); } else { @@ -599,17 +597,16 @@ public class Property extends Task { protected void loadResource(String name) { Properties props = new Properties(); log("Resource Loading " + name, Project.MSG_VERBOSE); - InputStream is = null; ClassLoader cL = null; boolean cleanup = false; + if (classpath != null) { + cleanup = true; + cL = getProject().createClassLoader(classpath); + } else { + cL = this.getClass().getClassLoader(); + } + InputStream is = null; try { - if (classpath != null) { - cleanup = true; - cL = getProject().createClassLoader(classpath); - } else { - cL = this.getClass().getClassLoader(); - } - if (cL == null) { is = ClassLoader.getSystemResourceAsStream(name); } else { @@ -642,9 +639,8 @@ public class Property extends Task { prefix += "."; } log("Loading Environment " + prefix, Project.MSG_VERBOSE); - Map osEnv = Execute.getEnvironmentVariables(); - for (Iterator e = osEnv.entrySet().iterator(); e.hasNext();) { - Map.Entry entry = (Map.Entry) e.next(); + Map<String, String> osEnv = Execute.getEnvironmentVariables(); + for (Map.Entry<String, String> entry : osEnv.entrySet()) { props.put(prefix + entry.getKey(), entry.getValue()); } addProperties(props); @@ -656,18 +652,17 @@ public class Property extends Task { * @param props the properties to iterate over */ protected void addProperties(Properties props) { - HashMap m = new HashMap(props); - resolveAllProperties(m); - for (Iterator it = m.keySet().iterator(); it.hasNext();) { - Object k = it.next(); + Map<String, Object> m = new HashMap<>(); + props.forEach((k, v) -> { if (k instanceof String) { - String propertyName = (String) k; - if (prefix != null) { - propertyName = prefix + propertyName; - } - addProperty(propertyName, m.get(k)); + m.put((String) k, v); } - } + }); + resolveAllProperties(m); + m.forEach((k, v) -> { + String propertyName = prefix == null ? k : prefix + k; + addProperty(propertyName, v); + }); } /** @@ -702,7 +697,7 @@ public class Property extends Task { * resolve properties inside a properties hashtable * @param props properties object to resolve */ - private void resolveAllProperties(Map props) throws BuildException { + private void resolveAllProperties(Map<String, Object> props) throws BuildException { PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(getProject()); new ResolvePropertyMap( http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/PropertyHelperTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/PropertyHelperTask.java b/src/main/org/apache/tools/ant/taskdefs/PropertyHelperTask.java index 5e8867a..5017fc3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/PropertyHelperTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/PropertyHelperTask.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.apache.tools.ant.BuildException; @@ -69,7 +68,7 @@ public class PropertyHelperTask extends Task { } private PropertyHelper propertyHelper; - private List delegates; + private List<Object> delegates; /** * Add a new PropertyHelper to be set on the Project. @@ -104,13 +103,14 @@ public class PropertyHelperTask extends Task { * Execute the task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { if (getProject() == null) { throw new BuildException("Project instance not set"); } if (propertyHelper == null && delegates == null) { - throw new BuildException("Either a new PropertyHelper" - + " or one or more PropertyHelper delegates are required"); + throw new BuildException( + "Either a new PropertyHelper or one or more PropertyHelper delegates are required"); } PropertyHelper ph = propertyHelper; if (ph == null) { @@ -120,8 +120,7 @@ public class PropertyHelperTask extends Task { } synchronized (ph) { if (delegates != null) { - for (Iterator iter = delegates.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : delegates) { PropertyHelper.Delegate delegate = o instanceof DelegateElement ? ((DelegateElement) o).resolve() : (PropertyHelper.Delegate) o; log("Adding PropertyHelper delegate " + delegate, Project.MSG_DEBUG); @@ -136,9 +135,9 @@ public class PropertyHelperTask extends Task { } } - private synchronized List getAddDelegateList() { + private synchronized List<Object> getAddDelegateList() { if (delegates == null) { - delegates = new ArrayList(); + delegates = new ArrayList<>(); } return delegates; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Replace.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Replace.java b/src/main/org/apache/tools/ant/taskdefs/Replace.java index 5090345..4213ef8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Replace.java +++ b/src/main/org/apache/tools/ant/taskdefs/Replace.java @@ -34,6 +34,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; +import java.util.Objects; import java.util.Properties; import org.apache.tools.ant.BuildException; @@ -69,7 +70,7 @@ public class Replace extends MatchingTask { private Resource propertyResource = null; private Resource replaceFilterResource = null; private Properties properties = null; - private ArrayList replacefilters = new ArrayList(); + private List<Replacefilter> replacefilters = new ArrayList<>(); private File dir = null; @@ -144,39 +145,34 @@ public class Replace extends MatchingTask { public void validate() throws BuildException { //Validate mandatory attributes if (token == null) { - String message = "token is a mandatory for replacefilter."; - throw new BuildException(message); + throw new BuildException( + "token is a mandatory for replacefilter."); } if ("".equals(token.getText())) { - String message = "The token must not be an empty " - + "string."; - throw new BuildException(message); + throw new BuildException( + "The token must not be an empty string."); } //value and property are mutually exclusive attributes if ((value != null) && (property != null)) { - String message = "Either value or property " - + "can be specified, but a replacefilter " - + "element cannot have both."; - throw new BuildException(message); + throw new BuildException( + "Either value or property can be specified, but a replacefilter element cannot have both."); } if ((property != null)) { //the property attribute must have access to a property file if (propertyResource == null) { - String message = "The replacefilter's property attribute " - + "can only be used with the replacetask's " - + "propertyFile/Resource attribute."; - throw new BuildException(message); + throw new BuildException( + "The replacefilter's property attribute can only be used with the replacetask's propertyFile/Resource attribute."); } //Make sure property exists in property file if (properties == null || properties.getProperty(property) == null) { - String message = "property \"" + property - + "\" was not found in " + propertyResource.getName(); - throw new BuildException(message); + throw new BuildException( + "property \"%s\" was not found in %s", property, + propertyResource.getName()); } } @@ -190,14 +186,15 @@ public class Replace extends MatchingTask { public String getReplaceValue() { if (property != null) { return properties.getProperty(property); - } else if (value != null) { + } + if (value != null) { return value.getText(); - } else if (Replace.this.value != null) { + } + if (Replace.this.value != null) { return Replace.this.value.getText(); - } else { - //Default is empty string - return ""; } + //Default is empty string + return ""; } /** @@ -354,11 +351,12 @@ public class Replace extends MatchingTask { * @since 1.7 */ private class FileInput implements AutoCloseable { + private static final int BUFF_SIZE = 4096; + private StringBuffer outputBuffer; private final InputStream is; private Reader reader; private char[] buffer; - private static final int BUFF_SIZE = 4096; /** * Constructs the input component. Opens the file for reading. @@ -370,7 +368,9 @@ public class Replace extends MatchingTask { buffer = new char[BUFF_SIZE]; is = Files.newInputStream(source.toPath()); try { - reader = new BufferedReader(encoding != null ? new InputStreamReader(is, encoding) : new InputStreamReader(is)); + reader = new BufferedReader( + encoding != null ? new InputStreamReader(is, encoding) + : new InputStreamReader(is)); } finally { if (reader == null) { is.close(); @@ -393,8 +393,7 @@ public class Replace extends MatchingTask { * @throws IOException When the file cannot be read from. */ boolean readChunk() throws IOException { - int bufferLength = 0; - bufferLength = reader.read(buffer); + int bufferLength = reader.read(buffer); if (bufferLength < 0) { return false; } @@ -406,6 +405,7 @@ public class Replace extends MatchingTask { * Closes the file. * @throws IOException When the file cannot be closed. */ + @Override public void close() throws IOException { is.close(); } @@ -430,7 +430,9 @@ public class Replace extends MatchingTask { FileOutput(File out) throws IOException { os = Files.newOutputStream(out.toPath()); try { - writer = new BufferedWriter(encoding != null ? new OutputStreamWriter(os, encoding) : new OutputStreamWriter(os)); + writer = new BufferedWriter( + encoding != null ? new OutputStreamWriter(os, encoding) + : new OutputStreamWriter(os)); } finally { if (writer == null) { os.close(); @@ -476,6 +478,7 @@ public class Replace extends MatchingTask { * Closes the file. * @throws IOException When the file cannot be closed. */ + @Override public void close() throws IOException { os.close(); } @@ -486,9 +489,9 @@ public class Replace extends MatchingTask { * Do the execution. * @throws BuildException if we can't build */ + @Override public void execute() throws BuildException { - - ArrayList savedFilters = (ArrayList) replacefilters.clone(); + List<Replacefilter> savedFilters = new ArrayList<>(replacefilters); Properties savedProperties = properties == null ? null : (Properties) properties.clone(); @@ -496,10 +499,10 @@ public class Replace extends MatchingTask { // line separators in values and tokens are "\n" // in order to compare with the file contents, replace them // as needed - StringBuffer val = new StringBuffer(value.getText()); + StringBuilder val = new StringBuilder(value.getText()); stringReplace(val, "\r\n", "\n"); stringReplace(val, "\n", StringUtils.LINE_SEP); - StringBuffer tok = new StringBuffer(token.getText()); + StringBuilder tok = new StringBuilder(token.getText()); stringReplace(tok, "\r\n", "\n"); stringReplace(tok, "\n", StringUtils.LINE_SEP); Replacefilter firstFilter = createPrimaryfilter(); @@ -510,7 +513,7 @@ public class Replace extends MatchingTask { try { if (replaceFilterResource != null) { Properties props = getProperties(replaceFilterResource); - Iterator e = getOrderedIterator(props); + Iterator<Object> e = getOrderedIterator(props); while (e.hasNext()) { String tok = e.next().toString(); Replacefilter replaceFilter = createReplacefilter(); @@ -535,19 +538,15 @@ public class Replace extends MatchingTask { if (dir != null) { DirectoryScanner ds = super.getDirectoryScanner(dir); - String[] srcs = ds.getIncludedFiles(); - - for (int i = 0; i < srcs.length; i++) { - File file = new File(dir, srcs[i]); + for (String src : ds.getIncludedFiles()) { + File file = new File(dir, src); processFile(file); } } if (resources != null) { for (Resource r : resources) { - FileProvider fp = - r.as(FileProvider.class); - processFile(fp.getFile()); + processFile(r.as(FileProvider.class).getFile()); } } @@ -573,23 +572,24 @@ public class Replace extends MatchingTask { */ public void validateAttributes() throws BuildException { if (sourceFile == null && dir == null && resources == null) { - String message = "Either the file or the dir attribute " - + "or nested resources must be specified"; - throw new BuildException(message, getLocation()); + throw new BuildException( + "Either the file or the dir attribute or nested resources must be specified", + getLocation()); } if (propertyResource != null && !propertyResource.isExists()) { - String message = "Property file " + propertyResource.getName() - + " does not exist."; - throw new BuildException(message, getLocation()); + throw new BuildException("Property file " + + propertyResource.getName() + " does not exist.", + getLocation()); } - if (token == null && replacefilters.size() == 0) { - String message = "Either token or a nested replacefilter " - + "must be specified"; - throw new BuildException(message, getLocation()); + if (token == null && replacefilters.isEmpty()) { + throw new BuildException( + "Either token or a nested replacefilter must be specified", + getLocation()); } if (token != null && "".equals(token.getText())) { - String message = "The token attribute must not be an empty string."; - throw new BuildException(message, getLocation()); + throw new BuildException( + "The token attribute must not be an empty string.", + getLocation()); } } @@ -601,12 +601,7 @@ public class Replace extends MatchingTask { */ public void validateReplacefilters() throws BuildException { - final int size = replacefilters.size(); - for (int i = 0; i < size; i++) { - Replacefilter element = - (Replacefilter) replacefilters.get(i); - element.validate(); - } + replacefilters.forEach(Replacefilter::validate); } /** @@ -630,18 +625,14 @@ public class Replace extends MatchingTask { throws BuildException { Properties props = new Properties(); - InputStream in = null; - try { - in = propertyResource.getInputStream(); + try ( + InputStream + in = propertyResource.getInputStream()){ props.load(in); } catch (IOException e) { - String message = "Property resource (" + propertyResource.getName() - + ") cannot be loaded."; - throw new BuildException(message); - } finally { - FileUtils.close(in); + throw new BuildException("Property resource (%s) cannot be loaded.", + propertyResource.getName()); } - return props; } @@ -705,11 +696,7 @@ public class Replace extends MatchingTask { * Flushes all filters. */ private void flushFilterChain() { - final int size = replacefilters.size(); - for (int i = 0; i < size; i++) { - Replacefilter filter = (Replacefilter) replacefilters.get(i); - filter.flush(); - } + replacefilters.forEach(Replacefilter::flush); } /** @@ -717,14 +704,7 @@ public class Replace extends MatchingTask { * @return true if the filter chain produced new output. */ private boolean processFilterChain() { - final int size = replacefilters.size(); - for (int i = 0; i < size; i++) { - Replacefilter filter = (Replacefilter) replacefilters.get(i); - if (!filter.process()) { - return false; - } - } - return true; + return replacefilters.stream().allMatch(Replacefilter::process); } /** @@ -737,7 +717,7 @@ public class Replace extends MatchingTask { StringBuffer buf = inputBuffer; final int size = replacefilters.size(); for (int i = 0; i < size; i++) { - Replacefilter filter = (Replacefilter) replacefilters.get(i); + Replacefilter filter = replacefilters.get(i); filter.setInputBuffer(buf); buf = filter.getOutputBuffer(); } @@ -749,13 +729,14 @@ public class Replace extends MatchingTask { * @param filename <code>String</code>. */ private void logFilterChain(String filename) { - final int size = replacefilters.size(); - for (int i = 0; i < size; i++) { - Replacefilter filter = (Replacefilter) replacefilters.get(i); - log("Replacing in " + filename + ": " + filter.getToken() - + " --> " + filter.getReplaceValue(), Project.MSG_VERBOSE); - } + replacefilters + .forEach( + filter -> log( + "Replacing in " + filename + ": " + filter.getToken() + + " --> " + filter.getReplaceValue(), + Project.MSG_VERBOSE)); } + /** * Set the source file; required unless <code>dir</code> is set. * @param file source <code>File</code>. @@ -937,7 +918,7 @@ public class Replace extends MatchingTask { /** * Replace occurrences of str1 in StringBuffer str with str2. */ - private void stringReplace(StringBuffer str, String str1, String str2) { + private void stringReplace(StringBuilder str, String str1, String str2) { int found = str.indexOf(str1); final int str1Length = str1.length(); final int str2Length = str2.length(); @@ -952,17 +933,9 @@ public class Replace extends MatchingTask { * strings are tried later. */ private Iterator<Object> getOrderedIterator(Properties props) { - List<Object> keys = new ArrayList<Object>(props.keySet()); - Collections.sort(keys, new Comparator<Object>() { - //Override annotation is not supported as long as we want to support building Ant on Java 1.5 - public int compare(Object key1, Object key2) { - return compare(key1.toString(), key2.toString()); - } - - private int compare(String key1, String key2) { - return key2.length() - key1.length(); - } - }); + List<Object> keys = new ArrayList<>(props.keySet()); + Collections.sort(keys, Comparator + .comparingInt(o -> Objects.toString(o, "").length()).reversed()); return keys.iterator(); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ResourceCount.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ResourceCount.java b/src/main/org/apache/tools/ant/taskdefs/ResourceCount.java index b29b57b..68a630a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ResourceCount.java +++ b/src/main/org/apache/tools/ant/taskdefs/ResourceCount.java @@ -61,8 +61,8 @@ public class ResourceCount extends Task implements Condition { public void setRefid(Reference r) { Object o = r.getReferencedObject(); if (!(o instanceof ResourceCollection)) { - throw new BuildException(r.getRefId() - + " doesn\'t denote a ResourceCollection"); + throw new BuildException("%s doesn\'t denote a ResourceCollection", + r.getRefId()); } add((ResourceCollection) o); } @@ -70,6 +70,7 @@ public class ResourceCount extends Task implements Condition { /** * Execute as a Task. */ + @Override public void execute() { if (rc == null) { throw new BuildException(ONE_NESTED_MESSAGE); @@ -86,6 +87,7 @@ public class ResourceCount extends Task implements Condition { * @return true if the specified ResourceCollection satisfies the set criteria. * @throws BuildException if an error occurs. */ + @Override public boolean eval() { if (rc == null) { throw new BuildException(ONE_NESTED_MESSAGE); @@ -93,7 +95,7 @@ public class ResourceCount extends Task implements Condition { if (count == null) { throw new BuildException(COUNT_REQUIRED); } - return when.evaluate(new Integer(rc.size()).compareTo(count)); + return when.evaluate(Integer.valueOf(rc.size()).compareTo(count)); } /** @@ -101,7 +103,7 @@ public class ResourceCount extends Task implements Condition { * @param c number of Resources as int. */ public void setCount(int c) { - count = new Integer(c); + count = Integer.valueOf(c); } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Retry.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Retry.java b/src/main/org/apache/tools/ant/taskdefs/Retry.java index bca5c15..564d80e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Retry.java +++ b/src/main/org/apache/tools/ant/taskdefs/Retry.java @@ -48,11 +48,11 @@ public class Retry extends Task implements TaskContainer { * set the task * @param t the task to retry. */ + @Override public synchronized void addTask(Task t) { if (nestedTask != null) { throw new BuildException( - "The retry task container accepts a single nested task" - + " (which may be a sequential task container)"); + "The retry task container accepts a single nested task (which may be a sequential task container)"); } nestedTask = t; } @@ -81,8 +81,9 @@ public class Retry extends Task implements TaskContainer { * perform the work * @throws BuildException if there is an error. */ + @Override public void execute() throws BuildException { - StringBuffer errorMessages = new StringBuffer(); + StringBuilder errorMessages = new StringBuilder(); for (int i = 0; i <= retryCount; i++) { try { nestedTask.perform(); @@ -90,7 +91,7 @@ public class Retry extends Task implements TaskContainer { } catch (Exception e) { errorMessages.append(e.getMessage()); if (i >= retryCount) { - StringBuffer exceptionMessage = new StringBuffer(); + StringBuilder exceptionMessage = new StringBuilder(); exceptionMessage.append("Task [").append(nestedTask.getTaskName()); exceptionMessage.append("] failed after [").append(retryCount); exceptionMessage.append("] attempts; giving up.").append(StringUtils.LINE_SEP); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Rmic.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Rmic.java b/src/main/org/apache/tools/ant/taskdefs/Rmic.java index 6935f9e..c24adfb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Rmic.java +++ b/src/main/org/apache/tools/ant/taskdefs/Rmic.java @@ -21,6 +21,7 @@ import java.io.File; import java.io.IOException; import java.rmi.Remote; import java.util.Vector; +import java.util.stream.Stream; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; @@ -90,6 +91,23 @@ public class Rmic extends MatchingTask { /** rmic failed message */ public static final String ERROR_RMIC_FAILED = "Rmic failed; see the compiler error output for details."; + + /** unable to verify message */ + public static final String ERROR_UNABLE_TO_VERIFY_CLASS = "Unable to verify class "; + /** could not be found message */ + public static final String ERROR_NOT_FOUND = ". It could not be found."; + /** not defined message */ + public static final String ERROR_NOT_DEFINED = ". It is not defined."; + /** loaded error message */ + public static final String ERROR_LOADING_CAUSED_EXCEPTION = ". Loading caused Exception: "; + /** base not exists message */ + public static final String ERROR_NO_BASE_EXISTS = "base or destdir does not exist: "; + /** base not a directory message */ + public static final String ERROR_NOT_A_DIR = "base or destdir is not a directory:"; + /** base attribute not set message */ + public static final String ERROR_BASE_NOT_SET = "base or destdir attribute must be set!"; + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); private File baseDir; private File destDir; @@ -109,28 +127,11 @@ public class Rmic extends MatchingTask { private boolean includeAntRuntime = true; private boolean includeJavaRuntime = false; - private Vector compileList = new Vector(); + private Vector<String> compileList = new Vector<>(); private AntClassLoader loader = null; private FacadeTaskHelper facade; - /** unable to verify message */ - public static final String ERROR_UNABLE_TO_VERIFY_CLASS = "Unable to verify class "; - /** could not be found message */ - public static final String ERROR_NOT_FOUND = ". It could not be found."; - /** not defined message */ - public static final String ERROR_NOT_DEFINED = ". It is not defined."; - /** loaded error message */ - public static final String ERROR_LOADING_CAUSED_EXCEPTION = ". Loading caused Exception: "; - /** base not exists message */ - public static final String ERROR_NO_BASE_EXISTS = "base or destdir does not exist: "; - /** base not a directory message */ - public static final String ERROR_NOT_A_DIR = "base or destdir is not a directory:"; - /** base attribute not set message */ - public static final String ERROR_BASE_NOT_SET = "base or destdir attribute must be set!"; - - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - private String executable = null; private boolean listFiles = false; @@ -405,7 +406,7 @@ public class Rmic extends MatchingTask { * Gets file list to compile. * @return the list of files to compile. */ - public Vector getFileList() { + public Vector<String> getFileList() { return compileList; } @@ -484,7 +485,7 @@ public class Rmic extends MatchingTask { /** * @return the compile list. */ - public Vector getCompileList() { + public Vector<String> getCompileList() { return compileList; } @@ -496,7 +497,7 @@ public class Rmic extends MatchingTask { * @since Ant 1.5 */ public void setCompiler(String compiler) { - if (compiler.length() > 0) { + if (!compiler.isEmpty()) { facade.setImplementation(compiler); } } @@ -645,9 +646,7 @@ public class Rmic extends MatchingTask { + outputDir, Project.MSG_INFO); if (listFiles) { - for (int i = 0; i < fileCount; i++) { - log(compileList.get(i).toString()); - } + compileList.forEach(this::log); } // finally, lets execute the compiler!! @@ -668,11 +667,8 @@ public class Rmic extends MatchingTask { log("sourcebase attribute will be ignored.", Project.MSG_WARN); } else { - for (int j = 0; j < fileCount; j++) { - moveGeneratedFile(outputDir, sourceBase, - (String) compileList.elementAt(j), - adapter); - } + compileList.forEach(f -> moveGeneratedFile(outputDir, + sourceBase, f, adapter)); } } } finally { @@ -704,16 +700,14 @@ public class Rmic extends MatchingTask { + ".class"; String[] generatedFiles = adapter.getMapper().mapFileName(classFileName); - for (int i = 0; i < generatedFiles.length; i++) { - final String generatedFile = generatedFiles[i]; + for (String generatedFile : generatedFiles) { if (!generatedFile.endsWith(".class")) { // don't know how to handle that - a IDL file doesn't // have a corresponding Java source for example. continue; } - String sourceFileName = StringUtils.removeSuffix(generatedFile, - ".class") - + ".java"; + String sourceFileName = + StringUtils.removeSuffix(generatedFile, ".class") + ".java"; File oldFile = new File(baseDir, sourceFileName); if (!oldFile.exists()) { @@ -732,10 +726,9 @@ public class Rmic extends MatchingTask { } oldFile.delete(); } catch (IOException ioe) { - String msg = "Failed to copy " + oldFile + " to " + newFile - + " due to " - + ioe.getMessage(); - throw new BuildException(msg, ioe, getLocation()); + throw new BuildException("Failed to copy " + oldFile + " to " + + newFile + " due to " + ioe.getMessage(), ioe, + getLocation()); } } } @@ -759,11 +752,9 @@ public class Rmic extends MatchingTask { SourceFileScanner sfs = new SourceFileScanner(this); newFiles = sfs.restrict(files, baseDir, getOutputDir(), mapper); } - for (int i = 0; i < newFiles.length; i++) { - String name = newFiles[i].replace(File.separatorChar, '.'); - name = name.substring(0, name.lastIndexOf(".class")); - compileList.addElement(name); - } + Stream.of(newFiles).map(s -> s.replace(File.separatorChar, '.')) + .map(s -> s.substring(0, s.lastIndexOf(".class"))) + .forEach(compileList::add); } /** @@ -773,7 +764,7 @@ public class Rmic extends MatchingTask { */ public boolean isValidRmiRemote(String classname) { try { - Class testClass = loader.loadClass(classname); + Class<?> testClass = loader.loadClass(classname); // One cannot RMIC an interface for "classic" RMI (JRMP) if (testClass.isInterface() && !iiop && !idl) { return false; @@ -801,26 +792,17 @@ public class Rmic extends MatchingTask { * @return the topmost interface that extends Remote, or null if there * is none. */ - public Class getRemoteInterface(Class testClass) { - if (Remote.class.isAssignableFrom(testClass)) { - Class [] interfaces = testClass.getInterfaces(); - if (interfaces != null) { - for (int i = 0; i < interfaces.length; i++) { - if (Remote.class.isAssignableFrom(interfaces[i])) { - return interfaces[i]; - } - } - } - } - return null; + public Class<?> getRemoteInterface(Class<?> testClass) { + return Stream.of(testClass.getInterfaces()) + .filter(Remote.class::isAssignableFrom).findFirst().orElse(null); } /** * Check to see if the class or (super)interfaces implement * java.rmi.Remote. */ - private boolean isValidRmiRemote (Class testClass) { - return getRemoteInterface(testClass) != null; + private boolean isValidRmiRemote(Class<?> testClass) { + return Remote.class.isAssignableFrom(testClass); } /** @@ -837,7 +819,7 @@ public class Rmic extends MatchingTask { * implementation. */ public class ImplementationSpecificArgument extends - org.apache.tools.ant.util.facade.ImplementationSpecificArgument { + org.apache.tools.ant.util.facade.ImplementationSpecificArgument { /** * Only pass the specified argument if the * chosen compiler implementation matches the http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/SQLExec.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java index 3ef604d..daf4c21 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SQLExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/SQLExec.java @@ -21,12 +21,12 @@ import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; +import java.nio.charset.Charset; import java.sql.Blob; import java.sql.Connection; import java.sql.ResultSet; @@ -35,7 +35,7 @@ import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.sql.Types; -import java.util.Enumeration; +import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import java.util.Vector; @@ -91,7 +91,7 @@ public class SQLExec extends JDBCTask { /** @return the enumerated strings */ @Override public String[] getValues() { - return new String[] {NORMAL, ROW}; + return new String[] { NORMAL, ROW }; } } @@ -127,7 +127,7 @@ public class SQLExec extends JDBCTask { /** * SQL transactions to perform */ - private Vector transactions = new Vector(); + private List<Transaction> transactions = new Vector<>(); /** * SQL Statement delimiter @@ -351,7 +351,7 @@ public class SQLExec extends JDBCTask { */ public Transaction createTransaction() { Transaction t = new Transaction(); - transactions.addElement(t); + transactions.add(t); return t; } @@ -553,8 +553,8 @@ public class SQLExec extends JDBCTask { */ public void setCsvQuoteCharacter(String s) { if (s != null && s.length() > 1) { - throw new BuildException("The quote character must be a single" - + " character."); + throw new BuildException( + "The quote character must be a single character."); } csvQuoteChar = s; } @@ -603,17 +603,17 @@ public class SQLExec extends JDBCTask { */ @Override public void execute() throws BuildException { - Vector savedTransaction = (Vector) transactions.clone(); + List<Transaction> savedTransaction = new Vector<>(transactions); String savedSqlCommand = sqlCommand; sqlCommand = sqlCommand.trim(); try { - if (srcFile == null && sqlCommand.length() == 0 && resources == null) { - if (transactions.size() == 0) { - throw new BuildException("Source file or resource collection, " - + "transactions or sql statement " - + "must be set!", getLocation()); + if (srcFile == null && sqlCommand.isEmpty() && resources == null) { + if (transactions.isEmpty()) { + throw new BuildException( + "Source file or resource collection, transactions or sql statement must be set!", + getLocation()); } } @@ -677,10 +677,8 @@ public class SQLExec extends JDBCTask { } // Process all transactions - for (Enumeration e = transactions.elements(); - e.hasMoreElements();) { - - ((Transaction) e.nextElement()).runTransaction(out); + for (Transaction txn : transactions) { + txn.runTransaction(out); if (!isAutocommit()) { log("Committing transaction", Project.MSG_VERBOSE); getConnection().commit(); @@ -689,16 +687,10 @@ public class SQLExec extends JDBCTask { } finally { FileUtils.close(out); } - } catch (IOException e) { - closeQuietly(); - setErrorProperty(); - if (onError.equals("abort")) { - throw new BuildException(e, getLocation()); - } - } catch (SQLException e) { + } catch (IOException | SQLException e) { closeQuietly(); setErrorProperty(); - if (onError.equals("abort")) { + if ("abort".equals(onError)) { throw new BuildException(e, getLocation()); } } finally { @@ -727,10 +719,10 @@ public class SQLExec extends JDBCTask { protected void runStatements(Reader reader, PrintStream out) throws SQLException, IOException { StringBuffer sql = new StringBuffer(); - String line; BufferedReader in = new BufferedReader(reader); + String line; while ((line = in.readLine()) != null) { if (!keepformat) { line = line.trim(); @@ -782,7 +774,7 @@ public class SQLExec extends JDBCTask { */ protected void execSQL(String sql, PrintStream out) throws SQLException { // Check and ignore empty statements - if ("".equals(sql.trim())) { + if (sql.trim().isEmpty()) { return; } @@ -830,10 +822,10 @@ public class SQLExec extends JDBCTask { } catch (SQLException e) { log("Failed to execute: " + sql, Project.MSG_ERR); setErrorProperty(); - if (!onError.equals("abort")) { + if (!"abort".equals(onError)) { log(e.toString(), Project.MSG_ERR); } - if (!onError.equals("continue")) { + if (!"continue".equals(onError)) { throw e; } } finally { @@ -907,7 +899,7 @@ public class SQLExec extends JDBCTask { if (csvQuoteChar == null || s == null || (!forceCsvQuoteChar && s.indexOf(csvColumnSep) == -1 && s.indexOf(csvQuoteChar) == -1)) { return s; } - StringBuffer sb = new StringBuffer(csvQuoteChar); + StringBuilder sb = new StringBuilder(csvQuoteChar); int len = s.length(); char q = csvQuoteChar.charAt(0); for (int i = 0; i < len; i++) { @@ -926,7 +918,7 @@ public class SQLExec extends JDBCTask { * @since Ant 1.7 */ private void closeQuietly() { - if (!isAutocommit() && getConnection() != null && onError.equals("abort")) { + if (!isAutocommit() && getConnection() != null && "abort".equals(onError)) { try { getConnection().rollback(); } catch (SQLException ex) { @@ -935,7 +927,6 @@ public class SQLExec extends JDBCTask { } } - /** * Caches the connection returned by the base class's getConnection method. * @@ -972,7 +963,6 @@ public class SQLExec extends JDBCTask { statement = getConnection().createStatement(); statement.setEscapeProcessing(escapeProcessing); } - return statement; } @@ -984,7 +974,7 @@ public class SQLExec extends JDBCTask { /** @return the enumerated values */ @Override public String[] getValues() { - return new String[] {"continue", "stop", "abort"}; + return new String[] { "continue", "stop", "abort" }; } } @@ -1039,18 +1029,15 @@ public class SQLExec extends JDBCTask { */ public void addConfigured(ResourceCollection a) { if (a.size() != 1) { - throw new BuildException("only single argument resource " - + "collections are supported."); + throw new BuildException( + "only single argument resource collections are supported."); } setSrcResource(a.iterator().next()); } - /** - * - */ private void runTransaction(PrintStream out) throws IOException, SQLException { - if (tSqlCommand.length() != 0) { + if (!tSqlCommand.isEmpty()) { log("Executing commands", Project.MSG_INFO); runStatements(new StringReader(tSqlCommand), out); } @@ -1058,16 +1045,11 @@ public class SQLExec extends JDBCTask { if (tSrcResource != null) { log("Executing resource: " + tSrcResource.toString(), Project.MSG_INFO); - InputStream is = null; - Reader reader = null; - try { - is = tSrcResource.getInputStream(); - reader = (encoding == null) ? new InputStreamReader(is) - : new InputStreamReader(is, encoding); + Charset charset = encoding == null ? Charset.defaultCharset() + : Charset.forName(encoding); + try (Reader reader = new InputStreamReader( + tSrcResource.getInputStream(), charset)) { runStatements(reader, out); - } finally { - FileUtils.close(is); - FileUtils.close(reader); } } } @@ -1083,35 +1065,33 @@ public class SQLExec extends JDBCTask { } // no match return -1; - } else { - String d = delimiter.trim().toLowerCase(Locale.ENGLISH); - if (delimiterType.equals(DelimiterType.NORMAL)) { - // still trying to avoid wasteful copying, see - // StringUtils.endsWith - int endIndex = delimiter.length() - 1; - int bufferIndex = buf.length() - 1; - while (bufferIndex >= 0 - && Character.isWhitespace(buf.charAt(bufferIndex))) { - --bufferIndex; - } - if (bufferIndex < endIndex) { + } + String d = delimiter.trim().toLowerCase(Locale.ENGLISH); + if (DelimiterType.NORMAL.equals(delimiterType)) { + // still trying to avoid wasteful copying, see + // StringUtils.endsWith + int endIndex = delimiter.length() - 1; + int bufferIndex = buf.length() - 1; + while (bufferIndex >= 0 + && Character.isWhitespace(buf.charAt(bufferIndex))) { + --bufferIndex; + } + if (bufferIndex < endIndex) { + return -1; + } + while (endIndex >= 0) { + if (buf.substring(bufferIndex, bufferIndex + 1) + .toLowerCase(Locale.ENGLISH).charAt(0) + != d.charAt(endIndex)) { return -1; } - while (endIndex >= 0) { - if (buf.substring(bufferIndex, bufferIndex + 1) - .toLowerCase(Locale.ENGLISH).charAt(0) - != d.charAt(endIndex)) { - return -1; - } - bufferIndex--; - endIndex--; - } - return bufferIndex + 1; - } else { - return currentLine.trim().toLowerCase(Locale.ENGLISH).equals(d) - ? buf.length() - currentLine.length() : -1; + bufferIndex--; + endIndex--; } + return bufferIndex + 1; } + return currentLine.trim().toLowerCase(Locale.ENGLISH).equals(d) + ? buf.length() - currentLine.length() : -1; } private void printWarnings(SQLWarning warning, boolean force) http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Sequential.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Sequential.java b/src/main/org/apache/tools/ant/taskdefs/Sequential.java index 468ac14..7d9787b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Sequential.java +++ b/src/main/org/apache/tools/ant/taskdefs/Sequential.java @@ -17,7 +17,7 @@ */ package org.apache.tools.ant.taskdefs; -import java.util.Iterator; +import java.util.List; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -41,7 +41,7 @@ import org.apache.tools.ant.property.LocalProperties; public class Sequential extends Task implements TaskContainer { /** Optional Vector holding the nested tasks */ - private Vector nestedTasks = new Vector(); + private List<Task> nestedTasks = new Vector<>(); /** * Add a nested task to Sequential. @@ -49,8 +49,9 @@ public class Sequential extends Task implements TaskContainer { * @param nestedTask Nested task to execute Sequential * <p> */ + @Override public void addTask(Task nestedTask) { - nestedTasks.addElement(nestedTask); + nestedTasks.add(nestedTask); } /** @@ -58,15 +59,13 @@ public class Sequential extends Task implements TaskContainer { * * @throws BuildException if one of the nested tasks fails. */ + @Override public void execute() throws BuildException { LocalProperties localProperties = LocalProperties.get(getProject()); localProperties.enterScope(); try { - for (Iterator i = nestedTasks.iterator(); i.hasNext();) { - Task nestedTask = (Task) i.next(); - nestedTask.perform(); - } + nestedTasks.forEach(Task::perform); } finally { localProperties.exitScope(); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/SetPermissions.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/SetPermissions.java b/src/main/org/apache/tools/ant/taskdefs/SetPermissions.java index 052c569..632b900 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SetPermissions.java +++ b/src/main/org/apache/tools/ant/taskdefs/SetPermissions.java @@ -137,6 +137,7 @@ public class SetPermissions extends Task { resources.add(rc); } + @Override public void execute() { if (resources == null) { throw new BuildException("At least one resource-collection is required"); @@ -169,18 +170,17 @@ public class SetPermissions extends Task { String msg = String.format(msgFormat, msgArgs); if (failonerror) { if (exc instanceof BuildException) { - throw (BuildException)exc; - } else { - throw new BuildException(msg, exc); - } - } else { - log("Warning: " + msg, Project.MSG_ERR); + throw (BuildException) exc; + } + throw new BuildException(msg, exc); } + log("Warning: " + msg, Project.MSG_ERR); } private void posixPermissionsNotSupported(Path p) { - String msg = String.format("the associated path '%s' does" - + " not support the PosixFileAttributeView", p); + String msg = String.format( + "the associated path '%s' does not support the PosixFileAttributeView", + p); switch (nonPosixMode) { case fail: throw new BuildException(msg); @@ -207,19 +207,18 @@ public class SetPermissions extends Task { maybeThrowException(ioe, "Failed to set permissions on '%s' due to %s", p, ioe.getMessage()); } catch (SecurityException uoe) { - maybeThrowException(null, "the SecurityManager denies role " - + "accessUserInformation or write access for " - + "SecurityManager.checkWrite for resource '%s'", - p); + maybeThrowException(null, + "the SecurityManager denies role accessUserInformation or write access for SecurityManager.checkWrite for resource '%s'", + p); } } else { - String msg = String.format("the associated path '%s' does" - + " not support the DosFileAttributeView", p); + String msg = String.format( + "the associated path '%s' does not support the DosFileAttributeView", + p); if (failIfDosIsNotSupported) { throw new BuildException(msg); - } else { - log("Warning: " + msg, Project.MSG_ERR); } + log("Warning: " + msg, Project.MSG_ERR); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/SignJar.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/SignJar.java b/src/main/org/apache/tools/ant/taskdefs/SignJar.java index ed271d8..14b7073 100644 --- a/src/main/org/apache/tools/ant/taskdefs/SignJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/SignJar.java @@ -53,6 +53,38 @@ public class SignJar extends AbstractJarSignerTask { private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_TODIR_AND_SIGNEDJAR + = "'destdir' and 'signedjar' cannot both be set"; + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_TOO_MANY_MAPPERS = "Too many mappers"; + /** + * error string for unit test verification {@value} + */ + public static final String ERROR_SIGNEDJAR_AND_PATHS + = "You cannot specify the signed JAR when using paths or filesets"; + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_BAD_MAP = "Cannot map source file to anything sensible: "; + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_MAPPER_WITHOUT_DEST + = "The destDir attribute is required if a mapper is set"; + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_NO_ALIAS = "alias attribute must be set"; + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_NO_STOREPASS = "storepass attribute must be set"; + + /** * name to a signature file */ protected String sigfile; @@ -133,37 +165,6 @@ public class SignJar extends AbstractJarSignerTask { */ private String tsaDigestAlg; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_TODIR_AND_SIGNEDJAR - = "'destdir' and 'signedjar' cannot both be set"; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_TOO_MANY_MAPPERS = "Too many mappers"; - /** - * error string for unit test verification {@value} - */ - public static final String ERROR_SIGNEDJAR_AND_PATHS - = "You cannot specify the signed JAR when using paths or filesets"; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_BAD_MAP = "Cannot map source file to anything sensible: "; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_MAPPER_WITHOUT_DEST - = "The destDir attribute is required if a mapper is set"; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_NO_ALIAS = "alias attribute must be set"; - /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_NO_STOREPASS = "storepass attribute must be set"; // CheckStyle:VisibilityModifier ON /** @@ -441,14 +442,7 @@ public class SignJar extends AbstractJarSignerTask { Path sources = createUnifiedSourcePath(); //set up our mapping policy - FileNameMapper destMapper; - if (hasMapper) { - destMapper = mapper; - } else { - //no mapper? use the identity policy - destMapper = new IdentityMapper(); - } - + FileNameMapper destMapper = hasMapper ? mapper : new IdentityMapper(); //at this point the paths are set up with lists of files, //and the mapper is ready to map from source dirs to dest files
