http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/LoadResource.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/LoadResource.java b/src/main/org/apache/tools/ant/taskdefs/LoadResource.java index f68b5ba..1f44d20 100644 --- a/src/main/org/apache/tools/ant/taskdefs/LoadResource.java +++ b/src/main/org/apache/tools/ant/taskdefs/LoadResource.java @@ -19,19 +19,18 @@ package org.apache.tools.ant.taskdefs; import java.io.BufferedInputStream; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; -import java.io.Reader; +import java.nio.charset.Charset; +import java.util.List; import java.util.Vector; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.filters.util.ChainReaderHelper; +import org.apache.tools.ant.filters.util.ChainReaderHelper.ChainReader; import org.apache.tools.ant.types.FilterChain; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; -import org.apache.tools.ant.util.FileUtils; /** * Load a resource into a property @@ -70,7 +69,7 @@ public class LoadResource extends Task { /** * Holds FilterChains */ - private final Vector<FilterChain> filterChains = new Vector<FilterChain>(); + private final List<FilterChain> filterChains = new Vector<>(); /** * Encoding to use for input, defaults to the platform's default @@ -124,6 +123,7 @@ public class LoadResource extends Task { * * @exception BuildException if something goes wrong with the build */ + @Override public final void execute() throws BuildException { //validation @@ -134,82 +134,67 @@ public class LoadResource extends Task { throw new BuildException("output property not defined"); } if (quiet && failOnError) { - throw new BuildException("quiet and failonerror cannot both be " - + "set to true"); + throw new BuildException("quiet and failonerror cannot both be set to true"); } if (!src.isExists()) { String message = src + " doesn't exist"; if (failOnError) { throw new BuildException(message); - } else { - log(message, quiet ? Project.MSG_WARN : Project.MSG_ERR); - return; } + log(message, quiet ? Project.MSG_WARN : Project.MSG_ERR); + return; } - InputStream is = null; - BufferedInputStream bis = null; - Reader instream = null; + log("loading " + src + " into property " + property, Project.MSG_VERBOSE); + + Charset charset = encoding == null ? Charset.defaultCharset() + : Charset.forName(encoding); try { final long len = src.getSize(); - log("resource size = " - + (len != Resource.UNKNOWN_SIZE ? String.valueOf(len) - : "unknown"), Project.MSG_DEBUG); + log("resource size = " + (len != Resource.UNKNOWN_SIZE + ? String.valueOf(len) : "unknown"), Project.MSG_DEBUG); //discard most of really big resources final int size = (int) len; //open up the resource - is = src.getInputStream(); - bis = new BufferedInputStream(is); - if (encoding == null) { - instream = new InputStreamReader(bis); - } else { - instream = new InputStreamReader(bis, encoding); - } - String text = ""; + String text; if (size != 0) { - ChainReaderHelper crh = new ChainReaderHelper(); - if (len != Resource.UNKNOWN_SIZE) { - crh.setBufferSize(size); + try (ChainReader chainReader = new ChainReaderHelper( + getProject(), + new InputStreamReader( + new BufferedInputStream(src.getInputStream()), charset), + filterChains).with(crh -> { + if (src.getSize() != Resource.UNKNOWN_SIZE) { + crh.setBufferSize(size); + } + }).getAssembledReader()) { + + text = chainReader.readFully(); } - crh.setPrimaryReader(instream); - crh.setFilterChains(filterChains); - crh.setProject(getProject()); - instream = crh.getAssembledReader(); - - text = crh.readFully(instream); } else { log("Do not set property " + property + " as its length is 0.", quiet ? Project.MSG_VERBOSE : Project.MSG_INFO); + text = null; } - if (text != null) { - if (text.length() > 0) { - getProject().setNewProperty(property, text); - log("loaded " + text.length() + " characters", - Project.MSG_VERBOSE); - log(property + " := " + text, Project.MSG_DEBUG); - } + if (!(text == null || text.isEmpty())) { + getProject().setNewProperty(property, text); + log("loaded " + text.length() + " characters", + Project.MSG_VERBOSE); + log(property + " := " + text, Project.MSG_DEBUG); } - } catch (final IOException ioe) { - final String message = "Unable to load resource: " - + ioe.toString(); + final String message = "Unable to load resource: " + ioe; if (failOnError) { throw new BuildException(message, ioe, getLocation()); - } else { - log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); } + log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); } catch (final BuildException be) { if (failOnError) { throw be; - } else { - log(be.getMessage(), - quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); } - } finally { - FileUtils.close(is); + log(be.getMessage(), quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); } } @@ -218,7 +203,7 @@ public class LoadResource extends Task { * @param filter the filter to add */ public final void addFilterChain(FilterChain filter) { - filterChains.addElement(filter); + filterChains.add(filter); } /** @@ -227,8 +212,8 @@ public class LoadResource extends Task { */ 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"); } src = a.iterator().next(); }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/LogStreamHandler.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/LogStreamHandler.java b/src/main/org/apache/tools/ant/taskdefs/LogStreamHandler.java index bc69c06..d25ecb2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/LogStreamHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/LogStreamHandler.java @@ -18,9 +18,6 @@ package org.apache.tools.ant.taskdefs; -import java.io.IOException; - -import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; @@ -58,6 +55,7 @@ public class LogStreamHandler extends PumpStreamHandler { /** * Stop the log stream handler. */ + @Override public void stop() { super.stop(); FileUtils.close(getErr()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/MacroDef.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java index 95757b6..ce04612 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MacroDef.java +++ b/src/main/org/apache/tools/ant/taskdefs/MacroDef.java @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import org.apache.tools.ant.AntTypeDefinition; import org.apache.tools.ant.BuildException; @@ -42,13 +43,13 @@ import org.apache.tools.ant.UnknownElement; public class MacroDef extends AntlibDefinition { private NestedSequential nestedSequential; - private String name; - private boolean backTrace = true; - private List<Attribute> attributes = new ArrayList<Attribute>(); - private Map<String, TemplateElement> elements = new HashMap<String, TemplateElement>(); - private String textName = null; - private Text text = null; - private boolean hasImplicitElement = false; + private String name; + private boolean backTrace = true; + private List<Attribute> attributes = new ArrayList<>(); + private Map<String, TemplateElement> elements = new HashMap<>(); + private String textName = null; + private Text text = null; + private boolean hasImplicitElement = false; /** * Name of the definition @@ -76,8 +77,8 @@ public class MacroDef extends AntlibDefinition { for (Attribute attribute : attributes) { if (text.getName().equals(attribute.getName())) { throw new BuildException( - "the name \"" + text.getName() - + "\" is already used as an attribute"); + "the name \"%s\" is already used as an attribute", + text.getName()); } } this.text = text; @@ -132,13 +133,14 @@ public class MacroDef extends AntlibDefinition { * This is a simple task container. */ public static class NestedSequential implements TaskContainer { - private List<Task> nested = new ArrayList<Task>(); + private List<Task> nested = new ArrayList<>(); /** * Add a task or type to the container. * * @param task an unknown element. */ + @Override public void addTask(Task task) { nested.add(task); } @@ -258,17 +260,16 @@ public class MacroDef extends AntlibDefinition { } if (attribute.getName().equals(textName)) { throw new BuildException( - "the name \"" + attribute.getName() - + "\" has already been used by the text element"); + "the name \"%s\" has already been used by the text element", + attribute.getName()); } final int size = attributes.size(); for (int i = 0; i < size; ++i) { - Attribute att = (Attribute) attributes.get(i); + Attribute att = attributes.get(i); if (att.getName().equals(attribute.getName())) { throw new BuildException( - "the name \"" + attribute.getName() - + "\" has already been used in " - + "another attribute element"); + "the name \"%s\" has already been used in another attribute element", + attribute.getName()); } } attributes.add(attribute); @@ -286,11 +287,10 @@ public class MacroDef extends AntlibDefinition { } if (elements.get(element.getName()) != null) { throw new BuildException( - "the element " + element.getName() - + " has already been specified"); + "the element %s has already been specified", element.getName()); } if (hasImplicitElement - || (element.isImplicit() && elements.size() != 0)) { + || (element.isImplicit() && !elements.isEmpty())) { throw new BuildException( "Only one element allowed when using implicit elements"); } @@ -301,6 +301,7 @@ public class MacroDef extends AntlibDefinition { /** * Create a new ant type based on the embedded tasks and types. */ + @Override public void execute() { if (nestedSequential == null) { throw new BuildException("Missing sequential element"); @@ -322,7 +323,6 @@ public class MacroDef extends AntlibDefinition { log("creating macro " + name, Project.MSG_VERBOSE); } - /** * An attribute for the MacroDef task. * @@ -340,8 +340,8 @@ public class MacroDef extends AntlibDefinition { */ public void setName(String name) { if (!isValidName(name)) { - throw new BuildException( - "Illegal name [" + name + "] for attribute"); + throw new BuildException("Illegal name [%s] for attribute", + name); } this.name = name.toLowerCase(Locale.ENGLISH); } @@ -412,6 +412,7 @@ public class MacroDef extends AntlibDefinition { * @param obj an <code>Object</code> value * @return a <code>boolean</code> value */ + @Override public boolean equals(Object obj) { if (obj == null) { return false; @@ -440,8 +441,9 @@ public class MacroDef extends AntlibDefinition { /** * @return a hash code value for this object. */ + @Override public int hashCode() { - return objectHashCode(defaultValue) + objectHashCode(name); + return Objects.hashCode(defaultValue) + Objects.hashCode(name); } } @@ -463,8 +465,8 @@ public class MacroDef extends AntlibDefinition { */ public void setName(String name) { if (!isValidName(name)) { - throw new BuildException( - "Illegal name [" + name + "] for attribute"); + throw new BuildException("Illegal name [%s] for element", + name); } this.name = name.toLowerCase(Locale.ENGLISH); } @@ -544,6 +546,7 @@ public class MacroDef extends AntlibDefinition { * @param obj an <code>Object</code> value * @return a <code>boolean</code> value */ + @Override public boolean equals(Object obj) { if (obj == null) { return false; @@ -552,24 +555,21 @@ public class MacroDef extends AntlibDefinition { return false; } Text other = (Text) obj; - return safeCompare(name, other.name) + return Objects.equals(name, other.name) && optional == other.optional && trim == other.trim - && safeCompare(defaultString, other.defaultString); + && Objects.equals(defaultString, other.defaultString); } /** * @return a hash code value for this object. */ + @Override public int hashCode() { - return objectHashCode(name); + return Objects.hashCode(name); } } - private static boolean safeCompare(Object a, Object b) { - return a == null ? b == null : a.equals(b); - } - /** * A nested element for the MacroDef task. */ @@ -587,8 +587,8 @@ public class MacroDef extends AntlibDefinition { */ public void setName(String name) { if (!isValidName(name)) { - throw new BuildException( - "Illegal name [" + name + "] for macro element"); + throw new BuildException("Illegal name [%s] for macro element", + name); } this.name = name.toLowerCase(Locale.ENGLISH); } @@ -668,6 +668,7 @@ public class MacroDef extends AntlibDefinition { * @param obj an <code>Object</code> value * @return a <code>boolean</code> value */ + @Override public boolean equals(Object obj) { if (obj == this) { return true; @@ -685,8 +686,9 @@ public class MacroDef extends AntlibDefinition { /** * @return a hash code value for this object. */ + @Override public int hashCode() { - return objectHashCode(name) + return Objects.hashCode(name) + (optional ? 1 : 0) + (implicit ? 1 : 0); } @@ -729,21 +731,17 @@ public class MacroDef extends AntlibDefinition { if (other.text != null) { return false; } - } else { - if (!text.equals(other.text)) { - return false; - } + } else if (!text.equals(other.text)) { + return false; } - if (getURI() == null || getURI().equals("") + if (getURI() == null || "".equals(getURI()) || getURI().equals(ProjectHelper.ANT_CORE_URI)) { - if (!(other.getURI() == null || other.getURI().equals("") + if (!(other.getURI() == null || "".equals(other.getURI()) || other.getURI().equals(ProjectHelper.ANT_CORE_URI))) { return false; } - } else { - if (!getURI().equals(other.getURI())) { - return false; - } + } else if (!getURI().equals(other.getURI())) { + return false; } if (!nestedSequential.similar(other.nestedSequential)) { @@ -801,6 +799,7 @@ public class MacroDef extends AntlibDefinition { * @param project the current project * @return the created object */ + @Override public Object create(Project project) { Object o = super.create(project); if (o == null) { @@ -817,6 +816,7 @@ public class MacroDef extends AntlibDefinition { * @param project the current project * @return true if the definitions are the same */ + @Override public boolean sameDefinition(AntTypeDefinition other, Project project) { if (!super.sameDefinition(other, project)) { return false; @@ -832,6 +832,7 @@ public class MacroDef extends AntlibDefinition { * @param project the current project * @return true if the definitions are the same */ + @Override public boolean similarDefinition( AntTypeDefinition other, Project project) { if (!super.similarDefinition(other, project)) { @@ -842,12 +843,4 @@ public class MacroDef extends AntlibDefinition { } } - private static int objectHashCode(Object o) { - if (o == null) { - return 0; - } else { - return o.hashCode(); - } - } - } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java b/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java index 9ffa9b2..12249e6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java +++ b/src/main/org/apache/tools/ant/taskdefs/MacroInstance.java @@ -23,11 +23,9 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import org.apache.tools.ant.BuildException; @@ -50,13 +48,13 @@ import org.apache.tools.ant.taskdefs.MacroDef.Attribute; */ public class MacroInstance extends Task implements DynamicAttribute, TaskContainer { private MacroDef macroDef; - private Map<String, String> map = new HashMap<String, String>(); - private Map<String, MacroDef.TemplateElement> nsElements = null; - private Map<String, UnknownElement> presentElements; - private Hashtable<String, String> localAttributes; - private String text = null; - private String implicitTag = null; - private List<Task> unknownElements = new ArrayList<Task>(); + private Map<String, String> map = new HashMap<>(); + private Map<String, MacroDef.TemplateElement> nsElements = null; + private Map<String, UnknownElement> presentElements; + private Map<String, String> localAttributes; + private String text = null; + private String implicitTag = null; + private List<Task> unknownElements = new ArrayList<>(); /** * Called from MacroDef.MyAntTypeDefinition#create() @@ -80,6 +78,7 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain * @param name the name of the attribute * @param value the value of the attribute */ + @Override public void setDynamicAttribute(String name, String value) { map.put(name.toLowerCase(Locale.ENGLISH), value); } @@ -91,22 +90,22 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain * @deprecated since 1.6.x. * @throws BuildException always */ + @Deprecated public Object createDynamicElement(String name) throws BuildException { throw new BuildException("Not implemented any more"); } private Map<String, MacroDef.TemplateElement> getNsElements() { if (nsElements == null) { - nsElements = new HashMap<String, MacroDef.TemplateElement>(); - for (Entry<String, MacroDef.TemplateElement> entry : macroDef.getElements().entrySet()) { - nsElements.put((String) entry.getKey(), - entry.getValue()); - MacroDef.TemplateElement te = (MacroDef.TemplateElement) - entry.getValue(); - if (te.isImplicit()) { - implicitTag = te.getName(); + nsElements = new HashMap<>(); + for (Map.Entry<String, MacroDef.TemplateElement> entry : macroDef + .getElements().entrySet()) { + nsElements.put(entry.getKey(), entry.getValue()); + MacroDef.TemplateElement te = entry.getValue(); + if (te.isImplicit()) { + implicitTag = te.getName(); + } } - } } return nsElements; } @@ -116,6 +115,7 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain * * @param nestedTask a nested element. */ + @Override public void addTask(Task nestedTask) { unknownElements.add(nestedTask); } @@ -124,15 +124,15 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain if (implicitTag != null) { return; } - for (Iterator<Task> i = unknownElements.iterator(); i.hasNext();) { - UnknownElement ue = (UnknownElement) i.next(); + for (Task task : unknownElements) { + UnknownElement ue = (UnknownElement) task; String name = ProjectHelper.extractNameFromComponentName( ue.getTag()).toLowerCase(Locale.ENGLISH); if (getNsElements().get(name) == null) { - throw new BuildException("unsupported element " + name); + throw new BuildException("unsupported element %s", name); } if (presentElements.get(name) != null) { - throw new BuildException("Element " + name + " already present"); + throw new BuildException("Element %s already present", name); } presentElements.put(name, ue); } @@ -142,13 +142,14 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain * Embedded element in macro instance */ public static class Element implements TaskContainer { - private List<Task> unknownElements = new ArrayList<Task>(); + private List<Task> unknownElements = new ArrayList<>(); /** * Add an unknown element (to be snipped into the macroDef instance) * * @param nestedTask an unknown element */ + @Override public void addTask(Task nestedTask) { unknownElements.add(nestedTask); } @@ -169,8 +170,8 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain if (s == null) { return null; } - StringBuffer ret = new StringBuffer(); - StringBuffer macroName = null; + StringBuilder ret = new StringBuilder(); + StringBuilder macroName = null; int state = STATE_NORMAL; for (int i = 0; i < s.length(); ++i) { @@ -186,7 +187,7 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain case STATE_EXPECT_BRACKET: if (ch == '{') { state = STATE_EXPECT_NAME; - macroName = new StringBuffer(); + macroName = new StringBuilder(); } else if (ch == '@') { state = STATE_NORMAL; ret.append('@'); @@ -203,7 +204,7 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain if (ch == '}') { state = STATE_NORMAL; String name = macroName.toString().toLowerCase(Locale.ENGLISH); //NOSONAR - String value = (String) macroMapping.get(name); + String value = macroMapping.get(name); if (value == null) { ret.append("@{"); ret.append(name); @@ -292,40 +293,36 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain rc.addChild(child.getWrapper()); ret.addChild(child); } else if (templateElement.isImplicit()) { - if (unknownElements.size() == 0 && !templateElement.isOptional()) { + if (unknownElements.isEmpty() && !templateElement.isOptional()) { throw new BuildException( - "Missing nested elements for implicit element " - + templateElement.getName()); + "Missing nested elements for implicit element %s", + templateElement.getName()); } - for (Iterator<Task> i = unknownElements.iterator(); - i.hasNext();) { - UnknownElement child - = copy((UnknownElement) i.next(), true); + for (Task task : unknownElements) { + UnknownElement child = copy((UnknownElement) task, true); rc.addChild(child.getWrapper()); ret.addChild(child); } } else { UnknownElement presentElement = - (UnknownElement) presentElements.get(tag); + presentElements.get(tag); if (presentElement == null) { if (!templateElement.isOptional()) { throw new BuildException( - "Required nested element " - + templateElement.getName() + " missing"); + "Required nested element %s missing", + templateElement.getName()); } continue; } String presentText = presentElement.getWrapper().getText().toString(); - if (!"".equals(presentText)) { + if (!presentText.isEmpty()) { rc.addText(macroSubs(presentText, localAttributes)); } List<UnknownElement> list = presentElement.getChildren(); if (list != null) { - for (Iterator<UnknownElement> i = list.iterator(); - i.hasNext();) { - UnknownElement child - = copy(i.next(), true); + for (UnknownElement unknownElement2 : list) { + UnknownElement child = copy(unknownElement2, true); rc.addChild(child.getWrapper()); ret.addChild(child); } @@ -341,14 +338,15 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain * and calls perform on the unknown element. * */ + @Override public void execute() { - presentElements = new HashMap<String, UnknownElement>(); + presentElements = new HashMap<>(); getNsElements(); processTasks(); - localAttributes = new Hashtable<String, String>(); - Set<String> copyKeys = new HashSet<String>(map.keySet()); + localAttributes = new Hashtable<>(); + Set<String> copyKeys = new HashSet<>(map.keySet()); for (Attribute attribute : macroDef.getAttributes()) { - String value = (String) map.get(attribute.getName()); + String value = map.get(attribute.getName()); if (value == null && "description".equals(attribute.getName())) { value = getDescription(); } @@ -357,21 +355,19 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain value = macroSubs(value, localAttributes); } if (value == null) { - throw new BuildException( - "required attribute " + attribute.getName() + " not set"); + throw new BuildException("required attribute %s not set", + attribute.getName()); } localAttributes.put(attribute.getName(), value); copyKeys.remove(attribute.getName()); } - if (copyKeys.contains("id")) { - copyKeys.remove("id"); - } + copyKeys.remove("id"); + if (macroDef.getText() != null) { if (text == null) { String defaultText = macroDef.getText().getDefault(); if (!macroDef.getText().getOptional() && defaultText == null) { - throw new BuildException( - "required text missing"); + throw new BuildException("required text missing"); } text = defaultText == null ? "" : defaultText; } @@ -379,24 +375,20 @@ public class MacroInstance extends Task implements DynamicAttribute, TaskContain text = text.trim(); } localAttributes.put(macroDef.getText().getName(), text); - } else { - if (text != null && !text.trim().equals("")) { - throw new BuildException( - "The \"" + getTaskName() + "\" macro does not support" - + " nested text data."); - } - } - if (copyKeys.size() != 0) { + } else if (!(text == null || text.trim().isEmpty())) { throw new BuildException( - "Unknown attribute" + (copyKeys.size() > 1 ? "s " : " ") - + copyKeys); + "The \"%s\" macro does not support nested text data.", + getTaskName()); + } + if (!copyKeys.isEmpty()) { + throw new BuildException("Unknown attribute" + + (copyKeys.size() > 1 ? "s " : " ") + copyKeys); } // need to set the project on unknown element UnknownElement c = copy(macroDef.getNestedTask(), false); c.init(); - LocalProperties localProperties - = LocalProperties.get(getProject()); + LocalProperties localProperties = LocalProperties.get(getProject()); localProperties.enterScope(); try { c.perform(); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java b/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java index e23c025..09e252b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java +++ b/src/main/org/apache/tools/ant/taskdefs/MakeUrl.java @@ -21,7 +21,6 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.util.LinkedList; import java.util.List; -import java.util.ListIterator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; @@ -42,6 +41,13 @@ import org.apache.tools.ant.util.FileUtils; */ public class MakeUrl extends Task { + // error message strings + /** Missing file */ + public static final String ERROR_MISSING_FILE = "A source file is missing: "; + /** No property defined */ + public static final String ERROR_NO_PROPERTY = "No property defined"; + /** No files defined */ + public static final String ERROR_NO_FILES = "No files defined"; /** * name of the property to set @@ -61,26 +67,18 @@ public class MakeUrl extends Task { /** * filesets of nested files to add to this url */ - private List<FileSet> filesets = new LinkedList<FileSet>(); + private List<FileSet> filesets = new LinkedList<>(); /** * paths to add */ - private List<Path> paths = new LinkedList<Path>(); + private List<Path> paths = new LinkedList<>(); /** * validation flag */ private boolean validate = true; - // error message strings - /** Missing file */ - public static final String ERROR_MISSING_FILE = "A source file is missing: "; - /** No property defined */ - public static final String ERROR_NO_PROPERTY = "No property defined"; - /** No files defined */ - public static final String ERROR_NO_FILES = "No files defined"; - /** * set the name of a property to fill with the URL * @@ -149,13 +147,10 @@ public class MakeUrl extends Task { } int count = 0; StringBuilder urls = new StringBuilder(); - ListIterator<FileSet> list = filesets.listIterator(); - while (list.hasNext()) { - FileSet set = list.next(); - DirectoryScanner scanner = set.getDirectoryScanner(getProject()); - String[] files = scanner.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - File f = new File(scanner.getBasedir(), files[i]); + for (FileSet fs : filesets) { + DirectoryScanner scanner = fs.getDirectoryScanner(getProject()); + for (String file : scanner.getIncludedFiles()) { + File f = new File(scanner.getBasedir(), file); validateFile(f); String asUrl = toURL(f); urls.append(asUrl); @@ -181,9 +176,8 @@ public class MakeUrl extends Task { if (count > 0) { urls.delete(urls.length() - separator.length(), urls.length()); return new String(urls); - } else { - return ""; } + return ""; } @@ -198,12 +192,9 @@ public class MakeUrl extends Task { } int count = 0; StringBuilder urls = new StringBuilder(); - ListIterator<Path> list = paths.listIterator(); - while (list.hasNext()) { - Path path = list.next(); - String[] elements = path.list(); - for (int i = 0; i < elements.length; i++) { - File f = new File(elements[i]); + for (Path path : paths) { + for (String element : path.list()) { + File f = new File(element); validateFile(f); String asUrl = toURL(f); urls.append(asUrl); @@ -224,7 +215,7 @@ public class MakeUrl extends Task { */ private void validateFile(File fileToCheck) { if (validate && !fileToCheck.exists()) { - throw new BuildException(ERROR_MISSING_FILE + fileToCheck.toString()); + throw new BuildException(ERROR_MISSING_FILE + fileToCheck); } } @@ -243,23 +234,23 @@ public class MakeUrl extends Task { } String url; String filesetURL = filesetsToURL(); - if (file != null) { + if (file == null) { + url = filesetURL; + } else { validateFile(file); url = toURL(file); //and add any files if also defined - if (filesetURL.length() > 0) { + if (!filesetURL.isEmpty()) { url = url + separator + filesetURL; } - } else { - url = filesetURL; } //add path URLs String pathURL = pathsToURL(); - if (pathURL.length() > 0) { - if (url.length() > 0) { - url = url + separator + pathURL; - } else { + if (!pathURL.isEmpty()) { + if (url.isEmpty()) { url = pathURL; + } else { + url = url + separator + pathURL; } } log("Setting " + property + " to URL " + url, Project.MSG_VERBOSE); @@ -287,12 +278,9 @@ public class MakeUrl extends Task { * @return the file converted to a URL */ private String toURL(File fileToConvert) { - String url; //create the URL //ant equivalent of fileToConvert.toURI().toURL().toExternalForm(); - url = FileUtils.getFileUtils().toURI(fileToConvert.getAbsolutePath()); - - return url; + return FileUtils.getFileUtils().toURI(fileToConvert.getAbsolutePath()); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Manifest.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Manifest.java b/src/main/org/apache/tools/ant/taskdefs/Manifest.java index 0d7c05e..f47f461 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Manifest.java +++ b/src/main/org/apache/tools/ant/taskdefs/Manifest.java @@ -26,11 +26,15 @@ import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; +import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; +import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Vector; +import java.util.stream.Collectors; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.util.CollectionUtils; @@ -168,14 +172,7 @@ public class Manifest { */ @Override public int hashCode() { - int hashCode = 0; - - if (name != null) { - hashCode += getKey().hashCode(); - } - - hashCode += values.hashCode(); - return hashCode; + return Objects.hash(getKey(), values); } /** @@ -216,8 +213,7 @@ public class Manifest { int index = line.indexOf(": "); if (index == -1) { throw new ManifestException("Manifest line \"" + line - + "\" is not valid as it does not " - + "contain a name and a value separated by ': ' "); + + "\" is not valid as it does not contain a name and a value separated by ': '"); } name = line.substring(0, index); setValue(line.substring(index + 2)); @@ -273,16 +269,8 @@ public class Manifest { * @return the attribute's value. */ public String getValue() { - if (values.size() == 0) { - return null; - } - - String fullValue = ""; - for (Enumeration<String> e = getValues(); e.hasMoreElements();) { - String value = e.nextElement(); - fullValue += value + " "; - } - return fullValue.trim(); + return values.isEmpty() ? null + : values.stream().collect(Collectors.joining(" ")); } /** @@ -343,12 +331,12 @@ public class Manifest { */ public void write(PrintWriter writer, boolean flatten) throws IOException { - if (!flatten) { - for (Enumeration<String> e = getValues(); e.hasMoreElements();) { - writeValue(writer, e.nextElement()); - } - } else { + if (flatten) { writeValue(writer, getValue()); + } else { + for (String value : values) { + writeValue(writer, value); + } } } @@ -362,7 +350,7 @@ public class Manifest { */ private void writeValue(PrintWriter writer, String value) throws IOException { - String line = null; + String line; int nameLength = name.getBytes(JAR_ENCODING).length; if (nameLength > MAX_NAME_VALUE_LENGTH) { if (nameLength > MAX_NAME_LENGTH) { @@ -404,7 +392,7 @@ public class Manifest { */ public static class Section { /** Warnings for this section */ - private Vector<String> warnings = new Vector<String>(); + private List<String> warnings = new Vector<>(); /** * The section's name if any. The main section in a @@ -413,7 +401,7 @@ public class Manifest { private String name = null; /** The section's attributes.*/ - private Map<String, Attribute> attributes = new LinkedHashMap<String, Attribute>(); + private Map<String, Attribute> attributes = new LinkedHashMap<>(); /** * The name of the section; optional -default is the main section. @@ -450,21 +438,20 @@ public class Manifest { Attribute attribute = null; while (true) { String line = reader.readLine(); - if (line == null || line.length() == 0) { + if (line == null || line.isEmpty()) { return null; } if (line.charAt(0) == ' ') { // continuation line if (attribute == null) { - if (name != null) { - // a continuation on the first line is a - // continuation of the name - concatenate this - // line and the name - name += line.substring(1); - } else { + if (name == null) { throw new ManifestException("Can't start an " + "attribute with a continuation line " + line); } + // a continuation on the first line is a + // continuation of the name - concatenate this + // line and the name + name += line.substring(1); } else { attribute.addContinuation(line); } @@ -507,8 +494,8 @@ public class Manifest { && !(name.toLowerCase(Locale.ENGLISH) .equals(section.getName().toLowerCase(Locale.ENGLISH)))) ) { - throw new ManifestException("Unable to merge sections " - + "with different names"); + throw new ManifestException( + "Unable to merge sections with different names"); } Enumeration<String> e = section.getAttributeKeys(); @@ -516,7 +503,7 @@ public class Manifest { while (e.hasMoreElements()) { String attributeName = e.nextElement(); Attribute attribute = section.getAttribute(attributeName); - if (attributeName.equalsIgnoreCase(ATTRIBUTE_CLASSPATH)) { + if (ATTRIBUTE_CLASSPATH.equalsIgnoreCase(attributeName)) { if (classpathAttribute == null) { classpathAttribute = new Attribute(); classpathAttribute.setName(ATTRIBUTE_CLASSPATH); @@ -547,10 +534,7 @@ public class Manifest { } // add in the warnings - Enumeration<String> warnEnum = section.warnings.elements(); - while (warnEnum.hasMoreElements()) { - warnings.addElement(warnEnum.nextElement()); - } + warnings.addAll(section.warnings); } /** @@ -650,9 +634,8 @@ public class Manifest { throws ManifestException { String check = addAttributeAndCheck(attribute); if (check != null) { - throw new BuildException("Specify the section name using " - + "the \"name\" attribute of the <section> element rather " - + "than using a \"Name\" manifest attribute"); + throw new BuildException( + "Specify the section name using the \"name\" attribute of the <section> element rather than using a \"Name\" manifest attribute"); } } @@ -674,15 +657,14 @@ public class Manifest { } String attributeKey = attribute.getKey(); if (attributeKey.equals(ATTRIBUTE_NAME_LC)) { - warnings.addElement("\"" + ATTRIBUTE_NAME + "\" attributes " - + "should not occur in the main section and must be the " - + "first element in all other sections: \"" + warnings.add("\"" + ATTRIBUTE_NAME + + "\" attributes should not occur in the main section and must be the first element in all other sections: \"" + attribute.getName() + ": " + attribute.getValue() + "\""); return attribute.getValue(); } if (attributeKey.startsWith(ATTRIBUTE_FROM_LC)) { - warnings.addElement(ERROR_FROM_FORBIDDEN + warnings.add(ERROR_FROM_FORBIDDEN + attribute.getName() + ": " + attribute.getValue() + "\""); } else { // classpath attributes go into a vector @@ -693,10 +675,8 @@ public class Manifest { if (classpathAttribute == null) { storeAttribute(attribute); } else { - warnings.addElement("Multiple Class-Path attributes " - + "are supported but violate the Jar " - + "specification and may not be correctly " - + "processed in all environments"); + warnings.add( + "Multiple Class-Path attributes are supported but violate the Jar specification and may not be correctly processed in all environments"); Enumeration<String> e = attribute.getValues(); while (e.hasMoreElements()) { String value = e.nextElement(); @@ -705,8 +685,8 @@ public class Manifest { } } else if (attributes.containsKey(attributeKey)) { throw new ManifestException("The attribute \"" - + attribute.getName() + "\" may not occur more " - + "than once in the same section"); + + attribute.getName() + + "\" may not occur more than once in the same section"); } else { storeAttribute(attribute); } @@ -721,7 +701,7 @@ public class Manifest { * @since Ant 1.5.2 */ @Override - public Object clone() { + public Section clone() { Section cloned = new Section(); cloned.setName(name); Enumeration<String> e = getAttributeKeys(); @@ -753,7 +733,7 @@ public class Manifest { * @return an Enumeration of warning strings. */ public Enumeration<String> getWarnings() { - return warnings.elements(); + return Collections.enumeration(warnings); } /** @@ -794,7 +774,7 @@ public class Manifest { private Section mainSection = new Section(); /** The named sections of this manifest */ - private Map<String, Section> sections = new LinkedHashMap<String, Section>(); + private Map<String, Section> sections = new LinkedHashMap<>(); /** * Construct a manifest from Ant's default manifest file. @@ -804,14 +784,12 @@ public class Manifest { * default manifest */ public static Manifest getDefaultManifest() throws BuildException { - InputStream in = null; InputStreamReader insr = null; - try { - String defManifest = "/org/apache/tools/ant/defaultManifest.mf"; - in = Manifest.class.getResourceAsStream(defManifest); + String defManifest = "/org/apache/tools/ant/defaultManifest.mf"; + try (InputStream in = Manifest.class.getResourceAsStream(defManifest)) { if (in == null) { - throw new BuildException("Could not find default manifest: " - + defManifest); + throw new BuildException("Could not find default manifest: %s", + defManifest); } try { insr = new InputStreamReader(in, "UTF-8"); @@ -835,7 +813,6 @@ public class Manifest { throw new BuildException("Unable to read default manifest", e); } finally { FileUtils.close(insr); - FileUtils.close(in); } } @@ -864,20 +841,20 @@ public class Manifest { mainSection.removeAttribute(ATTRIBUTE_MANIFEST_VERSION); } - String line = null; + String line; while ((line = reader.readLine()) != null) { - if (line.length() == 0) { + if (line.isEmpty()) { continue; } Section section = new Section(); if (nextSectionName == null) { Attribute sectionName = new Attribute(line); - if (!sectionName.getName().equalsIgnoreCase(ATTRIBUTE_NAME)) { - throw new ManifestException("Manifest sections should " - + "start with a \"" + ATTRIBUTE_NAME - + "\" attribute and not \"" - + sectionName.getName() + "\""); + if (!ATTRIBUTE_NAME.equalsIgnoreCase(sectionName.getName())) { + throw new ManifestException( + "Manifest sections should start with a \"" + + ATTRIBUTE_NAME + "\" attribute and not \"" + + sectionName.getName() + "\""); } nextSectionName = sectionName.getValue(); } else { @@ -922,7 +899,7 @@ public class Manifest { if (attribute.getKey() == null || attribute.getValue() == null) { throw new BuildException("Attributes must have name and value"); } - if (attribute.getKey().equals(ATTRIBUTE_MANIFEST_VERSION_LC)) { + if (ATTRIBUTE_MANIFEST_VERSION_LC.equals(attribute.getKey())) { manifestVersion = attribute.getValue(); } else { mainSection.addConfiguredAttribute(attribute); @@ -977,7 +954,7 @@ public class Manifest { throws ManifestException { if (other != null) { if (overwriteMain) { - mainSection = (Section) other.mainSection.clone(); + mainSection = other.mainSection.clone(); } else { mainSection.merge(other.mainSection, mergeClassPaths); } @@ -994,7 +971,7 @@ public class Manifest { = other.sections.get(sectionName); if (ourSection == null) { if (otherSection != null) { - addConfiguredSection((Section) otherSection.clone()); + addConfiguredSection(otherSection.clone()); } } else { ourSection.merge(otherSection, mergeClassPaths); @@ -1077,7 +1054,7 @@ public class Manifest { * @return an enumeration of warning strings */ public Enumeration<String> getWarnings() { - Vector<String> warnings = new Vector<String>(); + Vector<String> warnings = new Vector<>(); Enumeration<String> warnEnum = mainSection.getWarnings(); while (warnEnum.hasMoreElements()) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ManifestClassPath.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ManifestClassPath.java b/src/main/org/apache/tools/ant/taskdefs/ManifestClassPath.java index f605bd5..96cc050 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ManifestClassPath.java +++ b/src/main/org/apache/tools/ant/taskdefs/ManifestClassPath.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs; import java.io.File; -import java.io.UnsupportedEncodingException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; @@ -52,6 +51,7 @@ public class ManifestClassPath extends Task { * separated list of files and directories relative to the jar * file's parent directory. */ + @Override public void execute() { if (name == null) { throw new BuildException("Missing 'property' attribute!"); @@ -60,13 +60,13 @@ public class ManifestClassPath extends Task { throw new BuildException("Missing 'jarfile' attribute!"); } if (getProject().getProperty(name) != null) { - throw new BuildException("Property '" + name + "' already set!"); + throw new BuildException("Property '%s' already set!", name); } if (path == null) { throw new BuildException("Missing nested <classpath>!"); } - StringBuffer tooLongSb = new StringBuffer(); + StringBuilder tooLongSb = new StringBuilder(); for (int i = 0; i < maxParentLevels + 1; i++) { tooLongSb.append("../"); } @@ -77,10 +77,10 @@ public class ManifestClassPath extends Task { dir = fileUtils.normalize(dir.getAbsolutePath()); String[] elements = path.list(); - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < elements.length; ++i) { + StringBuilder buffer = new StringBuilder(); + for (String element : elements) { // Normalize the current file - File pathEntry = new File(elements[i]); + File pathEntry = new File(element); String fullPath = pathEntry.getAbsolutePath(); pathEntry = fileUtils.normalize(fullPath); @@ -108,8 +108,8 @@ public class ManifestClassPath extends Task { // No match, so bail out! if (relPath.equals(canonicalPath) || relPath.startsWith(tooLongPrefix)) { - throw new BuildException("No suitable relative path from " - + dir + " to " + fullPath); + throw new BuildException( + "No suitable relative path from %s to %s", dir, fullPath); } if (pathEntry.isDirectory() && !relPath.endsWith("/")) { @@ -146,7 +146,7 @@ public class ManifestClassPath extends Task { public void setJarFile(File jarfile) { File parent = jarfile.getParentFile(); if (!parent.isDirectory()) { - throw new BuildException("Jar's directory not found: " + parent); + throw new BuildException("Jar's directory not found: %s", parent); } this.dir = parent; } @@ -159,8 +159,8 @@ public class ManifestClassPath extends Task { */ public void setMaxParentLevels(int levels) { if (levels < 0) { - throw new BuildException("maxParentLevels must not be a negative" - + " number"); + throw new BuildException( + "maxParentLevels must not be a negative number"); } this.maxParentLevels = levels; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ManifestTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ManifestTask.java b/src/main/org/apache/tools/ant/taskdefs/ManifestTask.java index 8b459be..85dfd8a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ManifestTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ManifestTask.java @@ -20,11 +20,10 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; +import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Enumeration; @@ -33,7 +32,6 @@ import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Manifest.Attribute; import org.apache.tools.ant.types.EnumeratedAttribute; -import org.apache.tools.ant.util.FileUtils; /** * Creates a manifest file for inclusion in a JAR, Ant task wrapper @@ -92,8 +90,9 @@ public class ManifestTask extends Task { * * @return a String array of the allowed values. */ + @Override public String[] getValues() { - return new String[] {"update", "replace"}; + return new String[] { "update", "replace" }; } } @@ -158,13 +157,15 @@ public class ManifestTask extends Task { char ch = name.charAt(0); if (ch == '-' || ch == '_') { - throw new BuildException("Manifest attribute names must not start with '" + ch + "'."); + throw new BuildException( + "Manifest attribute names must not start with '%c'.", ch); } for (int i = 0; i < name.length(); i++) { ch = name.charAt(i); if (VALID_ATTRIBUTE_CHARS.indexOf(ch) < 0) { - throw new BuildException("Manifest attribute names must not contain '" + ch + "'"); + throw new BuildException( + "Manifest attribute names must not contain '%c'", ch); } } } @@ -218,6 +219,7 @@ public class ManifestTask extends Task { * * @throws BuildException if the manifest cannot be written. */ + @Override public void execute() throws BuildException { if (manifestFile == null) { throw new BuildException("the file attribute is required"); @@ -228,15 +230,9 @@ public class ManifestTask extends Task { BuildException error = null; if (manifestFile.exists()) { - InputStream fis = null; - InputStreamReader isr = null; - try { - fis = Files.newInputStream(manifestFile.toPath()); - if (encoding == null) { - isr = new InputStreamReader(fis, "UTF-8"); - } else { - isr = new InputStreamReader(fis, encoding); - } + Charset charset = Charset.forName(encoding == null ? "UTF-8" : encoding); + try (InputStreamReader isr = new InputStreamReader( + Files.newInputStream(manifestFile.toPath()), charset)) { current = new Manifest(isr); } catch (ManifestException m) { error = new BuildException("Existing manifest " + manifestFile @@ -244,8 +240,6 @@ public class ManifestTask extends Task { } catch (IOException e) { error = new BuildException("Failed to read " + manifestFile, e, getLocation()); - } finally { - FileUtils.close(isr); } } @@ -256,7 +250,7 @@ public class ManifestTask extends Task { Project.MSG_WARN); } try { - if (mode.getValue().equals("update") && manifestFile.exists()) { + if ("update".equals(mode.getValue()) && manifestFile.exists()) { if (current != null) { toWrite.merge(current, false, mergeClassPaths); } else if (error != null) { @@ -275,11 +269,8 @@ public class ManifestTask extends Task { return; } - PrintWriter w = null; - try { - OutputStream fos = Files.newOutputStream(manifestFile.toPath()); - OutputStreamWriter osw = new OutputStreamWriter(fos, Manifest.JAR_ENCODING); - w = new PrintWriter(osw); + try (PrintWriter w = new PrintWriter(new OutputStreamWriter( + Files.newOutputStream(manifestFile.toPath()), Manifest.JAR_ENCODING))) { toWrite.write(w, flattenClassPaths); if (w.checkError()) { throw new IOException("Encountered an error writing manifest"); @@ -287,8 +278,6 @@ public class ManifestTask extends Task { } catch (IOException e) { throw new BuildException("Failed to write " + manifestFile, e, getLocation()); - } finally { - FileUtils.close(w); } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java b/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java index 113ff5e..414a89a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/MatchingTask.java @@ -62,6 +62,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { // CheckStyle:VisibilityModifier ON /** {@inheritDoc}. */ + @Override public void setProject(Project project) { super.setProject(project); fileset.setProject(project); @@ -128,8 +129,8 @@ public abstract class MatchingTask extends Task implements SelectorContainer { public void XsetItems(String itemString) { log("The items attribute is deprecated. " + "Please use the includes attribute.", Project.MSG_WARN); - if (itemString == null || itemString.equals("*") - || itemString.equals(".")) { + if (itemString == null || "*".equals(itemString) + || ".".equals(itemString)) { createInclude().setName("**"); } else { StringTokenizer tok = new StringTokenizer(itemString, ", "); @@ -161,7 +162,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { public void XsetIgnore(String ignoreString) { log("The ignore attribute is deprecated." + "Please use the excludes attribute.", Project.MSG_WARN); - if (ignoreString != null && ignoreString.length() > 0) { + if (!(ignoreString == null || ignoreString.isEmpty())) { StringTokenizer tok = new StringTokenizer(ignoreString, ", ", false); while (tok.hasMoreTokens()) { @@ -237,6 +238,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * * @return whether any selectors are in this container */ + @Override public boolean hasSelectors() { return fileset.hasSelectors(); } @@ -246,6 +248,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * * @return the number of selectors in this container */ + @Override public int selectorCount() { return fileset.selectorCount(); } @@ -255,6 +258,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * @param p the current project * @return an array of selectors in this container */ + @Override public FileSelector[] getSelectors(Project p) { return fileset.getSelectors(p); } @@ -264,6 +268,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * * @return an enumerator that goes through each of the selectors */ + @Override public Enumeration<FileSelector> selectorElements() { return fileset.selectorElements(); } @@ -273,6 +278,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * * @param selector the new selector to add */ + @Override public void appendSelector(FileSelector selector) { fileset.appendSelector(selector); } @@ -283,6 +289,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a "Select" selector entry on the selector list * @param selector the selector to add */ + @Override public void addSelector(SelectSelector selector) { fileset.addSelector(selector); } @@ -291,6 +298,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add an "And" selector entry on the selector list * @param selector the selector to add */ + @Override public void addAnd(AndSelector selector) { fileset.addAnd(selector); } @@ -299,6 +307,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add an "Or" selector entry on the selector list * @param selector the selector to add */ + @Override public void addOr(OrSelector selector) { fileset.addOr(selector); } @@ -307,6 +316,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a "Not" selector entry on the selector list * @param selector the selector to add */ + @Override public void addNot(NotSelector selector) { fileset.addNot(selector); } @@ -315,6 +325,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a "None" selector entry on the selector list * @param selector the selector to add */ + @Override public void addNone(NoneSelector selector) { fileset.addNone(selector); } @@ -323,6 +334,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a majority selector entry on the selector list * @param selector the selector to add */ + @Override public void addMajority(MajoritySelector selector) { fileset.addMajority(selector); } @@ -331,6 +343,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a selector date entry on the selector list * @param selector the selector to add */ + @Override public void addDate(DateSelector selector) { fileset.addDate(selector); } @@ -339,6 +352,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a selector size entry on the selector list * @param selector the selector to add */ + @Override public void addSize(SizeSelector selector) { fileset.addSize(selector); } @@ -347,6 +361,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a selector filename entry on the selector list * @param selector the selector to add */ + @Override public void addFilename(FilenameSelector selector) { fileset.addFilename(selector); } @@ -355,6 +370,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add an extended selector entry on the selector list * @param selector the selector to add */ + @Override public void addCustom(ExtendSelector selector) { fileset.addCustom(selector); } @@ -363,6 +379,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a contains selector entry on the selector list * @param selector the selector to add */ + @Override public void addContains(ContainsSelector selector) { fileset.addContains(selector); } @@ -371,6 +388,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a present selector entry on the selector list * @param selector the selector to add */ + @Override public void addPresent(PresentSelector selector) { fileset.addPresent(selector); } @@ -379,6 +397,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a depth selector entry on the selector list * @param selector the selector to add */ + @Override public void addDepth(DepthSelector selector) { fileset.addDepth(selector); } @@ -387,6 +406,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a depends selector entry on the selector list * @param selector the selector to add */ + @Override public void addDepend(DependSelector selector) { fileset.addDepend(selector); } @@ -395,6 +415,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * add a regular expression selector entry on the selector list * @param selector the selector to add */ + @Override public void addContainsRegexp(ContainsRegexpSelector selector) { fileset.addContainsRegexp(selector); } @@ -404,6 +425,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * @param selector the selector to add * @since ant 1.6 */ + @Override public void addDifferent(DifferentSelector selector) { fileset.addDifferent(selector); } @@ -413,6 +435,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * @param selector the selector to add * @since ant 1.6 */ + @Override public void addType(TypeSelector selector) { fileset.addType(selector); } @@ -422,6 +445,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * @param selector the selector to add * @since ant 1.6 */ + @Override public void addModified(ModifiedSelector selector) { fileset.addModified(selector); } @@ -431,6 +455,7 @@ public abstract class MatchingTask extends Task implements SelectorContainer { * @param selector the selector to add * @since Ant 1.6 */ + @Override public void add(FileSelector selector) { fileset.add(selector); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Mkdir.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Mkdir.java b/src/main/org/apache/tools/ant/taskdefs/Mkdir.java index 71b6c94..8a672b6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Mkdir.java +++ b/src/main/org/apache/tools/ant/taskdefs/Mkdir.java @@ -46,29 +46,30 @@ public class Mkdir extends Task { * create the directory and all parents * @throws BuildException if dir is somehow invalid, or creation failed. */ + @Override public void execute() throws BuildException { if (dir == null) { throw new BuildException("dir attribute is required", getLocation()); } if (dir.isFile()) { - throw new BuildException("Unable to create directory as a file " - + "already exists with that name: " - + dir.getAbsolutePath()); + throw new BuildException( + "Unable to create directory as a file already exists with that name: %s", + dir.getAbsolutePath()); } if (!dir.exists()) { boolean result = mkdirs(dir); if (!result) { if (dir.exists()) { - log("A different process or task has already created " - + "dir " + dir.getAbsolutePath(), - Project.MSG_VERBOSE); + log("A different process or task has already created dir " + + dir.getAbsolutePath(), Project.MSG_VERBOSE); return; } - String msg = "Directory " + dir.getAbsolutePath() - + " creation was not successful for an unknown reason"; - throw new BuildException(msg, getLocation()); + throw new BuildException( + "Directory " + dir.getAbsolutePath() + + " creation was not successful for an unknown reason", + getLocation()); } log("Created dir: " + dir.getAbsolutePath()); } else { @@ -111,4 +112,3 @@ public class Mkdir extends Task { return true; } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Move.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Move.java b/src/main/org/apache/tools/ant/taskdefs/Move.java index 7f5d968..47d40e0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Move.java +++ b/src/main/org/apache/tools/ant/taskdefs/Move.java @@ -19,14 +19,12 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; -import java.util.Iterator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.condition.Os; import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.FilterSet; import org.apache.tools.ant.types.FilterSetCollection; /** @@ -79,6 +77,7 @@ public class Move extends Copy { } /** {@inheritDoc}. */ + @Override protected void validateAttributes() throws BuildException { if (file != null && file.isDirectory()) { if ((destFile != null && destDir != null) @@ -102,12 +101,12 @@ public class Move extends Copy { /** * Override copy's doFileOperations to move the files instead of copying them. */ + @Override protected void doFileOperations() { //Attempt complete directory renames, if any, first. if (completeDirMap.size() > 0) { - for (Iterator fromDirs = completeDirMap.keySet().iterator(); fromDirs.hasNext();) { - File fromDir = (File) fromDirs.next(); - File toDir = (File) completeDirMap.get(fromDir); + for (File fromDir : completeDirMap.keySet()) { + File toDir = completeDirMap.get(fromDir); boolean renamed = false; try { log("Attempting to rename dir: " + fromDir + " to " + toDir, verbosity); @@ -134,14 +133,13 @@ public class Move extends Copy { log("Moving " + moveCount + " file" + ((moveCount == 1) ? "" : "s") + " to " + destDir.getAbsolutePath()); - for (Iterator fromFiles = fileCopyMap.keySet().iterator(); fromFiles.hasNext();) { - String fromFile = (String) fromFiles.next(); + for (String fromFile : fileCopyMap.keySet()) { File f = new File(fromFile); boolean selfMove = false; if (f.exists()) { //Is this file still available to be moved? - String[] toFiles = (String[]) fileCopyMap.get(fromFile); + String[] toFiles = fileCopyMap.get(fromFile); for (int i = 0; i < toFiles.length; i++) { - String toFile = (String) toFiles[i]; + String toFile = toFiles[i]; if (fromFile.equals(toFile)) { log("Skipping self-move of " + fromFile, verbosity); @@ -166,9 +164,8 @@ public class Move extends Copy { if (includeEmpty) { int createCount = 0; - for (Iterator fromDirNames = dirCopyMap.keySet().iterator(); fromDirNames.hasNext();) { - String fromDirName = (String) fromDirNames.next(); - String[] toDirNames = (String[]) dirCopyMap.get(fromDirName); + for (String fromDirName : dirCopyMap.keySet()) { + String[] toDirNames = dirCopyMap.get(fromDirName); boolean selfMove = false; for (int i = 0; i < toDirNames.length; i++) { if (fromDirName.equals(toDirNames[i])) { @@ -213,16 +210,15 @@ public class Move extends Copy { log("Attempting to rename: " + fromFile + " to " + toFile, verbosity); moved = renameFile(fromFile, toFile, filtering, forceOverwrite); } catch (IOException ioe) { - String msg = "Failed to rename " + fromFile - + " to " + toFile + " due to " + ioe.getMessage(); - throw new BuildException(msg, ioe, getLocation()); + throw new BuildException("Failed to rename " + fromFile + " to " + + toFile + " due to " + ioe.getMessage(), ioe, getLocation()); } if (!moved) { copyFile(fromFile, toFile, filtering, overwrite); if (!getFileUtils().tryHardToDelete(fromFile, performGc)) { - throw new BuildException("Unable to delete " + "file " - + fromFile.getAbsolutePath()); + throw new BuildException("Unable to delete file %s", + fromFile.getAbsolutePath()); } } } @@ -242,9 +238,7 @@ public class Move extends Copy { if (filtering) { executionFilters.addFilterSet(getProject().getGlobalFilterSet()); } - for (Iterator filterIter = getFilterSets().iterator(); filterIter.hasNext();) { - executionFilters.addFilterSet((FilterSet) filterIter.next()); - } + getFilterSets().forEach(executionFilters::addFilterSet); getFileUtils().copyFile(fromFile, toFile, executionFilters, getFilterChains(), forceOverwrite, @@ -254,9 +248,8 @@ public class Move extends Copy { getOutputEncoding(), getProject(), getForce()); } catch (IOException ioe) { - String msg = "Failed to copy " + fromFile - + " to " + toFile + " due to " + ioe.getMessage(); - throw new BuildException(msg, ioe, getLocation()); + throw new BuildException("Failed to copy " + fromFile + " to " + + toFile + " due to " + ioe.getMessage(), ioe, getLocation()); } } @@ -271,8 +264,7 @@ public class Move extends Copy { return false; } // maybe io error? - for (int i = 0; i < list.length; i++) { - String s = list[i]; + for (String s : list) { File f = new File(d, s); if (f.isDirectory()) { if (!okToDelete(f)) { @@ -304,22 +296,24 @@ public class Move extends Copy { return; } // on an io error list() can return null - for (int i = 0; i < list.length; i++) { - String s = list[i]; + for (String s : list) { File f = new File(d, s); if (f.isDirectory()) { deleteDir(f); - } else if (deleteFiles && !getFileUtils().tryHardToDelete(f, - performGc)) { - throw new BuildException("Unable to delete file " + f.getAbsolutePath()); + } else if (deleteFiles + && !getFileUtils().tryHardToDelete(f, performGc)) { + throw new BuildException("Unable to delete file %s", + f.getAbsolutePath()); } else { - throw new BuildException("UNEXPECTED ERROR - The file " - + f.getAbsolutePath() + " should not exist!"); + throw new BuildException( + "UNEXPECTED ERROR - The file %s should not exist!", + f.getAbsolutePath()); } } log("Deleting directory " + d.getAbsolutePath(), verbosity); if (!getFileUtils().tryHardToDelete(d, performGc)) { - throw new BuildException("Unable to delete directory " + d.getAbsolutePath()); + throw new BuildException("Unable to delete directory %s", + d.getAbsolutePath()); } } @@ -343,19 +337,21 @@ public class Move extends Copy { */ protected boolean renameFile(File sourceFile, File destFile, boolean filtering, boolean overwrite) throws IOException, BuildException { - if (destFile.isDirectory() || filtering || getFilterSets().size() > 0 - || getFilterChains().size() > 0) { + if (destFile.isDirectory() || filtering || !getFilterSets().isEmpty() + || !getFilterChains().isEmpty()) { return false; } // identical logic lives in ResourceUtils.copyResource(): if (destFile.isFile() && !destFile.canWrite()) { if (!getForce()) { - throw new IOException("can't replace read-only destination " - + "file " + destFile); - } else if (!getFileUtils().tryHardToDelete(destFile)) { - throw new IOException("failed to delete read-only " - + "destination file " + destFile); + throw new IOException(String.format( + "can't replace read-only destination file %s", destFile)); + } + if (!getFileUtils().tryHardToDelete(destFile)) { + throw new IOException(String.format( + "failed to delete read-only destination file %s", + destFile)); } } @@ -374,7 +370,8 @@ public class Move extends Copy { } if (!(getFileUtils().areSame(sourceFile, destFile) || getFileUtils().tryHardToDelete(destFile, performGc))) { - throw new BuildException("Unable to remove existing file " + destFile); + throw new BuildException("Unable to remove existing file %s", + destFile); } } return sourceFile.renameTo(destFile); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Nice.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Nice.java b/src/main/org/apache/tools/ant/taskdefs/Nice.java index 5898cae..4bd5beb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Nice.java +++ b/src/main/org/apache/tools/ant/taskdefs/Nice.java @@ -48,12 +48,11 @@ public class Nice extends Task { */ private String currentPriority; - - /** * Execute the task * @exception BuildException if something goes wrong with the build */ + @Override public void execute() throws BuildException { Thread self = Thread.currentThread(); @@ -93,7 +92,7 @@ public class Nice extends Task { if (newPriority < Thread.MIN_PRIORITY || newPriority > Thread.MAX_PRIORITY) { throw new BuildException("The thread priority is out of the range 1-10"); } - this.newPriority = new Integer(newPriority); + this.newPriority = Integer.valueOf(newPriority); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Pack.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Pack.java b/src/main/org/apache/tools/ant/taskdefs/Pack.java index 59a998f..67a2dd8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Pack.java +++ b/src/main/org/apache/tools/ant/taskdefs/Pack.java @@ -38,6 +38,7 @@ import org.apache.tools.ant.types.resources.FileResource; public abstract class Pack extends Task { private static final int BUFFER_SIZE = 8 * 1024; + // CheckStyle:VisibilityModifier OFF - bc protected File zipFile; protected File source; @@ -91,13 +92,14 @@ public abstract class Pack extends Task { */ public void addConfigured(ResourceCollection a) { if (a.size() == 0) { - throw new BuildException("No resource selected, " + getTaskName() - + " needs exactly one resource."); + throw new BuildException( + "No resource selected, %s needs exactly one resource.", + getTaskName()); } if (a.size() != 1) { - throw new BuildException(getTaskName() - + " cannot handle multiple resources at once. (" + a.size() - + " resources were selected.)"); + throw new BuildException( + "%s cannot handle multiple resources at once. (%d resources were selected.)", + getTaskName(), a.size()); } setSrcResource(a.iterator().next()); } @@ -112,13 +114,14 @@ public abstract class Pack extends Task { } if (zipFile.isDirectory()) { - throw new BuildException("zipfile attribute must not " - + "represent a directory!", getLocation()); + throw new BuildException( + "zipfile attribute must not represent a directory!", + getLocation()); } if (getSrcResource() == null) { - throw new BuildException("src attribute or nested resource is" - + " required", getLocation()); + throw new BuildException( + "src attribute or nested resource is required", getLocation()); } } @@ -126,6 +129,7 @@ public abstract class Pack extends Task { * validate, then hand off to the subclass * @throws BuildException on error */ + @Override public void execute() throws BuildException { validate();
