http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/SelectSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/SelectSelector.java b/src/main/org/apache/tools/ant/types/selectors/SelectSelector.java index 2089012..2a00ce5 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SelectSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/SelectSelector.java @@ -40,16 +40,10 @@ public class SelectSelector extends BaseSelectorContainer { private Object unlessCondition; /** - * Default constructor. - */ - public SelectSelector() { - } - - /** * @return a string describing this object */ public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if (hasSelectors()) { buf.append("{select"); if (ifCondition != null) { @@ -80,6 +74,7 @@ public class SelectSelector extends BaseSelectorContainer { * Indicates whether there are any selectors here. * @return whether any selectors are in this container */ + @Override public boolean hasSelectors() { if (isReference()) { return getRef().hasSelectors(); @@ -91,6 +86,7 @@ public class SelectSelector extends BaseSelectorContainer { * Gives the count of the number of selectors in this container * @return the number of selectors in this container */ + @Override public int selectorCount() { if (isReference()) { return getRef().selectorCount(); @@ -103,6 +99,7 @@ public class SelectSelector extends BaseSelectorContainer { * @param p the current project * @return an array of selectors in this container */ + @Override public FileSelector[] getSelectors(Project p) { if (isReference()) { return getRef().getSelectors(p); @@ -114,6 +111,7 @@ public class SelectSelector extends BaseSelectorContainer { * Returns an enumerator for accessing the set of selectors. * @return an enumerator that goes through each of the selectors */ + @Override public Enumeration<FileSelector> selectorElements() { if (isReference()) { return getRef().selectorElements(); @@ -126,6 +124,7 @@ public class SelectSelector extends BaseSelectorContainer { * * @param selector the new selector to add */ + @Override public void appendSelector(FileSelector selector) { if (isReference()) { throw noChildrenAllowed(); @@ -138,11 +137,11 @@ public class SelectSelector extends BaseSelectorContainer { * Makes sure that there is only one entry, sets an error message if * not. */ + @Override public void verifySettings() { int cnt = selectorCount(); if (cnt < 0 || cnt > 1) { - setError("Only one selector is allowed within the " - + "<selector> tag"); + setError("Only one selector is allowed within the <selector> tag"); } } @@ -212,6 +211,7 @@ public class SelectSelector extends BaseSelectorContainer { * can use * @return whether the file should be selected or not */ + @Override public boolean isSelected(File basedir, String filename, File file) { validate();
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java index 277470b..baa79bd 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java +++ b/src/main/org/apache/tools/ant/types/selectors/SelectorUtils.java @@ -159,14 +159,14 @@ public final class SelectorUtils { if (strIdxStart > strIdxEnd) { // String is exhausted return true; - } else if (patIdxStart > patIdxEnd) { + } + if (patIdxStart > patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; - } else { - // pattern now holds ** while string is not exhausted - // this will generate false positives but we can live with that. - return true; } + // pattern now holds ** while string is not exhausted + // this will generate false positives but we can live with that. + return true; } /** @@ -245,11 +245,10 @@ public final class SelectorUtils { } } return true; - } else { - if (patIdxStart > patIdxEnd) { - // String not exhausted, but pattern is. Failure. - return false; - } + } + if (patIdxStart > patIdxEnd) { + // String not exhausted, but pattern is. Failure. + return false; } // up to last '**' @@ -293,19 +292,17 @@ public final class SelectorUtils { int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; strLoop: - for (int i = 0; i <= strLength - patLength; i++) { - for (int j = 0; j < patLength; j++) { - String subPat = tokenizedPattern[patIdxStart + j + 1]; - String subStr = strDirs[strIdxStart + i + j]; - if (!match(subPat, subStr, isCaseSensitive)) { - continue strLoop; - } - } - - foundIdx = strIdxStart + i; - break; - } - + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { + String subPat = tokenizedPattern[patIdxStart + j + 1]; + String subStr = strDirs[strIdxStart + i + j]; + if (!match(subPat, subStr, isCaseSensitive)) { + continue strLoop; + } + } + foundIdx = strIdxStart + i; + break; + } if (foundIdx == -1) { return false; } @@ -315,11 +312,10 @@ public final class SelectorUtils { } for (int i = patIdxStart; i <= patIdxEnd; i++) { - if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) { + if (!DEEP_TREE_MATCH.equals(tokenizedPattern[i])) { return false; } } - return true; } @@ -366,7 +362,6 @@ public final class SelectorUtils { int patIdxEnd = patArr.length - 1; int strIdxStart = 0; int strIdxEnd = strArr.length - 1; - char ch; boolean containsStar = false; for (int i = 0; i < patArr.length; i++) { @@ -382,11 +377,9 @@ public final class SelectorUtils { return false; // Pattern and string do not have the same size } for (int i = 0; i <= patIdxEnd; i++) { - ch = patArr[i]; - if (ch != '?') { - if (different(caseSensitive, ch, strArr[i])) { - return false; // Character mismatch - } + char ch = patArr[i]; + if (ch != '?' && different(caseSensitive, ch, strArr[i])) { + return false; // Character mismatch } } return true; // String matches against pattern @@ -398,14 +391,13 @@ public final class SelectorUtils { // Process characters before first star while (true) { - ch = patArr[patIdxStart]; + char ch = patArr[patIdxStart]; if (ch == '*' || strIdxStart > strIdxEnd) { break; } - if (ch != '?') { - if (different(caseSensitive, ch, strArr[strIdxStart])) { - return false; // Character mismatch - } + if (ch != '?' + && different(caseSensitive, ch, strArr[strIdxStart])) { + return false; // Character mismatch } patIdxStart++; strIdxStart++; @@ -418,14 +410,12 @@ public final class SelectorUtils { // Process characters after last star while (true) { - ch = patArr[patIdxEnd]; + char ch = patArr[patIdxEnd]; if (ch == '*' || strIdxStart > strIdxEnd) { break; } - if (ch != '?') { - if (different(caseSensitive, ch, strArr[strIdxEnd])) { - return false; // Character mismatch - } + if (ch != '?' && different(caseSensitive, ch, strArr[strIdxEnd])) { + return false; // Character mismatch } patIdxEnd--; strIdxEnd--; @@ -459,15 +449,12 @@ public final class SelectorUtils { strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { - ch = patArr[patIdxStart + j + 1]; - if (ch != '?') { - if (different(caseSensitive, ch, - strArr[strIdxStart + i + j])) { - continue strLoop; - } + char ch = patArr[patIdxStart + j + 1]; + if (ch != '?' && different(caseSensitive, ch, + strArr[strIdxStart + i + j])) { + continue strLoop; } } - foundIdx = strIdxStart + i; break; } @@ -475,7 +462,6 @@ public final class SelectorUtils { if (foundIdx == -1) { return false; } - patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } @@ -523,7 +509,7 @@ public final class SelectorUtils { * @since Ant 1.6 */ public static Vector<String> tokenizePath(String path, String separator) { - Vector<String> ret = new Vector<String>(); + Vector<String> ret = new Vector<>(); if (FileUtils.isAbsolutePath(path)) { String[] s = FILE_UTILS.dissect(path); ret.add(s[0]); @@ -664,7 +650,7 @@ public final class SelectorUtils { * @return a String that has had all whitespace removed. */ public static String removeWhitespace(String input) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); if (input != null) { StringTokenizer st = new StringTokenizer(input); while (st.hasMoreTokens()) { @@ -680,7 +666,7 @@ public final class SelectorUtils { * @return true if the string contains at least a star or a question mark */ public static boolean hasWildcards(String input) { - return (input.indexOf('*') != -1 || input.indexOf('?') != -1); + return input.indexOf('*') != -1 || input.indexOf('?') != -1; } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/SignedSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/SignedSelector.java b/src/main/org/apache/tools/ant/types/selectors/SignedSelector.java index cd51502..36d8785 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SignedSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/SignedSelector.java @@ -48,6 +48,7 @@ public class SignedSelector extends DataType implements FileSelector { * @param file path to file to be selected * @return whether the file should be selected or not */ + @Override public boolean isSelected(File basedir, String filename, File file) { if (file.isDirectory()) { return false; // Quick return: directories cannot be signed http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java b/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java index 9ff91ad..f62880b 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/SizeSelector.java @@ -62,13 +62,6 @@ public class SizeSelector extends BaseExtendSelector { private Comparison when = Comparison.EQUAL; /** - * Creates a new <code>SizeSelector</code> instance. - * - */ - public SizeSelector() { - } - - /** * Returns a <code>String</code> object representing the specified * SizeSelector. This is "{sizeselector value: " + <"compare", * "less", "more", "equal"> + "}". @@ -164,7 +157,8 @@ public class SizeSelector extends BaseExtendSelector { * * @param parameters the complete set of parameters for this selector. */ - public void setParameters(Parameter[] parameters) { + @Override + public void setParameters(Parameter... parameters) { super.setParameters(parameters); if (parameters != null) { for (int i = 0; i < parameters.length; i++) { @@ -220,6 +214,7 @@ public class SizeSelector extends BaseExtendSelector { * @param file A File object for this filename. * @return whether the file should be selected or not. */ + @Override public boolean isSelected(File basedir, String filename, File file) { // throw BuildException on error http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/SymlinkSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/SymlinkSelector.java b/src/main/org/apache/tools/ant/types/selectors/SymlinkSelector.java index 28c3bcb..d5df1ce 100644 --- a/src/main/org/apache/tools/ant/types/selectors/SymlinkSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/SymlinkSelector.java @@ -18,12 +18,8 @@ package org.apache.tools.ant.types.selectors; -import java.nio.file.Files; import java.io.File; - -import org.apache.tools.ant.types.Resource; -import org.apache.tools.ant.types.resources.FileProvider; -import org.apache.tools.ant.types.resources.selectors.ResourceSelector; +import java.nio.file.Files; /** * A selector that selects symbolic links. @@ -34,17 +30,10 @@ import org.apache.tools.ant.types.resources.selectors.ResourceSelector; * * @since Ant 1.10.0 */ -public class SymlinkSelector implements FileSelector, ResourceSelector { +public class SymlinkSelector implements FileSelector { public boolean isSelected(File basedir, String filename, File file) { return file != null && Files.isSymbolicLink(file.toPath()); } - public boolean isSelected(Resource r) { - FileProvider fp = r.as(FileProvider.class); - if (fp != null) { - return isSelected(null, null, fp.getFile()); - } - return false; - } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java b/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java index a712759..48e4ce7 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java +++ b/src/main/org/apache/tools/ant/types/selectors/TokenizedPath.java @@ -19,6 +19,7 @@ package org.apache.tools.ant.types.selectors; import java.io.File; +import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.util.FileUtils; @@ -148,7 +149,7 @@ public class TokenizedPath { return true; } base = new File(base, tokenizedPath[i]); - } catch (java.io.IOException ioe) { + } catch (IOException ioe) { String msg = "IOException caught while checking " + "for links, couldn't get canonical path!"; // will be caught and redirected to Ant's logging system @@ -189,8 +190,8 @@ public class TokenizedPath { } String[] files = base.list(); if (files == null) { - throw new BuildException("IO error scanning directory " - + base.getAbsolutePath()); + throw new BuildException("IO error scanning directory %s", + base.getAbsolutePath()); } boolean found = false; boolean[] matchCase = cs ? CS_SCAN_ONLY : CS_THEN_NON_CS; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/TokenizedPattern.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/TokenizedPattern.java b/src/main/org/apache/tools/ant/types/selectors/TokenizedPattern.java index dbe7ec8..e9413df 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TokenizedPattern.java +++ b/src/main/org/apache/tools/ant/types/selectors/TokenizedPattern.java @@ -19,6 +19,8 @@ package org.apache.tools.ant.types.selectors; import java.io.File; +import java.util.function.Predicate; +import java.util.stream.Stream; /** * Provides reusable path pattern matching. PathPattern is preferable @@ -114,12 +116,7 @@ public class TokenizedPattern { * Does the tokenized pattern contain the given string? */ public boolean containsPattern(String pat) { - for (int i = 0; i < tokenizedPattern.length; i++) { - if (tokenizedPattern[i].equals(pat)) { - return true; - } - } - return false; + return Stream.of(tokenizedPattern).anyMatch(Predicate.isEqual(pat)); } /** @@ -162,16 +159,16 @@ public class TokenizedPattern { public TokenizedPattern withoutLastToken() { if (tokenizedPattern.length == 0) { throw new IllegalStateException("can't strip a token from nothing"); - } else if (tokenizedPattern.length == 1) { + } + if (tokenizedPattern.length == 1) { return EMPTY_PATTERN; - } else { - String toStrip = tokenizedPattern[tokenizedPattern.length - 1]; - int index = pattern.lastIndexOf(toStrip); - String[] tokens = new String[tokenizedPattern.length - 1]; - System.arraycopy(tokenizedPattern, 0, tokens, 0, - tokenizedPattern.length - 1); - return new TokenizedPattern(pattern.substring(0, index), tokens); } + String toStrip = tokenizedPattern[tokenizedPattern.length - 1]; + int index = pattern.lastIndexOf(toStrip); + String[] tokens = new String[tokenizedPattern.length - 1]; + System.arraycopy(tokenizedPattern, 0, tokens, 0, + tokenizedPattern.length - 1); + return new TokenizedPattern(pattern.substring(0, index), tokens); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java b/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java index fd3684d..ef6853f 100644 --- a/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/TypeSelector.java @@ -30,17 +30,10 @@ import org.apache.tools.ant.types.Parameter; */ public class TypeSelector extends BaseExtendSelector { - private String type = null; - /** Key to used for parameterized custom selector */ public static final String TYPE_KEY = "type"; - - /** - * Creates a new <code>TypeSelector</code> instance. - * - */ - public TypeSelector() { - } + + private String type = null; /** * @return a string describing this object @@ -66,7 +59,8 @@ public class TypeSelector extends BaseExtendSelector { * * @param parameters the complete set of parameters for this selector */ - public void setParameters(Parameter[] parameters) { + @Override + public void setParameters(Parameter... parameters) { super.setParameters(parameters); if (parameters != null) { for (int i = 0; i < parameters.length; i++) { @@ -87,6 +81,7 @@ public class TypeSelector extends BaseExtendSelector { * means that the pattern attribute has been set. * */ + @Override public void verifySettings() { if (type == null) { setError("The type attribute is required"); @@ -102,6 +97,7 @@ public class TypeSelector extends BaseExtendSelector { * @param file is a java.io.File object the selector can use * @return whether the file should be selected or not */ + @Override public boolean isSelected(File basedir, String filename, File file) { // throw BuildException on error @@ -109,9 +105,8 @@ public class TypeSelector extends BaseExtendSelector { if (file.isDirectory()) { return type.equals(FileType.DIR); - } else { - return type.equals(FileType.FILE); } + return type.equals(FileType.FILE); } /** @@ -126,10 +121,10 @@ public class TypeSelector extends BaseExtendSelector { /** * @return the values as an array of strings */ + @Override public String[] getValues() { return new String[]{FILE, DIR}; } } - } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/WritableSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/WritableSelector.java b/src/main/org/apache/tools/ant/types/selectors/WritableSelector.java index 6ffd571..e7870a7 100644 --- a/src/main/org/apache/tools/ant/types/selectors/WritableSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/WritableSelector.java @@ -20,10 +20,6 @@ package org.apache.tools.ant.types.selectors; import java.io.File; -import org.apache.tools.ant.types.Resource; -import org.apache.tools.ant.types.resources.FileProvider; -import org.apache.tools.ant.types.resources.selectors.ResourceSelector; - /** * A selector that selects writable files. * @@ -33,14 +29,11 @@ import org.apache.tools.ant.types.resources.selectors.ResourceSelector; * * @since Ant 1.8.0 */ -public class WritableSelector implements FileSelector, ResourceSelector { +public class WritableSelector implements FileSelector { + @Override public boolean isSelected(File basedir, String filename, File file) { return file != null && file.canWrite(); } - public boolean isSelected(Resource r) { - FileProvider fp = r.as(FileProvider.class); - return fp != null && isSelected(null, null, fp.getFile()); - } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ChecksumAlgorithm.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ChecksumAlgorithm.java b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ChecksumAlgorithm.java index 26c6945..a660caf 100644 --- a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ChecksumAlgorithm.java +++ b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ChecksumAlgorithm.java @@ -20,7 +20,6 @@ package org.apache.tools.ant.types.selectors.modifiedselector; import java.io.BufferedInputStream; import java.io.File; -import java.io.InputStream; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; import java.util.Locale; @@ -105,6 +104,7 @@ public class ChecksumAlgorithm implements Algorithm { * This algorithm supports only CRC and Adler. * @return <i>true</i> if all is ok, otherwise <i>false</i>. */ + @Override public boolean isValid() { return "CRC".equals(algorithm) || "ADLER".equals(algorithm); } @@ -115,26 +115,22 @@ public class ChecksumAlgorithm implements Algorithm { * @param file File object for which the value should be evaluated. * @return The value for that file */ + @Override public String getValue(File file) { initChecksum(); - String rval = null; - - try { - if (file.canRead()) { - checksum.reset(); - InputStream fis = Files.newInputStream(file.toPath()); - CheckedInputStream check = new CheckedInputStream(fis, checksum); - BufferedInputStream in = new BufferedInputStream(check); - while (in.read() != -1) { - // Read the file - } - rval = Long.toString(check.getChecksum().getValue()); - in.close(); + + if (file.canRead()) { + checksum.reset(); + try (CheckedInputStream check = new CheckedInputStream( + new BufferedInputStream(Files.newInputStream(file.toPath())), checksum)) { + // Read the file + while (check.read() != -1) + ; + return Long.toString(check.getChecksum().getValue()); + } catch (Exception e) { } - } catch (Exception e) { - rval = null; } - return rval; + return null; } @@ -142,11 +138,8 @@ public class ChecksumAlgorithm implements Algorithm { * Override Object.toString(). * @return some information about this algorithm. */ + @Override public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("<ChecksumAlgorithm:"); - buf.append("algorithm=").append(algorithm); - buf.append(">"); - return buf.toString(); + return String.format("<ChecksumAlgorithm:algorithm=%s>", algorithm); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java index 9624145..cc9a66c 100644 --- a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java +++ b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/DigestAlgorithm.java @@ -20,7 +20,6 @@ package org.apache.tools.ant.types.selectors.modifiedselector; import java.io.File; -import java.io.InputStream; import java.nio.file.Files; import java.security.DigestInputStream; import java.security.MessageDigest; @@ -119,10 +118,8 @@ public class DigestAlgorithm implements Algorithm { if ((provider != null) && !"".equals(provider) && !"null".equals(provider)) { try { messageDigest = MessageDigest.getInstance(algorithm, provider); - } catch (NoSuchAlgorithmException noalgo) { - throw new BuildException(noalgo); - } catch (NoSuchProviderException noprovider) { - throw new BuildException(noprovider); + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { + throw new BuildException(e); } } else { try { @@ -141,69 +138,55 @@ public class DigestAlgorithm implements Algorithm { * This algorithm supports only MD5 and SHA. * @return <i>true</i> if all is ok, otherwise <i>false</i>. */ + @Override public boolean isValid() { return "SHA".equals(algorithm) || "MD5".equals(algorithm); } - /** * Computes a value for a file content with the specified digest algorithm. * @param file File object for which the value should be evaluated. * @return The value for that file */ // implementation adapted from ...taskdefs.Checksum, thanks to Magesh for hint + @Override public String getValue(File file) { initMessageDigest(); - String checksum = null; try { - if (!file.canRead()) { - return null; - } - InputStream fis = null; - - byte[] buf = new byte[readBufferSize]; - try { + if (file.canRead()) { + byte[] buf = new byte[readBufferSize]; messageDigest.reset(); - fis = Files.newInputStream(file.toPath()); - DigestInputStream dis = new DigestInputStream(fis, - messageDigest); - while (dis.read(buf, 0, readBufferSize) != -1) { - // do nothing - } - dis.close(); - fis.close(); - fis = null; - byte[] fileDigest = messageDigest.digest(); - StringBuffer checksumSb = new StringBuffer(); - for (int i = 0; i < fileDigest.length; i++) { - String hexStr - = Integer.toHexString(BYTE_MASK & fileDigest[i]); - if (hexStr.length() < 2) { - checksumSb.append("0"); + try (DigestInputStream dis = new DigestInputStream( + Files.newInputStream(file.toPath()), messageDigest)) { + // read the whole stream + while (dis.read(buf, 0, readBufferSize) != -1) + ; + byte[] fileDigest = messageDigest.digest(); + StringBuilder checksumSb = new StringBuilder(); + for (int i = 0; i < fileDigest.length; i++) { + String hexStr = + Integer.toHexString(BYTE_MASK & fileDigest[i]); + if (hexStr.length() < 2) { + checksumSb.append('0'); + } + checksumSb.append(hexStr); } - checksumSb.append(hexStr); + return checksumSb.toString(); + } catch (Exception e) { } - checksum = checksumSb.toString(); - } catch (Exception e) { - return null; } } catch (Exception e) { - return null; } - return checksum; + return null; } - /** * Override Object.toString(). * @return some information about this algorithm. */ + @Override public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("<DigestAlgorithm:"); - buf.append("algorithm=").append(algorithm); - buf.append(";provider=").append(provider); - buf.append(">"); - return buf.toString(); + return String.format("<DigestAlgorithm:algorithm=%s;provider=%s>", + algorithm, provider); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ModifiedSelector.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ModifiedSelector.java b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ModifiedSelector.java index 9f53809..f2097fd 100644 --- a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ModifiedSelector.java +++ b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/ModifiedSelector.java @@ -21,9 +21,10 @@ package org.apache.tools.ant.types.selectors.modifiedselector; // Java import java.io.File; +import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; -import java.util.Iterator; -import java.util.Vector; +import java.util.List; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildException; @@ -209,7 +210,8 @@ public class ModifiedSelector extends BaseExtendSelector * Parameter vector with parameters for later initialization. * @see #configure */ - private Vector<Parameter> configParameter = new Vector<Parameter>(); + private List<Parameter> configParameter = + Collections.synchronizedList(new ArrayList<>()); /** * Parameter vector with special parameters for later initialization. @@ -217,7 +219,8 @@ public class ModifiedSelector extends BaseExtendSelector * These parameters are used <b>after</b> the parameters with the pattern '*'. * @see #configure */ - private Vector<Parameter> specialParameter = new Vector<Parameter>(); + private List<Parameter> specialParameter = + Collections.synchronizedList(new ArrayList<>()); /** The classloader of this class. */ private ClassLoader myClassLoader = null; @@ -238,6 +241,7 @@ public class ModifiedSelector extends BaseExtendSelector /** Overrides BaseSelector.verifySettings(). */ + @Override public void verifySettings() { configure(); if (cache == null) { @@ -283,7 +287,7 @@ public class ModifiedSelector extends BaseExtendSelector // Project p = getProject(); String filename = "cache.properties"; - File cachefile = null; + File cachefile; if (p != null) { // normal use inside Ant cachefile = new File(p.getBaseDir(), filename); @@ -303,14 +307,14 @@ public class ModifiedSelector extends BaseExtendSelector // ----- Set the main attributes, pattern '*' ----- // for (Parameter parameter : configParameter) { - if (parameter.getName().indexOf(".") > 0) { + if (parameter.getName().indexOf('.') > 0) { // this is a *.* parameter for later use specialParameter.add(parameter); } else { useParameter(parameter); } } - configParameter = new Vector<Parameter>(); + configParameter.clear(); // specify the algorithm classname if (algoName != null) { @@ -322,17 +326,15 @@ public class ModifiedSelector extends BaseExtendSelector } else if ("checksum".equals(algoName.getValue())) { algorithm = new ChecksumAlgorithm(); } + } else if (algorithmClass != null) { + // use Algorithm specified by classname + algorithm = loadClass( + algorithmClass, + "is not an Algorithm.", + Algorithm.class); } else { - if (algorithmClass != null) { - // use Algorithm specified by classname - algorithm = loadClass( - algorithmClass, - "is not an Algorithm.", - Algorithm.class); - } else { - // nothing specified - use default - algorithm = defaultAlgorithm; - } + // nothing specified - use default + algorithm = defaultAlgorithm; } // specify the cache classname @@ -341,14 +343,12 @@ public class ModifiedSelector extends BaseExtendSelector if ("propertyfile".equals(cacheName.getValue())) { cache = new PropertiesfileCache(); } + } else if (cacheClass != null) { + // use Cache specified by classname + cache = loadClass(cacheClass, "is not a Cache.", Cache.class); } else { - if (cacheClass != null) { - // use Cache specified by classname - cache = loadClass(cacheClass, "is not a Cache.", Cache.class); - } else { - // nothing specified - use default - cache = defaultCache; - } + // nothing specified - use default + cache = defaultCache; } // specify the comparator classname @@ -364,26 +364,22 @@ public class ModifiedSelector extends BaseExtendSelector // Have to think about lazy initialization here... JHM // comparator = new java.text.RuleBasedCollator(); } + } else if (comparatorClass != null) { + // use Algorithm specified by classname + @SuppressWarnings("unchecked") + Comparator<? super String> localComparator = loadClass( + comparatorClass, "is not a Comparator.", Comparator.class); + comparator = localComparator; } else { - if (comparatorClass != null) { - // use Algorithm specified by classname - @SuppressWarnings("unchecked") - Comparator<? super String> localComparator = loadClass(comparatorClass, "is not a Comparator.", Comparator.class); - comparator = localComparator; - } else { - // nothing specified - use default - comparator = defaultComparator; - } + // nothing specified - use default + comparator = defaultComparator; } // // ----- Set the special attributes, pattern '*.*' ----- // - for (Iterator<Parameter> itSpecial = specialParameter.iterator(); itSpecial.hasNext();) { - Parameter par = itSpecial.next(); - useParameter(par); - } - specialParameter = new Vector<Parameter>(); + specialParameter.forEach(this::useParameter); + specialParameter.clear(); } @@ -400,21 +396,22 @@ public class ModifiedSelector extends BaseExtendSelector try { // load the specified class ClassLoader cl = getClassLoader(); - Class<?> clazz = null; + Class<?> clazz; if (cl != null) { clazz = cl.loadClass(classname); } else { clazz = Class.forName(classname); } - Object rv = clazz.newInstance(); + @SuppressWarnings("unchecked") + T rv = (T) clazz.newInstance(); if (!type.isInstance(rv)) { - throw new BuildException("Specified class (" + classname + ") " + msg); + throw new BuildException("Specified class (%s) %s",classname, msg); } - return (T) rv; + return rv; } catch (ClassNotFoundException e) { - throw new BuildException("Specified class (" + classname + ") not found."); + throw new BuildException("Specified class (%s) not found.", classname); } catch (Exception e) { throw new BuildException(e); } @@ -431,6 +428,7 @@ public class ModifiedSelector extends BaseExtendSelector * @return whether the resource is selected * @see ResourceSelector#isSelected(Resource) */ + @Override public boolean isSelected(Resource resource) { if (resource.isFilesystemOnly()) { // We have a 'resourced' file, so reconvert it and use @@ -440,30 +438,29 @@ public class ModifiedSelector extends BaseExtendSelector String filename = fileResource.getName(); File basedir = fileResource.getBaseDir(); return isSelected(basedir, filename, file); - } else { - try { - // How to handle non-file-Resources? I copy temporarily the - // resource to a file and use the file-implementation. - FileUtils fu = FileUtils.getFileUtils(); - File tmpFile = fu.createTempFile("modified-", ".tmp", null, true, false); - Resource tmpResource = new FileResource(tmpFile); - ResourceUtils.copyResource(resource, tmpResource); - boolean isSelected = isSelected(tmpFile.getParentFile(), - tmpFile.getName(), - resource.toLongString()); - tmpFile.delete(); - return isSelected; - } catch (UnsupportedOperationException uoe) { - log("The resource '" - + resource.getName() - + "' does not provide an InputStream, so it is not checked. " - + "Akkording to 'selres' attribute value it is " - + ((selectResourcesWithoutInputStream) ? "" : " not") - + "selected.", Project.MSG_INFO); - return selectResourcesWithoutInputStream; - } catch (Exception e) { - throw new BuildException(e); - } + } + try { + // How to handle non-file-Resources? I copy temporarily the + // resource to a file and use the file-implementation. + FileUtils fu = FileUtils.getFileUtils(); + File tmpFile = fu.createTempFile("modified-", ".tmp", null, true, false); + Resource tmpResource = new FileResource(tmpFile); + ResourceUtils.copyResource(resource, tmpResource); + boolean isSelected = isSelected(tmpFile.getParentFile(), + tmpFile.getName(), + resource.toLongString()); + tmpFile.delete(); + return isSelected; + } catch (UnsupportedOperationException uoe) { + log("The resource '" + + resource.getName() + + "' does not provide an InputStream, so it is not checked. " + + "Akkording to 'selres' attribute value it is " + + ((selectResourcesWithoutInputStream) ? "" : " not") + + "selected.", Project.MSG_INFO); + return selectResourcesWithoutInputStream; + } catch (Exception e) { + throw new BuildException(e); } } @@ -476,11 +473,11 @@ public class ModifiedSelector extends BaseExtendSelector * @param file as described in BaseExtendSelector * @return as described in BaseExtendSelector */ + @Override public boolean isSelected(File basedir, String filename, File file) { return isSelected(basedir, filename, file.getAbsolutePath()); } - /** * The business logic of this selector for use as ResourceSelector of * FileSelector. @@ -503,7 +500,7 @@ public class ModifiedSelector extends BaseExtendSelector String cachedValue = String.valueOf(cache.get(f.getAbsolutePath())); String newValue = algorithm.getValue(f); - boolean rv = (comparator.compare(cachedValue, newValue) != 0); + boolean rv = comparator.compare(cachedValue, newValue) != 0; // Maybe update the cache if (update && rv) { @@ -513,7 +510,6 @@ public class ModifiedSelector extends BaseExtendSelector saveCache(); } } - return rv; } @@ -690,13 +686,14 @@ public class ModifiedSelector extends BaseExtendSelector * Defined in org.apache.tools.ant.types.Parameterizable. * Overwrite implementation in superclass because only special * parameters are valid. - * @see #addParam(String,Object). + * @see #addParam(String,Object) * @param parameters the parameters to set. */ - public void setParameters(Parameter[] parameters) { + @Override + public void setParameters(Parameter... parameters) { if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - configParameter.add(parameters[i]); + for (Parameter p : parameters) { + configParameter.add(p); } } } @@ -731,23 +728,11 @@ public class ModifiedSelector extends BaseExtendSelector cn.setValue(value); setComparator(cn); } else if ("update".equals(key)) { - boolean updateValue = - ("true".equalsIgnoreCase(value)) - ? true - : false; - setUpdate(updateValue); + setUpdate("true".equalsIgnoreCase(value)); } else if ("delayupdate".equals(key)) { - boolean updateValue = - ("true".equalsIgnoreCase(value)) - ? true - : false; - setDelayUpdate(updateValue); + setDelayUpdate("true".equalsIgnoreCase(value)); } else if ("seldirs".equals(key)) { - boolean sdValue = - ("true".equalsIgnoreCase(value)) - ? true - : false; - setSeldirs(sdValue); + setSeldirs("true".equalsIgnoreCase(value)); } else if (key.startsWith(CACHE_PREFIX)) { String name = key.substring(CACHE_PREFIX.length()); tryToSetAParameter(cache, name, value); @@ -776,7 +761,7 @@ public class ModifiedSelector extends BaseExtendSelector = IntrospectionHelper.getHelper(prj, obj.getClass()); try { iHelper.setAttribute(prj, obj, name, value); - } catch (org.apache.tools.ant.BuildException e) { + } catch (BuildException e) { // no-op } } @@ -789,8 +774,9 @@ public class ModifiedSelector extends BaseExtendSelector * Override Object.toString(). * @return information about this selector */ + @Override public String toString() { - StringBuffer buf = new StringBuffer("{modifiedselector"); + StringBuilder buf = new StringBuilder("{modifiedselector"); buf.append(" update=").append(update); buf.append(" seldirs=").append(selectDirectories); buf.append(" cache=").append(cache); @@ -807,7 +793,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that the last target has finished. * @param event received BuildEvent - */ + */ + @Override public void buildFinished(BuildEvent event) { if (getDelayUpdate()) { saveCache(); @@ -818,7 +805,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that a target has finished. * @param event received BuildEvent - */ + */ + @Override public void targetFinished(BuildEvent event) { if (getDelayUpdate()) { saveCache(); @@ -829,7 +817,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that a task has finished. * @param event received BuildEvent - */ + */ + @Override public void taskFinished(BuildEvent event) { if (getDelayUpdate()) { saveCache(); @@ -840,7 +829,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that a build has started. * @param event received BuildEvent - */ + */ + @Override public void buildStarted(BuildEvent event) { // no-op } @@ -849,7 +839,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that a target is starting. * @param event received BuildEvent - */ + */ + @Override public void targetStarted(BuildEvent event) { // no-op } @@ -859,7 +850,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals that a task is starting. * @param event received BuildEvent - */ + */ + @Override public void taskStarted(BuildEvent event) { // no-op } @@ -868,7 +860,8 @@ public class ModifiedSelector extends BaseExtendSelector /** * Signals a message logging event. * @param event received BuildEvent - */ + */ + @Override public void messageLogged(BuildEvent event) { // no-op } @@ -903,8 +896,9 @@ public class ModifiedSelector extends BaseExtendSelector * {@inheritDoc} * @see EnumeratedAttribute#getValues() */ + @Override public String[] getValues() { - return new String[] {"propertyfile" }; + return new String[] { "propertyfile" }; } } @@ -933,8 +927,9 @@ public class ModifiedSelector extends BaseExtendSelector * {@inheritDoc} * @see EnumeratedAttribute#getValues() */ + @Override public String[] getValues() { - return new String[] {"hashvalue", "digest", "checksum" }; + return new String[] { "hashvalue", "digest", "checksum" }; } } @@ -963,8 +958,9 @@ public class ModifiedSelector extends BaseExtendSelector * {@inheritDoc} * @see EnumeratedAttribute#getValues() */ + @Override public String[] getValues() { - return new String[] {"equal", "rule" }; + return new String[] { "equal", "rule" }; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/selectors/modifiedselector/PropertiesfileCache.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/PropertiesfileCache.java b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/PropertiesfileCache.java index 2a16d1f..d0de982 100644 --- a/src/main/org/apache/tools/ant/types/selectors/modifiedselector/PropertiesfileCache.java +++ b/src/main/org/apache/tools/ant/types/selectors/modifiedselector/PropertiesfileCache.java @@ -22,13 +22,9 @@ package org.apache.tools.ant.types.selectors.modifiedselector; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; -import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; -import java.util.Vector; /** @@ -119,6 +115,7 @@ public class PropertiesfileCache implements Cache { * This cache is valid if the cachefile is set. * @return true if all is ok false otherwise */ + @Override public boolean isValid() { return (cachefile != null); } @@ -130,13 +127,12 @@ public class PropertiesfileCache implements Cache { /** * Load the cache from underlying properties file. */ + @Override public void load() { if ((cachefile != null) && cachefile.isFile() && cachefile.canRead()) { - try { - BufferedInputStream bis = new BufferedInputStream( - Files.newInputStream(cachefile.toPath())); + try (BufferedInputStream bis = new BufferedInputStream( + Files.newInputStream(cachefile.toPath()))) { cache.load(bis); - bis.close(); } catch (Exception e) { e.printStackTrace(); //NOSONAR } @@ -153,17 +149,16 @@ public class PropertiesfileCache implements Cache { * implementation checks the existence of entries before creating the file * for performance optimisation. */ + @Override public void save() { if (!cacheDirty) { return; } if ((cachefile != null) && cache.propertyNames().hasMoreElements()) { - try { - BufferedOutputStream bos = new BufferedOutputStream( - Files.newOutputStream(cachefile.toPath())); + try (BufferedOutputStream bos = new BufferedOutputStream( + Files.newOutputStream(cachefile.toPath()))) { cache.store(bos, null); bos.flush(); - bos.close(); } catch (Exception e) { e.printStackTrace(); //NOSONAR } @@ -172,6 +167,7 @@ public class PropertiesfileCache implements Cache { } /** Deletes the cache and its underlying file. */ + @Override public void delete() { cache = new Properties(); cachefile.delete(); @@ -184,6 +180,7 @@ public class PropertiesfileCache implements Cache { * @param key the key * @return the stored value */ + @Override public Object get(Object key) { if (!cacheLoaded) { load(); @@ -200,6 +197,7 @@ public class PropertiesfileCache implements Cache { * @param key the key * @param value the value */ + @Override public void put(Object key, Object value) { cache.put(String.valueOf(key), String.valueOf(value)); cacheDirty = true; @@ -209,13 +207,9 @@ public class PropertiesfileCache implements Cache { * Returns an iterator over the keys in the cache. * @return An iterator over the keys. */ + @Override public Iterator<String> iterator() { - Vector<String> v = new Vector<String>(); - Enumeration<?> en = cache.propertyNames(); - while (en.hasMoreElements()) { - v.add(en.nextElement().toString()); - } - return v.iterator(); + return cache.stringPropertyNames().iterator(); } @@ -226,8 +220,9 @@ public class PropertiesfileCache implements Cache { * Override Object.toString(). * @return information about this cache */ + @Override public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("<PropertiesfileCache:"); buf.append("cachefile=").append(cachefile); buf.append(";noOfEntries=").append(cache.size()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/spi/Provider.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/spi/Provider.java b/src/main/org/apache/tools/ant/types/spi/Provider.java index f73b019..bf9f13d 100644 --- a/src/main/org/apache/tools/ant/types/spi/Provider.java +++ b/src/main/org/apache/tools/ant/types/spi/Provider.java @@ -55,7 +55,7 @@ public class Provider extends ProjectComponent { "classname attribute must be set for provider element", getLocation()); } - if (type.length() == 0) { + if (type.isEmpty()) { throw new BuildException( "Invalid empty classname", getLocation()); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/types/spi/Service.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/types/spi/Service.java b/src/main/org/apache/tools/ant/types/spi/Service.java index 96c8e4e..064bd08 100644 --- a/src/main/org/apache/tools/ant/types/spi/Service.java +++ b/src/main/org/apache/tools/ant/types/spi/Service.java @@ -18,13 +18,11 @@ package org.apache.tools.ant.types.spi; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; @@ -36,7 +34,7 @@ import org.apache.tools.ant.ProjectComponent; * http://issues.apache.org/bugzilla/show_bug.cgi?id=31520</a> */ public class Service extends ProjectComponent { - private List<Provider> providerList = new ArrayList<Provider>(); + private List<Provider> providerList = new ArrayList<>(); private String type; /** @@ -83,14 +81,9 @@ public class Service extends ProjectComponent { * @throws IOException if there is an error. */ public InputStream getAsStream() throws IOException { - ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); - Writer writer = new OutputStreamWriter(arrayOut, "UTF-8"); - for (Provider provider : providerList) { - writer.write(provider.getClassName()); - writer.write("\n"); - } - writer.close(); - return new ByteArrayInputStream(arrayOut.toByteArray()); + return new ByteArrayInputStream( + providerList.stream().map(Provider::getClassName) + .collect(Collectors.joining("\n")).getBytes("UTF-8")); } /** @@ -107,7 +100,7 @@ public class Service extends ProjectComponent { throw new BuildException( "Invalid empty type classname", getLocation()); } - if (providerList.size() == 0) { + if (providerList.isEmpty()) { throw new BuildException( "provider attribute or nested provider element must be set!", getLocation()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ChainedMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ChainedMapper.java b/src/main/org/apache/tools/ant/util/ChainedMapper.java index 635a053..e47043a 100644 --- a/src/main/org/apache/tools/ant/util/ChainedMapper.java +++ b/src/main/org/apache/tools/ant/util/ChainedMapper.java @@ -18,10 +18,7 @@ package org.apache.tools.ant.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; +import java.util.stream.Stream; /** * A <code>ContainerMapper</code> that chains the results of the first @@ -32,29 +29,13 @@ import java.util.List; public class ChainedMapper extends ContainerMapper { /** {@inheritDoc}. */ + @Override public String[] mapFileName(String sourceFileName) { - List inputs = new ArrayList(); - List results = new ArrayList(); - results.add(sourceFileName); - FileNameMapper mapper = null; - - for (Iterator mIter = getMappers().iterator(); mIter.hasNext();) { - mapper = (FileNameMapper) (mIter.next()); - if (mapper != null) { - inputs.clear(); - inputs.addAll(results); - results.clear(); - - for (Iterator it = inputs.iterator(); it.hasNext();) { - String[] mapped = mapper.mapFileName((String) (it.next())); - if (mapped != null) { - results.addAll(Arrays.asList(mapped)); - } - } - } - } - return (results.size() == 0) ? null - : (String[]) results.toArray(new String[results.size()]); + String[] result = getMappers().stream() + .reduce(new String[] { sourceFileName }, (i, m) -> Stream.of(i) + .map(m::mapFileName).flatMap(Stream::of).toArray(String[]::new), + (i, o) -> o); + return result == null || result.length == 0 ? null : result; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ClasspathUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ClasspathUtils.java b/src/main/org/apache/tools/ant/util/ClasspathUtils.java index 309860e..0f7787a 100644 --- a/src/main/org/apache/tools/ant/util/ClasspathUtils.java +++ b/src/main/org/apache/tools/ant/util/ClasspathUtils.java @@ -107,8 +107,9 @@ public class ClasspathUtils { String pathId = ref.getRefId(); Object path = p.getReference(pathId); if (!(path instanceof Path)) { - throw new BuildException("The specified classpathref " + pathId - + " does not reference a Path."); + throw new BuildException( + "The specified classpathref %s does not reference a Path.", + pathId); } String loaderId = MagicNames.REFID_CLASSPATH_LOADER_PREFIX + pathId; return getClassLoaderForPath(p, (Path) path, loaderId, reverseLoader); @@ -174,8 +175,9 @@ public class ClasspathUtils { if (loaderId != null && reuseLoader) { Object reusedLoader = p.getReference(loaderId); if (reusedLoader != null && !(reusedLoader instanceof ClassLoader)) { - throw new BuildException("The specified loader id " + loaderId - + " does not reference a class loader"); + throw new BuildException( + "The specified loader id %s does not reference a class loader", + loaderId); } cl = (ClassLoader) reusedLoader; } @@ -243,14 +245,16 @@ public class ClasspathUtils { * @throws BuildException when loading or instantiation failed. * @since Ant 1.7 */ - public static Object newInstance(String className, ClassLoader userDefinedLoader, - Class expectedType) { + public static <T> T newInstance(String className, ClassLoader userDefinedLoader, + Class<T> expectedType) { try { - Class clazz = Class.forName(className, true, userDefinedLoader); - Object o = clazz.newInstance(); + @SuppressWarnings("unchecked") + Class<T> clazz = (Class<T>) Class.forName(className, true, userDefinedLoader); + T o = clazz.newInstance(); if (!expectedType.isInstance(o)) { - throw new BuildException("Class of unexpected Type: " + className + " expected :" - + expectedType); + throw new BuildException( + "Class of unexpected Type: %s expected : %s", className, + expectedType); } return o; } catch (ClassNotFoundException e) { @@ -286,6 +290,9 @@ public class ClasspathUtils { return p.getProperty(REUSE_LOADER_REF) != null; } + private ClasspathUtils() { + } + /** * Delegate that helps out any specific ProjectComponent that needs * dynamic classloading. @@ -457,7 +464,5 @@ public class ClasspathUtils { return reverseLoader; } - //TODO no methods yet for getClassname - //TODO no method for newInstance using a reverse-classloader } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/CollectionUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/CollectionUtils.java b/src/main/org/apache/tools/ant/util/CollectionUtils.java index 23f67a4..70b2810 100644 --- a/src/main/org/apache/tools/ant/util/CollectionUtils.java +++ b/src/main/org/apache/tools/ant/util/CollectionUtils.java @@ -25,7 +25,9 @@ import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Vector; +import java.util.stream.Collectors; // CheckStyle:HideUtilityClassConstructorCheck OFF - bc @@ -49,15 +51,7 @@ public class CollectionUtils { * @deprecated since 1.6.x. */ public static boolean equals(Vector<?> v1, Vector<?> v2) { - if (v1 == v2) { - return true; - } - - if (v1 == null || v2 == null) { - return false; - } - - return v1.equals(v2); + return Objects.equals(v1, v2); } /** @@ -109,14 +103,7 @@ public class CollectionUtils { * @since Ant 1.8.0 */ public static String flattenToString(Collection<?> c) { - final StringBuilder sb = new StringBuilder(); - for (Object o : c) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append(o); - } - return sb.toString(); + return c.stream().map(String::valueOf).collect(Collectors.joining(",")); } /** @@ -128,7 +115,8 @@ public class CollectionUtils { * @since Ant 1.6 * @deprecated since 1.6.x. */ - public static <K, V> void putAll(Dictionary<? super K, ? super V> m1, Dictionary<? extends K, ? extends V> m2) { + public static <K, V> void putAll(Dictionary<? super K, ? super V> m1, + Dictionary<? extends K, ? extends V> m2) { for (Enumeration<? extends K> it = m2.keys(); it.hasMoreElements();) { K key = it.nextElement(); m1.put(key, m2.get(key)); @@ -139,14 +127,13 @@ public class CollectionUtils { * An empty enumeration. * @since Ant 1.6 */ + @Deprecated public static final class EmptyEnumeration<E> implements Enumeration<E> { - /** Constructor for the EmptyEnumeration */ - public EmptyEnumeration() { - } /** * @return false always. */ + @Override public boolean hasMoreElements() { return false; } @@ -155,6 +142,7 @@ public class CollectionUtils { * @return nothing. * @throws NoSuchElementException always. */ + @Override public E nextElement() throws NoSuchElementException { throw new NoSuchElementException(); } @@ -170,7 +158,7 @@ public class CollectionUtils { * @since Ant 1.6.3 */ public static <E> Enumeration<E> append(Enumeration<E> e1, Enumeration<E> e2) { - return new CompoundEnumeration<E>(e1, e2); + return new CompoundEnumeration<>(e1, e2); } /** @@ -181,9 +169,11 @@ public class CollectionUtils { */ public static <E> Enumeration<E> asEnumeration(final Iterator<E> iter) { return new Enumeration<E>() { + @Override public boolean hasMoreElements() { return iter.hasNext(); } + @Override public E nextElement() { return iter.next(); } @@ -198,12 +188,15 @@ public class CollectionUtils { */ public static <E> Iterator<E> asIterator(final Enumeration<E> e) { return new Iterator<E>() { + @Override public boolean hasNext() { return e.hasMoreElements(); } + @Override public E next() { return e.nextElement(); } + @Override public void remove() { throw new UnsupportedOperationException(); } @@ -219,10 +212,8 @@ public class CollectionUtils { * @since Ant 1.8.0 */ public static <T> Collection<T> asCollection(final Iterator<? extends T> iter) { - List<T> l = new ArrayList<T>(); - while (iter.hasNext()) { - l.add(iter.next()); - } + List<T> l = new ArrayList<>(); + iter.forEachRemaining(l::add); return l; } @@ -235,16 +226,17 @@ public class CollectionUtils { this.e2 = e2; } + @Override public boolean hasMoreElements() { return e1.hasMoreElements() || e2.hasMoreElements(); } + @Override public E nextElement() throws NoSuchElementException { if (e1.hasMoreElements()) { return e1.nextElement(); - } else { - return e2.nextElement(); } + return e2.nextElement(); } } @@ -258,18 +250,11 @@ public class CollectionUtils { * @return frequency * @since Ant 1.8.0 */ + @Deprecated public static int frequency(Collection<?> c, Object o) { - // same as Collections.frequency introduced with JDK 1.5 - int freq = 0; - if (c != null) { - for (Iterator<?> i = c.iterator(); i.hasNext();) { - Object test = i.next(); - if (o == null ? test == null : o.equals(test)) { - freq++; - } - } - } - return freq; + return Collections.frequency(c, o); } + private CollectionUtils() { + } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/CompositeMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/CompositeMapper.java b/src/main/org/apache/tools/ant/util/CompositeMapper.java index d04a5fc..4ef9a76 100644 --- a/src/main/org/apache/tools/ant/util/CompositeMapper.java +++ b/src/main/org/apache/tools/ant/util/CompositeMapper.java @@ -17,8 +17,8 @@ */ package org.apache.tools.ant.util; -import java.util.Iterator; -import java.util.LinkedHashSet; +import java.util.Objects; +import java.util.stream.Stream; /** * A <code>ContainerMapper</code> that unites the results of its constituent @@ -28,23 +28,9 @@ public class CompositeMapper extends ContainerMapper { /** {@inheritDoc}. */ public String[] mapFileName(String sourceFileName) { - LinkedHashSet results = new LinkedHashSet(); - - FileNameMapper mapper = null; - for (Iterator mIter = getMappers().iterator(); mIter.hasNext();) { - mapper = (FileNameMapper) (mIter.next()); - if (mapper != null) { - String[] mapped = mapper.mapFileName(sourceFileName); - if (mapped != null) { - for (int i = 0; i < mapped.length; i++) { - results.add(mapped[i]); - } - } - } - } - return (results.size() == 0) ? null - : (String[]) results.toArray(new String[results.size()]); + String[] result = getMappers().stream().filter(Objects::nonNull) + .map(m -> m.mapFileName(sourceFileName)).filter(Objects::nonNull) + .flatMap(Stream::of).toArray(String[]::new); + return result.length == 0 ? null : result; } - } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ConcatFileInputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ConcatFileInputStream.java b/src/main/org/apache/tools/ant/util/ConcatFileInputStream.java index ff0111e..e39f09e 100644 --- a/src/main/org/apache/tools/ant/util/ConcatFileInputStream.java +++ b/src/main/org/apache/tools/ant/util/ConcatFileInputStream.java @@ -55,6 +55,7 @@ public class ConcatFileInputStream extends InputStream { * Close the stream. * @throws IOException if there is an error. */ + @Override public void close() throws IOException { closeCurrent(); eof = true; @@ -65,6 +66,7 @@ public class ConcatFileInputStream extends InputStream { * @return the byte (0 - 255) or -1 if this is the end of the stream. * @throws IOException if there is an error. */ + @Override public int read() throws IOException { int result = readCurrent(); if (result == EOF && !eof) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ConcatResourceInputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ConcatResourceInputStream.java b/src/main/org/apache/tools/ant/util/ConcatResourceInputStream.java index 7bae58e..d030a55 100644 --- a/src/main/org/apache/tools/ant/util/ConcatResourceInputStream.java +++ b/src/main/org/apache/tools/ant/util/ConcatResourceInputStream.java @@ -71,6 +71,7 @@ public class ConcatResourceInputStream extends InputStream { * Close the stream. * @throws IOException if there is an error. */ + @Override public void close() throws IOException { closeCurrent(); eof = true; @@ -81,6 +82,7 @@ public class ConcatResourceInputStream extends InputStream { * @return the byte (0 - 255) or -1 if this is the end of the stream. * @throws IOException if there is an error. */ + @Override public int read() throws IOException { if (eof) { return EOF; @@ -122,7 +124,7 @@ public class ConcatResourceInputStream extends InputStream { private void nextResource() throws IOException { closeCurrent(); while (iter.hasNext()) { - Resource r = (Resource) iter.next(); + Resource r = iter.next(); if (!r.isExists()) { continue; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ContainerMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ContainerMapper.java b/src/main/org/apache/tools/ant/util/ContainerMapper.java index 990ee14..2b5ee39 100644 --- a/src/main/org/apache/tools/ant/util/ContainerMapper.java +++ b/src/main/org/apache/tools/ant/util/ContainerMapper.java @@ -20,7 +20,6 @@ package org.apache.tools.ant.util; import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; import java.util.List; import org.apache.tools.ant.types.Mapper; @@ -32,7 +31,7 @@ import org.apache.tools.ant.types.Mapper; */ public abstract class ContainerMapper implements FileNameMapper { - private List mappers = new ArrayList(); + private List<FileNameMapper> mappers = new ArrayList<>(); /** * Add a <code>Mapper</code>. @@ -69,9 +68,8 @@ public abstract class ContainerMapper implements FileNameMapper { && ((ContainerMapper) fileNameMapper).contains(this))) { throw new IllegalArgumentException( "Circular mapper containment condition detected"); - } else { - mappers.add(fileNameMapper); } + mappers.add(fileNameMapper); } /** @@ -81,21 +79,23 @@ public abstract class ContainerMapper implements FileNameMapper { * @return <code>boolean</code>. */ protected synchronized boolean contains(FileNameMapper fileNameMapper) { - boolean foundit = false; - for (Iterator iter = mappers.iterator(); iter.hasNext() && !foundit;) { - FileNameMapper next = (FileNameMapper) (iter.next()); - foundit = (next == fileNameMapper - || (next instanceof ContainerMapper - && ((ContainerMapper) next).contains(fileNameMapper))); + for (FileNameMapper m : mappers) { + if (m == fileNameMapper) { + return true; + } + if (m instanceof ContainerMapper + && ((ContainerMapper) m).contains(fileNameMapper)) { + return true; + } } - return foundit; + return false; } /** * Get the <code>List</code> of <code>FileNameMapper</code>s. * @return <code>List</code>. */ - public synchronized List getMappers() { + public synchronized List<FileNameMapper> getMappers() { return Collections.unmodifiableList(mappers); } @@ -103,6 +103,7 @@ public abstract class ContainerMapper implements FileNameMapper { * Empty implementation. * @param ignore ignored. */ + @Override public void setFrom(String ignore) { //Empty } @@ -111,6 +112,7 @@ public abstract class ContainerMapper implements FileNameMapper { * Empty implementation. * @param ignore ignored. */ + @Override public void setTo(String ignore) { //Empty } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/DOMElementWriter.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/DOMElementWriter.java b/src/main/org/apache/tools/ant/util/DOMElementWriter.java index cafecf0..7f6013a 100644 --- a/src/main/org/apache/tools/ant/util/DOMElementWriter.java +++ b/src/main/org/apache/tools/ant/util/DOMElementWriter.java @@ -25,7 +25,8 @@ import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.w3c.dom.Attr; import org.w3c.dom.Element; @@ -68,7 +69,7 @@ public class DOMElementWriter { /** * Map (URI to prefix) of known namespaces. */ - private HashMap nsPrefixMap = new HashMap(); + private Map<String, String> nsPrefixMap = new HashMap<>(); /** * Number of generated prefix to use next. @@ -78,7 +79,7 @@ public class DOMElementWriter { /** * Map (Element to URI) of namespaces defined on a given element. */ - private HashMap nsURIByElement = new HashMap(); + private Map<Element, List<String>> nsURIByElement = new HashMap<>(); /** * Whether namespaces should be ignored for elements and attributes. @@ -346,12 +347,10 @@ public class DOMElementWriter { } // write namespace declarations - ArrayList al = (ArrayList) nsURIByElement.get(element); - if (al != null) { - Iterator iter = al.iterator(); - while (iter.hasNext()) { - String uri = (String) iter.next(); - String prefix = (String) nsPrefixMap.get(uri); + List<String> uris = nsURIByElement.get(element); + if (uris != null) { + for (String uri : uris) { + String prefix = nsPrefixMap.get(uri); out.write(" xmlns"); if (!"".equals(prefix)) { out.write(":"); @@ -436,7 +435,7 @@ public class DOMElementWriter { private String encode(final String value, final boolean encodeWhitespace) { final int len = value.length(); - final StringBuffer sb = new StringBuffer(len); + final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { final char c = value.charAt(i); switch (c) { @@ -596,13 +595,17 @@ public class DOMElementWriter { // CheckStyle:MagicNumber OFF if (c == 0x9 || c == 0xA || c == 0xD) { return true; - } else if (c < 0x20) { + } + if (c < 0x20) { return false; - } else if (c <= 0xD7FF) { + } + if (c <= 0xD7FF) { return true; - } else if (c < 0xE000) { + } + if (c < 0xE000) { return false; - } else if (c <= 0xFFFD) { + } + if (c <= 0xFFFD) { return true; } // CheckStyle:MagicNumber ON @@ -610,31 +613,20 @@ public class DOMElementWriter { } private void removeNSDefinitions(Element element) { - ArrayList al = (ArrayList) nsURIByElement.get(element); - if (al != null) { - Iterator iter = al.iterator(); - while (iter.hasNext()) { - nsPrefixMap.remove(iter.next()); - } + List<String> uris = nsURIByElement.get(element); + if (uris != null) { + uris.forEach(nsPrefixMap::remove); nsURIByElement.remove(element); } } private void addNSDefinition(Element element, String uri) { - ArrayList al = (ArrayList) nsURIByElement.get(element); - if (al == null) { - al = new ArrayList(); - nsURIByElement.put(element, al); - } - al.add(uri); + nsURIByElement.computeIfAbsent(element, e -> new ArrayList<>()) + .add(uri); } private static String getNamespaceURI(Node n) { String uri = n.getNamespaceURI(); - if (uri == null) { - // FIXME: Is "No Namespace is Empty Namespace" really OK? - uri = ""; - } - return uri; + return uri == null ? "" : uri; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/DOMUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/DOMUtils.java b/src/main/org/apache/tools/ant/util/DOMUtils.java index db00213..0e2cfce 100644 --- a/src/main/org/apache/tools/ant/util/DOMUtils.java +++ b/src/main/org/apache/tools/ant/util/DOMUtils.java @@ -160,4 +160,7 @@ public class DOMUtils { Element e = createChildElement(parent, name); appendCDATA(e, content); } + + private DOMUtils() { + } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/DateUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/DateUtils.java b/src/main/org/apache/tools/ant/util/DateUtils.java index 9ce737b..42b3eab 100644 --- a/src/main/org/apache/tools/ant/util/DateUtils.java +++ b/src/main/org/apache/tools/ant/util/DateUtils.java @@ -66,12 +66,12 @@ public final class DateUtils { * some other code is using the format in parallel. * Deprecated since ant 1.8 */ + @Deprecated public static final DateFormat DATE_HEADER_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US); - private static final DateFormat DATE_HEADER_FORMAT_INT - = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US); - + private static final DateFormat DATE_HEADER_FORMAT_INT = + new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US); // code from Magesh moved from DefaultLogger and slightly modified private static final MessageFormat MINUTE_SECONDS @@ -215,7 +215,7 @@ public final class DateUtils { cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_WEEK), cal.get(Calendar.MILLISECOND)); - StringBuffer tzMarker = new StringBuffer(offset < 0 ? "-" : "+"); + StringBuilder tzMarker = new StringBuilder(offset < 0 ? "-" : "+"); offset = Math.abs(offset); int hours = offset / (ONE_HOUR * ONE_MINUTE * ONE_SECOND); int minutes = offset / (ONE_MINUTE * ONE_SECOND) - ONE_HOUR * hours; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/DeweyDecimal.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/DeweyDecimal.java b/src/main/org/apache/tools/ant/util/DeweyDecimal.java index 003f140..32564fd 100644 --- a/src/main/org/apache/tools/ant/util/DeweyDecimal.java +++ b/src/main/org/apache/tools/ant/util/DeweyDecimal.java @@ -18,6 +18,8 @@ package org.apache.tools.ant.util; import java.util.StringTokenizer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * Utility class to contain version numbers in "Dewey Decimal" @@ -195,16 +197,8 @@ public class DeweyDecimal implements Comparable<DeweyDecimal> { * @return the string representation of DeweyDecimal. */ @Override public String toString() { - final StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < components.length; i++) { - if (i != 0) { - sb.append('.'); - } - sb.append(components[ i ]); - } - - return sb.toString(); + return IntStream.of(components).mapToObj(Integer::toString) + .collect(Collectors.joining(".")); } /** @@ -214,6 +208,7 @@ public class DeweyDecimal implements Comparable<DeweyDecimal> { * @return result * @see java.lang.Comparable#compareTo(Object) */ + @Override public int compareTo(DeweyDecimal other) { final int max = Math.max(other.components.length, components.length); for (int i = 0; i < max; i++) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/FileTokenizer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/FileTokenizer.java b/src/main/org/apache/tools/ant/util/FileTokenizer.java index 2807aa4..93f5480 100644 --- a/src/main/org/apache/tools/ant/util/FileTokenizer.java +++ b/src/main/org/apache/tools/ant/util/FileTokenizer.java @@ -34,6 +34,7 @@ public class FileTokenizer extends ProjectComponent implements Tokenizer { * @return the complete input * @throws IOException if error reading */ + @Override public String getToken(Reader in) throws IOException { return FileUtils.readFully(in); } @@ -42,6 +43,7 @@ public class FileTokenizer extends ProjectComponent implements Tokenizer { * Return the intra-token string * @return an empty string always */ + @Override public String getPostToken() { return ""; }
