http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Exit.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Exit.java b/src/main/org/apache/tools/ant/taskdefs/Exit.java index f48f248..7d7bfbe 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Exit.java +++ b/src/main/org/apache/tools/ant/taskdefs/Exit.java @@ -50,12 +50,13 @@ import org.apache.tools.ant.taskdefs.condition.ConditionBase; public class Exit extends Task { private static class NestedCondition extends ConditionBase implements Condition { + @Override public boolean eval() { if (countConditions() != 1) { throw new BuildException( "A single nested condition is required."); } - return ((Condition) (getConditions().nextElement())).eval(); + return getConditions().nextElement().eval(); } } @@ -131,12 +132,13 @@ public class Exit extends Task { * the if and unless parameters (if present). * @throws BuildException on error */ + @Override public void execute() throws BuildException { boolean fail = (nestedConditionPresent()) ? testNestedCondition() : (testIfCondition() && testUnlessCondition()); if (fail) { String text = null; - if (message != null && message.trim().length() > 0) { + if (!(message == null || message.trim().isEmpty())) { text = message.trim(); } else { if (ifCondition != null && !"".equals(ifCondition) @@ -154,15 +156,13 @@ public class Exit extends Task { } if (nestedConditionPresent()) { text = "condition satisfied"; - } else { - if (text == null) { - text = "No message"; - } + } else if (text == null) { + text = "No message"; } } log("failing due to " + text, Project.MSG_DEBUG); - throw ((status == null) ? new BuildException(text) - : new ExitStatusException(text, status.intValue())); + throw status == null ? new BuildException(text) + : new ExitStatusException(text, status.intValue()); } } @@ -217,8 +217,8 @@ public class Exit extends Task { boolean result = nestedConditionPresent(); if (result && ifCondition != null || unlessCondition != null) { - throw new BuildException("Nested conditions " - + "not permitted in conjunction with if/unless attributes"); + throw new BuildException( + "Nested conditions not permitted in conjunction with if/unless attributes"); } return result && nestedCondition.eval();
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Expand.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Expand.java b/src/main/org/apache/tools/ant/taskdefs/Expand.java index 6dd3c92..62fc196 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Expand.java +++ b/src/main/org/apache/tools/ant/taskdefs/Expand.java @@ -28,6 +28,7 @@ import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import java.util.Vector; @@ -59,25 +60,26 @@ import org.apache.tools.zip.ZipFile; * name="unwar" */ public class Expand extends Task { + public static final String NATIVE_ENCODING = "native-encoding"; + + /** Error message when more that one mapper is defined */ + public static final String ERROR_MULTIPLE_MAPPERS = "Cannot define more than one mapper"; + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private static final int BUFFER_SIZE = 1024; private File dest; //req private File source; // req private boolean overwrite = true; private Mapper mapperElement = null; - private Vector<PatternSet> patternsets = new Vector<PatternSet>(); + private List<PatternSet> patternsets = new Vector<>(); private Union resources = new Union(); private boolean resourcesSpecified = false; private boolean failOnEmptyArchive = false; private boolean stripAbsolutePathSpec = false; private boolean scanForUnicodeExtraFields = true; - public static final String NATIVE_ENCODING = "native-encoding"; - private String encoding; - /** Error message when more that one mapper is defined */ - public static final String ERROR_MULTIPLE_MAPPERS = "Cannot define more than one mapper"; - - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); /** * Creates an Expand instance and sets encoding to UTF-8. @@ -118,14 +120,15 @@ public class Expand extends Task { * * @exception BuildException Thrown in unrecoverable error. */ + @Override public void execute() throws BuildException { if ("expand".equals(getTaskType())) { log("!! expand is deprecated. Use unzip instead. !!"); } if (source == null && !resourcesSpecified) { - throw new BuildException("src attribute and/or resources must be " - + "specified"); + throw new BuildException( + "src attribute and/or resources must be specified"); } if (dest == null) { @@ -141,13 +144,14 @@ public class Expand extends Task { if (source.isDirectory()) { throw new BuildException("Src must not be a directory." + " Use nested filesets instead.", getLocation()); - } else if (!source.exists()) { + } + if (!source.exists()) { throw new BuildException("src '" + source + "' doesn't exist."); - } else if (!source.canRead()) { + } + if (!source.canRead()) { throw new BuildException("src '" + source + "' cannot be read."); - } else { - expandFile(FILE_UTILS, source, dest); } + expandFile(FILE_UTILS, source, dest); } for (Resource r : resources) { if (!r.isExists()) { @@ -173,7 +177,6 @@ public class Expand extends Task { */ protected void expandFile(FileUtils fileUtils, File srcF, File dir) { log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO); - ZipFile zf = null; FileNameMapper mapper = getMapper(); if (!srcF.exists()) { throw new BuildException("Unable to expand " @@ -181,8 +184,9 @@ public class Expand extends Task { + " as the file does not exist", getLocation()); } - try { - zf = new ZipFile(srcF, encoding, scanForUnicodeExtraFields); + try ( + ZipFile + zf = new ZipFile(srcF, encoding, scanForUnicodeExtraFields)){ boolean empty = true; Enumeration<ZipEntry> e = zf.getEntries(); while (e.hasMoreElements()) { @@ -200,7 +204,7 @@ public class Expand extends Task { } } if (empty && getFailOnEmptyArchive()) { - throw new BuildException("archive '" + srcF + "' is empty"); + throw new BuildException("archive '%s' is empty", srcF); } log("expand complete", Project.MSG_VERBOSE); } catch (IOException ioe) { @@ -208,8 +212,6 @@ public class Expand extends Task { "Error while expanding " + srcF.getPath() + "\n" + ioe.toString(), ioe); - } finally { - ZipFile.closeQuietly(zf); } } @@ -220,8 +222,8 @@ public class Expand extends Task { * @param dir the destination directory */ protected void expandResource(Resource srcR, File dir) { - throw new BuildException("only filesystem based resources are" - + " supported by this task."); + throw new BuildException( + "only filesystem based resources are supported by this task."); } /** @@ -229,13 +231,10 @@ public class Expand extends Task { * @return a filenamemapper for a file */ protected FileNameMapper getMapper() { - FileNameMapper mapper = null; if (mapperElement != null) { - mapper = mapperElement.getImplementation(); - } else { - mapper = new IdentityMapper(); + return mapperElement.getImplementation(); } - return mapper; + return new IdentityMapper(); } // CheckStyle:ParameterNumberCheck OFF - bc @@ -257,7 +256,7 @@ public class Expand extends Task { boolean isDirectory, FileNameMapper mapper) throws IOException { - if (stripAbsolutePathSpec && entryName.length() > 0 + if (stripAbsolutePathSpec && !entryName.isEmpty() && (entryName.charAt(0) == File.separatorChar || entryName.charAt(0) == '/' || entryName.charAt(0) == '\\')) { @@ -266,16 +265,16 @@ public class Expand extends Task { entryName = entryName.substring(1); } - if (patternsets != null && patternsets.size() > 0) { + if (!(patternsets == null || patternsets.isEmpty())) { String name = entryName.replace('/', File.separatorChar) .replace('\\', File.separatorChar); boolean included = false; - Set<String> includePatterns = new HashSet<String>(); - Set<String> excludePatterns = new HashSet<String>(); + Set<String> includePatterns = new HashSet<>(); + Set<String> excludePatterns = new HashSet<>(); final int size = patternsets.size(); for (int v = 0; v < size; v++) { - PatternSet p = patternsets.elementAt(v); + PatternSet p = patternsets.get(v); String[] incls = p.getIncludePatterns(getProject()); if (incls == null || incls.length == 0) { // no include pattern implicitly means includes="**" @@ -350,20 +349,11 @@ public class Expand extends Task { f.mkdirs(); } else { byte[] buffer = new byte[BUFFER_SIZE]; - int length = 0; - OutputStream fos = null; - try { - fos = Files.newOutputStream(f.toPath()); - - while ((length = - compressedInputStream.read(buffer)) >= 0) { + try (OutputStream fos = Files.newOutputStream(f.toPath())) { + int length; + while ((length = compressedInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } - - fos.close(); - fos = null; - } finally { - FileUtils.close(fos); } } @@ -410,7 +400,7 @@ public class Expand extends Task { * @param set a pattern set */ public void addPatternset(PatternSet set) { - patternsets.addElement(set); + patternsets.add(set); } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Filter.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Filter.java b/src/main/org/apache/tools/ant/taskdefs/Filter.java index 390ba5b..da4b350 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Filter.java +++ b/src/main/org/apache/tools/ant/taskdefs/Filter.java @@ -69,6 +69,7 @@ public class Filter extends Task { * Execute the task. * @throws BuildException on error */ + @Override public void execute() throws BuildException { boolean isFiltersFromFile = filtersFile != null && token == null && value == null; @@ -76,9 +77,9 @@ public class Filter extends Task { filtersFile == null && token != null && value != null; if (!isFiltersFromFile && !isSingleFilter) { - throw new BuildException("both token and value parameters, or " - + "only a filtersFile parameter is " - + "required", getLocation()); + throw new BuildException( + "both token and value parameters, or only a filtersFile parameter is required", + getLocation()); } if (isSingleFilter) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java index af2a21f..806c814 100644 --- a/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java +++ b/src/main/org/apache/tools/ant/taskdefs/FixCRLF.java @@ -115,6 +115,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { * @return a Reader. * @since Ant 1.7? */ + @Override public final Reader chain(final Reader rdr) { return filter.chain(rdr); } @@ -181,15 +182,16 @@ public class FixCRLF extends MatchingTask implements ChainableReader { * @deprecated since 1.4.x. * Use {@link #setEol setEol} instead. */ + @Deprecated public void setCr(AddAsisRemove attr) { log("DEPRECATED: The cr attribute has been deprecated,", Project.MSG_WARN); log("Please use the eol attribute instead", Project.MSG_WARN); String option = attr.getValue(); CrLf c = new CrLf(); - if (option.equals("remove")) { + if ("remove".equals(option)) { c.setValue("lf"); - } else if (option.equals("asis")) { + } else if ("asis".equals(option)) { c.setValue("asis"); } else { // must be "add" @@ -282,6 +284,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { * Executes the task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { // first off, make sure that we've got a srcdir and destdir validate(); @@ -322,22 +325,21 @@ public class FixCRLF extends MatchingTask implements ChainableReader { } if (!srcDir.exists()) { throw new BuildException( - FIXCRLF_ERROR + "srcdir does not exist: '" + srcDir + "'"); + FIXCRLF_ERROR + "srcdir does not exist: '%s'", srcDir); } if (!srcDir.isDirectory()) { throw new BuildException( - FIXCRLF_ERROR + "srcdir is not a directory: '" + srcDir + "'"); + FIXCRLF_ERROR + "srcdir is not a directory: '%s'", srcDir); } if (destDir != null) { if (!destDir.exists()) { throw new BuildException( - FIXCRLF_ERROR + "destdir does not exist: '" - + destDir + "'"); + FIXCRLF_ERROR + "destdir does not exist: '%s'", destDir); } if (!destDir.isDirectory()) { throw new BuildException( - FIXCRLF_ERROR + "destdir is not a directory: '" - + destDir + "'"); + FIXCRLF_ERROR + "destdir is not a directory: '%s'", + destDir); } } } @@ -350,7 +352,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { if (fcv == null) { FilterChain fc = new FilterChain(); fc.add(filter); - fcv = new Vector<FilterChain>(1); + fcv = new Vector<>(1); fcv.add(fc); } File tmpFile = FILE_UTILS.createTempFile("fixcrlf", "", null, true, true); @@ -391,6 +393,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { * Deprecated, the functionality has been moved to filters.FixCrLfFilter. * @deprecated since 1.7.0. */ + @Deprecated protected class OneLiner implements Enumeration<Object> { private static final int UNDEF = -1; private static final int NOTJAVA = 0; @@ -549,6 +552,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { /** * @return true if there is more elements. */ + @Override public boolean hasMoreElements() { return !reachedEof; } @@ -558,6 +562,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { * @return the next element. * @throws NoSuchElementException if there is no more. */ + @Override public Object nextElement() throws NoSuchElementException { if (!hasMoreElements()) { @@ -673,22 +678,24 @@ public class FixCRLF extends MatchingTask implements ChainableReader { */ public static class AddAsisRemove extends EnumeratedAttribute { /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[] {"add", "asis", "remove"}; + return new String[] { "add", "asis", "remove" }; } } /** - * Enumerated attribute with the values "asis", "cr", "lf" and "crlf". + * Enumerated attribute with the values "asis", "cr", "lf", "crlf", "mac", "unix" and "dos. */ public static class CrLf extends EnumeratedAttribute { /** * @see EnumeratedAttribute#getValues */ /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[] {"asis", "cr", "lf", "crlf", - "mac", "unix", "dos"}; + return new String[] { "asis", "cr", "lf", "crlf", "mac", "unix", + "dos" }; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/GUnzip.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/GUnzip.java b/src/main/org/apache/tools/ant/taskdefs/GUnzip.java index 94f08d7..d0fe4b0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/GUnzip.java +++ b/src/main/org/apache/tools/ant/taskdefs/GUnzip.java @@ -19,13 +19,11 @@ package org.apache.tools.ant.taskdefs; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.zip.GZIPInputStream; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.util.FileUtils; /** * Expands a file that has been compressed with the GZIP @@ -45,6 +43,7 @@ public class GUnzip extends Unpack { * Get the default extension. * @return the value ".gz" */ + @Override protected String getDefaultExtension() { return DEFAULT_EXTENSION; } @@ -52,18 +51,14 @@ public class GUnzip extends Unpack { /** * Implement the gunzipping. */ + @Override protected void extract() { if (srcResource.getLastModified() > dest.lastModified()) { log("Expanding " + srcResource.getName() + " to " + dest.getAbsolutePath()); - - OutputStream out = null; - GZIPInputStream zIn = null; - InputStream fis = null; - try { - out = Files.newOutputStream(dest.toPath()); - fis = srcResource.getInputStream(); - zIn = new GZIPInputStream(fis); + try (OutputStream out = Files.newOutputStream(dest.toPath()); + GZIPInputStream zIn = + new GZIPInputStream(srcResource.getInputStream())) { byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; do { @@ -73,10 +68,6 @@ public class GUnzip extends Unpack { } catch (IOException ioe) { String msg = "Problem expanding gzip " + ioe.getMessage(); throw new BuildException(msg, ioe, getLocation()); - } finally { - FileUtils.close(fis); - FileUtils.close(out); - FileUtils.close(zIn); } } } @@ -92,6 +83,7 @@ public class GUnzip extends Unpack { * @return true if this task supports non file resources. * @since Ant 1.7 */ + @Override protected boolean supportsNonFileResources() { return getClass().equals(GUnzip.class); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/GZip.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/GZip.java b/src/main/org/apache/tools/ant/taskdefs/GZip.java index 4d7be1f..8803647 100644 --- a/src/main/org/apache/tools/ant/taskdefs/GZip.java +++ b/src/main/org/apache/tools/ant/taskdefs/GZip.java @@ -19,12 +19,10 @@ package org.apache.tools.ant.taskdefs; import java.io.IOException; -import java.io.OutputStream; import java.nio.file.Files; import java.util.zip.GZIPOutputStream; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.util.FileUtils; /** * Compresses a file with the GZIP algorithm. Normally used to compress @@ -39,16 +37,14 @@ public class GZip extends Pack { /** * perform the GZip compression operation. */ + @Override protected void pack() { - GZIPOutputStream zOut = null; - try { - zOut = new GZIPOutputStream(Files.newOutputStream(zipFile.toPath())); + try (GZIPOutputStream zOut = + new GZIPOutputStream(Files.newOutputStream(zipFile.toPath()))) { zipResource(getSrcResource(), zOut); } catch (IOException ioe) { String msg = "Problem creating gzip " + ioe.getMessage(); throw new BuildException(msg, ioe, getLocation()); - } finally { - FileUtils.close(zOut); } } @@ -63,6 +59,7 @@ public class GZip extends Pack { * @return true if this case supports non file resources. * @since Ant 1.7 */ + @Override protected boolean supportsNonFileResources() { return getClass().equals(GZip.class); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java b/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java index c26ac36..7270e67 100644 --- a/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java +++ b/src/main/org/apache/tools/ant/taskdefs/GenerateKey.java @@ -17,8 +17,12 @@ */ package org.apache.tools.ant.taskdefs; +import java.util.Collections; import java.util.Enumeration; +import java.util.List; import java.util.Vector; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; @@ -83,7 +87,7 @@ public class GenerateKey extends Task { * A class corresponding to the dname nested element. */ public static class DistinguishedName { - private Vector<DnameParam> params = new Vector<DnameParam>(); + private List<DnameParam> params = new Vector<>(); /** * Create a param nested element. @@ -91,8 +95,7 @@ public class GenerateKey extends Task { */ public Object createParam() { DnameParam param = new DnameParam(); - params.addElement(param); - + params.add(param); return param; } @@ -101,7 +104,7 @@ public class GenerateKey extends Task { * @return an enumeration of the nested parameters. */ public Enumeration<DnameParam> getParams() { - return params.elements(); + return Collections.enumeration(params); } /** @@ -111,26 +114,10 @@ public class GenerateKey extends Task { * This is used on the command line. * @return a string rep of this name */ + @Override public String toString() { - final int size = params.size(); - final StringBuffer sb = new StringBuffer(); - boolean firstPass = true; - - for (int i = 0; i < size; i++) { - if (!firstPass) { - sb.append(" ,"); - } - firstPass = false; - - final DnameParam param = (DnameParam) params.elementAt(i); - if (param.isComplete()) { - sb.append(encode(param.getName())); - sb.append('='); - sb.append(encode(param.getValue())); - } - } - - return sb.toString(); + return params.stream().map(p -> p.getName() + "=" + p.getValue()) + .collect(Collectors.joining(", ")); } /** @@ -141,26 +128,8 @@ public class GenerateKey extends Task { * @return the encoded value. */ public String encode(final String string) { - int end = string.indexOf(','); - - if (-1 == end) { - return string; - } - - final StringBuffer sb = new StringBuffer(); - - int start = 0; - - while (-1 != end) { - sb.append(string.substring(start, end)); - sb.append("\\,"); - start = end + 1; - end = string.indexOf(',', start); - } - - sb.append(string.substring(start)); - - return sb.toString(); + return Stream.of(string.split(",")) + .collect(Collectors.joining("\\,")); } } @@ -197,12 +166,11 @@ public class GenerateKey extends Task { */ public DistinguishedName createDname() throws BuildException { if (null != expandedDname) { - throw new BuildException("DName sub-element can only be " - + "specified once."); + throw new BuildException("DName sub-element can only be specified once."); } if (null != dname) { - throw new BuildException("It is not possible to specify dname " - + " both as attribute and element."); + throw new BuildException( + "It is not possible to specify dname both as attribute and element."); } expandedDname = new DistinguishedName(); return expandedDname; @@ -215,8 +183,8 @@ public class GenerateKey extends Task { */ public void setDname(final String dname) { if (null != expandedDname) { - throw new BuildException("It is not possible to specify dname " - + " both as attribute and element."); + throw new BuildException( + "It is not possible to specify dname both as attribute and element."); } this.dname = dname; } @@ -324,6 +292,7 @@ public class GenerateKey extends Task { * Execute the task. * @throws BuildException on error */ + @Override public void execute() throws BuildException { if (null == alias) { @@ -338,7 +307,7 @@ public class GenerateKey extends Task { throw new BuildException("dname must be set"); } - final StringBuffer sb = new StringBuffer(); + final StringBuilder sb = new StringBuilder(); sb.append("-genkey "); @@ -400,7 +369,6 @@ public class GenerateKey extends Task { sb.append("\" "); } - if (0 < keysize) { sb.append("-keysize \""); sb.append(keysize); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Get.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Get.java b/src/main/org/apache/tools/ant/taskdefs/Get.java index 9b92f00..7e79128 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Get.java +++ b/src/main/org/apache/tools/ant/taskdefs/Get.java @@ -96,7 +96,7 @@ public class Get extends Task { + Main.getShortAntVersion()); // Store headers as key/value pair without duplicate in keyz - private Map<String, String> headers = new LinkedHashMap<String, String>(); + private Map<String, String> headers = new LinkedHashMap<>(); /** * Does the work. @@ -118,7 +118,7 @@ public class Get extends Task { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } - final int slash = path.lastIndexOf("/"); + final int slash = path.lastIndexOf('/'); if (slash > -1) { path = path.substring(slash + 1); } @@ -130,11 +130,13 @@ public class Get extends Task { log("skipping " + r + " - mapper can't handle it", Project.MSG_WARN); continue; - } else if (d.length == 0) { + } + if (d.length == 0) { log("skipping " + r + " - mapper returns no file name", Project.MSG_WARN); continue; - } else if (d.length > 1) { + } + if (d.length > 1) { log("skipping " + r + " - mapper returns multiple file" + " names", Project.MSG_WARN); continue; @@ -288,8 +290,8 @@ public class Get extends Task { for (final Resource r : sources) { final URLProvider up = r.as(URLProvider.class); if (up == null) { - throw new BuildException("Only URLProvider resources are" - + " supported", getLocation()); + throw new BuildException( + "Only URLProvider resources are supported", getLocation()); } } @@ -299,9 +301,8 @@ public class Get extends Task { if (destination.exists() && sources.size() > 1 && !destination.isDirectory()) { - throw new BuildException("The specified destination is not a" - + " directory", - getLocation()); + throw new BuildException( + "The specified destination is not a directory", getLocation()); } if (destination.exists() && !destination.canWrite()) { @@ -391,7 +392,6 @@ public class Get extends Task { useTimestamp = v; } - /** * Username for basic auth. * @@ -566,6 +566,7 @@ public class Get extends Task { /** * begin a download */ + @Override public void beginDownload() { } @@ -573,12 +574,14 @@ public class Get extends Task { * tick handler * */ + @Override public void onTick() { } /** * end a download */ + @Override public void endDownload() { } } @@ -603,6 +606,7 @@ public class Get extends Task { /** * begin a download */ + @Override public void beginDownload() { dots = 0; } @@ -611,6 +615,7 @@ public class Get extends Task { * tick handler * */ + @Override public void onTick() { out.print("."); if (dots++ > DOTS_PER_LINE) { @@ -622,6 +627,7 @@ public class Get extends Task { /** * end a download */ + @Override public void endDownload() { out.println(); out.flush(); @@ -699,9 +705,8 @@ public class Get extends Task { if (ignoreErrors) { log(message, logLevel); return false; - } else { - throw new BuildException(message); } + throw new BuildException(message); } redirections++; @@ -711,12 +716,9 @@ public class Get extends Task { if (ignoreErrors) { log(message, logLevel); return false; - } else { - throw new BuildException(message); } + throw new BuildException(message); } - - return true; } @@ -749,14 +751,12 @@ public class Get extends Task { connection.setRequestProperty("Accept-Encoding", GZIP_CONTENT_ENCODING); } - for (final Map.Entry<String, String> header : headers.entrySet()) { //we do not log the header value as it may contain sensitive data like passwords log(String.format("Adding header '%s' ", header.getKey())); connection.setRequestProperty(header.getKey(), header.getValue()); } - if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection) .setInstanceFollowRedirects(false); @@ -804,9 +804,8 @@ public class Get extends Task { if (ignoreErrors) { log(message, logLevel); return null; - } else { - throw new BuildException(message); } + throw new BuildException(message); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/HostInfo.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/HostInfo.java b/src/main/org/apache/tools/ant/taskdefs/HostInfo.java index 43a1211..af36afc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/HostInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/HostInfo.java @@ -105,8 +105,9 @@ public class HostInfo extends Task { * @throws BuildException * on error. */ + @Override public void execute() throws BuildException { - if (host == null || "".equals(host)) { + if (host == null || host.isEmpty()) { executeLocal(); } else { executeRemote(); @@ -115,7 +116,7 @@ public class HostInfo extends Task { private void executeLocal() { try { - inetAddrs = new LinkedList<InetAddress>(); + inetAddrs = new LinkedList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface currentif = interfaces.nextElement(); @@ -175,34 +176,32 @@ public class HostInfo extends Task { if (best == null) { // none selected so far, so this one is better. best = current; + } else if (current == null || current.isLoopbackAddress()) { + // definitely not better than the previously selected address. + } else if (current.isLinkLocalAddress()) { + // link local considered better than loopback + if (best.isLoopbackAddress()) { + best = current; + } + } else if (current.isSiteLocalAddress()) { + // site local considered better than link local (and loopback) + // address with hostname resolved considered better than + // address without hostname + if (best.isLoopbackAddress() + || best.isLinkLocalAddress() + || (best.isSiteLocalAddress() && !hasHostName(best))) { + best = current; + } } else { - if (current == null || current.isLoopbackAddress()) { - // definitely not better than the previously selected address. - } else if (current.isLinkLocalAddress()) { - // link local considered better than loopback - if (best.isLoopbackAddress()) { - best = current; - } - } else if (current.isSiteLocalAddress()) { - // site local considered better than link local (and loopback) - // address with hostname resolved considered better than - // address without hostname - if (best.isLoopbackAddress() - || best.isLinkLocalAddress() - || (best.isSiteLocalAddress() && !hasHostName(best))) { - best = current; - } - } else { - // current is a "Global address", considered better than - // site local (and better than link local, loopback) - // address with hostname resolved considered better than - // address without hostname - if (best.isLoopbackAddress() - || best.isLinkLocalAddress() - || best.isSiteLocalAddress() - || !hasHostName(best)) { - best = current; - } + // current is a "Global address", considered better than + // site local (and better than link local, loopback) + // address with hostname resolved considered better than + // address without hostname + if (best.isLoopbackAddress() + || best.isLinkLocalAddress() + || best.isSiteLocalAddress() + || !hasHostName(best)) { + best = current; } } return best; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/ImportTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/ImportTask.java b/src/main/org/apache/tools/ant/taskdefs/ImportTask.java index 63adf71..98bf4b3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/ImportTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/ImportTask.java @@ -63,12 +63,13 @@ import org.apache.tools.ant.util.FileUtils; * @ant.task category="control" */ public class ImportTask extends Task { + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private String file; private boolean optional; private String targetPrefix = ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX; private String prefixSeparator = "."; private final Union resources = new Union(); - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); public ImportTask() { resources.setCache(true); @@ -123,18 +124,18 @@ public class ImportTask extends Task { resources.add(r); } + @Override public void execute() { - if (file == null && resources.size() == 0) { - throw new BuildException("import requires file attribute or" - + " at least one nested resource"); + if (file == null && resources.isEmpty()) { + throw new BuildException( + "import requires file attribute or at least one nested resource"); } if (getOwningTarget() == null - || !"".equals(getOwningTarget().getName())) { + || !getOwningTarget().getName().isEmpty()) { throw new BuildException("import only allowed as a top-level task"); } - ProjectHelper helper = - (ProjectHelper) getProject(). + ProjectHelper helper = getProject(). getReference(ProjectHelper.PROJECTHELPER_REFERENCE); if (helper == null) { @@ -142,9 +143,7 @@ public class ImportTask extends Task { throw new BuildException("import requires support in ProjectHelper"); } - Vector<Object> importStack = helper.getImportStack(); - - if (importStack.size() == 0) { + if (helper.getImportStack().isEmpty()) { // this happens if ant is used with a project // helper that doesn't set the import. throw new BuildException("import requires support in ProjectHelper"); @@ -166,8 +165,6 @@ public class ImportTask extends Task { private void importResource(ProjectHelper helper, Resource importedResource) { - Vector<Object> importStack = helper.getImportStack(); - getProject().log("Importing file " + importedResource + " from " + getLocation().getFileName(), Project.MSG_VERBOSE); @@ -178,13 +175,12 @@ public class ImportTask extends Task { if (optional) { getProject().log(message, Project.MSG_VERBOSE); return; - } else { - throw new BuildException(message); } + throw new BuildException(message); } - if (!isInIncludeMode() && - hasAlreadyBeenImported(importedResource, importStack)) { + if (!isInIncludeMode() && hasAlreadyBeenImported(importedResource, + helper.getImportStack())) { getProject().log( "Skipped already imported file:\n " + importedResource + "\n", Project.MSG_VERBOSE); @@ -203,10 +199,10 @@ public class ImportTask extends Task { prefix = oldPrefix + oldSep + targetPrefix; } else if (isInIncludeMode()) { prefix = targetPrefix; - } else if (!ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX.equals(targetPrefix)) { - prefix = targetPrefix; - } else { + } else if (ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX.equals(targetPrefix)) { prefix = oldPrefix; + } else { + prefix = targetPrefix; } setProjectHelperProps(prefix, prefixSeparator, isInIncludeMode()); @@ -260,9 +256,8 @@ public class ImportTask extends Task { } catch (MalformedURLException ex) { log(ex.toString(), Project.MSG_VERBOSE); } - throw new BuildException("failed to resolve " + file - + " relative to " - + getLocation().getFileName()); + throw new BuildException("failed to resolve %s relative to %s", + file, getLocation().getFileName()); } return null; } @@ -274,22 +269,14 @@ public class ImportTask extends Task { private boolean hasAlreadyBeenImported(Resource importedResource, Vector<Object> importStack) { - File importedFile = null; - FileProvider fp = importedResource.as(FileProvider.class); - if (fp != null) { - importedFile = fp.getFile(); - } - URL importedURL = null; - URLProvider up = importedResource.as(URLProvider.class); - if (up != null) { - importedURL = up.getURL(); - } - for (Object o : importStack) { - if (isOneOf(o, importedResource, importedFile, importedURL)) { - return true; - } - } - return false; + File importedFile = importedResource.asOptional(FileProvider.class) + .map(FileProvider::getFile).orElse(null); + + URL importedURL = importedResource.asOptional(URLProvider.class) + .map(URLProvider::getURL).orElse(null); + + return importStack.stream().anyMatch( + o -> isOneOf(o, importedResource, importedFile, importedURL)); } private boolean isOneOf(Object o, Resource importedResource, http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Input.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Input.java b/src/main/org/apache/tools/ant/taskdefs/Input.java index ed05131..c7a5ec8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Input.java +++ b/src/main/org/apache/tools/ant/taskdefs/Input.java @@ -18,8 +18,7 @@ package org.apache.tools.ant.taskdefs; -import java.util.Vector; - +import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.input.DefaultInputHandler; @@ -59,6 +58,7 @@ public class Input extends Task { public void setRefid(final String refid) { this.refid = refid; } + /** * Get the refid of this Handler. * @return String refid. @@ -66,6 +66,7 @@ public class Input extends Task { public String getRefid() { return refid; } + /** * Set the InputHandler classname. * @param classname the String classname. @@ -73,6 +74,7 @@ public class Input extends Task { public void setClassname(final String classname) { this.classname = classname; } + /** * Get the classname of the InputHandler. * @return String classname. @@ -80,6 +82,7 @@ public class Input extends Task { public String getClassname() { return classname; } + /** * Set the handler type. * @param type a HandlerType. @@ -87,6 +90,7 @@ public class Input extends Task { public void setType(final HandlerType type) { this.type = type; } + /** * Get the handler type. * @return a HandlerType object. @@ -94,6 +98,7 @@ public class Input extends Task { public HandlerType getType() { return type; } + private InputHandler getInputHandler() { if (type != null) { return type.getInputHandler(); @@ -107,8 +112,8 @@ public class Input extends Task { } } if (classname != null) { - return (InputHandler) (ClasspathUtils.newInstance(classname, - createLoader(), InputHandler.class)); + return ClasspathUtils.newInstance(classname, + createLoader(), InputHandler.class); } throw new BuildException( "Must specify refid, classname or type"); @@ -120,19 +125,21 @@ public class Input extends Task { * "default", "propertyfile", "greedy", "secure" (since Ant 1.8). */ public static class HandlerType extends EnumeratedAttribute { - private static final String[] VALUES = {"default", "propertyfile", "greedy", "secure"}; + private static final String[] VALUES = + { "default", "propertyfile", "greedy", "secure" }; private static final InputHandler[] HANDLERS - = {new DefaultInputHandler(), - new PropertyFileInputHandler(), - new GreedyInputHandler(), - new SecureInputHandler()}; + = { new DefaultInputHandler(), + new PropertyFileInputHandler(), + new GreedyInputHandler(), + new SecureInputHandler() }; /** {@inheritDoc} */ @Override public String[] getValues() { return VALUES; } + private InputHandler getInputHandler() { return HANDLERS[getIndex()]; } @@ -193,19 +200,13 @@ public class Input extends Task { * @param msg The message to be displayed. */ public void addText(final String msg) { - if (messageAttribute && "".equals(msg.trim())) { + if (messageAttribute && msg.trim().isEmpty()) { return; } message += getProject().replaceProperties(msg); } /** - * No arg constructor. - */ - public Input () { - } - - /** * Actual method executed by ant. * @throws BuildException on error */ @@ -220,7 +221,7 @@ public class Input extends Task { InputRequest request = null; if (validargs != null) { - final Vector<String> accept = StringUtils.split(validargs, ','); + final List<String> accept = StringUtils.split(validargs, ','); request = new MultipleChoiceInputRequest(message, accept); } else { request = new InputRequest(message); @@ -234,7 +235,7 @@ public class Input extends Task { h.handleInput(request); String value = request.getInput(); - if ((value == null || value.trim().length() == 0) + if ((value == null || value.trim().isEmpty()) && defaultvalue != null) { value = defaultvalue; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java index 2ca6e22..3674586 100644 --- a/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/JDBCTask.java @@ -24,7 +24,6 @@ import java.sql.Driver; import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Properties; @@ -98,7 +97,7 @@ public abstract class JDBCTask extends Task { * getting an OutOfMemoryError when calling this task * multiple times in a row. */ - private static Hashtable<String, AntClassLoader> LOADER_MAP = new Hashtable<String, AntClassLoader>(HASH_TABLE_SIZE); + private static Hashtable<String, AntClassLoader> LOADER_MAP = new Hashtable<>(HASH_TABLE_SIZE); private boolean caching = true; @@ -152,7 +151,7 @@ public abstract class JDBCTask extends Task { * * @since Ant 1.8.0 */ - private List<Property> connectionProperties = new ArrayList<Property>(); + private List<Property> connectionProperties = new ArrayList<>(); /** * Sets the classpath for loading the driver. @@ -342,20 +341,17 @@ public abstract class JDBCTask extends Task { throw new BuildException("Url attribute must be set!", getLocation()); } try { - log("connecting to " + getUrl(), Project.MSG_VERBOSE); Properties info = new Properties(); info.put("user", getUserId()); info.put("password", getPassword()); - for (Iterator<Property> props = connectionProperties.iterator(); - props.hasNext();) { - Property p = props.next(); - String name = p.getName(); - String value = p.getValue(); + for (Property p : connectionProperties) { + String name = p.getName(); + String value = p.getValue(); if (name == null || value == null) { - log("Only name/value pairs are supported as connection" - + " properties.", Project.MSG_WARN); + log("Only name/value pairs are supported as connection properties.", + Project.MSG_WARN); } else { log("Setting connection property " + name + " to " + value, Project.MSG_VERBOSE); @@ -374,14 +370,12 @@ public abstract class JDBCTask extends Task { return conn; } catch (SQLException e) { // failed to connect - if (!failOnConnectionError) { - log("Failed to connect: " + e.getMessage(), Project.MSG_WARN); - return null; - } else { + if (failOnConnectionError) { throw new BuildException(e, getLocation()); } + log("Failed to connect: " + e.getMessage(), Project.MSG_WARN); + return null; } - } /** @@ -395,9 +389,9 @@ public abstract class JDBCTask extends Task { throw new BuildException("Driver attribute must be set!", getLocation()); } - Driver driverInstance = null; + Driver driverInstance; try { - Class<?> dc; + Class<? extends Driver> dc; if (classpath != null) { // check first that it is not already loaded otherwise // consecutive runs seems to end into an OutOfMemoryError @@ -423,13 +417,13 @@ public abstract class JDBCTask extends Task { Project.MSG_VERBOSE); } } - dc = loader.loadClass(driver); + dc = loader.loadClass(driver).asSubclass(Driver.class); } else { log("Loading " + driver + " using system loader.", Project.MSG_VERBOSE); - dc = Class.forName(driver); + dc = Class.forName(driver).asSubclass(Driver.class); } - driverInstance = (Driver) dc.newInstance(); + driverInstance = dc.newInstance(); } catch (ClassNotFoundException e) { throw new BuildException( "Class Not Found: JDBC driver " + driver + " could not be loaded", @@ -449,7 +443,6 @@ public abstract class JDBCTask extends Task { return driverInstance; } - /** * Set the caching attribute. * @param value a <code>boolean</code> value http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/Jar.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/Jar.java b/src/main/org/apache/tools/ant/taskdefs/Jar.java index 7902075..26f844c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/Jar.java +++ b/src/main/org/apache/tools/ant/taskdefs/Jar.java @@ -28,6 +28,7 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; @@ -35,6 +36,8 @@ import java.util.Comparator; import java.util.Enumeration; import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; @@ -74,7 +77,7 @@ public class Jar extends Zip { /** * List of all known SPI Services */ - private List<Service> serviceList = new ArrayList<Service>(); + private List<Service> serviceList = new ArrayList<>(); /** merged manifests added through addConfiguredManifest */ private Manifest configuredManifest; @@ -138,7 +141,7 @@ public class Jar extends Zip { * * @since Ant 1.6 */ - private Vector<String> rootEntries; + private List<String> rootEntries; /** * Path containing jars that shall be indexed in addition to this archive. @@ -182,7 +185,7 @@ public class Jar extends Zip { emptyBehavior = "create"; setEncoding("UTF8"); setZip64Mode(Zip64ModeAttribute.NEVER); - rootEntries = new Vector<String>(); + rootEntries = new Vector<>(); } /** @@ -190,6 +193,7 @@ public class Jar extends Zip { * @param we not used * @ant.attribute ignore="true" */ + @Override public void setWhenempty(WhenEmpty we) { log("JARs are never empty, they contain at least a manifest file", Project.MSG_WARN); @@ -225,6 +229,7 @@ public class Jar extends Zip { * @deprecated since 1.5.x. * Use setDestFile(File) instead. */ + @Deprecated public void setJarfile(File jarFile) { setDestFile(jarFile); } @@ -301,29 +306,13 @@ public class Jar extends Zip { } private Manifest getManifest(File manifestFile) { - - Manifest newManifest = null; - InputStream fis = null; - InputStreamReader isr = null; - try { - fis = Files.newInputStream(manifestFile.toPath()); - if (manifestEncoding == null) { - isr = new InputStreamReader(fis); - } else { - isr = new InputStreamReader(fis, manifestEncoding); - } - newManifest = getManifest(isr); - } catch (UnsupportedEncodingException e) { - throw new BuildException("Unsupported encoding while reading manifest: " - + e.getMessage(), e); + try (InputStreamReader isr = new InputStreamReader( + Files.newInputStream(manifestFile.toPath()), getManifestCharset())) { + return getManifest(isr); } catch (IOException e) { throw new BuildException("Unable to read manifest file: " - + manifestFile - + " (" + e.getMessage() + ")", e); - } finally { - FileUtils.close(isr); + + manifestFile + " (" + e.getMessage() + ")", e); } - return newManifest; } /** @@ -332,32 +321,27 @@ public class Jar extends Zip { * @since Ant 1.5.2 */ private Manifest getManifestFromJar(File jarFile) throws IOException { - ZipFile zf = null; - try { - zf = new ZipFile(jarFile); + try (ZipFile zf = new ZipFile(jarFile)) { // must not use getEntry as "well behaving" applications // must accept the manifest in any capitalization Enumeration<? extends ZipEntry> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); - if (ze.getName().equalsIgnoreCase(MANIFEST_NAME)) { - InputStreamReader isr = - new InputStreamReader(zf.getInputStream(ze), "UTF-8"); - return getManifest(isr); + if (MANIFEST_NAME.equalsIgnoreCase(ze.getName())) { + try (InputStreamReader isr = + new InputStreamReader(zf.getInputStream(ze), "UTF-8")) { + return getManifest(isr); + } } } return null; - } finally { - FileUtils.close(zf); } } private Manifest getManifest(Reader r) { - - Manifest newManifest = null; try { - newManifest = new Manifest(r); + return new Manifest(r); } catch (ManifestException e) { log("Manifest is invalid: " + e.getMessage(), Project.MSG_ERR); throw new BuildException("Invalid Manifest: " + manifestFile, @@ -366,23 +350,18 @@ public class Jar extends Zip { throw new BuildException("Unable to read manifest file" + " (" + e.getMessage() + ")", e); } - return newManifest; } private boolean jarHasIndex(File jarFile) throws IOException { - ZipFile zf = null; - try { - zf = new ZipFile(jarFile); + try (ZipFile zf = new ZipFile(jarFile)) { Enumeration<? extends ZipEntry> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); - if (ze.getName().equalsIgnoreCase(INDEX_NAME)) { + if (INDEX_NAME.equalsIgnoreCase(ze.getName())) { return true; } } return false; - } finally { - FileUtils.close(zf); } } @@ -404,7 +383,7 @@ public class Jar extends Zip { mergeManifestsMain = config != null && "merge".equals(config.getValue()); if (filesetManifestConfig != null - && !filesetManifestConfig.getValue().equals("skip")) { + && !"skip".equals(filesetManifestConfig.getValue())) { doubleFilePass = true; } @@ -449,19 +428,12 @@ public class Jar extends Zip { */ private void writeServices(ZipOutputStream zOut) throws IOException { for (Service service : serviceList) { - InputStream is = null; - try { - is = service.getAsStream(); - //stolen from writeManifest + try (InputStream is = service.getAsStream()) { + //stolen from writeManifest super.zipFile(is, zOut, "META-INF/services/" + service.getType(), System.currentTimeMillis(), null, ZipFileSet.DEFAULT_FILE_MODE); - } finally { - // technically this is unnecessary since - // Service.getAsStream returns a ByteArrayInputStream - // and not closing it wouldn't do any harm. - FileUtils.close(is); } } } @@ -491,6 +463,7 @@ public class Jar extends Zip { * @throws IOException on I/O errors * @throws BuildException on other errors */ + @Override protected void initZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException { @@ -504,12 +477,10 @@ public class Jar extends Zip { private Manifest createManifest() throws BuildException { try { - if (manifest == null) { - if (manifestFile != null) { - // if we haven't got the manifest yet, attempt to - // get it now and have manifest be the final merge - manifest = getManifest(manifestFile); - } + if (manifest == null && manifestFile != null) { + // if we haven't got the manifest yet, attempt to + // get it now and have manifest be the final merge + manifest = getManifest(manifestFile); } // fileset manifest must come even before the default @@ -598,6 +569,7 @@ public class Jar extends Zip { * @throws IOException on I/O errors * @throws BuildException on other errors */ + @Override protected void finalizeZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException { @@ -667,14 +639,10 @@ public class Jar extends Zip { throw new IOException("Encountered an error writing jar index"); } writer.close(); - ByteArrayInputStream bais = - new ByteArrayInputStream(baos.toByteArray()); - try { + try (ByteArrayInputStream bais = + new ByteArrayInputStream(baos.toByteArray())) { super.zipFile(bais, zOut, INDEX_NAME, System.currentTimeMillis(), null, ZipFileSet.DEFAULT_FILE_MODE); - } finally { - // not really required - FileUtils.close(bais); } } @@ -690,6 +658,7 @@ public class Jar extends Zip { * @param mode the Unix permissions to set. * @throws IOException on error */ + @Override protected void zipFile(InputStream is, ZipOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode) throws IOException { @@ -703,8 +672,8 @@ public class Jar extends Zip { + " be replaced by a newly generated one.", Project.MSG_WARN); } else { - if (index && vPath.indexOf("/") == -1) { - rootEntries.addElement(vPath); + if (index && vPath.indexOf('/') == -1) { + rootEntries.add(vPath); } super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode); } @@ -715,40 +684,29 @@ public class Jar extends Zip { // If this is the same name specified in 'manifest', this // is the manifest to use log("Found manifest " + file, Project.MSG_VERBOSE); - try { - if (is != null) { - InputStreamReader isr; - if (manifestEncoding == null) { - isr = new InputStreamReader(is); - } else { - isr = new InputStreamReader(is, manifestEncoding); - } + if (is == null) { + manifest = getManifest(file); + } else { + try (InputStreamReader isr = + new InputStreamReader(is, getManifestCharset())) { manifest = getManifest(isr); - } else { - manifest = getManifest(file); } - } catch (UnsupportedEncodingException e) { - throw new BuildException("Unsupported encoding while reading " - + "manifest: " + e.getMessage(), e); } } else if (filesetManifestConfig != null - && !filesetManifestConfig.getValue().equals("skip")) { + && !"skip".equals(filesetManifestConfig.getValue())) { // we add this to our group of fileset manifests logWhenWriting("Found manifest to merge in file " + file, Project.MSG_VERBOSE); try { - Manifest newManifest = null; - if (is != null) { - InputStreamReader isr; - if (manifestEncoding == null) { - isr = new InputStreamReader(is); - } else { - isr = new InputStreamReader(is, manifestEncoding); - } - newManifest = getManifest(isr); - } else { + Manifest newManifest; + if (is == null) { newManifest = getManifest(file); + } else { + try (InputStreamReader isr = + new InputStreamReader(is, getManifestCharset())) { + newManifest = getManifest(isr); + } } if (filesetManifest == null) { @@ -804,6 +762,7 @@ public class Jar extends Zip { * * @exception BuildException if it likes */ + @Override protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs, File zipFile, boolean needsUpdate) @@ -874,33 +833,32 @@ public class Jar extends Zip { * @return true for historic reasons * @throws BuildException on error */ + @Override protected boolean createEmptyZip(File zipFile) throws BuildException { if (!createEmpty) { return true; } - if (emptyBehavior.equals("skip")) { + if ("skip".equals(emptyBehavior)) { if (!skipWriting) { log("Warning: skipping " + archiveType + " archive " + zipFile + " because no files were included.", Project.MSG_WARN); } return true; - } else if (emptyBehavior.equals("fail")) { + } + if ("fail".equals(emptyBehavior)) { throw new BuildException("Cannot create " + archiveType + " archive " + zipFile + ": no files were included.", getLocation()); } - ZipOutputStream zOut = null; - try { - if (!skipWriting) { - log("Building MANIFEST-only jar: " + if (!skipWriting) { + log("Building MANIFEST-only jar: " + getDestFile().getAbsolutePath()); - } - zOut = new ZipOutputStream(getDestFile()); - + } + try (ZipOutputStream zOut = new ZipOutputStream(getDestFile())) { zOut.setEncoding(getEncoding()); zOut.setUseZip64(getZip64Mode().getMode()); if (isCompress()) { @@ -915,8 +873,6 @@ public class Jar extends Zip { + " (" + ioe.getMessage() + ")", ioe, getLocation()); } finally { - // Close the output stream. - FileUtils.close(zOut); createEmpty = false; } return true; @@ -928,6 +884,7 @@ public class Jar extends Zip { * * @see Zip#cleanUp */ + @Override protected void cleanUp() { super.cleanUp(); checkJarSpec(); @@ -939,7 +896,7 @@ public class Jar extends Zip { filesetManifest = null; originalManifest = null; } - rootEntries.removeAllElements(); + rootEntries.clear(); } // CheckStyle:LineLength OFF - Link is too long. @@ -950,7 +907,7 @@ public class Jar extends Zip { // CheckStyle:LineLength ON private void checkJarSpec() { String br = System.getProperty("line.separator"); - StringBuffer message = new StringBuffer(); + StringBuilder message = new StringBuilder(); Section mainSection = (configuredManifest == null) ? null : configuredManifest.getMainSection(); @@ -975,11 +932,10 @@ public class Jar extends Zip { message.append(br); message.append("Location: ").append(getLocation()); message.append(br); - if (strict.getValue().equalsIgnoreCase("fail")) { + if ("fail".equalsIgnoreCase(strict.getValue())) { throw new BuildException(message.toString(), getLocation()); - } else { - logWhenWriting(message.toString(), strict.getLogLevel()); } + logWhenWriting(message.toString(), strict.getLogLevel()); } } @@ -990,6 +946,7 @@ public class Jar extends Zip { * * @since 1.44, Ant 1.5 */ + @Override public void reset() { super.reset(); emptyBehavior = "create"; @@ -1008,8 +965,9 @@ public class Jar extends Zip { * Get the list of valid strings. * @return the list of values - "skip", "merge" and "mergewithoutmain" */ + @Override public String[] getValues() { - return new String[] {"skip", "merge", "mergewithoutmain"}; + return new String[] { "skip", "merge", "mergewithoutmain" }; } } @@ -1056,9 +1014,7 @@ public class Jar extends Zip { writer.println(dir); } - for (String file : files) { - writer.println(file); - } + files.forEach(writer::println); } /** @@ -1084,39 +1040,27 @@ public class Jar extends Zip { protected static String findJarName(String fileName, String[] classpath) { if (classpath == null) { - return (new File(fileName)).getName(); + return new File(fileName).getName(); } fileName = fileName.replace(File.separatorChar, '/'); - TreeMap<String, String> matches = new TreeMap<String, String>(new Comparator<Object>() { - // longest match comes first - public int compare(Object o1, Object o2) { - if (o1 instanceof String && o2 instanceof String) { - return ((String) o2).length() - - ((String) o1).length(); - } - return 0; + SortedMap<String, String> matches = new TreeMap<>(Comparator + .<String> comparingInt(s -> s == null ? 0 : s.length()).reversed()); + + for (String element : classpath) { + String candidate = element; + while (true) { + if (fileName.endsWith(candidate)) { + matches.put(candidate, element); + break; } - }); - - for (int i = 0; i < classpath.length; i++) { - if (fileName.endsWith(classpath[i])) { - matches.put(classpath[i], classpath[i]); - } else { - int slash = classpath[i].indexOf("/"); - String candidate = classpath[i]; - while (slash > -1) { - candidate = candidate.substring(slash + 1); - if (fileName.endsWith(candidate)) { - matches.put(candidate, classpath[i]); - break; - } - slash = candidate.indexOf("/"); + int slash = candidate.indexOf('/'); + if (slash < 0) { + break; } + candidate = candidate.substring(slash + 1); } } - - return matches.size() == 0 - ? null : (String) matches.get(matches.firstKey()); + return matches.isEmpty() ? null : matches.get(matches.firstKey()); } /** @@ -1133,21 +1077,21 @@ public class Jar extends Zip { throws IOException { try (org.apache.tools.zip.ZipFile zf = new org.apache.tools.zip.ZipFile(file, "utf-8")) { Enumeration<org.apache.tools.zip.ZipEntry> entries = zf.getEntries(); - HashSet<String> dirSet = new HashSet<String>(); + Set<String> dirSet = new HashSet<>(); while (entries.hasMoreElements()) { org.apache.tools.zip.ZipEntry ze = entries.nextElement(); String name = ze.getName(); if (ze.isDirectory()) { dirSet.add(name); - } else if (name.indexOf("/") == -1) { + } else if (name.indexOf('/') == -1) { files.add(name); } else { // a file, not in the root // since the jar may be one without directory // entries, add the parent dir of this file as // well. - dirSet.add(name.substring(0, name.lastIndexOf("/") + 1)); + dirSet.add(name.substring(0, name.lastIndexOf('/') + 1)); } } dirs.addAll(dirSet); @@ -1157,13 +1101,12 @@ public class Jar extends Zip { private Resource[][] grabManifests(ResourceCollection[] rcs) { Resource[][] manifests = new Resource[rcs.length][]; for (int i = 0; i < rcs.length; i++) { - Resource[][] resources = null; + Resource[][] resources; if (rcs[i] instanceof FileSet) { - resources = grabResources(new FileSet[] {(FileSet) rcs[i]}); + resources = grabResources(new FileSet[] { (FileSet) rcs[i] }); } else { - resources = grabNonFileSetResources(new ResourceCollection[] { - rcs[i] - }); + resources = grabNonFileSetResources( + new ResourceCollection[] { rcs[i] }); } for (int j = 0; j < resources[0].length; j++) { String name = resources[0][j].getName().replace('\\', '/'); @@ -1179,7 +1122,7 @@ public class Jar extends Zip { name = prefix + name; } } - if (name.equalsIgnoreCase(MANIFEST_NAME)) { + if (MANIFEST_NAME.equalsIgnoreCase(name)) { manifests[i] = new Resource[] {resources[0][j]}; break; } @@ -1191,11 +1134,26 @@ public class Jar extends Zip { return manifests; } + private Charset getManifestCharset() { + if (manifestEncoding == null) { + return Charset.defaultCharset(); + } + try { + return Charset.forName(manifestEncoding); + } catch (IllegalArgumentException e) { + throw new BuildException( + "Unsupported encoding while reading manifest: " + + e.getMessage(), + e); + } + } + /** The strict enumerated type. */ public static class StrictMode extends EnumeratedAttribute { /** Public no arg constructor. */ public StrictMode() { } + /** * Constructor with an arg. * @param value the enumerated value as a string. @@ -1203,18 +1161,21 @@ public class Jar extends Zip { public StrictMode(String value) { setValue(value); } + /** * Get List of valid strings. * @return the list of values. */ + @Override public String[] getValues() { - return new String[]{"fail", "warn", "ignore"}; + return new String[] { "fail", "warn", "ignore" }; } + /** * @return The log level according to the strict mode. */ public int getLogLevel() { - return (getValue().equals("ignore")) ? Project.MSG_VERBOSE : Project.MSG_WARN; + return "ignore".equals(getValue()) ? Project.MSG_VERBOSE : Project.MSG_WARN; } } }
