http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/FileUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/FileUtils.java b/src/main/org/apache/tools/ant/util/FileUtils.java index 11ae06b..8bbdf91 100644 --- a/src/main/org/apache/tools/ant/util/FileUtils.java +++ b/src/main/org/apache/tools/ant/util/FileUtils.java @@ -37,19 +37,20 @@ import java.nio.file.StandardOpenOption; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import java.util.jar.JarFile; +import java.util.stream.Collectors; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.PathTokenizer; import org.apache.tools.ant.Project; import org.apache.tools.ant.launch.Locator; import org.apache.tools.ant.taskdefs.condition.Os; +import org.apache.tools.ant.types.FilterChain; import org.apache.tools.ant.types.FilterSetCollection; import org.apache.tools.ant.types.resources.FileResource; @@ -112,6 +113,7 @@ public class FileUtils { * Use getFileUtils instead, * FileUtils do not have state. */ + @Deprecated public static FileUtils newFileUtils() { return new FileUtils(); } @@ -275,7 +277,7 @@ public class FileUtils { * @since Ant 1.5 */ public void copyFile(String sourceFile, String destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, String encoding, Project project) throws IOException { copyFile(new File(sourceFile), new File(destFile), filters, filterChains, overwrite, @@ -305,7 +307,7 @@ public class FileUtils { * @since Ant 1.6 */ public void copyFile(String sourceFile, String destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, String inputEncoding, String outputEncoding, Project project) throws IOException { @@ -440,7 +442,7 @@ public class FileUtils { * @since Ant 1.5 */ public void copyFile(File sourceFile, File destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, String encoding, Project project) throws IOException { copyFile(sourceFile, destFile, filters, filterChains, @@ -476,7 +478,7 @@ public class FileUtils { * @since Ant 1.6 */ public void copyFile(File sourceFile, File destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, String inputEncoding, String outputEncoding, Project project) throws IOException { @@ -514,7 +516,7 @@ public class FileUtils { * @since Ant 1.8 */ public void copyFile(File sourceFile, File destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, boolean append, String inputEncoding, String outputEncoding, @@ -554,7 +556,7 @@ public class FileUtils { * @since Ant 1.8.2 */ public void copyFile(File sourceFile, File destFile, - FilterSetCollection filters, Vector filterChains, + FilterSetCollection filters, Vector<FilterChain> filterChains, boolean overwrite, boolean preserveLastModified, boolean append, String inputEncoding, String outputEncoding, @@ -698,10 +700,10 @@ public class FileUtils { * @see PathTokenizer */ public static String translatePath(String toProcess) { - if (toProcess == null || toProcess.length() == 0) { + if (toProcess == null || toProcess.isEmpty()) { return ""; } - StringBuffer path = new StringBuffer(toProcess.length() + EXPAND_SPACE); + StringBuilder path = new StringBuilder(toProcess.length() + EXPAND_SPACE); PathTokenizer tokenizer = new PathTokenizer(toProcess); while (tokenizer.hasMoreTokens()) { String pathComponent = tokenizer.nextToken(); @@ -735,7 +737,7 @@ public class FileUtils { * @throws java.lang.NullPointerException if path is null. */ public File normalize(final String path) { - Stack s = new Stack(); + Stack<String> s = new Stack<>(); String[] dissect = dissect(path); s.push(dissect[0]); @@ -755,7 +757,7 @@ public class FileUtils { s.push(thisToken); } } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); final int size = s.size(); for (int i = 0; i < size; i++) { if (i > 1) { @@ -783,7 +785,7 @@ public class FileUtils { if (!isAbsolutePath(path)) { throw new BuildException(path + " is not an absolute path"); } - String root = null; + String root; int colon = path.indexOf(':'); if (colon > 0 && (ON_DOS || ON_NETWARE)) { @@ -836,7 +838,7 @@ public class FileUtils { && !name.regionMatches(true, name.length() - 4, ".DIR", 0, 4); // CheckStyle:MagicNumber ON String device = null; - StringBuffer directory = null; + StringBuilder directory = null; String file = null; int index = 0; @@ -849,13 +851,13 @@ public class FileUtils { device = path.substring(1, index++); } if (isDirectory) { - directory = new StringBuffer(path.substring(index).replace(File.separatorChar, '.')); + directory = new StringBuilder(path.substring(index).replace(File.separatorChar, '.')); } else { int dirEnd = path.lastIndexOf(File.separatorChar, path.length()); if (dirEnd == -1 || dirEnd < index) { file = path.substring(index); } else { - directory = new StringBuffer(path.substring(index, dirEnd). + directory = new StringBuilder(path.substring(index, dirEnd). replace(File.separatorChar, '.')); index = dirEnd + 1; if (path.length() > index) { @@ -897,6 +899,7 @@ public class FileUtils { * boolean, boolean) instead. * @return a File reference to the new, nonexistent temporary file. */ + @Deprecated public File createTempFile(String prefix, String suffix, File parentDir) { return createTempFile(prefix, suffix, parentDir, false, false); } @@ -926,7 +929,7 @@ public class FileUtils { */ public File createTempFile(String prefix, String suffix, File parentDir, boolean deleteOnExit, boolean createFile) { - File result = null; + File result; String parent = (parentDir == null) ? System.getProperty("java.io.tmpdir") : parentDir.getPath(); @@ -987,6 +990,7 @@ public class FileUtils { * boolean, boolean) instead. * @return a File reference to the new, nonexistent temporary file. */ + @Deprecated public File createTempFile(String prefix, String suffix, File parentDir, boolean deleteOnExit) { return createTempFile(prefix, suffix, parentDir, deleteOnExit, false); @@ -1032,8 +1036,9 @@ public class FileUtils { * @since 1.10 * @deprecated since 1.7. Just use {@link File#getParentFile} directly. */ + @Deprecated public File getParentFile(File f) { - return (f == null) ? null : f.getParentFile(); + return f == null ? null : f.getParentFile(); } /** @@ -1062,17 +1067,17 @@ public class FileUtils { public static String readFully(Reader rdr, int bufferSize) throws IOException { if (bufferSize <= 0) { - throw new IllegalArgumentException("Buffer size must be greater " - + "than 0"); + throw new IllegalArgumentException( + "Buffer size must be greater than 0"); } final char[] buffer = new char[bufferSize]; int bufferLength = 0; - StringBuffer textBuffer = null; + StringBuilder textBuffer = null; while (bufferLength != -1) { bufferLength = rdr.read(buffer); if (bufferLength > 0) { - textBuffer = (textBuffer == null) ? new StringBuffer() : textBuffer; - textBuffer.append(new String(buffer, 0, bufferLength)); + textBuffer = (textBuffer == null) ? new StringBuilder() : textBuffer; + textBuffer.append(buffer, 0, bufferLength); } } return (textBuffer == null) ? null : textBuffer.toString(); @@ -1138,6 +1143,7 @@ public class FileUtils { * @since Ant 1.5 * @deprecated use SymbolicLinkUtils instead */ + @Deprecated public boolean isSymbolicLink(File parent, String name) throws IOException { SymbolicLinkUtils u = SymbolicLinkUtils.getSymbolicLinkUtils(); @@ -1375,11 +1381,8 @@ public class FileUtils { return false; } final String localFileName = localFile.getName(); - FilenameFilter ff = new FilenameFilter () { - public boolean accept(File dir, String name) { - return name.equalsIgnoreCase(localFileName) && (!name.equals(localFileName)); - } - }; + FilenameFilter ff = (dir, name) -> name.equalsIgnoreCase(localFileName) + && (!name.equals(localFileName)); String[] names = localFile.getParentFile().list(ff); return names != null && names.length == 1; } @@ -1506,7 +1509,6 @@ public class FileUtils { JarURLConnection juc = (JarURLConnection) conn; JarFile jf = juc.getJarFile(); jf.close(); - jf = null; } else if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } @@ -1623,7 +1625,7 @@ public class FileUtils { // Do nothing } - List relativePathStack = new ArrayList(); + List<String> relativePathStack = new ArrayList<>(); // if "from" part is longer, fill it up with ".." // to reach path which is equal to both paths @@ -1661,7 +1663,7 @@ public class FileUtils { * * @since Ant 1.7 */ - public static String getPath(List pathStack) { + public static String getPath(List<String> pathStack) { // can safely use '/' because Windows understands '/' as separator return getPath(pathStack, '/'); } @@ -1675,18 +1677,8 @@ public class FileUtils { * * @since Ant 1.7 */ - public static String getPath(final List pathStack, final char separatorChar) { - final StringBuffer buffer = new StringBuffer(); - - final Iterator iter = pathStack.iterator(); - if (iter.hasNext()) { - buffer.append(iter.next()); - } - while (iter.hasNext()) { - buffer.append(separatorChar); - buffer.append(iter.next()); - } - return buffer.toString(); + public static String getPath(final List<String> pathStack, final char separatorChar) { + return pathStack.stream().collect(Collectors.joining(Character.toString(separatorChar))); } /** @@ -1700,6 +1692,7 @@ public class FileUtils { public String getDefaultEncoding() { InputStreamReader is = new InputStreamReader( new InputStream() { //NOSONAR + @Override public int read() { return -1; }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/FirstMatchMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/FirstMatchMapper.java b/src/main/org/apache/tools/ant/util/FirstMatchMapper.java index b0e47f2..0b5a53de 100644 --- a/src/main/org/apache/tools/ant/util/FirstMatchMapper.java +++ b/src/main/org/apache/tools/ant/util/FirstMatchMapper.java @@ -17,7 +17,7 @@ */ package org.apache.tools.ant.util; -import java.util.Iterator; +import java.util.Objects; /** * A <code>ContainerMapper</code> that returns the results of its @@ -28,17 +28,11 @@ import java.util.Iterator; public class FirstMatchMapper extends ContainerMapper { /** {@inheritDoc}. */ + @Override public String[] mapFileName(String sourceFileName) { - for (Iterator iter = getMappers().iterator(); iter.hasNext();) { - FileNameMapper mapper = (FileNameMapper) iter.next(); - if (mapper != null) { - String[] mapped = mapper.mapFileName(sourceFileName); - if (mapped != null) { - return mapped; - } - } - } - return null; + return getMappers().stream().filter(Objects::nonNull) + .map(m -> m.mapFileName(sourceFileName)).filter(Objects::nonNull) + .findFirst().orElse(null); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/FlatFileNameMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/FlatFileNameMapper.java b/src/main/org/apache/tools/ant/util/FlatFileNameMapper.java index 420ccc6..8465c78 100644 --- a/src/main/org/apache/tools/ant/util/FlatFileNameMapper.java +++ b/src/main/org/apache/tools/ant/util/FlatFileNameMapper.java @@ -32,6 +32,7 @@ public class FlatFileNameMapper implements FileNameMapper { * Ignored. * @param from ignored. */ + @Override public void setFrom(String from) { } @@ -39,6 +40,7 @@ public class FlatFileNameMapper implements FileNameMapper { * Ignored. * @param to ignored. */ + @Override public void setTo(String to) { } @@ -48,7 +50,8 @@ public class FlatFileNameMapper implements FileNameMapper { * @param sourceFileName the name to map. * @return the file name in a one-element array. */ + @Override public String[] mapFileName(String sourceFileName) { - return new String[] {new java.io.File(sourceFileName).getName()}; + return new String[] { new java.io.File(sourceFileName).getName() }; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/GlobPatternMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/GlobPatternMapper.java b/src/main/org/apache/tools/ant/util/GlobPatternMapper.java index da2a0f1..4d2d5cc 100644 --- a/src/main/org/apache/tools/ant/util/GlobPatternMapper.java +++ b/src/main/org/apache/tools/ant/util/GlobPatternMapper.java @@ -107,42 +107,42 @@ public class GlobPatternMapper implements FileNameMapper { * Sets the "from" pattern. Required. * @param from a string */ + @Override public void setFrom(String from) { - if (from != null) { - int index = from.lastIndexOf("*"); - if (index == -1) { - fromPrefix = from; - fromPostfix = ""; - } else { - fromPrefix = from.substring(0, index); - fromPostfix = from.substring(index + 1); - fromContainsStar = true; - } - prefixLength = fromPrefix.length(); - postfixLength = fromPostfix.length(); - } else { + if (from == null) { throw new BuildException("this mapper requires a 'from' attribute"); } + int index = from.lastIndexOf('*'); + if (index < 0) { + fromPrefix = from; + fromPostfix = ""; + } else { + fromPrefix = from.substring(0, index); + fromPostfix = from.substring(index + 1); + fromContainsStar = true; + } + prefixLength = fromPrefix.length(); + postfixLength = fromPostfix.length(); } /** * Sets the "to" pattern. Required. * @param to a string */ + @Override public void setTo(String to) { - if (to != null) { - int index = to.lastIndexOf("*"); - if (index == -1) { - toPrefix = to; - toPostfix = ""; - } else { - toPrefix = to.substring(0, index); - toPostfix = to.substring(index + 1); - toContainsStar = true; - } - } else { + if (to == null) { throw new BuildException("this mapper requires a 'to' attribute"); } + int index = to.lastIndexOf('*'); + if (index < 0 ) { + toPrefix = to; + toPostfix = ""; + } else { + toPrefix = to.substring(0, index); + toPostfix = to.substring(index + 1); + toContainsStar = true; + } } /** @@ -152,6 +152,7 @@ public class GlobPatternMapper implements FileNameMapper { * @param sourceFileName the filename to map * @return a list of converted filenames */ + @Override public String[] mapFileName(String sourceFileName) { String modName = modifyName(sourceFileName); if (fromPrefix == null http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/IdentityMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/IdentityMapper.java b/src/main/org/apache/tools/ant/util/IdentityMapper.java index 22c6c7e..548803d 100644 --- a/src/main/org/apache/tools/ant/util/IdentityMapper.java +++ b/src/main/org/apache/tools/ant/util/IdentityMapper.java @@ -31,6 +31,7 @@ public class IdentityMapper implements FileNameMapper { * Ignored. * @param from ignored. */ + @Override public void setFrom(String from) { } @@ -38,6 +39,7 @@ public class IdentityMapper implements FileNameMapper { * Ignored. * @param to ignored. */ + @Override public void setTo(String to) { } @@ -46,7 +48,8 @@ public class IdentityMapper implements FileNameMapper { * @param sourceFileName the name to map. * @return the source filename in a one-element array. */ + @Override public String[] mapFileName(String sourceFileName) { - return new String[] {sourceFileName}; + return new String[] { sourceFileName }; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/IdentityStack.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/IdentityStack.java b/src/main/org/apache/tools/ant/util/IdentityStack.java index ac806d7..56e9f7b 100644 --- a/src/main/org/apache/tools/ant/util/IdentityStack.java +++ b/src/main/org/apache/tools/ant/util/IdentityStack.java @@ -40,7 +40,7 @@ public class IdentityStack<E> extends Stack<E> { if (s instanceof IdentityStack) { return (IdentityStack<E>) s; } - IdentityStack<E> result = new IdentityStack<E>(); + IdentityStack<E> result = new IdentityStack<>(); if (s != null) { result.addAll(s); } @@ -69,6 +69,7 @@ public class IdentityStack<E> extends Stack<E> { * @return true if the stack contains the object. * @see java.util.Vector#contains(Object) */ + @Override public synchronized boolean contains(Object o) { return indexOf(o) >= 0; } @@ -80,6 +81,7 @@ public class IdentityStack<E> extends Stack<E> { * @return the position of the object, -1 if not found. * @see java.util.Vector#indexOf(Object, int) */ + @Override public synchronized int indexOf(Object o, int pos) { final int size = size(); for (int i = pos; i < size; i++) { @@ -97,6 +99,7 @@ public class IdentityStack<E> extends Stack<E> { * @return the position of the object, -1 if not found. * @see java.util.Vector#indexOf(Object, int) */ + @Override public synchronized int lastIndexOf(Object o, int pos) { for (int i = pos; i >= 0; i--) { if (get(i) == o) { @@ -106,22 +109,25 @@ public class IdentityStack<E> extends Stack<E> { return -1; } + @Override public synchronized boolean removeAll(Collection<?> c) { - if (!(c instanceof Set)) { - c = new HashSet(c); + if (!(c instanceof Set<?>)) { + c = new HashSet<>(c); } return super.removeAll(c); } - public synchronized boolean retainAll(Collection c) { - if (!(c instanceof Set)) { - c = new HashSet(c); + @Override + public synchronized boolean retainAll(Collection<?> c) { + if (!(c instanceof Set<?>)) { + c = new HashSet<>(c); } return super.retainAll(c); } + @Override public synchronized boolean containsAll(Collection<?> c) { - IdentityHashMap map = new IdentityHashMap(); + IdentityHashMap<Object, Boolean> map = new IdentityHashMap<>(); for (Object e : this) { map.put(e, Boolean.TRUE); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/JAXPUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/JAXPUtils.java b/src/main/org/apache/tools/ant/util/JAXPUtils.java index 76460ae..2af9f8e 100644 --- a/src/main/org/apache/tools/ant/util/JAXPUtils.java +++ b/src/main/org/apache/tools/ant/util/JAXPUtils.java @@ -232,9 +232,8 @@ public class JAXPUtils { Exception nested = e.getException(); if (nested != null) { return new BuildException(nested); - } else { - return new BuildException(e); } + return new BuildException(e); } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/JavaEnvUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java index 84e82fd..ea21b6b 100644 --- a/src/main/org/apache/tools/ant/util/JavaEnvUtils.java +++ b/src/main/org/apache/tools/ant/util/JavaEnvUtils.java @@ -448,7 +448,7 @@ public final class JavaEnvUtils { */ private static void buildJrePackages() { - jrePackages = new Vector<String>(); + jrePackages = new Vector<>(); switch(javaVersionNumber) { case VERSION_9: case VERSION_1_8: @@ -502,7 +502,7 @@ public final class JavaEnvUtils { * @return a list of test classes depending on the java version. */ public static Vector<String> getJrePackageTestCases() { - Vector<String> tests = new Vector<String>(); + Vector<String> tests = new Vector<>(); tests.addElement("java.lang.Object"); switch(javaVersionNumber) { case VERSION_9: @@ -577,15 +577,11 @@ public final class JavaEnvUtils { public static File createVmsJavaOptionFile(String[] cmd) throws IOException { File script = FILE_UTILS.createTempFile("ANT", ".JAVA_OPTS", null, false, true); - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(script)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(script))) { for (int i = 0; i < cmd.length; i++) { out.write(cmd[i]); out.newLine(); } - } finally { - FileUtils.close(out); } return script; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java index 853bec2..f4f2fe7 100644 --- a/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java +++ b/src/main/org/apache/tools/ant/util/LayoutPreservingProperties.java @@ -27,10 +27,12 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PushbackReader; +import java.io.Serializable; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Properties; /** @@ -78,6 +80,8 @@ import java.util.Properties; * although the key-value pair <code>beta=two</code> is removed.</p> */ public class LayoutPreservingProperties extends Properties { + private static final long serialVersionUID = 1L; + private String LS = StringUtils.LINE_SEP; /** @@ -85,12 +89,12 @@ public class LayoutPreservingProperties extends Properties { * of. Comments and blank lines are logical lines; they are not * removed. */ - private ArrayList logicalLines = new ArrayList(); + private List<LogicalLine> logicalLines = new ArrayList<>(); /** * Position in the <code>logicalLines</code> list, keyed by property name. */ - private HashMap keyedPairLines = new HashMap(); + private Map<String, Integer> keyedPairLines = new HashMap<>(); /** * Flag to indicate that, when we remove a property from the file, we @@ -175,14 +179,14 @@ public class LayoutPreservingProperties extends Properties { value = escapeValue(value); if (keyedPairLines.containsKey(key)) { - final Integer i = (Integer) keyedPairLines.get(key); + final Integer i = keyedPairLines.get(key); final Pair p = (Pair) logicalLines.get(i.intValue()); p.setValue(value); } else { key = escapeName(key); final Pair p = new Pair(key, value); p.setNew(true); - keyedPairLines.put(key, new Integer(logicalLines.size())); + keyedPairLines.put(key, Integer.valueOf(logicalLines.size())); logicalLines.add(p); } } @@ -197,7 +201,7 @@ public class LayoutPreservingProperties extends Properties { @Override public Object remove(final Object key) { final Object obj = super.remove(key); - final Integer i = (Integer) keyedPairLines.remove(key); + final Integer i = keyedPairLines.remove(key); if (null != i) { if (removeComments) { removeCommentsEndingAt(i.intValue()); @@ -208,14 +212,14 @@ public class LayoutPreservingProperties extends Properties { } @Override - public Object clone() { + public LayoutPreservingProperties clone() { final LayoutPreservingProperties dolly = (LayoutPreservingProperties) super.clone(); - dolly.keyedPairLines = (HashMap) this.keyedPairLines.clone(); - dolly.logicalLines = (ArrayList) this.logicalLines.clone(); + dolly.keyedPairLines = new HashMap<>(this.keyedPairLines); + dolly.logicalLines = new ArrayList<>(this.logicalLines); final int size = dolly.logicalLines.size(); for (int j = 0; j < size; j++) { - final LogicalLine line = (LogicalLine) dolly.logicalLines.get(j); + final LogicalLine line = dolly.logicalLines.get(j); if (line instanceof Pair) { final Pair p = (Pair) line; dolly.logicalLines.set(j, p.clone()); @@ -232,9 +236,7 @@ public class LayoutPreservingProperties extends Properties { */ public void listLines(final PrintStream out) { out.println("-- logical lines --"); - final Iterator i = logicalLines.iterator(); - while (i.hasNext()) { - final LogicalLine line = (LogicalLine) i.next(); + for (LogicalLine line : logicalLines) { if (line instanceof Blank) { out.println("blank: \"" + line + "\""); } else if (line instanceof Comment) { @@ -288,11 +290,9 @@ public class LayoutPreservingProperties extends Properties { osw.write("#" + DateUtils.getDateForHeader() + LS); boolean writtenSep = false; - for (final Iterator i = logicalLines.subList(skipLines, totalLines).iterator(); - i.hasNext();) { - final LogicalLine line = (LogicalLine) i.next(); + for (LogicalLine line : logicalLines.subList(skipLines, totalLines)) { if (line instanceof Pair) { - if (((Pair)line).isNew()) { + if (((Pair) line).isNew()) { if (!writtenSep) { osw.write(LS); writtenSep = true; @@ -317,7 +317,7 @@ public class LayoutPreservingProperties extends Properties { final InputStreamReader isr = new InputStreamReader(is, ResourceUtils.ISO_8859_1); final PushbackReader pbr = new PushbackReader(isr, 1); - if (logicalLines.size() > 0) { + if (!logicalLines.isEmpty()) { // we add a blank line for spacing logicalLines.add(new Blank()); } @@ -327,8 +327,8 @@ public class LayoutPreservingProperties extends Properties { boolean continuation = false; boolean comment = false; - final StringBuffer fileBuffer = new StringBuffer(); - final StringBuffer logicalLineBuffer = new StringBuffer(); + final StringBuilder fileBuffer = new StringBuilder(); + final StringBuilder logicalLineBuffer = new StringBuilder(); while (s != null) { fileBuffer.append(s).append(LS); @@ -349,7 +349,7 @@ public class LayoutPreservingProperties extends Properties { logicalLineBuffer.append(s); if (!continuation) { - LogicalLine line = null; + LogicalLine line; if (comment) { line = new Comment(logicalLineBuffer.toString()); } else if (logicalLineBuffer.toString().trim().length() == 0) { @@ -384,7 +384,7 @@ public class LayoutPreservingProperties extends Properties { * @since Ant 1.8.2 */ private String readFirstLine(final PushbackReader r) throws IOException { - final StringBuffer sb = new StringBuffer(80); + final StringBuilder sb = new StringBuilder(80); int ch = r.read(); boolean hasCR = false; // when reaching EOF before the first EOL, assume native line @@ -454,13 +454,14 @@ public class LayoutPreservingProperties extends Properties { final char[] ch = new char[s.length() + 1]; s.getChars(0, s.length(), ch, 0); ch[s.length()] = '\n'; - final StringBuffer buffy = new StringBuffer(s.length()); + final StringBuilder buffy = new StringBuilder(s.length()); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (c == '\n') { // we have hit out end-of-string marker break; - } else if (c == '\\') { + } + if (c == '\\') { // possibly an escape sequence c = ch[++i]; if (c == 'n') { @@ -540,7 +541,7 @@ public class LayoutPreservingProperties extends Properties { s.getChars(0, s.length(), ch, 0); final String forEscaping = "\t\f\r\n\\:=#!"; final String escaped = "tfrn\\:=#!"; - final StringBuffer buffy = new StringBuffer(s.length()); + final StringBuilder buffy = new StringBuilder(s.length()); boolean leadingSpace = true; for (int i = 0; i < ch.length; i++) { final char c = ch[i]; @@ -571,7 +572,7 @@ public class LayoutPreservingProperties extends Properties { */ private String escapeUnicode(final char ch) { return "\\" + UnicodeUtil.EscapeUnicode(ch); - } + } /** * Remove the comments in the leading up the {@link logicalLines} @@ -618,7 +619,9 @@ public class LayoutPreservingProperties extends Properties { /** * A logical line of the properties input stream. */ - private abstract static class LogicalLine { + private abstract static class LogicalLine implements Serializable { + private static final long serialVersionUID = 1L; + private String text; public LogicalLine(final String text) { @@ -639,6 +642,8 @@ public class LayoutPreservingProperties extends Properties { * A blank line of the input stream. */ private static class Blank extends LogicalLine { + private static final long serialVersionUID = 1L; + public Blank() { super(""); } @@ -648,6 +653,8 @@ public class LayoutPreservingProperties extends Properties { * A comment line of the input stream. */ private class Comment extends LogicalLine { + private static final long serialVersionUID = 1L; + public Comment(final String text) { super(text); } @@ -659,6 +666,8 @@ public class LayoutPreservingProperties extends Properties { * line. */ private static class Pair extends LogicalLine implements Cloneable { + private static final long serialVersionUID = 1L; + private String name; private String value; private boolean added; @@ -676,6 +685,7 @@ public class LayoutPreservingProperties extends Properties { return name; } + @SuppressWarnings("unused") public String getValue() { return value; } @@ -694,10 +704,10 @@ public class LayoutPreservingProperties extends Properties { } @Override - public Object clone() { - Object dolly = null; + public Pair clone() { + Pair dolly = null; try { - dolly = super.clone(); + dolly = (Pair) super.clone(); } catch (final CloneNotSupportedException e) { // should be fine e.printStackTrace(); //NOSONAR @@ -711,10 +721,10 @@ public class LayoutPreservingProperties extends Properties { if (pos == -1) { // trim leading whitespace only name = text; - value = null; + setValue(null); } else { name = text.substring(0, pos); - value = text.substring(pos+1, text.length()); + setValue(text.substring(pos+1, text.length())); } // trim leading whitespace only name = stripStart(name, " \t\f"); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LazyFileOutputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LazyFileOutputStream.java b/src/main/org/apache/tools/ant/util/LazyFileOutputStream.java index 781d0c7..cd7801d 100644 --- a/src/main/org/apache/tools/ant/util/LazyFileOutputStream.java +++ b/src/main/org/apache/tools/ant/util/LazyFileOutputStream.java @@ -107,6 +107,7 @@ public class LazyFileOutputStream extends OutputStream { * Close the file. * @throws IOException if there is an error. */ + @Override public synchronized void close() throws IOException { if (alwaysCreate && !closed) { ensureOpened(); @@ -122,6 +123,7 @@ public class LazyFileOutputStream extends OutputStream { * @param b the bytearray to write. * @throws IOException if there is a problem. */ + @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @@ -133,6 +135,7 @@ public class LazyFileOutputStream extends OutputStream { * @param len the number of bytes to write. * @throws IOException if there is a problem. */ + @Override public synchronized void write(byte[] b, int offset, int len) throws IOException { ensureOpened(); @@ -144,6 +147,7 @@ public class LazyFileOutputStream extends OutputStream { * @param b the byte to write. * @throws IOException if there is a problem. */ + @Override public synchronized void write(int b) throws IOException { ensureOpened(); fos.write(b); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LazyHashtable.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LazyHashtable.java b/src/main/org/apache/tools/ant/util/LazyHashtable.java index 1df953c..9ef9091 100644 --- a/src/main/org/apache/tools/ant/util/LazyHashtable.java +++ b/src/main/org/apache/tools/ant/util/LazyHashtable.java @@ -28,6 +28,7 @@ import java.util.Hashtable; * * @since Ant 1.6 */ +@Deprecated public class LazyHashtable extends Hashtable { // CheckStyle:VisibilityModifier OFF - bc protected boolean initAllDone = false; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LeadPipeInputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LeadPipeInputStream.java b/src/main/org/apache/tools/ant/util/LeadPipeInputStream.java index 0081912..fa82a00 100644 --- a/src/main/org/apache/tools/ant/util/LeadPipeInputStream.java +++ b/src/main/org/apache/tools/ant/util/LeadPipeInputStream.java @@ -81,6 +81,7 @@ public class LeadPipeInputStream extends PipedInputStream { * @return the byte (0 to 255) or -1 if there are no more. * @throws IOException if there is an error. */ + @Override public synchronized int read() throws IOException { int result = -1; try { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LineTokenizer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LineTokenizer.java b/src/main/org/apache/tools/ant/util/LineTokenizer.java index 778606d..89d0b97 100644 --- a/src/main/org/apache/tools/ant/util/LineTokenizer.java +++ b/src/main/org/apache/tools/ant/util/LineTokenizer.java @@ -54,19 +54,19 @@ public class LineTokenizer extends ProjectComponent * @exception IOException if an error occurs reading */ public String getToken(Reader in) throws IOException { - int ch = -1; - if (pushed != NOT_A_CHAR) { + int ch; + if (pushed == NOT_A_CHAR) { + ch = in.read(); + } else { ch = pushed; pushed = NOT_A_CHAR; - } else { - ch = in.read(); } if (ch == -1) { return null; } lineEnd = ""; - StringBuffer line = new StringBuffer(); + StringBuilder line = new StringBuilder(); int state = 0; while (ch != -1) { @@ -104,11 +104,9 @@ public class LineTokenizer extends ProjectComponent /** * @return the line ending character(s) for the current line */ + @Override public String getPostToken() { - if (includeDelims) { - return ""; - } - return lineEnd; + return includeDelims ? "" : lineEnd; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LinkedHashtable.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LinkedHashtable.java b/src/main/org/apache/tools/ant/util/LinkedHashtable.java index 73fc83c..4f73273 100644 --- a/src/main/org/apache/tools/ant/util/LinkedHashtable.java +++ b/src/main/org/apache/tools/ant/util/LinkedHashtable.java @@ -43,89 +43,106 @@ public class LinkedHashtable<K, V> extends Hashtable<K, V> { private final LinkedHashMap<K, V> map; public LinkedHashtable() { - map = new LinkedHashMap<K, V>(); + map = new LinkedHashMap<>(); } public LinkedHashtable(int initialCapacity) { - map = new LinkedHashMap<K, V>(initialCapacity); + map = new LinkedHashMap<>(initialCapacity); } public LinkedHashtable(int initialCapacity, float loadFactor) { - map = new LinkedHashMap<K, V>(initialCapacity, loadFactor); + map = new LinkedHashMap<>(initialCapacity, loadFactor); } public LinkedHashtable(Map<K, V> m) { - map = new LinkedHashMap<K, V>(m); + map = new LinkedHashMap<>(m); } public synchronized void clear() { map.clear(); } + @Override public boolean contains(Object value) { return containsKey(value); } + @Override public synchronized boolean containsKey(Object value) { return map.containsKey(value); } + @Override public synchronized boolean containsValue(Object value) { return map.containsValue(value); } + @Override public Enumeration<V> elements() { return CollectionUtils.asEnumeration(values().iterator()); } + @Override public synchronized Set<Map.Entry<K, V>> entrySet() { return map.entrySet(); } + @Override public synchronized boolean equals(Object o) { return map.equals(o); } + @Override public synchronized V get(Object k) { return map.get(k); } + @Override public synchronized int hashCode() { return map.hashCode(); } + @Override public synchronized boolean isEmpty() { return map.isEmpty(); } + @Override public Enumeration<K> keys() { return CollectionUtils.asEnumeration(keySet().iterator()); } + @Override public synchronized Set<K> keySet() { return map.keySet(); } + @Override public synchronized V put(K k, V v) { return map.put(k, v); } + @Override public synchronized void putAll(Map<? extends K, ? extends V> m) { map.putAll(m); } + @Override public synchronized V remove(Object k) { return map.remove(k); } + @Override public synchronized int size() { return map.size(); } + @Override public synchronized String toString() { return map.toString(); } + @Override public synchronized Collection<V> values() { return map.values(); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/LoaderUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/LoaderUtils.java b/src/main/org/apache/tools/ant/util/LoaderUtils.java index e0514f6..799feb5 100644 --- a/src/main/org/apache/tools/ant/util/LoaderUtils.java +++ b/src/main/org/apache/tools/ant/util/LoaderUtils.java @@ -94,7 +94,7 @@ public class LoaderUtils { * * @since Ant 1.6 */ - public static File getClassSource(Class c) { + public static File getClassSource(Class<?> c) { return normalizeSource(Locator.getClassSource(c)); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/MergingMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/MergingMapper.java b/src/main/org/apache/tools/ant/util/MergingMapper.java index 7f158db..9298a73 100644 --- a/src/main/org/apache/tools/ant/util/MergingMapper.java +++ b/src/main/org/apache/tools/ant/util/MergingMapper.java @@ -44,6 +44,7 @@ public class MergingMapper implements FileNameMapper { * Ignored. * @param from ignored. */ + @Override public void setFrom(String from) { } @@ -51,6 +52,7 @@ public class MergingMapper implements FileNameMapper { * Sets the name of the merged file. * @param to the name of the merged file. */ + @Override public void setTo(String to) { mergedFile = new String[] {to}; } @@ -60,6 +62,7 @@ public class MergingMapper implements FileNameMapper { * @param sourceFileName ignored. * @return a one-element array containing the merged filename. */ + @Override public String[] mapFileName(String sourceFileName) { return mergedFile; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/OutputStreamFunneler.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/OutputStreamFunneler.java b/src/main/org/apache/tools/ant/util/OutputStreamFunneler.java index 9b4cef3..84e0a0a 100644 --- a/src/main/org/apache/tools/ant/util/OutputStreamFunneler.java +++ b/src/main/org/apache/tools/ant/util/OutputStreamFunneler.java @@ -44,6 +44,7 @@ public class OutputStreamFunneler { } } + @Override public void flush() throws IOException { synchronized (OutputStreamFunneler.this) { dieIfClosed(); @@ -51,6 +52,7 @@ public class OutputStreamFunneler { } } + @Override public void write(int b) throws IOException { synchronized (OutputStreamFunneler.this) { dieIfClosed(); @@ -58,6 +60,7 @@ public class OutputStreamFunneler { } } + @Override public void write(byte[] b) throws IOException { synchronized (OutputStreamFunneler.this) { dieIfClosed(); @@ -65,6 +68,7 @@ public class OutputStreamFunneler { } } + @Override public void write(byte[] b, int off, int len) throws IOException { synchronized (OutputStreamFunneler.this) { dieIfClosed(); @@ -72,6 +76,7 @@ public class OutputStreamFunneler { } } + @Override public void close() throws IOException { release(this); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/PackageNameMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/PackageNameMapper.java b/src/main/org/apache/tools/ant/util/PackageNameMapper.java index 3025667..e50906d 100644 --- a/src/main/org/apache/tools/ant/util/PackageNameMapper.java +++ b/src/main/org/apache/tools/ant/util/PackageNameMapper.java @@ -37,6 +37,7 @@ public class PackageNameMapper extends GlobPatternMapper { *@param name Source filename *@return Replaced variable part */ + @Override protected String extractVariablePart(String name) { String var = name.substring(prefixLength, name.length() - postfixLength); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/PropertyOutputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/PropertyOutputStream.java b/src/main/org/apache/tools/ant/util/PropertyOutputStream.java index 59a1b7e..6fdfdbd 100644 --- a/src/main/org/apache/tools/ant/util/PropertyOutputStream.java +++ b/src/main/org/apache/tools/ant/util/PropertyOutputStream.java @@ -19,13 +19,15 @@ package org.apache.tools.ant.util; import java.io.ByteArrayOutputStream; +import java.io.OutputStream; import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.resources.PropertyResource; /** - * Exception thrown when an attempt is made to get an OutputStream - * from an immutable Resource. + * {@link OutputStream} that writes an Ant property. * @since Ant 1.7 + * @see PropertyResource#getOutputStream() */ public class PropertyOutputStream extends ByteArrayOutputStream { private Project project; @@ -58,6 +60,7 @@ public class PropertyOutputStream extends ByteArrayOutputStream { /** * Close the PropertyOutputStream, storing the property. */ + @Override public void close() { if (project != null && property != null) { String s = new String(toByteArray()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ProxySetup.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ProxySetup.java b/src/main/org/apache/tools/ant/util/ProxySetup.java index ea69e72..60f9eb7 100644 --- a/src/main/org/apache/tools/ant/util/ProxySetup.java +++ b/src/main/org/apache/tools/ant/util/ProxySetup.java @@ -95,7 +95,7 @@ public class ProxySetup { * is set, use that instead. Else set to "true". */ public void enableProxies() { - if (!(getSystemProxySetting() != null)) { + if (getSystemProxySetting() == null) { String proxies = owner.getProperty(USE_SYSTEM_PROXIES); if (proxies == null || Project.toBoolean(proxies)) { proxies = "true"; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ReaderInputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ReaderInputStream.java b/src/main/org/apache/tools/ant/util/ReaderInputStream.java index f327b77..be3523d 100644 --- a/src/main/org/apache/tools/ant/util/ReaderInputStream.java +++ b/src/main/org/apache/tools/ant/util/ReaderInputStream.java @@ -60,9 +60,8 @@ public class ReaderInputStream extends InputStream { this(reader); if (encoding == null) { throw new IllegalArgumentException("encoding must not be null"); - } else { - this.encoding = encoding; } + this.encoding = encoding; } /** @@ -72,6 +71,7 @@ public class ReaderInputStream extends InputStream { * * @exception IOException if the original <code>Reader</code> fails to be read */ + @Override public synchronized int read() throws IOException { if (in == null) { throw new IOException("Stream Closed"); @@ -104,6 +104,7 @@ public class ReaderInputStream extends InputStream { * the end of the stream * @exception IOException if an error occurs */ + @Override public synchronized int read(byte[] b, int off, int len) throws IOException { if (in == null) { @@ -144,6 +145,7 @@ public class ReaderInputStream extends InputStream { * @param limit the maximum limit of bytes that can be read before the * mark position becomes invalid */ + @Override public synchronized void mark(final int limit) { try { in.mark(limit); @@ -152,11 +154,11 @@ public class ReaderInputStream extends InputStream { } } - /** * @return the current number of bytes ready for reading * @exception IOException if an error occurs */ + @Override public synchronized int available() throws IOException { if (in == null) { throw new IOException("Stream Closed"); @@ -173,6 +175,7 @@ public class ReaderInputStream extends InputStream { /** * @return false - mark is not supported */ + @Override public boolean markSupported () { return false; // would be imprecise } @@ -182,6 +185,7 @@ public class ReaderInputStream extends InputStream { * * @exception IOException if the Reader fails to be reset */ + @Override public synchronized void reset() throws IOException { if (in == null) { throw new IOException("Stream Closed"); @@ -195,6 +199,7 @@ public class ReaderInputStream extends InputStream { * * @exception IOException if the original Reader fails to be closed */ + @Override public synchronized void close() throws IOException { if (in != null) { in.close(); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ReflectUtil.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ReflectUtil.java b/src/main/org/apache/tools/ant/util/ReflectUtil.java index ed8b47a..27ba8ce 100644 --- a/src/main/org/apache/tools/ant/util/ReflectUtil.java +++ b/src/main/org/apache/tools/ant/util/ReflectUtil.java @@ -21,6 +21,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; @@ -60,12 +62,11 @@ public class ReflectUtil { * @param methodName the name of the method to call * @return the object returned by the method */ - public static Object invoke(Object obj, String methodName) { + @SuppressWarnings("unchecked") + public static <T> T invoke(Object obj, String methodName) { try { - Method method; - method = obj.getClass().getMethod( - methodName, (Class[]) null); - return method.invoke(obj, (Object[]) null); + Method method = obj.getClass().getMethod(methodName); + return (T) method.invoke(obj); } catch (Exception t) { throwBuildException(t); return null; // NotReached @@ -80,12 +81,11 @@ public class ReflectUtil { * @param methodName the name of the method to call * @return the object returned by the method */ - public static Object invokeStatic(Object obj, String methodName) { + @SuppressWarnings("unchecked") + public static <T> T invokeStatic(Object obj, String methodName) { try { - Method method; - method = ((Class<?>) obj).getMethod( - methodName, (Class[]) null); - return method.invoke(obj, (Object[]) null); + Method method = ((Class<?>) obj).getMethod(methodName); + return (T) method.invoke(obj); } catch (Exception t) { throwBuildException(t); return null; // NotReached @@ -100,13 +100,12 @@ public class ReflectUtil { * @param arg the value of the argument. * @return the object returned by the method */ - public static Object invoke( + @SuppressWarnings("unchecked") + public static <T> T invoke( Object obj, String methodName, Class<?> argType, Object arg) { try { - Method method; - method = obj.getClass().getMethod( - methodName, new Class[] {argType}); - return method.invoke(obj, new Object[] {arg}); + Method method = obj.getClass().getMethod(methodName, argType); + return (T) method.invoke(obj, arg); } catch (Exception t) { throwBuildException(t); return null; // NotReached @@ -123,14 +122,14 @@ public class ReflectUtil { * @param arg2 the value of the second argument. * @return the object returned by the method */ - public static Object invoke( + @SuppressWarnings("unchecked") + public static <T> T invoke( Object obj, String methodName, Class<?> argType1, Object arg1, Class<?> argType2, Object arg2) { try { - Method method; - method = obj.getClass().getMethod( - methodName, new Class[] {argType1, argType2}); - return method.invoke(obj, new Object[] {arg1, arg2}); + Method method = + obj.getClass().getMethod(methodName, argType1, argType2); + return (T) method.invoke(obj, arg1, arg2); } catch (Exception t) { throwBuildException(t); return null; // NotReached @@ -144,12 +143,13 @@ public class ReflectUtil { * @return the value of the field. * @throws BuildException if there is an error. */ - public static Object getField(Object obj, String fieldName) + @SuppressWarnings("unchecked") + public static <T> T getField(Object obj, String fieldName) throws BuildException { try { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); - return field.get(obj); + return (T) field.get(obj); } catch (Exception t) { throwBuildException(t); return null; // NotReached @@ -182,9 +182,8 @@ public class ReflectUtil { return (BuildException) t2; } return new BuildException(t2); - } else { - return new BuildException(t); } + return new BuildException(t); } /** @@ -198,13 +197,8 @@ public class ReflectUtil { public static boolean respondsTo(Object o, String methodName) throws BuildException { try { - Method[] methods = o.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(methodName)) { - return true; - } - } - return false; + return Stream.of(o.getClass().getMethods()).map(Method::getName) + .anyMatch(Predicate.isEqual(methodName)); } catch (Exception t) { throw toBuildException(t); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ReflectWrapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ReflectWrapper.java b/src/main/org/apache/tools/ant/util/ReflectWrapper.java index e34363e..f803c88 100644 --- a/src/main/org/apache/tools/ant/util/ReflectWrapper.java +++ b/src/main/org/apache/tools/ant/util/ReflectWrapper.java @@ -28,6 +28,7 @@ import java.lang.reflect.Constructor; public class ReflectWrapper { private Object obj; + /** * Construct a wrapped object using the no arg constructor. * @param loader the classloader to use to construct the class. @@ -35,11 +36,9 @@ public class ReflectWrapper { */ public ReflectWrapper(ClassLoader loader, String name) { try { - Class clazz; - clazz = Class.forName(name, true, loader); - Constructor constructor; - constructor = clazz.getConstructor((Class[]) null); - obj = constructor.newInstance((Object[]) null); + Class<?> clazz = Class.forName(name, true, loader); + Constructor<?> constructor = clazz.getConstructor(); + obj = constructor.newInstance(); } catch (Exception t) { ReflectUtil.throwBuildException(t); } @@ -56,8 +55,9 @@ public class ReflectWrapper { /** * @return the wrapped object. */ - public Object getObject() { - return obj; + @SuppressWarnings("unchecked") + public <T> T getObject() { + return (T) obj; } /** @@ -65,7 +65,7 @@ public class ReflectWrapper { * @param methodName the name of the method to call * @return the object returned by the method */ - public Object invoke(String methodName) { + public <T> T invoke(String methodName) { return ReflectUtil.invoke(obj, methodName); } @@ -76,8 +76,7 @@ public class ReflectWrapper { * @param arg the value of the argument. * @return the object returned by the method */ - public Object invoke( - String methodName, Class argType, Object arg) { + public <T> T invoke(String methodName, Class<?> argType, Object arg) { return ReflectUtil.invoke(obj, methodName, argType, arg); } @@ -90,10 +89,9 @@ public class ReflectWrapper { * @param arg2 the value of the second argument. * @return the object returned by the method */ - public Object invoke( - String methodName, Class argType1, Object arg1, - Class argType2, Object arg2) { - return ReflectUtil.invoke( - obj, methodName, argType1, arg1, argType2, arg2); + public <T> T invoke(String methodName, Class<?> argType1, Object arg1, + Class<?> argType2, Object arg2) { + return ReflectUtil.invoke(obj, methodName, argType1, arg1, argType2, + arg2); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java b/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java index fa620d9..5974847 100644 --- a/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java +++ b/src/main/org/apache/tools/ant/util/RegexpPatternMapper.java @@ -18,7 +18,7 @@ package org.apache.tools.ant.util; -import java.util.Vector; +import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.util.regexp.RegexpMatcher; @@ -77,18 +77,18 @@ public class RegexpPatternMapper implements FileNameMapper { * @param from the from pattern. * @throws BuildException on error. */ + @Override public void setFrom(String from) throws BuildException { - if (from != null) { - try { - reg.setPattern(from); - } catch (NoClassDefFoundError e) { - // depending on the implementation the actual RE won't - // get instantiated in the constructor. - throw new BuildException("Cannot load regular expression matcher", - e); - } - } else { + if (from == null) { throw new BuildException("this mapper requires a 'from' attribute"); + } + try { + reg.setPattern(from); + } catch (NoClassDefFoundError e) { + // depending on the implementation the actual RE won't + // get instantiated in the constructor. + throw new BuildException("Cannot load regular expression matcher", + e); } } @@ -97,12 +97,12 @@ public class RegexpPatternMapper implements FileNameMapper { * @param to the to pattern. * @throws BuildException on error. */ + @Override public void setTo(String to) { - if (to != null) { - this.to = to.toCharArray(); - } else { + if (to == null) { throw new BuildException("this mapper requires a 'to' attribute"); } + this.to = to.toCharArray(); } /** @@ -113,6 +113,7 @@ public class RegexpPatternMapper implements FileNameMapper { * @return a one-element array containing the translated file or * null if the to pattern did not match */ + @Override public String[] mapFileName(String sourceFileName) { if (handleDirSep) { if (sourceFileName.indexOf("\\") != -1) { @@ -123,7 +124,7 @@ public class RegexpPatternMapper implements FileNameMapper { || !reg.matches(sourceFileName, regexpOptions)) { return null; } - return new String[] {replaceReferences(sourceFileName)}; + return new String[] { replaceReferences(sourceFileName) }; } /** @@ -133,7 +134,7 @@ public class RegexpPatternMapper implements FileNameMapper { * @return the translated file name. */ protected String replaceReferences(String source) { - Vector v = reg.getGroups(source, regexpOptions); + List<String> v = reg.getGroups(source, regexpOptions); result.setLength(0); for (int i = 0; i < to.length; i++) { @@ -141,7 +142,7 @@ public class RegexpPatternMapper implements FileNameMapper { if (++i < to.length) { int value = Character.digit(to[i], DECIMAL); if (value > -1) { - result.append((String) v.elementAt(value)); + result.append(v.get(value)); } else { result.append(to[i]); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ResourceUtils.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ResourceUtils.java b/src/main/org/apache/tools/ant/util/ResourceUtils.java index c4532a7..9b246a0 100644 --- a/src/main/org/apache/tools/ant/util/ResourceUtils.java +++ b/src/main/org/apache/tools/ant/util/ResourceUtils.java @@ -28,6 +28,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.nio.channels.FileChannel; +import java.nio.charset.Charset; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Vector; @@ -35,6 +36,7 @@ import java.util.Vector; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.filters.util.ChainReaderHelper; +import org.apache.tools.ant.types.FilterChain; import org.apache.tools.ant.types.FilterSetCollection; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; @@ -142,24 +144,8 @@ public class ResourceUtils { final ResourceFactory targets, final long granularity) { logFuture(logTo, source, granularity); - final ResourceSelectorProvider p = - new ResourceSelectorProvider() { - public ResourceSelector - getTargetSelectorForSource(final Resource sr) { - return new ResourceSelector() { - public boolean isSelected(final Resource target) { - /* Extra I/O, probably wasted: - if (target.isDirectory()) { - return false; - } - */ - return SelectorUtils.isOutOfDate(sr, target, - granularity); - } - }; - } - }; - return selectSources(logTo, source, mapper, targets, p); + return selectSources(logTo, source, mapper, targets, + sr -> target -> SelectorUtils.isOutOfDate(sr, target, granularity)); } /** @@ -181,7 +167,7 @@ public class ResourceUtils { final FileNameMapper mapper, final ResourceFactory targets, final ResourceSelectorProvider selector) { - if (source.size() == 0) { + if (source.isEmpty()) { logTo.log("No sources found.", Project.MSG_VERBOSE); return Resources.NONE; } @@ -301,7 +287,7 @@ public class ResourceUtils { * @since Ant 1.7 */ public static void copyResource(final Resource source, final Resource dest, - final FilterSetCollection filters, final Vector filterChains, + final FilterSetCollection filters, final Vector<FilterChain> filterChains, final boolean overwrite, final boolean preserveLastModified, final String inputEncoding, final String outputEncoding, final Project project) @@ -338,7 +324,7 @@ public class ResourceUtils { * @since Ant 1.8 */ public static void copyResource(final Resource source, final Resource dest, - final FilterSetCollection filters, final Vector filterChains, + final FilterSetCollection filters, final Vector<FilterChain> filterChains, final boolean overwrite, final boolean preserveLastModified, final boolean append, final String inputEncoding, final String outputEncoding, @@ -378,7 +364,7 @@ public class ResourceUtils { * @since Ant 1.8.2 */ public static void copyResource(final Resource source, final Resource dest, - final FilterSetCollection filters, final Vector filterChains, + final FilterSetCollection filters, final Vector<FilterChain> filterChains, final boolean overwrite, final boolean preserveLastModified, final boolean append, final String inputEncoding, final String outputEncoding, @@ -391,8 +377,8 @@ public class ResourceUtils { final boolean filterSetsAvailable = (filters != null && filters.hasFilters()); final boolean filterChainsAvailable = (filterChains != null - && filterChains.size() > 0); - String effectiveInputEncoding = null; + && !filterChains.isEmpty()); + String effectiveInputEncoding; if (source instanceof StringResource) { effectiveInputEncoding = ((StringResource) source).getEncoding(); } else { @@ -405,25 +391,25 @@ public class ResourceUtils { if (destFile != null && destFile.isFile() && !destFile.canWrite()) { if (!force) { throw new ReadOnlyTargetFileException(destFile); - } else if (!FILE_UTILS.tryHardToDelete(destFile)) { - throw new IOException("failed to delete read-only " - + "destination file " + destFile); + } + if (!FILE_UTILS.tryHardToDelete(destFile)) { + throw new IOException( + "failed to delete read-only destination file " + destFile); } } if (filterSetsAvailable) { copyWithFilterSets(source, dest, filters, filterChains, - filterChainsAvailable, append, - effectiveInputEncoding, outputEncoding, - project); + append, effectiveInputEncoding, + outputEncoding, project); } else if (filterChainsAvailable || (effectiveInputEncoding != null && !effectiveInputEncoding.equals(outputEncoding)) || (effectiveInputEncoding == null && outputEncoding != null)) { copyWithFilterChainsOrTranscoding(source, dest, filterChains, - filterChainsAvailable, append, - effectiveInputEncoding, - outputEncoding, project); + append, effectiveInputEncoding, + outputEncoding, + project); } else { boolean copied = false; if (source.as(FileProvider.class) != null @@ -561,9 +547,8 @@ public class ResourceUtils { if (fileProvider instanceof FileResource || fileProvider == null) { return (FileResource) fileProvider; } - final FileResource result = new FileResource(fileProvider.getFile()); - result.setProject(Project.getProject(fileProvider)); - return result; + return new FileResource(Project.getProject(fileProvider), + fileProvider.getFile()); } /** @@ -582,11 +567,9 @@ public class ResourceUtils { * @since Ant 1.7 */ private static int binaryCompare(final Resource r1, final Resource r2) throws IOException { - InputStream in1 = null; - InputStream in2 = null; - try { - in1 = new BufferedInputStream(r1.getInputStream()); - in2 = new BufferedInputStream(r2.getInputStream()); + try (InputStream in1 = new BufferedInputStream(r1.getInputStream()); + InputStream in2 = + new BufferedInputStream(r2.getInputStream())) { for (int b1 = in1.read(); b1 != -1; b1 = in1.read()) { final int b2 = in2.read(); @@ -595,9 +578,6 @@ public class ResourceUtils { } } return in2.read() == -1 ? 0 : -1; - } finally { - FileUtils.close(in1); - FileUtils.close(in2); } } @@ -612,11 +592,10 @@ public class ResourceUtils { * @since Ant 1.7 */ private static int textCompare(final Resource r1, final Resource r2) throws IOException { - BufferedReader in1 = null; - BufferedReader in2 = null; - try { - in1 = new BufferedReader(new InputStreamReader(r1.getInputStream())); - in2 = new BufferedReader(new InputStreamReader(r2.getInputStream())); + try (BufferedReader in1 = + new BufferedReader(new InputStreamReader(r1.getInputStream())); + BufferedReader in2 = new BufferedReader( + new InputStreamReader(r2.getInputStream()))) { String expected = in1.readLine(); while (expected != null) { @@ -630,9 +609,6 @@ public class ResourceUtils { expected = in1.readLine(); } return in2.readLine() == null ? 0 : -1; //NOSONAR - } finally { - FileUtils.close(in1); - FileUtils.close(in2); } } @@ -659,40 +635,18 @@ public class ResourceUtils { private static void copyWithFilterSets(final Resource source, final Resource dest, final FilterSetCollection filters, - final Vector filterChains, - final boolean filterChainsAvailable, - final boolean append, final String inputEncoding, - final String outputEncoding, + final Vector<FilterChain> filterChains, + final boolean append, + final String inputEncoding, final String outputEncoding, final Project project) throws IOException { - BufferedReader in = null; - BufferedWriter out = null; - try { - InputStreamReader isr = null; - if (inputEncoding == null) { - isr = new InputStreamReader(source.getInputStream()); - } else { - isr = new InputStreamReader(source.getInputStream(), - inputEncoding); - } - in = new BufferedReader(isr); - final OutputStream os = getOutputStream(dest, append, project); - OutputStreamWriter osw; - if (outputEncoding == null) { - osw = new OutputStreamWriter(os); - } else { - osw = new OutputStreamWriter(os, outputEncoding); - } - out = new BufferedWriter(osw); - if (filterChainsAvailable) { - final ChainReaderHelper crh = new ChainReaderHelper(); - crh.setBufferSize(FileUtils.BUF_SIZE); - crh.setPrimaryReader(in); - crh.setFilterChains(filterChains); - crh.setProject(project); - final Reader rdr = crh.getAssembledReader(); - in = new BufferedReader(rdr); - } + + try (Reader in = filterWith(project, inputEncoding, filterChains, + source.getInputStream()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter( + getOutputStream(dest, append, project), + charsetFor(outputEncoding)))) { + final LineTokenizer lineTokenizer = new LineTokenizer(); lineTokenizer.setIncludeDelims(true); String newline = null; @@ -708,49 +662,40 @@ public class ResourceUtils { } line = lineTokenizer.getToken(in); } - } finally { - FileUtils.close(out); - FileUtils.close(in); } } + private static Reader filterWith(Project project, String encoding, + Vector<FilterChain> filterChains, InputStream input) { + Reader r = new InputStreamReader(input, charsetFor(encoding)); + if (filterChains != null && !filterChains.isEmpty()) { + final ChainReaderHelper crh = new ChainReaderHelper(); + crh.setBufferSize(FileUtils.BUF_SIZE); + crh.setPrimaryReader(r); + crh.setFilterChains(filterChains); + crh.setProject(project); + r = crh.getAssembledReader(); + } + return new BufferedReader(r); + } + + private static Charset charsetFor(String encoding) { + return encoding == null ? Charset.defaultCharset() : Charset.forName(encoding); + } + private static void copyWithFilterChainsOrTranscoding(final Resource source, final Resource dest, - final Vector filterChains, - final boolean filterChainsAvailable, + final Vector<FilterChain> filterChains, final boolean append, final String inputEncoding, final String outputEncoding, final Project project) throws IOException { - BufferedReader in = null; - BufferedWriter out = null; - try { - InputStreamReader isr = null; - if (inputEncoding == null) { - isr = new InputStreamReader(source.getInputStream()); - } else { - isr = new InputStreamReader(source.getInputStream(), - inputEncoding); - } - in = new BufferedReader(isr); - final OutputStream os = getOutputStream(dest, append, project); - OutputStreamWriter osw; - if (outputEncoding == null) { - osw = new OutputStreamWriter(os); - } else { - osw = new OutputStreamWriter(os, outputEncoding); - } - out = new BufferedWriter(osw); - if (filterChainsAvailable) { - final ChainReaderHelper crh = new ChainReaderHelper(); - crh.setBufferSize(FileUtils.BUF_SIZE); - crh.setPrimaryReader(in); - crh.setFilterChains(filterChains); - crh.setProject(project); - final Reader rdr = crh.getAssembledReader(); - in = new BufferedReader(rdr); - } + try (Reader in = filterWith(project, inputEncoding, filterChains, + source.getInputStream()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter( + getOutputStream(dest, append, project), + charsetFor(outputEncoding)))) { final char[] buffer = new char[FileUtils.BUF_SIZE]; while (true) { final int nRead = in.read(buffer, 0, buffer.length); @@ -759,9 +704,6 @@ public class ResourceUtils { } out.write(buffer, 0, nRead); } - } finally { - FileUtils.close(out); - FileUtils.close(in); } } @@ -776,35 +718,28 @@ public class ResourceUtils { + " for " + destFile); } - FileChannel srcChannel = null; - FileChannel destChannel = null; - - try { - srcChannel = FileChannel.open(sourceFile.toPath(), StandardOpenOption.READ); - destChannel = FileChannel.open(destFile.toPath(), StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); - + try (FileChannel srcChannel = + FileChannel.open(sourceFile.toPath(), StandardOpenOption.READ); + FileChannel destChannel = FileChannel.open(destFile.toPath(), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE)) { long position = 0; final long count = srcChannel.size(); while (position < count) { - final long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); + final long chunk = + Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } - } finally { - FileUtils.close(srcChannel); - FileUtils.close(destChannel); } } private static void copyUsingStreams(final Resource source, final Resource dest, final boolean append, final Project project) throws IOException { - InputStream in = null; - OutputStream out = null; - try { - in = source.getInputStream(); - out = getOutputStream(dest, append, project); + try (InputStream in = source.getInputStream(); + OutputStream out = getOutputStream(dest, append, project)) { final byte[] buffer = new byte[FileUtils.BUF_SIZE]; int count = 0; @@ -812,9 +747,6 @@ public class ResourceUtils { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); - } finally { - FileUtils.close(out); - FileUtils.close(in); } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/util/ScriptFixBSFPath.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/util/ScriptFixBSFPath.java b/src/main/org/apache/tools/ant/util/ScriptFixBSFPath.java index ca76e56..407c5c6 100644 --- a/src/main/org/apache/tools/ant/util/ScriptFixBSFPath.java +++ b/src/main/org/apache/tools/ant/util/ScriptFixBSFPath.java @@ -56,7 +56,7 @@ public class ScriptFixBSFPath { "xslt", "org.apache.xpath.objects.XObject"}; /** A map of languages for which the engine in located in bsf */ - private static final Map BSF_LANGUAGE_MAP = new HashMap(); + private static final Map<String, String> BSF_LANGUAGE_MAP = new HashMap<>(); static { for (int i = 0; i < BSF_LANGUAGES.length; i = i + 2) { BSF_LANGUAGE_MAP.put(BSF_LANGUAGES[i], BSF_LANGUAGES[i + 1]);
