http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java index 8fce71e..0902e55 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java +++ b/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java @@ -18,6 +18,7 @@ package org.apache.tools.ant.taskdefs; import java.io.File; +import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; @@ -32,7 +33,6 @@ import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import javax.xml.xpath.XPathVariableResolver; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; @@ -71,6 +71,15 @@ import org.apache.tools.ant.util.StringUtils; */ public class XSLTProcess extends MatchingTask implements XSLTLogger { + /** + * The default processor is trax + * @since Ant 1.7 + */ + public static final String PROCESSOR_TRAX = "trax"; + + /** Utilities used for file operations */ + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + /** destination directory */ private File destDir = null; @@ -93,7 +102,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private String fileDirParameter = null; /** additional parameters to be passed to the stylesheets */ - private final List<Param> params = new ArrayList<Param>(); + private final List<Param> params = new ArrayList<>(); /** Input XML document to be used */ private File inFile = null; @@ -119,14 +128,11 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private boolean force = false; /** XSL output properties to be used */ - private final Vector outputProperties = new Vector(); + private final List<OutputProperty> outputProperties = new Vector<>(); /** for resolving entities such as dtds */ private final XMLCatalog xmlCatalog = new XMLCatalog(); - /** Utilities used for file operations */ - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - /** * Whether to style all files in the included directories as well. * @@ -180,12 +186,6 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private boolean useImplicitFileset = true; /** - * The default processor is trax - * @since Ant 1.7 - */ - public static final String PROCESSOR_TRAX = "trax"; - - /** * whether to suppress warnings. * * @since Ant 1.8.0 @@ -243,12 +243,6 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private TraceConfiguration traceConfiguration; /** - * Creates a new XSLTProcess Task. - */ - public XSLTProcess() { - } //-- XSLTProcess - - /** * Whether to style all files in the included directories as well; * optional, default is true. * @@ -303,8 +297,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { */ public void addConfiguredStyle(final Resources rc) { if (rc.size() != 1) { - handleError("The style element must be specified with exactly one" - + " nested resource."); + handleError( + "The style element must be specified with exactly one nested resource."); } else { setXslResource(rc.iterator().next()); } @@ -345,13 +339,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { } final File savedBaseDir = baseDir; - DirectoryScanner scanner; - String[] list; - String[] dirs; - final String baseMessage = - "specify the stylesheet either as a filename in style attribute " - + "or as a nested resource"; + "specify the stylesheet either as a filename in style attribute or as a nested resource"; if (xslResource == null && xslFile == null) { handleError(baseMessage); @@ -395,8 +384,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * the wrong version has been used. */ if (alternative.exists()) { - log("DEPRECATED - the 'style' attribute should be " - + "relative to the project's"); + log("DEPRECATED - the 'style' attribute should be relative to the project's"); log(" basedir, not the tasks's basedir."); stylesheet = alternative; } @@ -427,33 +415,30 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { //-- make sure destination directory exists... checkDest(); + if (useImplicitFileset) { - scanner = getDirectoryScanner(baseDir); + DirectoryScanner scanner = getDirectoryScanner(baseDir); log("Transforming into " + destDir, Project.MSG_INFO); // Process all the files marked for styling - list = scanner.getIncludedFiles(); - for (int i = 0; i < list.length; ++i) { - process(baseDir, list[i], destDir, styleResource); + for (String element : scanner.getIncludedFiles()) { + process(baseDir, element, destDir, styleResource); } if (performDirectoryScan) { // Process all the directories marked for styling - dirs = scanner.getIncludedDirectories(); - for (int j = 0; j < dirs.length; ++j) { - list = new File(baseDir, dirs[j]).list(); - for (int i = 0; i < list.length; ++i) { - process(baseDir, dirs[j] + File.separator + list[i], destDir, + for (String dir : scanner.getIncludedDirectories()) { + for (String element : new File(baseDir, dir).list()) { + process(baseDir, dir + File.separator + element, destDir, styleResource); } } } - } else { // only resource collections, there better be some - if (resources.size() == 0) { - if (failOnNoResources) { - handleError("no resources specified"); - } - return; + } else if (resources.isEmpty()) { + // only resource collections, there better be some + if (failOnNoResources) { + handleError("no resources specified"); } + return; } processResources(styleResource); } finally { @@ -678,8 +663,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { */ public TraceConfiguration createTrace() { if (traceConfiguration != null) { - throw new BuildException("can't have more than one trace" - + " configuration"); + throw new BuildException("can't have more than one trace configuration"); } traceConfiguration = new TraceConfiguration(); return traceConfiguration; @@ -703,12 +687,12 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @exception Exception if the processor cannot be loaded. */ private void resolveProcessor(final String proc) throws Exception { - if (proc.equals(PROCESSOR_TRAX)) { + if (PROCESSOR_TRAX.equals(proc)) { liaison = new org.apache.tools.ant.taskdefs.optional.TraXLiaison(); } else { //anything else is a classname - final Class clazz = loadClass(proc); - liaison = (XSLTLiaison) clazz.newInstance(); + final Class<? extends XSLTLiaison> clazz = loadClass(proc).asSubclass(XSLTLiaison.class); + liaison = clazz.newInstance(); } } @@ -721,7 +705,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @return the requested class. * @exception Exception if the class could not be loaded. */ - private Class loadClass(final String classname) throws ClassNotFoundException { + private Class<?> loadClass(final String classname) throws ClassNotFoundException { setupLoader(); if (loader == null) { return Class.forName(classname); @@ -811,29 +795,25 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { throws BuildException { File outF = null; - File inF = null; try { final long styleSheetLastModified = stylesheet.getLastModified(); - inF = new File(baseDir, xmlFile); + File inF = new File(baseDir, xmlFile); if (inF.isDirectory()) { log("Skipping " + inF + " it is a directory.", Project.MSG_VERBOSE); return; } - FileNameMapper mapper = null; - if (mapperElement != null) { - mapper = mapperElement.getImplementation(); - } else { - mapper = new StyleMapper(); - } + FileNameMapper mapper = mapperElement == null ? new StyleMapper() + : mapperElement.getImplementation(); final String[] outFileName = mapper.mapFileName(xmlFile); if (outFileName == null || outFileName.length == 0) { log("Skipping " + inFile + " it cannot get mapped to output.", Project.MSG_VERBOSE); return; - } else if (outFileName.length > 1) { - log("Skipping " + inFile + " its mapping is ambiguos.", Project.MSG_VERBOSE); + } + if (outFileName.length > 1) { + log("Skipping " + inFile + " its mapping is ambiguous.", Project.MSG_VERBOSE); return; } outF = new File(destDir, outFileName[0]); @@ -931,8 +911,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * Get an enumeration on the outputproperties. * @return the outputproperties */ - public Enumeration getOutputProperties() { - return outputProperties.elements(); + public Enumeration<OutputProperty> getOutputProperties() { + return Collections.enumeration(outputProperties); } /** @@ -1175,7 +1155,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { */ public OutputProperty createOutputProperty() { final OutputProperty p = new OutputProperty(); - outputProperties.addElement(p); + outputProperties.add(p); return p; } @@ -1236,11 +1216,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { xpathFactory = XPathFactory.newInstance(); xpath = xpathFactory.newXPath(); - xpath.setXPathVariableResolver(new XPathVariableResolver() { - public Object resolveVariable(final QName variableName) { - return getProject().getProperty(variableName.toString()); - } - }); + xpath.setXPathVariableResolver( + variableName -> getProject().getProperty(variableName.toString())); } /** @@ -1300,16 +1277,15 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { if (p.shouldUse()) { final Object evaluatedParam = evaluateParam(p); if (liaison instanceof XSLTLiaison4) { - ((XSLTLiaison4)liaison).addParam(p.getName(), evaluatedParam); + ((XSLTLiaison4) liaison).addParam(p.getName(), + evaluatedParam); + } else if (evaluatedParam == null || evaluatedParam instanceof String) { + liaison.addParam(p.getName(), (String)evaluatedParam); } else { - if (evaluatedParam == null || evaluatedParam instanceof String) { - liaison.addParam(p.getName(), (String)evaluatedParam); - } else { - log("XSLTLiaison '" + liaison.getClass().getName() - + "' supports only String parameters. Converting parameter '" + p.getName() - + "' to its String value '" + evaluatedParam, Project.MSG_WARN); - liaison.addParam(p.getName(), String.valueOf(evaluatedParam)); - } + log("XSLTLiaison '" + liaison.getClass().getName() + + "' supports only String parameters. Converting parameter '" + p.getName() + + "' to its String value '" + evaluatedParam, Project.MSG_WARN); + liaison.addParam(p.getName(), String.valueOf(evaluatedParam)); } } } @@ -1336,7 +1312,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { ParamType type; - if (typeName == null || "".equals(typeName)) { + if (typeName == null || typeName.isEmpty()) { type = ParamType.STRING; // String is default } else { try { @@ -1361,11 +1337,10 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { final QName xpathType = ParamType.XPATH_TYPES.get(type); if (xpathType == null) { throw new IllegalArgumentException("Invalid XSLT parameter type: " + typeName); - } else { - final XPathExpression xpe = xpath.compile(expression); - // null = evaluate XPath on empty XML document - return xpe.evaluate((Object) null, xpathType); } + final XPathExpression xpe = xpath.compile(expression); + // null = evaluate XPath on empty XML document + return xpe.evaluate((Object) null, xpathType); } } @@ -1432,9 +1407,8 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { protected void handleError(final Throwable ex) { if (failOnError) { throw new BuildException(ex); - } else { - log("Caught an exception: " + ex, Project.MSG_WARN); } + log("Caught an exception: " + ex, Project.MSG_WARN); } /** @@ -1447,10 +1421,9 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { protected void handleTransformationError(final Exception ex) { if (failOnError && failOnTransformationError) { throw new BuildException(ex); - } else { - log("Caught an error during transformation: " + ex, - Project.MSG_WARN); } + log("Caught an error during transformation: " + ex, + Project.MSG_WARN); } /** @@ -1465,12 +1438,12 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { /** * the list of factory attributes to use for TraXLiaison */ - private final List<Attribute> attributes = new ArrayList<Attribute>(); + private final List<Attribute> attributes = new ArrayList<>(); /** * the list of factory features to use for TraXLiaison */ - private final List<Feature> features = new ArrayList<Feature>(); + private final List<Feature> features = new ArrayList<>(); /** * @return the name of the factory. @@ -1499,7 +1472,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * return the attribute elements. * @return the enumeration of attributes */ - public Enumeration getAttributes() { + public Enumeration<Attribute> getAttributes() { return Collections.enumeration(attributes); } @@ -1528,8 +1501,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * <li>http://xml.apache.org/xalan/features/incremental (true|false) </li> * </ul> */ - public static class Attribute - extends ProjectComponent + public static class Attribute extends ProjectComponent implements DynamicConfigurator { /** attribute name, mostly processor specific */ @@ -1558,6 +1530,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @return null * @throws BuildException never */ + @Override public Object createDynamicElement(final String name) throws BuildException { return null; } @@ -1569,6 +1542,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @param value the value of the attribute * @throws BuildException on error */ + @Override public void setDynamicAttribute(final String name, final String value) throws BuildException { // only 'name' and 'value' exist. if ("name".equalsIgnoreCase(name)) { @@ -1582,7 +1556,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { this.value = Boolean.FALSE; } else { try { - this.value = new Integer(value); + this.value = Integer.valueOf(value); } catch (final NumberFormatException e) { this.value = value; } @@ -1595,7 +1569,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { new Reference(getProject(), value)); } else { - throw new BuildException("Unsupported attribute: " + name); + throw new BuildException("Unsupported attribute: %s", name); } } } // -- class Attribute @@ -1608,7 +1582,9 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { private String name; private boolean value; - public Feature() { } + public Feature() { + } + public Feature(String name, boolean value) { this.name = name; this.value = value; @@ -1654,10 +1630,15 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { * @since Ant 1.6.2 */ private class StyleMapper implements FileNameMapper { + @Override public void setFrom(final String from) { } + + @Override public void setTo(final String to) { } + + @Override public String[] mapFileName(String xmlFile) { final int dotPos = xmlFile.lastIndexOf('.'); if (dotPos > 0) { @@ -1758,7 +1739,7 @@ public class XSLTProcess extends MatchingTask implements XSLTLogger { /** * The stream to write traces to. */ - public java.io.OutputStream getOutputStream() { + public OutputStream getOutputStream() { return new LogOutputStream(XSLTProcess.this); } }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/XmlProperty.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/XmlProperty.java b/src/main/org/apache/tools/ant/taskdefs/XmlProperty.java index ffd89d1..9ebfc83 100644 --- a/src/main/org/apache/tools/ant/taskdefs/XmlProperty.java +++ b/src/main/org/apache/tools/ant/taskdefs/XmlProperty.java @@ -19,7 +19,9 @@ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; +import java.util.Arrays; import java.util.Hashtable; +import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -175,19 +177,6 @@ import org.xml.sax.SAXException; * @ant.task name="xmlproperty" category="xml" */ public class XmlProperty extends org.apache.tools.ant.Task { - - private Resource src; - private String prefix = ""; - private boolean keepRoot = true; - private boolean validate = false; - private boolean collapseAttributes = false; - private boolean semanticAttributes = false; - private boolean includeSemanticAttribute = false; - private File rootDirectory = null; - private Hashtable addedAttributes = new Hashtable(); - private XMLCatalog xmlCatalog = new XMLCatalog(); - private String delimiter = ","; - private static final String ID = "id"; private static final String REF_ID = "refid"; private static final String LOCATION = "location"; @@ -200,17 +189,22 @@ public class XmlProperty extends org.apache.tools.ant.Task { private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - /** - * Constructor. - */ - public XmlProperty() { - super(); - } + private Resource src; + private String prefix = ""; + private boolean keepRoot = true; + private boolean validate = false; + private boolean collapseAttributes = false; + private boolean semanticAttributes = false; + private boolean includeSemanticAttribute = false; + private File rootDirectory = null; + private Map<String, String> addedAttributes = new Hashtable<>(); + private XMLCatalog xmlCatalog = new XMLCatalog(); + private String delimiter = ","; /** * Initializes the task. */ - + @Override public void init() { super.init(); xmlCatalog.setProject(getProject()); @@ -229,6 +223,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { * @todo validate the source file is valid before opening, print a better error message * @todo add a verbose level log message listing the name of the file being loaded */ + @Override public void execute() throws BuildException { Resource r = getResource(); @@ -245,7 +240,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(getEntityResolver()); - Document document = null; + Document document; FileProvider fp = src.as(FileProvider.class); if (fp != null) { document = builder.parse(fp.getFile()); @@ -258,7 +253,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { // This task is allow to override its own properties // but not other properties. So we need to keep track // of which properties we've added. - addedAttributes = new Hashtable(); + addedAttributes = new Hashtable<>(); if (keepRoot) { addNodeRecursively(topElement, prefix, null); @@ -377,23 +372,23 @@ public class XmlProperty extends org.apache.tools.ant.Task { * semantic meaning) then deal with it * appropriately. */ - if (nodeName.equals(ID)) { + if (ID.equals(nodeName)) { // ID has already been found above. continue; } - if (containingPath != null && nodeName.equals(PATH)) { + if (containingPath != null && PATH.equals(nodeName)) { // A "path" attribute for a node within a Path object. containingPath.setPath(attributeValue); } else if (containingPath != null - && container instanceof Path && nodeName.equals(REF_ID)) { + && container instanceof Path && REF_ID.equals(nodeName)) { // A "refid" attribute for a node within a Path object. containingPath.setPath(attributeValue); } else if (containingPath != null && container instanceof Path - && nodeName.equals(LOCATION)) { + && LOCATION.equals(nodeName)) { // A "location" attribute for a node within a // Path object. containingPath.setLocation(resolveFile(attributeValue)); - } else if (nodeName.equals(PATHID)) { + } else if (PATHID.equals(nodeName)) { // A node identifying a new path if (container != null) { throw new BuildException("XmlProperty does not support nested paths"); @@ -429,7 +424,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { && node.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE) { nodeText = node.getFirstChild().getNodeValue(); - if ("".equals(nodeText) && !semanticEmptyOverride) { + if (nodeText.isEmpty() && !semanticEmptyOverride) { emptyNode = true; } } else if (node.getNodeType() == Node.ELEMENT_NODE @@ -440,7 +435,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { } else if (node.getNodeType() == Node.ELEMENT_NODE && node.getChildNodes().getLength() == 1 && node.getFirstChild().getNodeType() == Node.TEXT_NODE - && "".equals(node.getFirstChild().getNodeValue()) + && node.getFirstChild().getNodeValue().isEmpty() && !semanticEmptyOverride) { nodeText = ""; emptyNode = true; @@ -450,7 +445,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { if (semanticAttributes && id == null && container instanceof String) { id = (String) container; } - if (nodeText.trim().length() != 0 || emptyNode) { + if (!nodeText.trim().isEmpty() || emptyNode) { addProperty(prefix, nodeText, id); } } @@ -458,7 +453,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { // children to reference if needed. Path objects are // definitely used by child path elements, and ID may be used // for a child text node. - return (addedPath != null ? addedPath : id); + return addedPath != null ? addedPath : id; } /** @@ -481,7 +476,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { // when we read them, though (instead of keeping them // outside of the project and batch adding them at the end) // to allow other properties to reference them. - value = (String) addedAttributes.get(name) + getDelimiter() + value; + value = addedAttributes.get(name) + getDelimiter() + value; getProject().setProperty(name, value); addedAttributes.put(name, value); } else if (getProject().getProperty(name) == null) { @@ -508,7 +503,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { if (semanticAttributes) { // Never include the "refid" attribute as part of the // attribute name. - if (attributeName.equals(REF_ID)) { + if (REF_ID.equals(attributeName)) { return ""; } // Otherwise, return it appended unless property to hide it is set. @@ -524,12 +519,7 @@ public class XmlProperty extends org.apache.tools.ant.Task { * Return whether the provided attribute name is recognized or not. */ private static boolean isSemanticAttribute (String attributeName) { - for (int i = 0; i < ATTRIBUTES.length; i++) { - if (attributeName.equals(ATTRIBUTES[i])) { - return true; - } - } - return false; + return Arrays.asList(ATTRIBUTES).contains(attributeName); } /** @@ -549,11 +539,11 @@ public class XmlProperty extends org.apache.tools.ant.Task { if (semanticAttributes) { String attributeName = attributeNode.getNodeName(); nodeValue = getProject().replaceProperties(nodeValue); - if (attributeName.equals(LOCATION)) { + if (LOCATION.equals(attributeName)) { File f = resolveFile(nodeValue); return f.getPath(); } - if (attributeName.equals(REF_ID)) { + if (REF_ID.equals(attributeName)) { Object ref = getProject().getReference(nodeValue); if (ref != null) { return ref.toString(); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Zip.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Zip.java b/src/main/org/apache/tools/ant/taskdefs/Zip.java index 1a17bfc..ff72014 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Zip.java +++ b/src/main/org/apache/tools/ant/taskdefs/Zip.java @@ -28,12 +28,13 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; -import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; +import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Vector; +import java.util.stream.Stream; import java.util.zip.CRC32; import org.apache.tools.ant.BuildException; @@ -43,7 +44,6 @@ import org.apache.tools.ant.Project; import org.apache.tools.ant.types.ArchiveFileSet; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.ZipFileSet; @@ -84,13 +84,24 @@ public class Zip extends MatchingTask { private static final int ROUNDUP_MILLIS = ZIP_FILE_TIMESTAMP_GRANULARITY - 1; // CheckStyle:VisibilityModifier OFF - bc + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + + // For directories: + private static final long EMPTY_CRC = new CRC32 ().getValue (); + + private static final ResourceSelector MISSING_SELECTOR = + target -> !target.isExists(); + + private static final ResourceUtils.ResourceSelectorProvider + MISSING_DIR_PROVIDER = sr -> MISSING_SELECTOR; + protected File zipFile; // use to scan own archive private ZipScanner zs; private File baseDir; - protected Hashtable<String, String> entries = new Hashtable<String, String>(); - private final Vector<FileSet> groupfilesets = new Vector<FileSet>(); - private final Vector<ZipFileSet> filesetsFromGroupfilesets = new Vector<ZipFileSet>(); + protected Hashtable<String, String> entries = new Hashtable<>(); + private final List<FileSet> groupfilesets = new Vector<>(); + private final List<ZipFileSet> filesetsFromGroupfilesets = new Vector<>(); protected String duplicate = "add"; private boolean doCompress = true; private boolean doUpdate = false; @@ -99,27 +110,10 @@ public class Zip extends MatchingTask { private boolean doFilesonly = false; protected String archiveType = "zip"; - // For directories: - private static final long EMPTY_CRC = new CRC32 ().getValue (); protected String emptyBehavior = "skip"; - private final Vector<ResourceCollection> resources = new Vector<ResourceCollection>(); - protected Hashtable<String, String> addedDirs = new Hashtable<String, String>(); - private final Vector<String> addedFiles = new Vector<String>(); - - private static final ResourceSelector MISSING_SELECTOR = - new ResourceSelector() { - public boolean isSelected(final Resource target) { - return !target.isExists(); - } - }; - - private static final ResourceUtils.ResourceSelectorProvider - MISSING_DIR_PROVIDER = new ResourceUtils.ResourceSelectorProvider() { - public ResourceSelector - getTargetSelectorForSource(final Resource sr) { - return MISSING_SELECTOR; - } - }; + private final List<ResourceCollection> resources = new Vector<>(); + protected Hashtable<String, String> addedDirs = new Hashtable<>(); + private final List<String> addedFiles = new Vector<>(); /** * If this flag is true, execute() will run most operations twice, @@ -152,8 +146,6 @@ public class Zip extends MatchingTask { return !doubleFilePass || skipWriting; } - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - // CheckStyle:VisibilityModifier ON // This boolean is set if the task detects that the @@ -363,7 +355,7 @@ public class Zip extends MatchingTask { * @param set the group (a fileset) to add */ public void addZipGroupFileset(final FileSet set) { - groupfilesets.addElement(set); + groupfilesets.add(set); } /** @@ -390,7 +382,7 @@ public class Zip extends MatchingTask { */ @Override public String[] getValues() { - return new String[] {"fail", "skip", "create"}; + return new String[] { "fail", "skip", "create" }; } } @@ -627,20 +619,17 @@ public class Zip extends MatchingTask { processGroupFilesets(); // collect filesets to pass them to getResourcesToAdd - final Vector<ResourceCollection> vfss = new Vector<ResourceCollection>(); + final List<ResourceCollection> vfss = new ArrayList<>(); if (baseDir != null) { - final FileSet fs = (FileSet) getImplicitFileSet().clone(); + final FileSet fs = getImplicitFileSet().clone(); fs.setDir(baseDir); - vfss.addElement(fs); - } - final int size = resources.size(); - for (int i = 0; i < size; i++) { - final ResourceCollection rc = resources.elementAt(i); - vfss.addElement(rc); + vfss.add(fs); } + vfss.addAll(resources); + + final ResourceCollection[] fss = + vfss.toArray(new ResourceCollection[vfss.size()]); - final ResourceCollection[] fss = new ResourceCollection[vfss.size()]; - vfss.copyInto(fss); boolean success = false; try { // can also handle empty archives @@ -654,8 +643,9 @@ public class Zip extends MatchingTask { final File parent = zipFile.getParentFile(); if (parent != null && !parent.isDirectory() && !(parent.mkdirs() || parent.isDirectory())) { - throw new BuildException("Failed to create missing parent" - + " directory for " + zipFile); + throw new BuildException( + "Failed to create missing parent directory for %s", + zipFile); } updatedFile = true; @@ -706,32 +696,25 @@ public class Zip extends MatchingTask { oldFiles.setSrc(renamedFile); oldFiles.setDefaultexcludes(false); - final int addSize = addedFiles.size(); - for (int i = 0; i < addSize; i++) { - final PatternSet.NameEntry ne = oldFiles.createExclude(); - ne.setName(addedFiles.elementAt(i)); + for (String addedFile : addedFiles) { + oldFiles.createExclude().setName(addedFile); } final DirectoryScanner ds = oldFiles.getDirectoryScanner(getProject()); ((ZipScanner) ds).setEncoding(encoding); - final String[] f = ds.getIncludedFiles(); - Resource[] r = new Resource[f.length]; - for (int i = 0; i < f.length; i++) { - r[i] = ds.getResource(f[i]); - } + Stream<String> includedResourceNames = + Stream.of(ds.getIncludedFiles()); if (!doFilesonly) { - final String[] d = ds.getIncludedDirectories(); - final Resource[] dr = new Resource[d.length]; - for (int i = 0; i < d.length; i++) { - dr[i] = ds.getResource(d[i]); - } - final Resource[] tmp = r; - r = new Resource[tmp.length + dr.length]; - System.arraycopy(dr, 0, r, 0, dr.length); - System.arraycopy(tmp, 0, r, dr.length, tmp.length); + includedResourceNames = + Stream.concat(includedResourceNames, + Stream.of(ds.getIncludedDirectories())); } + + Resource[] r = includedResourceNames.map(ds::getResource) + .toArray(Resource[]::new); + addResources(oldFiles, r, zOut); } if (zOut != null) { @@ -783,16 +766,10 @@ public class Zip extends MatchingTask { "zip", ".tmp", zipFile.getParentFile(), true, false); try { FILE_UTILS.rename(zipFile, renamedFile); - } catch (final SecurityException e) { - throw new BuildException( - "Not allowed to rename old file (" - + zipFile.getAbsolutePath() - + ") to temporary file"); - } catch (final IOException e) { + } catch (final SecurityException | IOException e) { throw new BuildException( - "Unable to rename old file (" - + zipFile.getAbsolutePath() - + ") to temporary file"); + "Unable to rename old file (%s) to temporary file", + zipFile.getAbsolutePath()); } return renamedFile; } @@ -823,24 +800,23 @@ public class Zip extends MatchingTask { /** Check the attributes and elements */ private void checkAttributesAndElements() { - if (baseDir == null && resources.size() == 0 - && groupfilesets.size() == 0 && "zip".equals(archiveType)) { - throw new BuildException("basedir attribute must be set, " - + "or at least one " - + "resource collection must be given!"); + if (baseDir == null && resources.isEmpty() && groupfilesets.isEmpty() + && "zip".equals(archiveType)) { + throw new BuildException( + "basedir attribute must be set, or at least one resource collection must be given!"); } if (zipFile == null) { - throw new BuildException("You must specify the " - + archiveType + " file to create!"); + throw new BuildException("You must specify the %s file to create!", + archiveType); } if (zipFile.exists() && !zipFile.isFile()) { - throw new BuildException(zipFile + " is not a file."); + throw new BuildException("%s is not a file.", zipFile); } if (zipFile.exists() && !zipFile.canWrite()) { - throw new BuildException(zipFile + " is read-only."); + throw new BuildException("%s is read-only.", zipFile); } } @@ -858,23 +834,18 @@ public class Zip extends MatchingTask { /** Process groupfilesets */ private void processGroupFilesets() { // Add the files found in groupfileset to fileset - final int size = groupfilesets.size(); - for (int i = 0; i < size; i++) { - + for (FileSet fs : groupfilesets) { logWhenWriting("Processing groupfileset ", Project.MSG_VERBOSE); - final FileSet fs = groupfilesets.elementAt(i); final FileScanner scanner = fs.getDirectoryScanner(getProject()); - final String[] files = scanner.getIncludedFiles(); final File basedir = scanner.getBasedir(); - for (int j = 0; j < files.length; j++) { - - logWhenWriting("Adding file " + files[j] + " to fileset", + for (String file : scanner.getIncludedFiles()) { + logWhenWriting("Adding file " + file + " to fileset", Project.MSG_VERBOSE); final ZipFileSet zf = new ZipFileSet(); zf.setProject(getProject()); - zf.setSrc(new File(basedir, files[j])); + zf.setSrc(new File(basedir, file)); add(zf); - filesetsFromGroupfilesets.addElement(zf); + filesetsFromGroupfilesets.add(zf); } } } @@ -918,17 +889,16 @@ public class Zip extends MatchingTask { } if (prefix.length() > 0 && fullpath.length() > 0) { - throw new BuildException("Both prefix and fullpath attributes must" - + " not be set on the same fileset."); + throw new BuildException( + "Both prefix and fullpath attributes must not be set on the same fileset."); } if (resources.length != 1 && fullpath.length() > 0) { - throw new BuildException("fullpath attribute may only be specified" - + " for filesets that specify a single" - + " file."); + throw new BuildException( + "fullpath attribute may only be specified for filesets that specify a single file."); } - if (prefix.length() > 0) { + if (!prefix.isEmpty()) { if (!prefix.endsWith("/") && !prefix.endsWith("\\")) { prefix += "/"; } @@ -947,26 +917,26 @@ public class Zip extends MatchingTask { zf = new ZipFile(zfs.getSrc(getProject()), encoding); } - for (int i = 0; i < resources.length; i++) { - String name = null; - if (fullpath.length() > 0) { - name = fullpath; + for (Resource resource : resources) { + String name; + if (fullpath.isEmpty()) { + name = resource.getName(); } else { - name = resources[i].getName(); + name = fullpath; } name = name.replace(File.separatorChar, '/'); - if ("".equals(name)) { + if (name.isEmpty()) { continue; } - if (resources[i].isDirectory()) { + if (resource.isDirectory()) { if (doFilesonly) { continue; } final int thisDirMode = zfs != null && zfs.hasDirModeBeenSet() - ? dirMode : getUnixMode(resources[i], zf, dirMode); - addDirectoryResource(resources[i], name, prefix, + ? dirMode : getUnixMode(resource, zf, dirMode); + addDirectoryResource(resource, name, prefix, base, zOut, dirMode, thisDirMode); @@ -976,14 +946,14 @@ public class Zip extends MatchingTask { if (dealingWithFiles) { final File f = FILE_UTILS.resolveFile(base, - resources[i].getName()); + resource.getName()); zipFile(f, zOut, prefix + name, fileMode); } else { final int thisFileMode = zfs != null && zfs.hasFileModeBeenSet() - ? fileMode : getUnixMode(resources[i], zf, + ? fileMode : getUnixMode(resource, zf, fileMode); - addResource(resources[i], name, prefix, + addResource(resource, name, prefix, zOut, thisFileMode, zf, zfs == null ? null : zfs.getSrc(getProject())); @@ -1011,7 +981,7 @@ public class Zip extends MatchingTask { name = name + "/"; } - final int nextToLastSlash = name.lastIndexOf("/", name.length() - 2); + final int nextToLastSlash = name.lastIndexOf('/', name.length() - 2); if (nextToLastSlash != -1) { addParentDirs(base, name.substring(0, nextToLastSlash + 1), zOut, prefix, defaultDirMode); @@ -1057,25 +1027,18 @@ public class Zip extends MatchingTask { if (keepCompression) { doCompress = (ze.getMethod() == ZipEntry.DEFLATED); } - InputStream is = null; - try { - is = zf.getInputStream(ze); + try (InputStream is = zf.getInputStream(ze)) { zipFile(is, zOut, prefix + name, ze.getTime(), fromArchive, mode, ze.getExtraFields(true)); } finally { doCompress = oldCompress; - FileUtils.close(is); } } } else { - InputStream is = null; - try { - is = r.getInputStream(); + try (InputStream is = r.getInputStream()) { zipFile(is, zOut, prefix + name, r.getLastModified(), fromArchive, mode, r instanceof ZipResource ? ((ZipResource) r).getExtraFields() : null); - } finally { - FileUtils.close(is); } } } @@ -1099,15 +1062,14 @@ public class Zip extends MatchingTask { addResources((FileSet) rc, resources, zOut); return; } - for (int i = 0; i < resources.length; i++) { - final Resource resource = resources[i]; + for (final Resource resource : resources) { String name = resource.getName(); if (name == null) { continue; } name = name.replace(File.separatorChar, '/'); - if ("".equals(name)) { + if (name.isEmpty()) { continue; } if (resource.isDirectory() && doFilesonly) { @@ -1174,9 +1136,7 @@ public class Zip extends MatchingTask { log("Note: creating empty " + archiveType + " archive " + zipFile, Project.MSG_INFO); } - OutputStream os = null; - try { - os = Files.newOutputStream(zipFile.toPath()); + try (OutputStream os = Files.newOutputStream(zipFile.toPath())) { // CheckStyle:MagicNumber OFF // Cf. PKZIP specification. final byte[] empty = new byte[22]; @@ -1191,8 +1151,6 @@ public class Zip extends MatchingTask { throw new BuildException("Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe, getLocation()); - } finally { - FileUtils.close(os); } return true; } @@ -1241,13 +1199,13 @@ public class Zip extends MatchingTask { final File zipFile, final boolean needsUpdate) throws BuildException { - final ArrayList<ResourceCollection> filesets = new ArrayList<ResourceCollection>(); - final ArrayList<ResourceCollection> rest = new ArrayList<ResourceCollection>(); - for (int i = 0; i < rcs.length; i++) { - if (rcs[i] instanceof FileSet) { - filesets.add(rcs[i]); + final List<ResourceCollection> filesets = new ArrayList<>(); + final List<ResourceCollection> rest = new ArrayList<>(); + for (ResourceCollection rc : rcs) { + if (rc instanceof FileSet) { + filesets.add(rc); } else { - rest.add(rcs[i]); + rest.add(rc); } } final ResourceCollection[] rc = @@ -1349,7 +1307,7 @@ public class Zip extends MatchingTask { return new ArchiveState(true, initialResources); } - if (emptyBehavior.equals("skip")) { + if ("skip".equals(emptyBehavior)) { if (doUpdate) { logWhenWriting(archiveType + " archive " + zipFile + " not updated because no new files were" @@ -1360,7 +1318,7 @@ public class Zip extends MatchingTask { + " because no files were included.", Project.MSG_WARN); } - } else if (emptyBehavior.equals("fail")) { + } else if ("fail".equals(emptyBehavior)) { throw new BuildException("Cannot create " + archiveType + " archive " + zipFile + ": no files were included.", @@ -1521,8 +1479,8 @@ public class Zip extends MatchingTask { final FileProvider fp = initialResources[i][j].as(FileProvider.class); if (fp != null && zipFile.equals(fp.getFile())) { - throw new BuildException("A zip file cannot include " - + "itself", getLocation()); + throw new BuildException("A zip file cannot include itself", + getLocation()); } } @@ -1559,8 +1517,8 @@ public class Zip extends MatchingTask { ResourceUtils.selectSources(this, u, mapper, getZipScanner(), MISSING_DIR_PROVIDER); - if (rc.size() > 0) { - final ArrayList<Resource> newer = new ArrayList<Resource>(); + if (!rc.isEmpty()) { + final List<Resource> newer = new ArrayList<>(); newer.addAll(Arrays.asList(((Union) rc).listResources())); newer.addAll(Arrays.asList(result)); result = newer.toArray(result); @@ -1583,32 +1541,28 @@ public class Zip extends MatchingTask { boolean skipEmptyNames = true; if (filesets[i] instanceof ZipFileSet) { final ZipFileSet zfs = (ZipFileSet) filesets[i]; - skipEmptyNames = zfs.getPrefix(getProject()).equals("") - && zfs.getFullpath(getProject()).equals(""); + skipEmptyNames = zfs.getPrefix(getProject()).isEmpty() + && zfs.getFullpath(getProject()).isEmpty(); } final DirectoryScanner rs = filesets[i].getDirectoryScanner(getProject()); if (rs instanceof ZipScanner) { ((ZipScanner) rs).setEncoding(encoding); } - final Vector<Resource> resources = new Vector<Resource>(); + final List<Resource> resources = new Vector<>(); if (!doFilesonly) { - final String[] directories = rs.getIncludedDirectories(); - for (int j = 0; j < directories.length; j++) { - if (!"".equals(directories[j]) || !skipEmptyNames) { - resources.addElement(rs.getResource(directories[j])); + for (String d : rs.getIncludedDirectories()) { + if (!(d.isEmpty() && skipEmptyNames)) { + resources.add(rs.getResource(d)); } } } - final String[] files = rs.getIncludedFiles(); - for (int j = 0; j < files.length; j++) { - if (!"".equals(files[j]) || !skipEmptyNames) { - resources.addElement(rs.getResource(files[j])); + for (String f : rs.getIncludedFiles()) { + if (!(f.isEmpty() && skipEmptyNames)) { + resources.add(rs.getResource(f)); } } - - result[i] = new Resource[resources.size()]; - resources.copyInto(result[i]); + result[i] = resources.toArray(new Resource[resources.size()]); } return result; } @@ -1624,25 +1578,19 @@ public class Zip extends MatchingTask { protected Resource[][] grabNonFileSetResources(final ResourceCollection[] rcs) { final Resource[][] result = new Resource[rcs.length][]; for (int i = 0; i < rcs.length; i++) { - final ArrayList<Resource> dirs = new ArrayList<Resource>(); - final ArrayList<Resource> files = new ArrayList<Resource>(); + final List<Resource> dirs = new ArrayList<>(); + final List<Resource> files = new ArrayList<>(); for (final Resource r : rcs[i]) { - if (r.isExists()) { - if (r.isDirectory()) { - dirs.add(r); - } else { - files.add(r); - } + if (r.isDirectory()) { + dirs.add(r); + } else if (r.isExists()) { + files.add(r); } } // make sure directories are in alpha-order - this also // ensures parents come before their children - Collections.sort(dirs, new Comparator<Resource>() { - public int compare(final Resource r1, final Resource r2) { - return r1.getName().compareTo(r2.getName()); - } - }); - final ArrayList<Resource> rs = new ArrayList<Resource>(dirs); + Collections.sort(dirs, Comparator.comparing(Resource::getName)); + final List<Resource> rs = new ArrayList<>(dirs); rs.addAll(files); result[i] = rs.toArray(new Resource[rs.size()]); } @@ -1677,8 +1625,8 @@ public class Zip extends MatchingTask { protected void zipDir(final File dir, final ZipOutputStream zOut, final String vPath, final int mode, final ZipExtraField[] extra) throws IOException { - zipDir(dir == null ? (Resource) null : new FileResource(dir), - zOut, vPath, mode, extra); + zipDir(dir == null ? null : new FileResource(dir), zOut, vPath, mode, + extra); } /** @@ -1739,7 +1687,7 @@ public class Zip extends MatchingTask { * support a new parameter (extra fields to preserve) without * breaking subclasses that override the old method signature. */ - private static final ThreadLocal<ZipExtraField[]> CURRENT_ZIP_EXTRA = new ThreadLocal<ZipExtraField[]>(); + private static final ThreadLocal<ZipExtraField[]> CURRENT_ZIP_EXTRA = new ThreadLocal<>(); /** * Provides the extra fields for the zip entry currently being @@ -1781,19 +1729,19 @@ public class Zip extends MatchingTask { if (entries.containsKey(vPath)) { - if (duplicate.equals("preserve")) { + if ("preserve".equals(duplicate)) { logWhenWriting(vPath + " already added, skipping", Project.MSG_INFO); return; - } else if (duplicate.equals("fail")) { - throw new BuildException("Duplicate file " + vPath - + " was found and the duplicate " - + "attribute is 'fail'."); - } else { - // duplicate equal to add, so we continue - logWhenWriting("duplicate file " + vPath - + " found, adding.", Project.MSG_VERBOSE); } + if ("fail".equals(duplicate)) { + throw new BuildException( + "Duplicate file %s was found and the duplicate attribute is 'fail'.", + vPath); + } + // duplicate equal to add, so we continue + logWhenWriting("duplicate file " + vPath + + " found, adding.", Project.MSG_VERBOSE); } else { logWhenWriting("adding entry " + vPath, Project.MSG_VERBOSE); } @@ -1861,7 +1809,7 @@ public class Zip extends MatchingTask { count = in.read(buffer, 0, buffer.length); } while (count != -1); } - addedFiles.addElement(vPath); + addedFiles.add(vPath); } /** @@ -1937,7 +1885,7 @@ public class Zip extends MatchingTask { final int dirMode) throws IOException { if (!doFilesonly) { - final Stack<String> directories = new Stack<String>(); + final Stack<String> directories = new Stack<>(); int slashPos = entry.length(); while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) { @@ -1950,7 +1898,7 @@ public class Zip extends MatchingTask { while (!directories.isEmpty()) { final String dir = directories.pop(); - File f = null; + File f; if (baseDir != null) { f = new File(baseDir, dir); } else { @@ -1977,16 +1925,12 @@ public class Zip extends MatchingTask { */ protected void cleanUp() { addedDirs.clear(); - addedFiles.removeAllElements(); + addedFiles.clear(); entries.clear(); addingNewFiles = false; doUpdate = savedDoUpdate; - final Enumeration<ZipFileSet> e = filesetsFromGroupfilesets.elements(); - while (e.hasMoreElements()) { - final ZipFileSet zf = e.nextElement(); - resources.removeElement(zf); - } - filesetsFromGroupfilesets.removeAllElements(); + filesetsFromGroupfilesets.forEach(resources::remove); + filesetsFromGroupfilesets.clear(); HAVE_NON_FILE_SET_RESOURCES_TO_ADD.set(Boolean.FALSE); } @@ -1999,10 +1943,10 @@ public class Zip extends MatchingTask { * @see #cleanUp */ public void reset() { - resources.removeAllElements(); + resources.clear(); zipFile = null; baseDir = null; - groupfilesets.removeAllElements(); + groupfilesets.clear(); duplicate = "add"; archiveType = "zip"; doCompress = true; @@ -2020,8 +1964,8 @@ public class Zip extends MatchingTask { * @since Ant 1.5.2 */ protected static final boolean isEmpty(final Resource[][] r) { - for (int i = 0; i < r.length; i++) { - if (r[i].length > 0) { + for (Resource[] element : r) { + if (element.length > 0) { return false; } } @@ -2036,19 +1980,18 @@ public class Zip extends MatchingTask { */ protected Resource[] selectFileResources(final Resource[] orig) { return selectResources(orig, - new ResourceSelector() { - public boolean isSelected(final Resource r) { - if (!r.isDirectory()) { - return true; - } else if (doFilesonly) { - logWhenWriting("Ignoring directory " - + r.getName() - + " as only files will" - + " be added.", - Project.MSG_VERBOSE); - } - return false; + r -> { + if (!r.isDirectory()) { + return true; + } + if (doFilesonly) { + logWhenWriting("Ignoring directory " + + r.getName() + + " as only files will" + + " be added.", + Project.MSG_VERBOSE); } + return false; }); } @@ -2059,12 +2002,7 @@ public class Zip extends MatchingTask { * @since Ant 1.8.0 */ protected Resource[] selectDirectoryResources(final Resource[] orig) { - return selectResources(orig, - new ResourceSelector() { - public boolean isSelected(final Resource r) { - return r.isDirectory(); - } - }); + return selectResources(orig, Resource::isDirectory); } /** @@ -2078,18 +2016,9 @@ public class Zip extends MatchingTask { if (orig.length == 0) { return orig; } - - final ArrayList<Resource> v = new ArrayList<Resource>(orig.length); - for (int i = 0; i < orig.length; i++) { - if (selector.isSelected(orig[i])) { - v.add(orig[i]); - } - } - - if (v.size() != orig.length) { - return v.toArray(new Resource[v.size()]); - } - return orig; + Resource[] result = Stream.of(orig).filter(selector::isSelected) + .toArray(Resource[]::new); + return result.length == orig.length ? orig : result; } /** @@ -2115,7 +2044,7 @@ public class Zip extends MatchingTask { /** {@inheritDoc} */ @Override public String[] getValues() { - return new String[] {"add", "preserve", "fail"}; + return new String[] { "add", "preserve", "fail" }; } } @@ -2158,11 +2087,9 @@ public class Zip extends MatchingTask { if (resourcesToAdd == null) { return true; } - for (int counter = 0; counter < resourcesToAdd.length; counter++) { - if (resourcesToAdd[counter] != null) { - if (resourcesToAdd[counter].length > 0) { - return false; - } + for (Resource[] element : resourcesToAdd) { + if (element != null && element.length > 0) { + return false; } } return true; @@ -2176,7 +2103,7 @@ public class Zip extends MatchingTask { * @since Ant 1.8.0 */ public static final class UnicodeExtraField extends EnumeratedAttribute { - private static final Map<String, UnicodeExtraFieldPolicy> POLICIES = new HashMap<String, UnicodeExtraFieldPolicy>(); + private static final Map<String, UnicodeExtraFieldPolicy> POLICIES = new HashMap<>(); private static final String NEVER_KEY = "never"; private static final String ALWAYS_KEY = "always"; private static final String N_E_KEY = "not-encodeable"; @@ -2210,7 +2137,6 @@ public class Zip extends MatchingTask { } } - /** * The choices for Zip64 extensions. * @@ -2238,7 +2164,7 @@ public class Zip extends MatchingTask { * @since Ant 1.9.1 */ public static final class Zip64ModeAttribute extends EnumeratedAttribute { - private static final Map<String, Zip64Mode> MODES = new HashMap<String, Zip64Mode>(); + private static final Map<String, Zip64Mode> MODES = new HashMap<>(); private static final String NEVER_KEY = "never"; private static final String ALWAYS_KEY = "always"; @@ -2251,7 +2177,7 @@ public class Zip extends MatchingTask { @Override public String[] getValues() { - return new String[] {NEVER_KEY, ALWAYS_KEY, A_N_KEY}; + return new String[] { NEVER_KEY, ALWAYS_KEY, A_N_KEY }; } public static final Zip64ModeAttribute NEVER = http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java b/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java index 8712715..a1fe5c8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java @@ -96,69 +96,59 @@ public final class CompilerAdapterFactory { * @since Ant 1.8.0 */ public static CompilerAdapter getCompiler(String compilerType, Task task, - Path classpath) - throws BuildException { - if (compilerType.equalsIgnoreCase("jikes")) { - return new Jikes(); - } - if (compilerType.equalsIgnoreCase("extjavac")) { - return new JavacExternal(); - } - if (compilerType.equalsIgnoreCase("classic") - || compilerType.equalsIgnoreCase("javac1.1") - || compilerType.equalsIgnoreCase("javac1.2")) { - task.log("This version of java does " - + "not support the classic " - + "compiler; upgrading to modern", - Project.MSG_WARN); - compilerType = "modern"; - } - //on java<=1.3 the modern falls back to classic if it is not found - //but on java>=1.4 we just bail out early - if (compilerType.equalsIgnoreCase("modern") - || compilerType.equalsIgnoreCase("javac1.3") - || compilerType.equalsIgnoreCase("javac1.4") - || compilerType.equalsIgnoreCase("javac1.5") - || compilerType.equalsIgnoreCase("javac1.6") - || compilerType.equalsIgnoreCase("javac1.7") - || compilerType.equalsIgnoreCase("javac1.8") - || compilerType.equalsIgnoreCase("javac1.9") - || compilerType.equalsIgnoreCase("javac9")) { - // does the modern compiler exist? - if (doesModernCompilerExist()) { - return new Javac13(); - } else { - throw new BuildException("Unable to find a javac " - + "compiler;\n" - + MODERN_COMPILER - + " is not on the " - + "classpath.\n" - + "Perhaps JAVA_HOME does not" - + " point to the JDK.\n" - + "It is currently set to \"" - + JavaEnvUtils.getJavaHome() - + "\""); - } + Path classpath) throws BuildException { + if ("jikes".equalsIgnoreCase(compilerType)) { + return new Jikes(); + } + if ("extjavac".equalsIgnoreCase(compilerType)) { + return new JavacExternal(); + } + if ("classic".equalsIgnoreCase(compilerType) + || "javac1.1".equalsIgnoreCase(compilerType) + || "javac1.2".equalsIgnoreCase(compilerType)) { + task.log( + "This version of java does not support the classic compiler; upgrading to modern", + Project.MSG_WARN); + compilerType = "modern"; + } + //on java<=1.3 the modern falls back to classic if it is not found + //but on java>=1.4 we just bail out early + if ("modern".equalsIgnoreCase(compilerType) + || "javac1.3".equalsIgnoreCase(compilerType) + || "javac1.4".equalsIgnoreCase(compilerType) + || "javac1.5".equalsIgnoreCase(compilerType) + || "javac1.6".equalsIgnoreCase(compilerType) + || "javac1.7".equalsIgnoreCase(compilerType) + || "javac1.8".equalsIgnoreCase(compilerType) + || "javac1.9".equalsIgnoreCase(compilerType) + || "javac9".equalsIgnoreCase(compilerType)) { + // does the modern compiler exist? + if (doesModernCompilerExist()) { + return new Javac13(); } + throw new BuildException( + "Unable to find a javac compiler;\n%s is not on the classpath.\nPerhaps JAVA_HOME does not point to the JDK.\nIt is currently set to \"%s\"", + MODERN_COMPILER, JavaEnvUtils.getJavaHome()); + } - if (compilerType.equalsIgnoreCase("jvc") - || compilerType.equalsIgnoreCase("microsoft")) { - return new Jvc(); - } - if (compilerType.equalsIgnoreCase("kjc")) { - return new Kjc(); - } - if (compilerType.equalsIgnoreCase("gcj")) { - return new Gcj(); - } - if (compilerType.equalsIgnoreCase("sj") - || compilerType.equalsIgnoreCase("symantec")) { - return new Sj(); - } - return resolveClassName(compilerType, - // Memory-Leak in line below - task.getProject().createClassLoader(classpath)); + if ("jvc".equalsIgnoreCase(compilerType) + || "microsoft".equalsIgnoreCase(compilerType)) { + return new Jvc(); } + if ("kjc".equalsIgnoreCase(compilerType)) { + return new Kjc(); + } + if ("gcj".equalsIgnoreCase(compilerType)) { + return new Gcj(); + } + if ("sj".equalsIgnoreCase(compilerType) + || "symantec".equalsIgnoreCase(compilerType)) { + return new Sj(); + } + return resolveClassName(compilerType, + // Memory-Leak in line below + task.getProject().createClassLoader(classpath)); + } /** * query for the Modern compiler existing @@ -194,7 +184,7 @@ public final class CompilerAdapterFactory { private static CompilerAdapter resolveClassName(String className, ClassLoader loader) throws BuildException { - return (CompilerAdapter) ClasspathUtils.newInstance(className, + return ClasspathUtils.newInstance(className, loader != null ? loader : CompilerAdapterFactory.class.getClassLoader(), CompilerAdapter.class); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java b/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java index 82373a9..f33c4a5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapter.java @@ -18,13 +18,13 @@ package org.apache.tools.ant.taskdefs.compilers; -//Java5 style -//import static org.apache.tools.ant.util.StringUtils.LINE_SEP; - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; @@ -61,6 +61,10 @@ public abstract class DefaultCompilerAdapter private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + //must keep for subclass BC, though unused: + // CheckStyle:ConstantNameCheck OFF - bc + protected static final String lSep = StringUtils.LINE_SEP; + protected Path src; protected File destDir; protected String encoding; @@ -88,10 +92,6 @@ public abstract class DefaultCompilerAdapter protected File[] compileList; protected Javac attributes; - //must keep for subclass BC, though unused: - // CheckStyle:ConstantNameCheck OFF - bc - protected static final String lSep = StringUtils.LINE_SEP; - // CheckStyle:ConstantNameCheck ON // CheckStyle:VisibilityModifier ON @@ -101,6 +101,7 @@ public abstract class DefaultCompilerAdapter * * @param attributes a configured Javac task. */ + @Override public void setJavac(final Javac attributes) { this.attributes = attributes; src = attributes.getSrcdir(); @@ -147,8 +148,9 @@ public abstract class DefaultCompilerAdapter * but specialized compilers can recognize multiple kinds * of files. */ + @Override public String[] getSupportedFileExtensions() { - return new String[] {"java"}; + return new String[] { "java" }; } /** @@ -254,7 +256,7 @@ public abstract class DefaultCompilerAdapter final Path classpath = getCompileClasspath(); // For -sourcepath, use the "sourcepath" value if present. // Otherwise default to the "srcdir" value. - Path sourcepath = null; + Path sourcepath; if (compileSourcepath != null) { sourcepath = compileSourcepath; } else { @@ -264,9 +266,9 @@ public abstract class DefaultCompilerAdapter final String memoryParameterPrefix = assumeJava11() ? "-J-" : "-J-X"; if (memoryInitialSize != null) { if (!attributes.isForkedJavac()) { - attributes.log("Since fork is false, ignoring " - + "memoryInitialSize setting.", - Project.MSG_WARN); + attributes.log( + "Since fork is false, ignoring memoryInitialSize setting.", + Project.MSG_WARN); } else { cmd.createArgument().setValue(memoryParameterPrefix + "ms" + memoryInitialSize); @@ -275,9 +277,9 @@ public abstract class DefaultCompilerAdapter if (memoryMaximumSize != null) { if (!attributes.isForkedJavac()) { - attributes.log("Since fork is false, ignoring " - + "memoryMaximumSize setting.", - Project.MSG_WARN); + attributes.log( + "Since fork is false, ignoring memoryMaximumSize setting.", + Project.MSG_WARN); } else { cmd.createArgument().setValue(memoryParameterPrefix + "mx" + memoryMaximumSize); @@ -303,11 +305,7 @@ public abstract class DefaultCompilerAdapter // as well as "bootclasspath" and "extdirs" if (assumeJava11()) { final Path cp = new Path(project); - - final Path bp = getBootClassPath(); - if (bp.size() > 0) { - cp.append(bp); - } + Optional.ofNullable(getBootClassPath()).ifPresent(cp::append); if (extdirs != null) { cp.addExtdirs(extdirs); @@ -330,13 +328,13 @@ public abstract class DefaultCompilerAdapter } final Path bp = getBootClassPath(); - if (bp.size() > 0) { + if (!bp.isEmpty()) { cmd.createArgument().setValue("-bootclasspath"); cmd.createArgument().setPath(bp); } } - if (extdirs != null && extdirs.size() > 0) { + if (!(extdirs == null || extdirs.isEmpty())) { cmd.createArgument().setValue("-extdirs"); cmd.createArgument().setPath(extdirs); } @@ -370,8 +368,9 @@ public abstract class DefaultCompilerAdapter } else if (assumeJava12()) { cmd.createArgument().setValue("-Xdepend"); } else { - attributes.log("depend attribute is not supported by the " - + "modern compiler", Project.MSG_WARN); + attributes.log( + "depend attribute is not supported by the modern compiler", + Project.MSG_WARN); } } @@ -397,8 +396,8 @@ public abstract class DefaultCompilerAdapter final String s = attributes.getSource(); if (release == null || !assumeJava19()) { if (release != null) { - attributes.log("Support for javac --release has been added" - + " in Java9 ignoring it"); + attributes.log( + "Support for javac --release has been added in Java9 ignoring it"); } if (s != null) { cmd.createArgument().setValue("-source"); @@ -409,34 +408,34 @@ public abstract class DefaultCompilerAdapter } } else { // Java 9+ and release has been set if (t != null || s != null || getBootClassPath().size() > 0) { - attributes.log("Ignoring source, target and bootclasspath" - + " as release has been set", - Project.MSG_WARN); + attributes.log( + "Ignoring source, target and bootclasspath as release has been set", + Project.MSG_WARN); } cmd.createArgument().setValue("--release"); cmd.createArgument().setValue(release); } } final Path msp = getModulesourcepath(); - if (msp.size() > 0) { + if (!msp.isEmpty()) { cmd.createArgument().setValue("--module-source-path"); cmd.createArgument().setPath(msp); } final Path mp = getModulepath(); - if (mp.size() > 0) { + if (!mp.isEmpty()) { cmd.createArgument().setValue("--module-path"); cmd.createArgument().setPath(mp); } final Path ump = getUpgrademodulepath(); - if (ump.size() > 0) { + if (!ump.isEmpty()) { cmd.createArgument().setValue("--upgrade-module-path"); cmd.createArgument().setPath(ump); } if (attributes.getNativeHeaderDir() != null) { if (assumeJava13() || assumeJava14() || assumeJava15() || assumeJava16() || assumeJava17()) { - attributes.log("Support for javac -h has been added in Java8," - + " ignoring it"); + attributes.log( + "Support for javac -h has been added in Java8, ignoring it"); } else { cmd.createArgument().setValue("-h"); cmd.createArgument().setFile(attributes.getNativeHeaderDir()); @@ -486,25 +485,19 @@ public abstract class DefaultCompilerAdapter */ protected void logAndAddFilesToCompile(final Commandline cmd) { attributes.log("Compilation " + cmd.describeArguments(), - Project.MSG_VERBOSE); + Project.MSG_VERBOSE); - final StringBuffer niceSourceList = new StringBuffer("File"); - if (compileList.length != 1) { - niceSourceList.append("s"); - } - niceSourceList.append(" to be compiled:"); + attributes.log( + String.format("%s to be compiled:", + compileList.length == 1 ? "File" : "Files"), + Project.MSG_VERBOSE); - niceSourceList.append(StringUtils.LINE_SEP); - - for (int i = 0; i < compileList.length; i++) { - final String arg = compileList[i].getAbsolutePath(); - cmd.createArgument().setValue(arg); - niceSourceList.append(" "); - niceSourceList.append(arg); - niceSourceList.append(StringUtils.LINE_SEP); - } - - attributes.log(niceSourceList.toString(), Project.MSG_VERBOSE); + attributes.log( + Stream.of(compileList).map(File::getAbsolutePath) + .peek(arg -> cmd.createArgument().setValue(arg)) + .map(arg -> " " + arg) + .collect(Collectors.joining(StringUtils.LINE_SEP)), + Project.MSG_VERBOSE); } /** @@ -554,29 +547,30 @@ public abstract class DefaultCompilerAdapter */ if (Commandline.toString(args).length() > COMMAND_LINE_LIMIT && firstFileName >= 0) { - BufferedWriter out = null; try { tmpFile = FILE_UTILS.createTempFile( "files", "", getJavac().getTempdir(), true, true); - out = new BufferedWriter(new FileWriter(tmpFile)); - for (int i = firstFileName; i < args.length; i++) { - if (quoteFiles && args[i].indexOf(" ") > -1) { - args[i] = args[i].replace(File.separatorChar, '/'); - out.write("\"" + args[i] + "\""); - } else { - out.write(args[i]); + try (BufferedWriter out = + new BufferedWriter(new FileWriter(tmpFile))) { + for (int i = firstFileName; i < args.length; i++) { + if (quoteFiles && args[i].indexOf(' ') > -1) { + args[i] = + args[i].replace(File.separatorChar, '/'); + out.write("\"" + args[i] + "\""); + } else { + out.write(args[i]); + } + out.newLine(); } - out.newLine(); + out.flush(); + commandArray = new String[firstFileName + 1]; + System.arraycopy(args, 0, commandArray, 0, + firstFileName); + commandArray[firstFileName] = "@" + tmpFile; } - out.flush(); - commandArray = new String[firstFileName + 1]; - System.arraycopy(args, 0, commandArray, 0, firstFileName); - commandArray[firstFileName] = "@" + tmpFile; } catch (final IOException e) { throw new BuildException("Error creating temporary file", e, location); - } finally { - FileUtils.close(out); } } else { commandArray = args; @@ -705,6 +699,7 @@ public abstract class DefaultCompilerAdapter * @since Ant 1.9.4 * @deprecated use #assumeJava9 instead */ + @Deprecated protected boolean assumeJava19() { return assumeJavaXY("javac1.9", JavaEnvUtils.JAVA_9) || assumeJavaXY("javac9", JavaEnvUtils.JAVA_9); @@ -814,24 +809,22 @@ public abstract class DefaultCompilerAdapter if (t.startsWith("1.")) { t = t.substring(2); } - return t.equals("1") || t.equals("2") || t.equals("3") || t.equals("4") - || ((t.equals("5") || t.equals("6")) + return "1".equals(t) || "2".equals(t) || "3".equals(t) || "4".equals(t) + || (("5".equals(t) || "6".equals(t)) && !assumeJava15() && !assumeJava16()) - || (t.equals("7") && !assumeJava17()) - || (t.equals("8") && !assumeJava18()) - || (t.equals("9") && !assumeJava9()); + || ("7".equals(t) && !assumeJava17()) + || ("8".equals(t) && !assumeJava18()) + || ("9".equals(t) && !assumeJava9()); } - /** - * Turn the task's attribute for -source into soemthing that is + * Turn the task's attribute for -source into something that is * understood by all javac's after 1.4. * * <p>support for -source 1.1 and -source 1.2 has been added with * JDK 1.4.2 but isn't present in 1.5.0+</p> */ private String adjustSourceValue(final String source) { - return (source.equals("1.1") || source.equals("1.2")) ? "1.3" : source; + return "1.1".equals(source) || "1.2".equals(source) ? "1.3" : source; } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/compilers/Gcj.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/compilers/Gcj.java b/src/main/org/apache/tools/ant/taskdefs/compilers/Gcj.java index 3167cc2..b1c60a2 100644 --- a/src/main/org/apache/tools/ant/taskdefs/compilers/Gcj.java +++ b/src/main/org/apache/tools/ant/taskdefs/compilers/Gcj.java @@ -31,16 +31,19 @@ import org.apache.tools.ant.types.Path; * @since Ant 1.4 */ public class Gcj extends DefaultCompilerAdapter { + private static final String [] CONFLICT_WITH_DASH_C = { + "-o" , "--main=", "-D", "-fjni", "-L" + }; /** * Performs a compile using the gcj compiler. * @return true if the compilation succeeded * @throws BuildException on error */ + @Override public boolean execute() throws BuildException { - Commandline cmd; attributes.log("Using gcj compiler", Project.MSG_VERBOSE); - cmd = setupGCJCommand(); + Commandline cmd = setupGCJCommand(); int firstFileName = cmd.size(); logAndAddFilesToCompile(cmd); @@ -60,7 +63,7 @@ public class Gcj extends DefaultCompilerAdapter { // gcj doesn't support bootclasspath dir (-bootclasspath) // so we'll emulate it for compatibility and convenience. Path p = getBootClassPath(); - if (p.size() > 0) { + if (!p.isEmpty()) { classpath.append(p); } @@ -89,8 +92,8 @@ public class Gcj extends DefaultCompilerAdapter { if (!destDir.exists() && !(destDir.mkdirs() || destDir.isDirectory())) { - throw new BuildException("Can't make output directories. " - + "Maybe permission is wrong. "); + throw new BuildException( + "Can't make output directories. Maybe permission is wrong."); } } @@ -153,8 +156,4 @@ public class Gcj extends DefaultCompilerAdapter { return nativeBuild; } - private static final String [] CONFLICT_WITH_DASH_C = { - "-o" , "--main=", "-D", "-fjni", "-L" - }; - }
