http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java b/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java index 8762ddc..e5fa4dd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/AbstractCvsTask.java @@ -55,10 +55,10 @@ public abstract class AbstractCvsTask extends Task { private Commandline cmd = new Commandline(); - private ArrayList<Module> modules = new ArrayList<Module>(); + private List<Module> modules = new ArrayList<>(); /** list of Commandline children */ - private Vector<Commandline> vecCommandlines = new Vector<Commandline>(); + private List<Commandline> commandlines = new Vector<>(); /** * the CVSROOT variable. @@ -149,11 +149,6 @@ public abstract class AbstractCvsTask extends Task { private OutputStream outputStream; private OutputStream errorStream; - /** empty no-arg constructor*/ - public AbstractCvsTask() { - super(); - } - /** * sets the handler * @param handler a handler able of processing the output and error streams from the cvs exe @@ -385,11 +380,12 @@ public abstract class AbstractCvsTask extends Task { * @throws BuildException if failonerror is set to true and the * cvs command fails. */ + @Override public void execute() throws BuildException { String savedCommand = getCommand(); - if (this.getCommand() == null && vecCommandlines.size() == 0) { + if (this.getCommand() == null && commandlines.isEmpty()) { // re-implement legacy behaviour: this.setCommand(AbstractCvsTask.DEFAULT_COMMAND); } @@ -397,16 +393,13 @@ public abstract class AbstractCvsTask extends Task { String c = this.getCommand(); Commandline cloned = null; if (c != null) { - cloned = (Commandline) cmd.clone(); + cloned = cmd.clone(); cloned.createArgument(true).setLine(c); this.addConfiguredCommandline(cloned, true); } try { - final int size = vecCommandlines.size(); - for (int i = 0; i < size; i++) { - this.runCommand((Commandline) vecCommandlines.elementAt(i)); - } + commandlines.forEach(this::runCommand); } finally { if (cloned != null) { removeCommandline(cloned); @@ -421,24 +414,24 @@ public abstract class AbstractCvsTask extends Task { String cmdLine = Commandline.describeCommand(execute .getCommandline()); - StringBuffer stringBuffer = removeCvsPassword(cmdLine); + StringBuilder buf = removeCvsPassword(cmdLine); String newLine = StringUtils.LINE_SEP; String[] variableArray = execute.getEnvironment(); if (variableArray != null) { - stringBuffer.append(newLine); - stringBuffer.append(newLine); - stringBuffer.append("environment:"); - stringBuffer.append(newLine); + buf.append(newLine); + buf.append(newLine); + buf.append("environment:"); + buf.append(newLine); for (int z = 0; z < variableArray.length; z++) { - stringBuffer.append(newLine); - stringBuffer.append("\t"); - stringBuffer.append(variableArray[z]); + buf.append(newLine); + buf.append("\t"); + buf.append(variableArray[z]); } } - return stringBuffer.toString(); + return buf.toString(); } /** @@ -449,24 +442,24 @@ public abstract class AbstractCvsTask extends Task { * @param cmdLine the CVS command line * @return a StringBuffer where the password has been removed (if available) */ - private StringBuffer removeCvsPassword(String cmdLine) { - StringBuffer stringBuffer = new StringBuffer(cmdLine); + private StringBuilder removeCvsPassword(String cmdLine) { + StringBuilder buf = new StringBuilder(cmdLine); int start = cmdLine.indexOf("-d:"); if (start >= 0) { - int stop = cmdLine.indexOf("@", start); - int startproto = cmdLine.indexOf(":", start); - int startuser = cmdLine.indexOf(":", startproto + 1); - int startpass = cmdLine.indexOf(":", startuser + 1); - stop = cmdLine.indexOf("@", start); + int stop = cmdLine.indexOf('@', start); + int startproto = cmdLine.indexOf(':', start); + int startuser = cmdLine.indexOf(':', startproto + 1); + int startpass = cmdLine.indexOf(':', startuser + 1); + stop = cmdLine.indexOf('@', start); if (stop >= 0 && startpass > startproto && startpass < stop) { for (int i = startpass + 1; i < stop; i++) { - stringBuffer.replace(i, i + 1, "*"); + buf.replace(i, i + 1, "*"); } } } - return stringBuffer; + return buf; } /** @@ -478,10 +471,8 @@ public abstract class AbstractCvsTask extends Task { public void setCvsRoot(String root) { // Check if not real cvsroot => set it to null - if (root != null) { - if (root.trim().equals("")) { - root = null; - } + if (root != null && root.trim().isEmpty()) { + root = null; } this.cvsRoot = root; @@ -502,11 +493,8 @@ public abstract class AbstractCvsTask extends Task { * @param rsh the CVS_RSH variable */ public void setCvsRsh(String rsh) { - // Check if not real cvsrsh => set it to null - if (rsh != null) { - if (rsh.trim().equals("")) { - rsh = null; - } + if (rsh != null && rsh.trim().isEmpty()) { + rsh = null; } this.cvsRsh = rsh; @@ -535,7 +523,6 @@ public abstract class AbstractCvsTask extends Task { * @return the port of CVS */ public int getPort() { - return this.port; } @@ -553,7 +540,6 @@ public abstract class AbstractCvsTask extends Task { * @return password file */ public File getPassFile() { - return this.passFile; } @@ -576,7 +562,6 @@ public abstract class AbstractCvsTask extends Task { * @return directory where the checked out files should be placed */ public File getDest() { - return this.dest; } @@ -595,7 +580,6 @@ public abstract class AbstractCvsTask extends Task { * @return package/module */ public String getPackage() { - return this.cvsPackage; } /** @@ -613,7 +597,7 @@ public abstract class AbstractCvsTask extends Task { */ public void setTag(String p) { // Check if not real tag => set it to null - if (p != null && p.trim().length() > 0) { + if (!(p == null || p.trim().isEmpty())) { tag = p; addCommandArgument("-r" + p); } @@ -649,7 +633,7 @@ public abstract class AbstractCvsTask extends Task { * can understand see man cvs */ public void setDate(String p) { - if (p != null && p.trim().length() > 0) { + if (!(p == null || p.trim().isEmpty())) { addCommandArgument("-D"); addCommandArgument(p); } @@ -695,7 +679,6 @@ public abstract class AbstractCvsTask extends Task { reallyquiet = q; } - /** * If true, report only and don't change any files. * @@ -794,7 +777,7 @@ public abstract class AbstractCvsTask extends Task { * @param c command line which should be removed */ protected void removeCommandline(Commandline c) { - vecCommandlines.removeElement(c); + commandlines.remove(c); } /** @@ -818,9 +801,9 @@ public abstract class AbstractCvsTask extends Task { } this.configureCommandline(c); if (insertAtStart) { - vecCommandlines.insertElementAt(c, 0); + commandlines.add(0, c); } else { - vecCommandlines.addElement(c); + commandlines.add(c); } } @@ -854,13 +837,12 @@ public abstract class AbstractCvsTask extends Task { } protected List<Module> getModules() { - @SuppressWarnings("unchecked") - final List<Module> clone = (List<Module>) modules.clone(); - return clone; + return new ArrayList<>(modules); } public static final class Module { private String name; + public void setName(String s) { name = s; }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java b/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java index c93173b..6fda283 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java @@ -37,6 +37,17 @@ import org.apache.tools.ant.util.JavaEnvUtils; */ public abstract class AbstractJarSignerTask extends Task { + /** + * error string for unit test verification: {@value} + */ + public static final String ERROR_NO_SOURCE = + "jar must be set through jar attribute or nested filesets"; + + /** + * name of JDK program we are looking for + */ + protected static final String JARSIGNER_COMMAND = "jarsigner"; + // CheckStyle:VisibilityModifier OFF - bc /** * The name of the jar file. @@ -78,12 +89,7 @@ public abstract class AbstractJarSignerTask extends Task { /** * the filesets of the jars to sign */ - protected Vector<FileSet> filesets = new Vector<FileSet>(); - /** - * name of JDK program we are looking for - */ - protected static final String JARSIGNER_COMMAND = "jarsigner"; - + protected Vector<FileSet> filesets = new Vector<>(); // CheckStyle:VisibilityModifier ON /** @@ -97,12 +103,6 @@ public abstract class AbstractJarSignerTask extends Task { private Environment sysProperties = new Environment(); /** - * error string for unit test verification: {@value} - */ - public static final String ERROR_NO_SOURCE = "jar must be set through jar attribute " - + "or nested filesets"; - - /** * Path holding all non-filesets of filesystem resources we want to sign. * * @since Ant 1.7 @@ -253,7 +253,7 @@ public abstract class AbstractJarSignerTask extends Task { private RedirectorElement createRedirector() { RedirectorElement result = new RedirectorElement(); if (storepass != null) { - StringBuffer input = new StringBuffer(storepass).append('\n'); + StringBuilder input = new StringBuilder(storepass).append('\n'); if (keypass != null) { input.append(keypass).append('\n'); } @@ -324,7 +324,6 @@ public abstract class AbstractJarSignerTask extends Task { addValue(cmd, "-J-D" + property.getContent()); } - /** * bind to a keystore if the attributes are there * @param cmd command to configure @@ -373,8 +372,7 @@ public abstract class AbstractJarSignerTask extends Task { * @return a vector of FileSet instances */ protected Vector<FileSet> createUnifiedSources() { - @SuppressWarnings("unchecked") - Vector<FileSet> sources = (Vector<FileSet>) filesets.clone(); + Vector<FileSet> sources = new Vector<>(filesets); if (jar != null) { //we create a fileset with the source file. //this lets us combine our logic for handling output directories, @@ -408,7 +406,7 @@ public abstract class AbstractJarSignerTask extends Task { * @since Ant 1.7 */ protected boolean hasResources() { - return path != null || filesets.size() > 0; + return !(path == null && filesets.isEmpty()); } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Ant.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Ant.java b/src/main/org/apache/tools/ant/taskdefs/Ant.java index 88fddf8..b121ade 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Ant.java +++ b/src/main/org/apache/tools/ant/taskdefs/Ant.java @@ -22,11 +22,13 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Method; +import java.util.HashMap; import java.nio.file.Files; -import java.util.Enumeration; import java.util.HashSet; -import java.util.Hashtable; import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.Vector; @@ -88,10 +90,10 @@ public class Ant extends Task { private boolean inheritRefs = false; /** the properties to pass to the new project */ - private Vector<Property> properties = new Vector<Property>(); + private List<Property> properties = new Vector<>(); /** the references to pass to the new project */ - private Vector<Reference> references = new Vector<Reference>(); + private List<Reference> references = new Vector<>(); /** the temporary project created to run the build file */ private Project newProject; @@ -100,10 +102,10 @@ public class Ant extends Task { private PrintStream out = null; /** the sets of properties to pass to the new project */ - private Vector<PropertySet> propertySets = new Vector<PropertySet>(); + private List<PropertySet> propertySets = new Vector<>(); /** the targets to call on the new project */ - private Vector<String> targets = new Vector<String>(); + private List<String> targets = new Vector<>(); /** whether the target attribute was specified **/ private boolean targetAttributeSet = false; @@ -164,6 +166,7 @@ public class Ant extends Task { /** * Creates a Project instance for the project to call. */ + @Override public void init() { newProject = getProject().createSubProject(); newProject.setJavaVersionProperty(); @@ -195,11 +198,11 @@ public class Ant extends Task { Iterator<BuildListener> iter = getBuildListeners(); while (iter.hasNext()) { - newProject.addBuildListener((BuildListener) iter.next()); + newProject.addBuildListener(iter.next()); } if (output != null) { - File outfile = null; + File outfile; if (dir != null) { outfile = FILE_UTILS.resolveFile(dir, output); } else { @@ -246,6 +249,7 @@ public class Ant extends Task { * @see Task#handleOutput(String) * @since Ant 1.5 */ + @Override public void handleOutput(String outputToHandle) { if (newProject != null) { newProject.demuxOutput(outputToHandle, false); @@ -268,6 +272,7 @@ public class Ant extends Task { * @see Task#handleInput(byte[], int, int) * @since Ant 1.6 */ + @Override public int handleInput(byte[] buffer, int offset, int length) throws IOException { if (newProject != null) { @@ -284,6 +289,7 @@ public class Ant extends Task { * @see Task#handleFlush(String) * @since Ant 1.5.2 */ + @Override public void handleFlush(String toFlush) { if (newProject != null) { newProject.demuxFlush(toFlush, false); @@ -301,6 +307,7 @@ public class Ant extends Task { * @see Task#handleErrorOutput(String) * @since Ant 1.5 */ + @Override public void handleErrorOutput(String errorOutputToHandle) { if (newProject != null) { newProject.demuxOutput(errorOutputToHandle, true); @@ -317,6 +324,7 @@ public class Ant extends Task { * @see Task#handleErrorFlush(String) * @since Ant 1.5.2 */ + @Override public void handleErrorFlush(String errorOutputToFlush) { if (newProject != null) { newProject.demuxFlush(errorOutputToFlush, true); @@ -330,10 +338,11 @@ public class Ant extends Task { * @throws BuildException if a target tries to call itself; * probably also if a BuildException is thrown by the new project. */ + @Override public void execute() throws BuildException { File savedDir = dir; String savedAntFile = antFile; - Vector<String> locals = new VectorSet<String>(targets); + Vector<String> locals = new VectorSet<>(targets); try { getNewProject(); @@ -366,7 +375,7 @@ public class Ant extends Task { antFile = file.getAbsolutePath(); log("calling target(s) " - + ((locals.size() > 0) ? locals.toString() : "[default]") + + (!locals.isEmpty() ? locals.toString() : "[default]") + " in build file " + antFile, Project.MSG_VERBOSE); newProject.setUserProperty(MagicNames.ANT_FILE , antFile); @@ -377,14 +386,14 @@ public class Ant extends Task { && file.equals(getProject().resolveFile(thisAntFile)) && getOwningTarget() != null) { - if (getOwningTarget().getName().equals("")) { - if (getTaskName().equals("antcall")) { - throw new BuildException("antcall must not be used at" - + " the top level."); + if ("".equals(getOwningTarget().getName())) { + if ("antcall".equals(getTaskName())) { + throw new BuildException( + "antcall must not be used at the top level."); } - throw new BuildException(getTaskName() + " task at the" - + " top level must not invoke" - + " its own build file."); + throw new BuildException( + "%s task at the top level must not invoke its own build file.", + getTaskName()); } } @@ -395,7 +404,7 @@ public class Ant extends Task { ex, getLocation()); } - if (locals.size() == 0) { + if (locals.isEmpty()) { String defaultTarget = newProject.getDefaultTarget(); if (defaultTarget != null) { locals.add(defaultTarget); @@ -409,30 +418,25 @@ public class Ant extends Task { String owningTargetName = getOwningTarget().getName(); if (locals.contains(owningTargetName)) { - throw new BuildException(getTaskName() + " task calling " - + "its own parent target."); + throw new BuildException( + "%s task calling its own parent target.", + getTaskName()); } - boolean circular = false; - for (Iterator<String> it = locals.iterator(); - !circular && it.hasNext();) { - Target other = - getProject().getTargets().get(it.next()); - circular |= (other != null - && other.dependsOn(owningTargetName)); - } - if (circular) { - throw new BuildException(getTaskName() - + " task calling a target" - + " that depends on" - + " its parent target \'" - + owningTargetName - + "\'."); + + final Map<String, Target> targetsMap = getProject().getTargets(); + + if (locals.stream().map(targetsMap::get) + .filter(Objects::nonNull) + .anyMatch(other -> other.dependsOn(owningTargetName))) { + throw new BuildException( + "%s task calling a target that depends on its parent target '%s'.", + getTaskName(), owningTargetName); } } addReferences(); - if (locals.size() > 0 && !(locals.size() == 1 + if (!locals.isEmpty() && !(locals.size() == 1 && "".equals(locals.get(0)))) { BuildException be = null; try { @@ -484,10 +488,10 @@ public class Ant extends Task { private void overrideProperties() throws BuildException { // remove duplicate properties - last property wins // Needed for backward compatibility - Set<String> set = new HashSet<String>(); + Set<String> set = new HashSet<>(); for (int i = properties.size() - 1; i >= 0; --i) { Property p = properties.get(i); - if (p.getName() != null && !p.getName().equals("")) { + if (p.getName() != null && !"".equals(p.getName())) { if (set.contains(p.getName())) { properties.remove(i); } else { @@ -495,12 +499,9 @@ public class Ant extends Task { } } } - Enumeration<Property> e = properties.elements(); - while (e.hasMoreElements()) { - Property p = e.nextElement(); - p.setProject(newProject); - p.execute(); - } + properties.stream().peek(p -> p.setProject(newProject)) + .forEach(Property::execute); + if (useNativeBasedir) { addAlmostAll(getProject().getInheritedProperties(), PropertyType.INHERITED); @@ -517,14 +518,13 @@ public class Ant extends Task { * @throws BuildException if a reference does not have a refid. */ private void addReferences() throws BuildException { - @SuppressWarnings("unchecked") - Hashtable<String, Object> thisReferences - = (Hashtable<String, Object>) getProject().getReferences().clone(); + Map<String, Object> thisReferences = + new HashMap<>(getProject().getReferences()); for (Reference ref : references) { String refid = ref.getRefId(); if (refid == null) { - throw new BuildException("the refid attribute is required" - + " for reference elements"); + throw new BuildException( + "the refid attribute is required for reference elements"); } if (!thisReferences.containsKey(refid)) { log("Parent project doesn't contain any reference '" @@ -544,7 +544,7 @@ public class Ant extends Task { // Now add all references that are not defined in the // subproject, if inheritRefs is true if (inheritRefs) { - Hashtable<String, Object> newReferences = newProject.getReferences(); + Map<String, Object> newReferences = newProject.getReferences(); for (String key : thisReferences.keySet()) { if (newReferences.containsKey(key)) { continue; @@ -576,32 +576,32 @@ public class Ant extends Task { Class<?> c = orig.getClass(); Object copy = orig; try { - Method cloneM = c.getMethod("clone", new Class[0]); + Method cloneM = c.getMethod("clone"); if (cloneM != null) { - copy = cloneM.invoke(orig, new Object[0]); + copy = cloneM.invoke(orig); log("Adding clone of reference " + oldKey, Project.MSG_DEBUG); } } catch (Exception e) { // not Clonable } - if (copy instanceof ProjectComponent) { ((ProjectComponent) copy).setProject(newProject); } else { try { Method setProjectM = - c.getMethod("setProject", new Class[] {Project.class}); + c.getMethod("setProject", Project.class); if (setProjectM != null) { - setProjectM.invoke(copy, new Object[] {newProject}); + setProjectM.invoke(copy, newProject); } } catch (NoSuchMethodException e) { // ignore this if the class being referenced does not have // a set project method. } catch (Exception e2) { - String msg = "Error setting new project instance for " - + "reference with id " + oldKey; - throw new BuildException(msg, e2, getLocation()); + throw new BuildException( + "Error setting new project instance for " + + "reference with id " + oldKey, + e2, getLocation()); } } newProject.addReference(newKey, copy); @@ -617,29 +617,31 @@ public class Ant extends Task { * user property or an inherited property). * @since Ant 1.8.0 */ - private void addAlmostAll(Hashtable<?, ?> props, PropertyType type) { - Enumeration<?> e = props.keys(); - while (e.hasMoreElements()) { - String key = e.nextElement().toString(); + private void addAlmostAll(Map<?, ?> props, PropertyType type) { + props.forEach((k, v) -> { + String key = k.toString(); if (MagicNames.PROJECT_BASEDIR.equals(key) - || MagicNames.ANT_FILE.equals(key)) { + || MagicNames.ANT_FILE.equals(key)) { // basedir and ant.file get special treatment in execute() - continue; + return; } - - String value = props.get(key).toString(); - if (type == PropertyType.PLAIN) { + String value = v.toString(); + switch (type) { + case PLAIN: // don't re-set user properties, avoid the warning message if (newProject.getProperty(key) == null) { // no user property newProject.setNewProperty(key, value); } - } else if (type == PropertyType.USER) { + break; + case USER: newProject.setUserProperty(key, value); - } else if (type == PropertyType.INHERITED) { + break; + case INHERITED: newProject.setInheritedProperty(key, value); + break; } - } + }); } /** @@ -671,7 +673,7 @@ public class Ant extends Task { * @param targetToAdd the name of the target to invoke. */ public void setTarget(String targetToAdd) { - if (targetToAdd.equals("")) { + if ("".equals(targetToAdd)) { throw new BuildException("target attribute must not be empty"); } targets.add(targetToAdd); @@ -697,7 +699,7 @@ public class Ant extends Task { Property p = new Property(true, getProject()); p.setProject(getNewProject()); p.setTaskName("property"); - properties.addElement(p); + properties.add(p); return p; } @@ -707,7 +709,7 @@ public class Ant extends Task { * @param ref <code>Reference</code> to add. */ public void addReference(Reference ref) { - references.addElement(ref); + references.add(ref); } /** @@ -721,7 +723,7 @@ public class Ant extends Task { "nested target is incompatible with the target attribute"); } String name = t.getName(); - if (name.equals("")) { + if ("".equals(name)) { throw new BuildException("target name must not be empty"); } targets.add(name); @@ -734,7 +736,7 @@ public class Ant extends Task { * @since Ant 1.6 */ public void addPropertyset(PropertySet ps) { - propertySets.addElement(ps); + propertySets.add(ps); } /** @@ -760,14 +762,10 @@ public class Ant extends Task { * Helper class that implements the nested <reference> * element of <ant> and <antcall>. */ + @SuppressWarnings("deprecation") public static class Reference extends org.apache.tools.ant.types.Reference { - /** Creates a reference to be configured by Ant. */ - public Reference() { - super(); - } - private String targetid = null; /** @@ -823,10 +821,7 @@ public class Ant extends Task { } } - private static final class PropertyType { - private PropertyType() {} - private static final PropertyType PLAIN = new PropertyType(); - private static final PropertyType INHERITED = new PropertyType(); - private static final PropertyType USER = new PropertyType(); + private enum PropertyType { + PLAIN, INHERITED, USER; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/AntStructure.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java index eeaab53..8dd7ff1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AntStructure.java +++ b/src/main/org/apache/tools/ant/taskdefs/AntStructure.java @@ -25,10 +25,15 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; +import java.util.ArrayList; import java.nio.file.Files; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Vector; +import java.util.List; +import java.util.Set; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.IntrospectionHelper; @@ -122,8 +127,8 @@ public class AntStructure extends Task { printer.printTail(out); if (out.checkError()) { - throw new IOException("Encountered an error writing Ant" - + " structure"); + throw new IOException( + "Encountered an error writing Ant structure"); } } catch (final IOException ioe) { throw new BuildException("Error writing " @@ -187,13 +192,15 @@ public class AntStructure extends Task { private final Hashtable<String, String> visited = new Hashtable<String, String>(); + @Override public void printTail(final PrintWriter out) { visited.clear(); } + @Override public void printHead(final PrintWriter out, final Project p, final Hashtable<String, Class<?>> tasks, final Hashtable<String, Class<?>> types) { - printHead(out, tasks.keys(), types.keys()); + printHead(out, tasks.keySet(), types.keySet()); } @@ -203,36 +210,18 @@ public class AntStructure extends Task { * <p>Basically this prints the XML declaration, defines some * entities and the project element.</p> */ - private void printHead(final PrintWriter out, final Enumeration<String> tasks, - final Enumeration<String> types) { + private void printHead(final PrintWriter out, final Set<String> tasks, + final Set<String> types) { out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); out.println("<!ENTITY % boolean \"(true|false|on|off|yes|no)\">"); - out.print("<!ENTITY % tasks \""); - boolean first = true; - while (tasks.hasMoreElements()) { - final String tName = tasks.nextElement(); - if (!first) { - out.print(" | "); - } else { - first = false; - } - out.print(tName); - } - out.println("\">"); - out.print("<!ENTITY % types \""); - first = true; - while (types.hasMoreElements()) { - final String typeName = types.nextElement(); - if (!first) { - out.print(" | "); - } else { - first = false; - } - out.print(typeName); - } - out.println("\">"); + + out.println(tasks.stream().collect( + Collectors.joining(" | ", "<!ENTITY % tasks \"", "\">"))); - out.println(""); + out.println(types.stream().collect( + Collectors.joining(" | ", "<!ENTITY % types \"", "\">"))); + + out.println(); out.print("<!ELEMENT project (target | extension-point | "); out.print(TASKS); @@ -249,6 +238,7 @@ public class AntStructure extends Task { /** * Prints the definition for the target element. */ + @Override public void printTargetDecl(final PrintWriter out) { out.print("<!ELEMENT target ("); out.print(TASKS); @@ -282,6 +272,7 @@ public class AntStructure extends Task { /** * Print the definition for a given element. */ + @Override public void printElementDecl(final PrintWriter out, final Project p, final String name, final Class<?> element) { @@ -290,7 +281,7 @@ public class AntStructure extends Task { } visited.put(name, ""); - IntrospectionHelper ih = null; + IntrospectionHelper ih; try { ih = IntrospectionHelper.getHelper(p, element); } catch (final Throwable t) { @@ -302,10 +293,10 @@ public class AntStructure extends Task { return; } - StringBuffer sb = new StringBuffer("<!ELEMENT "); - sb.append(name).append(" "); + StringBuilder sb = + new StringBuilder("<!ELEMENT ").append(name).append(" "); - if (org.apache.tools.ant.types.Reference.class.equals(element)) { + if (Reference.class.equals(element)) { sb.append("EMPTY>").append(LINE_SEP); sb.append("<!ATTLIST ").append(name); sb.append(LINE_SEP).append(" id ID #IMPLIED"); @@ -315,40 +306,35 @@ public class AntStructure extends Task { return; } - final Vector<String> v = new Vector<String>(); + final List<String> v = new ArrayList<>(); if (ih.supportsCharacters()) { - v.addElement("#PCDATA"); + v.add("#PCDATA"); } if (TaskContainer.class.isAssignableFrom(element)) { - v.addElement(TASKS); + v.add(TASKS); } Enumeration<String> e = ih.getNestedElements(); while (e.hasMoreElements()) { - v.addElement(e.nextElement()); + v.add(e.nextElement()); } + final Collector<CharSequence, ?, String> joinAlts = + Collectors.joining(" | ", "(", ")"); + if (v.isEmpty()) { sb.append("EMPTY"); } else { - sb.append("("); - final int count = v.size(); - for (int i = 0; i < count; i++) { - if (i != 0) { - sb.append(" | "); - } - sb.append(v.elementAt(i)); - } - sb.append(")"); - if (count > 1 || !v.elementAt(0).equals("#PCDATA")) { + sb.append(v.stream().collect(joinAlts)); + if (v.size() > 1 || !"#PCDATA".equals(v.get(0))) { sb.append("*"); } } sb.append(">"); out.println(sb); - sb = new StringBuffer("<!ATTLIST "); + sb = new StringBuilder("<!ATTLIST "); sb.append(name); sb.append(LINE_SEP).append(" id ID #IMPLIED"); @@ -362,29 +348,23 @@ public class AntStructure extends Task { sb.append(LINE_SEP).append(" ") .append(attrName).append(" "); final Class<?> type = ih.getAttributeType(attrName); - if (type.equals(java.lang.Boolean.class) - || type.equals(java.lang.Boolean.TYPE)) { + if (type.equals(Boolean.class) + || type.equals(Boolean.TYPE)) { sb.append(BOOLEAN).append(" "); } else if (Reference.class.isAssignableFrom(type)) { sb.append("IDREF "); } else if (EnumeratedAttribute.class.isAssignableFrom(type)) { try { final EnumeratedAttribute ea = - (EnumeratedAttribute) type.newInstance(); + type.asSubclass(EnumeratedAttribute.class) + .newInstance(); final String[] values = ea.getValues(); if (values == null || values.length == 0 || !areNmtokens(values)) { sb.append("CDATA "); } else { - sb.append("("); - for (int i = 0; i < values.length; i++) { - if (i != 0) { - sb.append(" | "); - } - sb.append(values[i]); - } - sb.append(") "); + sb.append(Stream.of(values).collect(joinAlts)); } } catch (final InstantiationException ie) { sb.append("CDATA "); @@ -393,20 +373,13 @@ public class AntStructure extends Task { } } else if (Enum.class.isAssignableFrom(type)) { try { - final Object[] values = (Object[]) type.getMethod("values", (Class[]) null) - .invoke(null, (Object[]) null); + final Enum<?>[] values = + (Enum<?>[]) type.getMethod("values").invoke(null); if (values.length == 0) { sb.append("CDATA "); } else { - sb.append('('); - for (int i = 0; i < values.length; i++) { - if (i != 0) { - sb.append(" | "); - } - sb.append(type.getMethod("name", (Class[]) null) - .invoke(values[i], (Object[]) null)); - } - sb.append(") "); + sb.append(Stream.of(values).map(Enum::name) + .collect(joinAlts)); } } catch (final Exception x) { sb.append("CDATA "); @@ -419,9 +392,7 @@ public class AntStructure extends Task { sb.append(">").append(LINE_SEP); out.println(sb); - final int count = v.size(); - for (int i = 0; i < count; i++) { - final String nestedName = v.elementAt(i); + for (String nestedName : v) { if (!"#PCDATA".equals(nestedName) && !TASKS.equals(nestedName) && !TYPES.equals(nestedName)) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Antlib.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Antlib.java b/src/main/org/apache/tools/ant/taskdefs/Antlib.java index 8ff836a..24489cd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Antlib.java +++ b/src/main/org/apache/tools/ant/taskdefs/Antlib.java @@ -22,9 +22,7 @@ import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ComponentHelper; import org.apache.tools.ant.Project; @@ -94,7 +92,7 @@ public class Antlib extends Task implements TaskContainer { UnknownElement ue = parser.parseAntlibDescriptor(project, antlibResource); // Check name is "antlib" - if (!(ue.getTag().equals(TAG))) { + if (!(TAG.equals(ue.getTag()))) { throw new BuildException( "Unexpected tag " + ue.getTag() + " expecting " + TAG, ue.getLocation()); @@ -116,7 +114,7 @@ public class Antlib extends Task implements TaskContainer { // private ClassLoader classLoader; private String uri = ""; - private List<Object> tasks = new ArrayList<Object>(); + private List<Task> tasks = new ArrayList<>(); /** * Set the class loader for this antlib. @@ -149,6 +147,7 @@ public class Antlib extends Task implements TaskContainer { * * @param nestedTask Nested task to execute in antlib */ + @Override public void addTask(Task nestedTask) { tasks.add(nestedTask); } @@ -157,10 +156,12 @@ public class Antlib extends Task implements TaskContainer { * Execute the nested tasks, setting the classloader for * any tasks that derive from Definer. */ + @Override public void execute() { //TODO handle tasks added via #addTask() - for (Iterator<Object> i = tasks.iterator(); i.hasNext();) { - UnknownElement ue = (UnknownElement) i.next(); + + for (Task task : tasks) { + UnknownElement ue = (UnknownElement) task; setLocation(ue.getLocation()); ue.maybeConfigure(); Object configuredObject = ue.getRealThing(); @@ -169,9 +170,9 @@ public class Antlib extends Task implements TaskContainer { } if (!(configuredObject instanceof AntlibDefinition)) { throw new BuildException( - "Invalid task in antlib " + ue.getTag() - + " " + configuredObject.getClass() + " does not " - + "extend org.apache.tools.ant.taskdefs.AntlibDefinition"); + "Invalid task in antlib %s %s does not extend %s", + ue.getTag(), configuredObject.getClass(), + AntlibDefinition.class.getName()); } AntlibDefinition def = (AntlibDefinition) configuredObject; def.setURI(uri); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/AntlibDefinition.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/AntlibDefinition.java b/src/main/org/apache/tools/ant/taskdefs/AntlibDefinition.java index eef3334..210f443 100644 --- a/src/main/org/apache/tools/ant/taskdefs/AntlibDefinition.java +++ b/src/main/org/apache/tools/ant/taskdefs/AntlibDefinition.java @@ -44,11 +44,11 @@ public class AntlibDefinition extends Task { * @throws BuildException if a reserved URI is used */ public void setURI(String uri) throws BuildException { - if (uri.equals(ProjectHelper.ANT_CORE_URI)) { + if (ProjectHelper.ANT_CORE_URI.equals(uri)) { uri = ""; } if (uri.startsWith("ant:")) { - throw new BuildException("Attempt to use a reserved URI " + uri); + throw new BuildException("Attempt to use a reserved URI %s", uri); } this.uri = uri; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Available.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Available.java b/src/main/org/apache/tools/ant/taskdefs/Available.java index f4919a1..6b37116 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Available.java +++ b/src/main/org/apache/tools/ant/taskdefs/Available.java @@ -193,9 +193,9 @@ public class Available extends Task implements Condition { * the type in its own class. * @param type the type of resource */ + @Deprecated public void setType(String type) { - log("DEPRECATED - The setType(String) method has been deprecated." - + " Use setType(Available.FileDir) instead.", + log("DEPRECATED - The setType(String) method has been deprecated. Use setType(Available.FileDir) instead.", Project.MSG_WARN); this.type = new FileDir(); this.type.setValue(type); @@ -227,6 +227,7 @@ public class Available extends Task implements Condition { * * @exception BuildException if the task is not configured correctly. */ + @Override public void execute() throws BuildException { if (property == null) { throw new BuildException("property attribute is required", @@ -261,17 +262,19 @@ public class Available extends Task implements Condition { * @return boolean is the resource is available. * @exception BuildException if the condition is not configured correctly */ + @Override public boolean eval() throws BuildException { try { if (classname == null && file == null && resource == null) { - throw new BuildException("At least one of (classname|file|" - + "resource) is required", getLocation()); + throw new BuildException( + "At least one of (classname|file|resource) is required", + getLocation()); } if (type != null) { if (file == null) { - throw new BuildException("The type attribute is only valid " - + "when specifying the file " - + "attribute.", getLocation()); + throw new BuildException( + "The type attribute is only valid when specifying the file attribute.", + getLocation()); } } if (classpath != null) { @@ -284,13 +287,13 @@ public class Available extends Task implements Condition { } else { setTaskName("available"); } - if ((classname != null) && !checkClass(classname)) { + if (!(classname == null || checkClass(classname))) { log("Unable to load class " + classname + appendix, Project.MSG_VERBOSE); return false; } if ((file != null) && !checkFile()) { - StringBuffer buf = new StringBuffer("Unable to find "); + StringBuilder buf = new StringBuilder("Unable to find "); if (type != null) { buf.append(type).append(' '); } @@ -334,62 +337,64 @@ public class Available extends Task implements Condition { private boolean checkFile() { if (filepath == null) { return checkFile(file, filename); - } else { - String[] paths = filepath.list(); - for (int i = 0; i < paths.length; ++i) { - log("Searching " + paths[i], Project.MSG_VERBOSE); - File path = new File(paths[i]); - - // ** full-pathname specified == path in list - // ** simple name specified == path in list - if (path.exists() - && (filename.equals(paths[i]) - || filename.equals(path.getName()))) { - if (type == null) { - log("Found: " + path, Project.MSG_VERBOSE); - return true; - } else if (type.isDir() - && path.isDirectory()) { - log("Found directory: " + path, Project.MSG_VERBOSE); - return true; - } else if (type.isFile() - && path.isFile()) { - log("Found file: " + path, Project.MSG_VERBOSE); - return true; - } - // not the requested type - return false; + } + String[] paths = filepath.list(); + for (String p : paths) { + log("Searching " + p, Project.MSG_VERBOSE); + File path = new File(p); + + // ** full-pathname specified == path in list + // ** simple name specified == path in list + if (path.exists() + && (filename.equals(p) + || filename.equals(path.getName()))) { + if (type == null) { + log("Found: " + path, Project.MSG_VERBOSE); + return true; } - File parent = path.getParentFile(); - // ** full-pathname specified == parent dir of path in list - if (parent != null && parent.exists() - && filename.equals(parent.getAbsolutePath())) { - if (type == null) { - log("Found: " + parent, Project.MSG_VERBOSE); - return true; - } else if (type.isDir()) { - log("Found directory: " + parent, Project.MSG_VERBOSE); - return true; - } - // not the requested type - return false; + if (type.isDir() + && path.isDirectory()) { + log("Found directory: " + path, Project.MSG_VERBOSE); + return true; } - // ** simple name specified == path in list + name - if (path.exists() && path.isDirectory()) { - if (checkFile(new File(path, filename), - filename + " in " + path)) { - return true; - } + if (type.isFile() + && path.isFile()) { + log("Found file: " + path, Project.MSG_VERBOSE); + return true; } + // not the requested type + return false; + } + File parent = path.getParentFile(); + // ** full-pathname specified == parent dir of path in list + if (parent != null && parent.exists() + && filename.equals(parent.getAbsolutePath())) { + if (type == null) { + log("Found: " + parent, Project.MSG_VERBOSE); + return true; + } + if (type.isDir()) { + log("Found directory: " + parent, Project.MSG_VERBOSE); + return true; + } + // not the requested type + return false; + } + // ** simple name specified == path in list + name + if (path.exists() && path.isDirectory()) { + if (checkFile(new File(path, filename), + filename + " in " + path)) { + return true; + } + } - // ** simple name specified == parent dir + name - while (searchParents && parent != null && parent.exists()) { - if (checkFile(new File(parent, filename), - filename + " in " + parent)) { - return true; - } - parent = parent.getParentFile(); + // ** simple name specified == parent dir + name + while (searchParents && parent != null && parent.exists()) { + if (checkFile(new File(parent, filename), + filename + " in " + parent)) { + return true; } + parent = parent.getParentFile(); } } return false; @@ -405,7 +410,8 @@ public class Available extends Task implements Condition { log("Found directory: " + text, Project.MSG_VERBOSE); } return f.isDirectory(); - } else if (type.isFile()) { + } + if (type.isFile()) { if (f.isFile()) { log("Found file: " + text, Project.MSG_VERBOSE); } @@ -488,12 +494,13 @@ public class Available extends Task implements Condition { */ public static class FileDir extends EnumeratedAttribute { - private static final String[] VALUES = {"file", "dir"}; + private static final String[] VALUES = { "file", "dir" }; /** * @see EnumeratedAttribute#getValues */ /** {@inheritDoc}. */ + @Override public String[] getValues() { return VALUES; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Basename.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Basename.java b/src/main/org/apache/tools/ant/taskdefs/Basename.java index 0415af7..a02822c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Basename.java +++ b/src/main/org/apache/tools/ant/taskdefs/Basename.java @@ -85,6 +85,7 @@ public class Basename extends Task { * @throws BuildException if required attributes are not supplied * property and attribute are required attributes */ + @Override public void execute() throws BuildException { if (property == null) { throw new BuildException("property attribute required", getLocation()); @@ -92,19 +93,21 @@ public class Basename extends Task { if (file == null) { throw new BuildException("file attribute required", getLocation()); } - String value = file.getName(); - if (suffix != null && value.endsWith(suffix)) { - // if the suffix does not starts with a '.' and the - // char preceding the suffix is a '.', we assume the user - // wants to remove the '.' as well (see docs) - int pos = value.length() - suffix.length(); - if (pos > 0 && suffix.charAt(0) != '.' - && value.charAt(pos - 1) == '.') { - pos--; - } - value = value.substring(0, pos); + getProject().setNewProperty(property, + removeExtension(file.getName(), suffix)); + } + + private String removeExtension(String s, String ext) { + if (ext == null || !s.endsWith(ext)) { + return s; } - getProject().setNewProperty(property, value); + int clipFrom = s.length() - ext.length(); + // if the suffix does not starts with a '.' and the + // char preceding the suffix is a '.', we assume the user + // wants to remove the '.' as well (see docs) + if (ext.charAt(0) != '.' && clipFrom > 0 && s.charAt(clipFrom - 1) == '.') { + clipFrom -= 1; + } + return s.substring(0, clipFrom); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/BindTargets.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/BindTargets.java b/src/main/org/apache/tools/ant/taskdefs/BindTargets.java index 45ad9ae..a78729d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/BindTargets.java +++ b/src/main/org/apache/tools/ant/taskdefs/BindTargets.java @@ -18,8 +18,8 @@ package org.apache.tools.ant.taskdefs; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectHelper; @@ -54,13 +54,8 @@ public class BindTargets extends Task { } public void setTargets(final String target) { - final String[] inputs = target.split(","); - for (int i = 0; i < inputs.length; i++) { - final String input = inputs[i].trim(); - if (input.length() > 0) { - targets.add(input); - } - } + Stream.of(target.split(",")).map(String::trim).filter(s -> !s.isEmpty()) + .forEach(targets::add); } @Override @@ -81,11 +76,9 @@ public class BindTargets extends Task { final ProjectHelper helper = (ProjectHelper) getProject().getReference( ProjectHelper.PROJECTHELPER_REFERENCE); - for (final Iterator<String> itTarget = targets.iterator(); itTarget.hasNext();) { - helper.getExtensionStack().add( - new String[] {extensionPoint, itTarget.next(), - onMissingExtensionPoint.name()}); + for (String target : targets) { + helper.getExtensionStack().add(new String[] { extensionPoint, + target, onMissingExtensionPoint.name() }); } - } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/BuildNumber.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/BuildNumber.java b/src/main/org/apache/tools/ant/taskdefs/BuildNumber.java index 30552f7..226ba7a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/BuildNumber.java +++ b/src/main/org/apache/tools/ant/taskdefs/BuildNumber.java @@ -25,7 +25,6 @@ import java.nio.file.Files; import java.util.Properties; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; @@ -40,8 +39,7 @@ import org.apache.tools.ant.util.FileUtils; * @since Ant 1.5 * @ant.task name="buildnumber" */ -public class BuildNumber - extends Task { +public class BuildNumber extends Task { /** * The name of the property in which the build number is stored. */ @@ -55,7 +53,6 @@ public class BuildNumber /** The File in which the build number is stored. */ private File myFile; - /** * The file in which the build number is stored. Defaults to * "build.number" if not specified. @@ -66,14 +63,13 @@ public class BuildNumber myFile = file; } - /** * Run task. * * @exception BuildException if an error occurs */ - public void execute() - throws BuildException { + @Override + public void execute() throws BuildException { File savedFile = myFile; // may be altered in validate validate(); @@ -85,26 +81,12 @@ public class BuildNumber String.valueOf(buildNumber + 1)); // Write the properties file back out - OutputStream output = null; - - try { - output = Files.newOutputStream(myFile.toPath()); - final String header = "Build Number for ANT. Do not edit!"; - - properties.store(output, header); + try (OutputStream output = Files.newOutputStream(myFile.toPath())) { + properties.store(output, "Build Number for ANT. Do not edit!"); } catch (final IOException ioe) { - final String message = "Error while writing " + myFile; - - throw new BuildException(message, ioe); + throw new BuildException("Error while writing " + myFile, ioe); } finally { - if (null != output) { - try { - output.close(); - } catch (final IOException ioe) { - log("error closing output stream " + ioe, Project.MSG_ERR); - } - } myFile = savedFile; } @@ -113,7 +95,6 @@ public class BuildNumber String.valueOf(buildNumber)); } - /** * Utility method to retrieve build number from properties object. * @@ -130,43 +111,28 @@ public class BuildNumber try { return Integer.parseInt(buildNumber); } catch (final NumberFormatException nfe) { - final String message = - myFile + " contains a non integer build number: " + buildNumber; - throw new BuildException(message, nfe); + throw new BuildException( + myFile + " contains a non integer build number: " + buildNumber, + nfe); } } - /** * Utility method to load properties from file. * * @return the loaded properties * @throws BuildException */ - private Properties loadProperties() - throws BuildException { - InputStream input = null; - - try { + private Properties loadProperties() throws BuildException { + try (InputStream input = Files.newInputStream(myFile.toPath())) { final Properties properties = new Properties(); - - input = Files.newInputStream(myFile.toPath()); properties.load(input); return properties; } catch (final IOException ioe) { throw new BuildException(ioe); - } finally { - if (null != input) { - try { - input.close(); - } catch (final IOException ioe) { - log("error closing input stream " + ioe, Project.MSG_ERR); - } - } } } - /** * Validate that the task parameters are valid. * @@ -182,21 +148,18 @@ public class BuildNumber try { FILE_UTILS.createNewFile(myFile); } catch (final IOException ioe) { - final String message = - myFile + " doesn't exist and new file can't be created."; - throw new BuildException(message, ioe); + throw new BuildException( + myFile + " doesn't exist and new file can't be created.", + ioe); } } if (!myFile.canRead()) { - final String message = "Unable to read from " + myFile + "."; - throw new BuildException(message); + throw new BuildException("Unable to read from " + myFile + "."); } if (!myFile.canWrite()) { - final String message = "Unable to write to " + myFile + "."; - throw new BuildException(message); + throw new BuildException("Unable to write to " + myFile + "."); } } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/CVSPass.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/CVSPass.java b/src/main/org/apache/tools/ant/taskdefs/CVSPass.java index af24504..b15c55d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/CVSPass.java +++ b/src/main/org/apache/tools/ant/taskdefs/CVSPass.java @@ -82,6 +82,7 @@ public class CVSPass extends Task { * * @exception BuildException if something goes wrong with the build */ + @Override public final void execute() throws BuildException { if (cvsRoot == null) { throw new BuildException("cvsroot is required"); @@ -97,7 +98,7 @@ public class CVSPass extends Task { BufferedReader reader = null; BufferedWriter writer = null; try { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if (passFile.exists()) { reader = new BufferedReader(new FileReader(passFile)); @@ -129,7 +130,7 @@ public class CVSPass extends Task { } private final String mangle(String password) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (int i = 0; i < password.length(); i++) { buf.append(shifts[password.charAt(i)]); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Checksum.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Checksum.java b/src/main/org/apache/tools/ant/taskdefs/Checksum.java index f30d8d7..3531b20 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Checksum.java +++ b/src/main/org/apache/tools/ant/taskdefs/Checksum.java @@ -71,6 +71,7 @@ public class Checksum extends MatchingTask implements Condition { super.add(u); super.add(Type.FILE); } + @Override public void add(ResourceCollection rc) { u.add(rc); } @@ -110,14 +111,14 @@ public class Checksum extends MatchingTask implements Condition { * Key: java.util.File (source file) * Value: java.lang.String (digest) */ - private Map<File, byte[]> allDigests = new HashMap<File, byte[]>(); + private Map<File, byte[]> allDigests = new HashMap<>(); /** * Holds relative file names for all files (always with a forward slash). * This is used to calculate the total hash. * Key: java.util.File (source file) * Value: java.lang.String (relative file name) */ - private Map<File, String> relativeFilePaths = new HashMap<File, String>(); + private Map<File, String> relativeFilePaths = new HashMap<>(); /** * Property where totalChecksum gets set. */ @@ -138,7 +139,7 @@ public class Checksum extends MatchingTask implements Condition { /** * Stores SourceFile, DestFile pairs and SourceFile, Property String pairs. */ - private Hashtable<File, Object> includeFileMap = new Hashtable<File, Object>(); + private Hashtable<File, Object> includeFileMap = new Hashtable<>(); /** * Message Digest instance */ @@ -294,13 +295,13 @@ public class Checksum extends MatchingTask implements Condition { * Calculate the checksum(s). * @throws BuildException on error */ + @Override public void execute() throws BuildException { isCondition = false; boolean value = validateAndExecute(); if (verifyProperty != null) { - getProject().setNewProperty( - verifyProperty, - (value ? Boolean.TRUE.toString() : Boolean.FALSE.toString())); + getProject().setNewProperty(verifyProperty, + Boolean.toString(value)); } } @@ -311,6 +312,7 @@ public class Checksum extends MatchingTask implements Condition { * false otherwise. * @throws BuildException on error */ + @Override public boolean eval() throws BuildException { isCondition = true; return validateAndExecute(); @@ -386,7 +388,7 @@ public class Checksum extends MatchingTask implements Condition { } if (fileext == null) { fileext = "." + algorithm; - } else if (fileext.trim().length() == 0) { + } else if (fileext.trim().isEmpty()) { throw new BuildException("File extension when specified must not be an empty string"); } try { @@ -463,8 +465,7 @@ public class Checksum extends MatchingTask implements Condition { // This directory will exist directory = file.getParentFile(); } - File checksumFile = new File(directory, file.getName() + fileext); - return checksumFile; + return new File(directory, file.getName() + fileext); } /** @@ -498,7 +499,7 @@ public class Checksum extends MatchingTask implements Condition { String checksum = createDigestString(fileDigest); //can either be a property name string or a file Object destination = e.getValue(); - if (destination instanceof java.lang.String) { + if (destination instanceof String) { String prop = (String) destination; if (isCondition) { checksumMatches @@ -506,7 +507,7 @@ public class Checksum extends MatchingTask implements Condition { } else { getProject().setNewProperty(prop, checksum); } - } else if (destination instanceof java.io.File) { + } else if (destination instanceof File) { if (isCondition) { File existingFile = (File) destination; if (existingFile.exists()) { @@ -550,14 +551,9 @@ public class Checksum extends MatchingTask implements Condition { File[] keyArray = allDigests.keySet().toArray(new File[allDigests.size()]); // File is Comparable, but sort-order is platform // dependent (case-insensitive on Windows) - Arrays.sort(keyArray, new Comparator<File>() { - public int compare(File f1, File f2) { - return f1 == null ? (f2 == null ? 0 : -1) - : (f2 == null ? 1 - : getRelativeFilePath(f1) - .compareTo(getRelativeFilePath(f2))); - } - }); + Arrays.sort(keyArray, Comparator.nullsFirst( + Comparator.comparing(this::getRelativeFilePath))); + // Loop over the checksums and generate a total hash. messageDigest.reset(); for (File src : keyArray) { @@ -582,11 +578,11 @@ public class Checksum extends MatchingTask implements Condition { } private String createDigestString(byte[] fileDigest) { - StringBuffer checksumSb = new StringBuffer(); + StringBuilder checksumSb = new StringBuilder(); for (int i = 0; i < fileDigest.length; i++) { String hexStr = Integer.toHexString(BYTE_MASK & fileDigest[i]); if (hexStr.length() < 2) { - checksumSb.append("0"); + checksumSb.append('0'); } checksumSb.append(hexStr); } @@ -630,20 +626,15 @@ public class Checksum extends MatchingTask implements Condition { * @since 1.7 */ private String readChecksum(File f) { - BufferedReader diskChecksumReader = null; - try { - diskChecksumReader = new BufferedReader(new FileReader(f)); + try (BufferedReader diskChecksumReader = + new BufferedReader(new FileReader(f))) { Object[] result = format.parse(diskChecksumReader.readLine()); if (result == null || result.length == 0 || result[0] == null) { throw new BuildException("failed to find a checksum"); } return (String) result[0]; - } catch (IOException e) { - throw new BuildException("Couldn't read checksum file " + f, e); - } catch (ParseException e) { + } catch (IOException | ParseException e) { throw new BuildException("Couldn't read checksum file " + f, e); - } finally { - FileUtils.close(diskChecksumReader); } } @@ -651,13 +642,12 @@ public class Checksum extends MatchingTask implements Condition { * @since Ant 1.8.2 */ private String getRelativeFilePath(File f) { - String path = (String) relativeFilePaths.get(f); + String path = relativeFilePaths.get(f); if (path == null) { //bug 37386. this should not occur, but it has, once. - throw new BuildException("Internal error: " - + "relativeFilePaths could not match file " - + f + "\n" - + "please file a bug report on this"); + throw new BuildException( + "Internal error: relativeFilePaths could not match file %s\nplease file a bug report on this", + f); } return path; } @@ -679,11 +669,6 @@ public class Checksum extends MatchingTask implements Condition { formatMap.put(SVF, new MessageFormat("MD5 ({1}) = {0}")); } - /** Constructor for FormatElement */ - public FormatElement() { - super(); - } - /** * Get the default value - CHECKSUM. * @return the defaul value. @@ -699,15 +684,16 @@ public class Checksum extends MatchingTask implements Condition { * @return a <code>MessageFormat</code> object. */ public MessageFormat getFormat() { - return (MessageFormat) formatMap.get(getValue()); + return formatMap.get(getValue()); } /** * Get the valid values. * @return an array of values. */ + @Override public String[] getValues() { - return new String[] {CHECKSUM, MD5SUM, SVF}; + return new String[] { CHECKSUM, MD5SUM, SVF }; } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Chmod.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Chmod.java b/src/main/org/apache/tools/ant/taskdefs/Chmod.java index ac0c3d8..a83dcd0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Chmod.java +++ b/src/main/org/apache/tools/ant/taskdefs/Chmod.java @@ -58,6 +58,7 @@ public class Chmod extends ExecuteOn { * @param project the project for this task. * @see org.apache.tools.ant.ProjectComponent#setProject */ + @Override public void setProject(Project project) { super.setProject(project); defaultSet.setProject(project); @@ -77,6 +78,7 @@ public class Chmod extends ExecuteOn { * The directory which holds the files whose permissions must be changed. * @param src the directory. */ + @Override public void setDir(File src) { defaultSet.setDir(src); } @@ -154,6 +156,7 @@ public class Chmod extends ExecuteOn { /** * Check the attributes and nested elements. */ + @Override protected void checkConfiguration() { if (!havePerm) { throw new BuildException("Required attribute perm not set in chmod", @@ -170,6 +173,7 @@ public class Chmod extends ExecuteOn { * Carry out the chmoding. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { /* * In Ant 1.1, <chmod dir="foo" /> means, change the permissions @@ -188,7 +192,7 @@ public class Chmod extends ExecuteOn { } else if (isValidOs()) { // we are chmodding the given directory Execute execute = prepareExec(); - Commandline cloned = (Commandline) cmdl.clone(); + Commandline cloned = cmdl.clone(); cloned.createArgument().setValue(defaultSet.getDir(getProject()) .getPath()); try { @@ -210,6 +214,7 @@ public class Chmod extends ExecuteOn { * @throws BuildException always. * @ant.attribute ignore="true" */ + @Override public void setExecutable(String e) { throw new BuildException(getTaskType() + " doesn\'t support the executable attribute", getLocation()); @@ -222,6 +227,7 @@ public class Chmod extends ExecuteOn { * @throws BuildException always. * @ant.attribute ignore="true" */ + @Override public void setCommand(Commandline cmdl) { throw new BuildException(getTaskType() + " doesn\'t support the command attribute", getLocation()); @@ -233,6 +239,7 @@ public class Chmod extends ExecuteOn { * @throws BuildException always. * @ant.attribute ignore="true" */ + @Override public void setSkipEmptyFilesets(boolean skip) { throw new BuildException(getTaskType() + " doesn\'t support the skipemptyfileset attribute", getLocation()); @@ -244,6 +251,7 @@ public class Chmod extends ExecuteOn { * @throws BuildException always. * @ant.attribute ignore="true" */ + @Override public void setAddsourcefile(boolean b) { throw new BuildException(getTaskType() + " doesn\'t support the addsourcefile attribute", getLocation()); @@ -254,6 +262,7 @@ public class Chmod extends ExecuteOn { * Always include unix. * @return true if the os is valid. */ + @Override protected boolean isValidOs() { return getOs() == null && getOsFamily() == null ? Os.isFamily(Os.FAMILY_UNIX) : super.isValidOs(); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Classloader.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Classloader.java b/src/main/org/apache/tools/ant/taskdefs/Classloader.java index 99d47a1..e13d111 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Classloader.java +++ b/src/main/org/apache/tools/ant/taskdefs/Classloader.java @@ -70,12 +70,6 @@ public class Classloader extends Task { private boolean parentFirst = true; private String parentName = null; - /** - * Default constructor - */ - public Classloader() { - } - /** Name of the loader. If none, the default loader will be modified * * @param name the name of this loader @@ -101,6 +95,7 @@ public class Classloader extends Task { * @param b if true reverse the normal classloader lookup. * @deprecated use setParentFirst with a negated argument instead */ + @Deprecated public void setReverse(boolean b) { this.parentFirst = !b; } @@ -156,17 +151,17 @@ public class Classloader extends Task { return this.classpath.createPath(); } - /** * do the classloader manipulation. */ + @Override public void execute() { try { // Gump friendly - don't mess with the core loader if only classpath if ("only".equals(getProject().getProperty("build.sysclasspath")) && (name == null || SYSTEM_LOADER_REF.equals(name))) { - log("Changing the system loader is disabled " - + "by build.sysclasspath=only", Project.MSG_WARN); + log("Changing the system loader is disabled by build.sysclasspath=only", + Project.MSG_WARN); return; } @@ -186,6 +181,7 @@ public class Classloader extends Task { return; } + @SuppressWarnings("resource") AntClassLoader acl = (AntClassLoader) obj; boolean existingLoader = acl != null; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Concat.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Concat.java b/src/main/org/apache/tools/ant/taskdefs/Concat.java index afffcef..27b3132 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Concat.java +++ b/src/main/org/apache/tools/ant/taskdefs/Concat.java @@ -130,7 +130,7 @@ public class Concat extends Task implements ResourceCollection { public void setFile(File file) throws BuildException { // non-existing files are not allowed if (!file.exists()) { - throw new BuildException("File " + file + " does not exist."); + throw new BuildException("File %s does not exist.", file); } BufferedReader reader = null; @@ -181,12 +181,12 @@ public class Concat extends Task implements ResourceCollection { if (value == null) { value = ""; } - if (value.trim().length() == 0) { + if (value.trim().isEmpty()) { value = ""; } if (trimLeading) { char[] current = value.toCharArray(); - StringBuffer b = new StringBuffer(current.length); + StringBuilder b = new StringBuilder(current.length); boolean startOfLine = true; int pos = 0; while (pos < current.length) { @@ -253,6 +253,7 @@ public class Concat extends Task implements ResourceCollection { * @exception IOException - possibly thrown by the read for a reader * object. */ + @Override public int read() throws IOException { if (needAddSeparator) { if (lastPos >= eolString.length()) { @@ -287,6 +288,7 @@ public class Concat extends Task implements ResourceCollection { * @exception IOException - possibly thrown by the reads to the * reader objects. */ + @Override public int read(char[] cbuf, int off, int len) throws IOException { @@ -334,14 +336,14 @@ public class Concat extends Task implements ResourceCollection { } if (amountRead == 0) { return -1; - } else { - return amountRead; } + return amountRead; } /** * Close the current reader */ + @Override public void close() throws IOException { if (reader != null) { reader.close(); @@ -383,6 +385,7 @@ public class Concat extends Task implements ResourceCollection { private ConcatResource(ResourceCollection c) { this.c = c; } + @Override public InputStream getInputStream() { if (binary) { ConcatResourceInputStream result = new ConcatResourceInputStream(c); @@ -424,6 +427,7 @@ public class Concat extends Task implements ResourceCollection { return outputEncoding == null ? new ReaderInputStream(rdr) : new ReaderInputStream(rdr, outputEncoding); } + @Override public String getName() { return resourceName == null ? "concat (" + String.valueOf(c) + ")" : resourceName; @@ -492,6 +496,7 @@ public class Concat extends Task implements ResourceCollection { private String resourceName; private ReaderFactory<Resource> resourceReaderFactory = new ReaderFactory<Resource>() { + @Override public Reader getReader(Resource o) throws IOException { InputStream is = o.getInputStream(); return new BufferedReader(encoding == null @@ -501,6 +506,7 @@ public class Concat extends Task implements ResourceCollection { }; private ReaderFactory<Reader> identityReaderFactory = new ReaderFactory<Reader>() { + @Override public Reader getReader(Reader o) { return o; } @@ -594,6 +600,7 @@ public class Concat extends Task implements ResourceCollection { * @since Ant 1.6 * @deprecated use #setOverwrite instead */ + @Deprecated public void setForce(boolean forceOverwrite) { this.forceOverwrite = forceOverwrite; } @@ -752,11 +759,11 @@ public class Concat extends Task implements ResourceCollection { */ public void setEol(FixCRLF.CrLf crlf) { String s = crlf.getValue(); - if (s.equals("cr") || s.equals("mac")) { + if ("cr".equals(s) || "mac".equals(s)) { eolString = "\r"; - } else if (s.equals("lf") || s.equals("unix")) { + } else if ("lf".equals(s) || "unix".equals(s)) { eolString = "\n"; - } else if (s.equals("crlf") || s.equals("dos")) { + } else if ("crlf".equals(s) || "dos".equals(s)) { eolString = "\r\n"; } } @@ -785,6 +792,7 @@ public class Concat extends Task implements ResourceCollection { /** * Execute the concat task. */ + @Override public void execute() { validate(); if (binary && dest == null) { @@ -796,7 +804,7 @@ public class Concat extends Task implements ResourceCollection { log(dest + " is up-to-date.", Project.MSG_VERBOSE); return; } - if (c.size() == 0 && ignoreEmpty) { + if (c.isEmpty() && ignoreEmpty) { return; } try { @@ -815,15 +823,19 @@ public class Concat extends Task implements ResourceCollection { * Implement ResourceCollection. * @return Iterator<Resource>. */ + @Override public Iterator<Resource> iterator() { validate(); - return Collections.<Resource>singletonList(new ConcatResource(getResources())).iterator(); + return Collections + .<Resource> singletonList(new ConcatResource(getResources())) + .iterator(); } /** * Implement ResourceCollection. * @return 1. */ + @Override public int size() { return 1; } @@ -832,6 +844,7 @@ public class Concat extends Task implements ResourceCollection { * Implement ResourceCollection. * @return false. */ + @Override public boolean isFilesystemOnly() { return false; } @@ -852,8 +865,7 @@ public class Concat extends Task implements ResourceCollection { } if (encoding != null || outputEncoding != null) { throw new BuildException( - "Setting input or output encoding is incompatible with binary" - + " concatenation"); + "Setting input or output encoding is incompatible with binary concatenation"); } if (filterChains != null) { throw new BuildException( @@ -899,8 +911,9 @@ public class Concat extends Task implements ResourceCollection { checkDestNotInSources.add(rc); checkDestNotInSources.add(dest); if (checkDestNotInSources.size() > 0) { - throw new BuildException("Destination resource " + dest - + " was specified as an input resource."); + throw new BuildException( + "Destination resource %s was specified as an input resource.", + dest); } } Restrict noexistRc = new Restrict(); @@ -919,12 +932,8 @@ public class Concat extends Task implements ResourceCollection { if (dest == null || forceOverwrite) { return false; } - for (Resource r : c) { - if (SelectorUtils.isOutOfDate(r, dest, FILE_UTILS.getFileTimestampGranularity())) { - return false; - } - } - return true; + return c.stream().noneMatch(r -> SelectorUtils.isOutOfDate(r, dest, + FILE_UTILS.getFileTimestampGranularity())); } /** @@ -934,7 +943,7 @@ public class Concat extends Task implements ResourceCollection { * for "ignorable whitespace" as well.</p> */ private void sanitizeText() { - if (textBuffer != null && "".equals(textBuffer.toString().trim())) { + if (textBuffer != null && textBuffer.toString().trim().isEmpty()) { textBuffer = null; } }
