diff options
Diffstat (limited to 'src/main/org/apache/tools/ant/taskdefs/optional')
175 files changed, 4464 insertions, 5434 deletions
diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java index 2ed40e571..2ca244320 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java @@ -118,8 +118,9 @@ public class ANTLR extends Task { * @param superGrammar the super grammar filename * @deprecated since ant 1.6 */ + @Deprecated public void setGlib(String superGrammar) { - String sg = null; + String sg; if (Os.isFamily("dos")) { sg = superGrammar.replace('\\', '/'); } else { @@ -127,6 +128,7 @@ public class ANTLR extends Task { } setGlib(FILE_UTILS.resolveFile(getProject().getBaseDir(), sg)); } + /** * Sets an optional super grammar file * @param superGrammar the super grammar file @@ -135,6 +137,7 @@ public class ANTLR extends Task { public void setGlib(File superGrammar) { this.superGrammar = superGrammar; } + /** * Sets a flag to enable ParseView debugging * @param enable a <code>boolean</code> value @@ -200,7 +203,6 @@ public class ANTLR extends Task { * @param s a <code>boolean</code> value */ public void setFork(boolean s) { - //this.fork = s; } /** @@ -235,6 +237,7 @@ public class ANTLR extends Task { * specify it directly. * @throws BuildException on error */ + @Override public void init() throws BuildException { addClasspathEntry("/antlr/ANTLRGrammarParseBehavior.class"); } @@ -278,6 +281,7 @@ public class ANTLR extends Task { * Execute the task. * @throws BuildException on error */ + @Override public void execute() throws BuildException { validateAttributes(); @@ -302,12 +306,11 @@ public class ANTLR extends Task { int err = run(commandline.getCommandline()); if (err != 0) { throw new BuildException("ANTLR returned: " + err, getLocation()); - } else { - String output = bos.toString(); - if (output.indexOf("error:") > -1) { - throw new BuildException("ANTLR signaled an error: " - + output, getLocation()); - } + } + String output = bos.toString(); + if (output.indexOf("error:") > -1) { + throw new BuildException("ANTLR signaled an error: " + + output, getLocation()); } } else { log("Skipped grammar file. Generated file " + generatedFile @@ -357,7 +360,6 @@ public class ANTLR extends Task { if (targetFile == null || !targetFile.isFile()) { throw new BuildException("Invalid target: " + targetFile); } - // if no output directory is specified, used the target's directory if (outputDirectory == null) { setOutputdirectory(new File(targetFile.getParent())); @@ -369,8 +371,8 @@ public class ANTLR extends Task { private File getGeneratedFile() throws BuildException { String generatedFileName = null; - try { - BufferedReader in = new BufferedReader(new FileReader(targetFile)); + try (BufferedReader in = + new BufferedReader(new FileReader(targetFile))) { String line; while ((line = in.readLine()) != null) { int extendsIndex = line.indexOf(" extends "); @@ -380,7 +382,6 @@ public class ANTLR extends Task { break; } } - in.close(); } catch (Exception e) { throw new BuildException("Unable to determine generated class", e); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java index 11c091a8b..43acdbef1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java @@ -23,7 +23,8 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; -import java.util.Enumeration; +import java.io.PrintWriter; +import java.util.Collections; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -46,9 +47,9 @@ import org.apache.tools.ant.util.FileUtils; public class Cab extends MatchingTask { private static final int DEFAULT_RESULT = -99; + private File cabFile; private File baseDir; - private Vector filesets = new Vector(); private boolean doCompress = true; private boolean doVerbose = false; private String cmdOptions; @@ -59,6 +60,10 @@ public class Cab extends MatchingTask { private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + { + fileset = null; + } + /** * The name/location of where to create the .cab file. * @param cabFile the location of the cab file. @@ -101,13 +106,13 @@ public class Cab extends MatchingTask { /** * Adds a set of files to archive. - * @param set a set of files to archive. + * @param fileset a set of files to archive. */ - public void addFileset(FileSet set) { - if (filesets.size() > 0) { + public void addFileset(FileSet fileset) { + if (fileset != null) { throw new BuildException("Only one nested fileset allowed"); } - filesets.addElement(set); + this.fileset = fileset; } /* @@ -120,15 +125,15 @@ public class Cab extends MatchingTask { * @throws BuildException on error. */ protected void checkConfiguration() throws BuildException { - if (baseDir == null && filesets.size() == 0) { - throw new BuildException("basedir attribute or one " - + "nested fileset is required!", - getLocation()); + if (baseDir == null && fileset == null) { + throw new BuildException( + "basedir attribute or one nested fileset is required!", + getLocation()); } if (baseDir != null && !baseDir.exists()) { throw new BuildException("basedir does not exist!", getLocation()); } - if (baseDir != null && filesets.size() > 0) { + if (baseDir != null && fileset != null) { throw new BuildException( "Both basedir attribute and a nested fileset is not allowed"); } @@ -145,8 +150,7 @@ public class Cab extends MatchingTask { * @throws BuildException on error. */ protected ExecTask createExec() throws BuildException { - ExecTask exec = new ExecTask(this); - return exec; + return new ExecTask(this); } /** @@ -154,17 +158,10 @@ public class Cab extends MatchingTask { * @param files the list of files to check. * @return true if the cab file is newer than its dependents. */ - protected boolean isUpToDate(Vector files) { - boolean upToDate = true; - final int size = files.size(); - for (int i = 0; i < size && upToDate; i++) { - String file = files.elementAt(i).toString(); - if (FILE_UTILS.resolveFile(baseDir, file).lastModified() - > cabFile.lastModified()) { - upToDate = false; - } - } - return upToDate; + protected boolean isUpToDate(Vector<String> files) { + final long cabModified = cabFile.lastModified(); + return files.stream().map(f -> FILE_UTILS.resolveFile(baseDir, f)) + .mapToLong(File::lastModified).allMatch(t -> t < cabModified); } /** @@ -177,23 +174,15 @@ public class Cab extends MatchingTask { * @return the list file created. * @throws IOException if there is an error. */ - protected File createListFile(Vector files) + protected File createListFile(Vector<String> files) throws IOException { File listFile = FILE_UTILS.createTempFile("ant", "", null, true, true); - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(listFile)); - - final int size = files.size(); - for (int i = 0; i < size; i++) { - writer.write('\"' + files.elementAt(i).toString() + '\"'); - writer.newLine(); - } - } finally { - FileUtils.close(writer); + try (PrintWriter writer = + new PrintWriter(new BufferedWriter(new FileWriter(listFile)))) { + files.stream().map(f -> String.format("\"%s\"", f)) + .forEach(writer::println); } - return listFile; } @@ -202,12 +191,8 @@ public class Cab extends MatchingTask { * @param files the vector to append the files to. * @param ds the scanner to get the files from. */ - protected void appendFiles(Vector files, DirectoryScanner ds) { - String[] dsfiles = ds.getIncludedFiles(); - - for (int i = 0; i < dsfiles.length; i++) { - files.addElement(dsfiles[i]); - } + protected void appendFiles(Vector<String> files, DirectoryScanner ds) { + Collections.addAll(files, ds.getIncludedFiles()); } /** @@ -217,18 +202,16 @@ public class Cab extends MatchingTask { * @return the list of files. * @throws BuildException if there is an error. */ - protected Vector getFileList() throws BuildException { - Vector files = new Vector(); + protected Vector<String> getFileList() throws BuildException { + Vector<String> files = new Vector<>(); if (baseDir != null) { // get files from old methods - includes and nested include appendFiles(files, super.getDirectoryScanner(baseDir)); } else { - FileSet fs = (FileSet) filesets.elementAt(0); - baseDir = fs.getDir(); - appendFiles(files, fs.getDirectoryScanner(getProject())); + baseDir = fileset.getDir(); + appendFiles(files, fileset.getDirectoryScanner(getProject())); } - return files; } @@ -236,11 +219,12 @@ public class Cab extends MatchingTask { * execute this task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { checkConfiguration(); - Vector files = getFileList(); + Vector<String> files = getFileList(); // quick exit if the target is up to date if (isUpToDate(files)) { @@ -252,21 +236,17 @@ public class Cab extends MatchingTask { if (!Os.isFamily("windows")) { log("Using listcab/libcabinet", Project.MSG_VERBOSE); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); - Enumeration fileEnum = files.elements(); + files.forEach(f -> sb.append(f).append("\n")); - while (fileEnum.hasMoreElements()) { - sb.append(fileEnum.nextElement()).append("\n"); - } sb.append("\n").append(cabFile.getAbsolutePath()).append("\n"); try { Process p = Execute.launch(getProject(), - new String[] {"listcab"}, null, - baseDir != null ? baseDir - : getProject().getBaseDir(), - true); + new String[] { "listcab" }, null, + baseDir != null ? baseDir : getProject().getBaseDir(), + true); OutputStream out = p.getOutputStream(); // Create the stream pumpers to forward listcab's stdout and stderr to the log @@ -278,8 +258,8 @@ public class Cab extends MatchingTask { StreamPumper errPump = new StreamPumper(p.getErrorStream(), errLog); // Pump streams asynchronously - (new Thread(outPump)).start(); - (new Thread(errPump)).start(); + new Thread(outPump).start(); + new Thread(errPump).start(); out.write(sb.toString().getBytes()); out.flush(); @@ -306,8 +286,9 @@ public class Cab extends MatchingTask { log("Error executing listcab; error code: " + result); } } catch (IOException ex) { - String msg = "Problem creating " + cabFile + " " + ex.getMessage(); - throw new BuildException(msg, getLocation()); + throw new BuildException( + "Problem creating " + cabFile + " " + ex.getMessage(), + getLocation()); } } else { try { @@ -349,8 +330,9 @@ public class Cab extends MatchingTask { listFile.delete(); } catch (IOException ioe) { - String msg = "Problem creating " + cabFile + " " + ioe.getMessage(); - throw new BuildException(msg, getLocation()); + throw new BuildException( + "Problem creating " + cabFile + " " + ioe.getMessage(), + getLocation()); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java index f6681f8b1..8132f36ae 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java @@ -17,7 +17,6 @@ */ package org.apache.tools.ant.taskdefs.optional; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -31,25 +30,25 @@ import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.Vector; - +import java.util.function.Function; +import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.LogOutputStream; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.PropertySet; -import org.apache.tools.ant.util.CollectionUtils; import org.apache.tools.ant.util.DOMElementWriter; -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.JavaEnvUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -127,7 +126,7 @@ public class EchoProperties extends Task { */ private boolean failonerror = true; - private Vector propertySets = new Vector(); + private List<PropertySet> propertySets = new Vector<>(); private String format = "text"; @@ -157,7 +156,6 @@ public class EchoProperties extends Task { this.destfile = destfile; } - /** * If true, the task will fail if an error occurs writing the properties * file, otherwise errors are just logged. @@ -169,7 +167,6 @@ public class EchoProperties extends Task { this.failonerror = failonerror; } - /** * If the prefix is set, then only properties which start with this * prefix string will be recorded. If regex is not set and if this @@ -209,7 +206,7 @@ public class EchoProperties extends Task { * @since Ant 1.7 */ public void setRegex(String regex) { - if (regex != null && regex.length() != 0) { + if (!(regex == null || regex.isEmpty())) { this.regex = regex; PropertySet ps = new PropertySet(); ps.setProject(getProject()); @@ -224,7 +221,7 @@ public class EchoProperties extends Task { * @since Ant 1.6 */ public void addPropertyset(PropertySet ps) { - propertySets.addElement(ps); + propertySets.add(ps); } /** @@ -240,12 +237,13 @@ public class EchoProperties extends Task { * The values are "xml" and "text". */ public static class FormatAttribute extends EnumeratedAttribute { - private String [] formats = new String[]{"xml", "text"}; + private String[] formats = new String[] { "xml", "text" }; /** * @see EnumeratedAttribute#getValues() * @return accepted values */ + @Override public String[] getValues() { return formats; } @@ -256,27 +254,28 @@ public class EchoProperties extends Task { * *@exception BuildException trouble, probably file IO */ + @Override public void execute() throws BuildException { if (prefix != null && regex != null) { - throw new BuildException("Please specify either prefix" - + " or regex, but not both", getLocation()); + throw new BuildException( + "Please specify either prefix or regex, but not both", + getLocation()); } //copy the properties file - Hashtable allProps = new Hashtable(); + Hashtable<Object, Object> allProps = new Hashtable<>(); /* load properties from file if specified, otherwise use Ant's properties */ - if (inFile == null && propertySets.size() == 0) { + if (inFile == null && propertySets.isEmpty()) { // add ant properties allProps.putAll(getProject().getProperties()); } else if (inFile != null) { - if (inFile.exists() && inFile.isDirectory()) { + if (inFile.isDirectory()) { String message = "srcfile is a directory!"; if (failonerror) { throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); } + log(message, Project.MSG_ERR); return; } @@ -290,9 +289,7 @@ public class EchoProperties extends Task { return; } - InputStream in = null; - try { - in = Files.newInputStream(inFile.toPath()); + try (InputStream in = Files.newInputStream(inFile.toPath())) { Properties props = new Properties(); props.load(in); allProps.putAll(props); @@ -301,72 +298,35 @@ public class EchoProperties extends Task { "Could not find file " + inFile.getAbsolutePath(); if (failonerror) { throw new BuildException(message, fnfe, getLocation()); - } else { - log(message, Project.MSG_WARN); } + log(message, Project.MSG_WARN); return; } catch (IOException ioe) { String message = "Could not read file " + inFile.getAbsolutePath(); if (failonerror) { throw new BuildException(message, ioe, getLocation()); - } else { - log(message, Project.MSG_WARN); } + log(message, Project.MSG_WARN); return; - } finally { - FileUtils.close(in); } } - Enumeration e = propertySets.elements(); - while (e.hasMoreElements()) { - PropertySet ps = (PropertySet) e.nextElement(); - allProps.putAll(ps.getProperties()); - } - - OutputStream os = null; - try { - if (destfile == null) { - os = new ByteArrayOutputStream(); - saveProperties(allProps, os); - log(os.toString(), Project.MSG_INFO); - } else { - if (destfile.exists() && destfile.isDirectory()) { - String message = "destfile is a directory!"; - if (failonerror) { - throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); - } - return; - } + propertySets.stream().map(PropertySet::getProperties) + .forEach(allProps::putAll); - if (destfile.exists() && !destfile.canWrite()) { - String message = - "Can not write to the specified destfile!"; - if (failonerror) { - throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); - } - return; - } - os = Files.newOutputStream(this.destfile.toPath()); + try (OutputStream os = createOutputStream()) { + if (os != null) { saveProperties(allProps, os); } } catch (IOException ioe) { if (failonerror) { throw new BuildException(ioe, getLocation()); - } else { - log(ioe.getMessage(), Project.MSG_INFO); } - } finally { - FileUtils.close(os); + log(ioe.getMessage(), Project.MSG_INFO); } } - /** * Send the key/value pairs in the hashtable to the given output stream. * Only those properties matching the <tt>prefix</tt> constraint will be @@ -378,37 +338,37 @@ public class EchoProperties extends Task { * @throws IOException on output errors * @throws BuildException on other errors */ - protected void saveProperties(Hashtable allProps, OutputStream os) + protected void saveProperties(Hashtable<Object, Object> allProps, OutputStream os) throws IOException, BuildException { - final List keyList = new ArrayList(allProps.keySet()); - Collections.sort(keyList); + final List<Object> keyList = new ArrayList<>(allProps.keySet()); + Properties props = new Properties() { private static final long serialVersionUID = 5090936442309201654L; - public Enumeration keys() { - return CollectionUtils.asEnumeration(keyList.iterator()); + + @Override + public Enumeration<Object> keys() { + return keyList.stream() + .sorted(Comparator.comparing(Object::toString)) + .collect(Collectors.collectingAndThen(Collectors.toList(), + Collections::enumeration)); } - public Set entrySet() { - Set result = super.entrySet(); + + @Override + public Set<Map.Entry<Object,Object>> entrySet() { + Set<Map.Entry<Object, Object>> result = super.entrySet(); if (JavaEnvUtils.isKaffe()) { - TreeSet t = new TreeSet(new Comparator() { - public int compare(Object o1, Object o2) { - String key1 = (String) ((Map.Entry) o1).getKey(); - String key2 = (String) ((Map.Entry) o2).getKey(); - return key1.compareTo(key2); - } - }); + Set<Map.Entry<Object, Object>> t = + new TreeSet<>(Comparator.comparing( + ((Function<Map.Entry<Object, Object>, Object>) Map.Entry::getKey) + .andThen(Object::toString))); t.addAll(result); - result = t; + return t; } return result; } }; - final int size = keyList.size(); - for (int i = 0; i < size; i++) { - String name = keyList.get(i).toString(); - String value = allProps.get(name).toString(); - props.setProperty(name, value); - } + allProps.forEach((k, v) -> props.put(String.valueOf(k), String.valueOf(v))); + if ("text".equals(format)) { jdkSaveProperties(props, os, "Ant properties"); } else if ("xml".equals(format)) { @@ -419,7 +379,7 @@ public class EchoProperties extends Task { /** * a tuple for the sort list. */ - private static final class Tuple implements Comparable { + private static final class Tuple implements Comparable<Tuple> { private String key; private String value; @@ -436,9 +396,9 @@ public class EchoProperties extends Task { * @throws ClassCastException if the specified object's type prevents it * from being compared to this Object. */ - public int compareTo(Object o) { - Tuple that = (Tuple) o; - return key.compareTo(that.key); + @Override + public int compareTo(Tuple o) { + return Comparator.<String> naturalOrder().compare(key, o.key); } @Override @@ -450,26 +410,21 @@ public class EchoProperties extends Task { return false; } Tuple that = (Tuple) o; - return (key == null ? that.key == null : key.equals(that.key)) - && (value == null ? that.value == null : value.equals(that.value)); + return Objects.equals(key, that.key) + && Objects.equals(value, that.value); } @Override public int hashCode() { - return key != null ? key.hashCode() : 0; + return Objects.hash(key); } } - private List sortProperties(Properties props) { + private List<Tuple> sortProperties(Properties props) { //sort the list. Makes SCM and manual diffs easier. - List sorted = new ArrayList(props.size()); - Enumeration e = props.propertyNames(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - sorted.add(new Tuple(name, props.getProperty(name))); - } - Collections.sort(sorted); - return sorted; + return props.stringPropertyNames().stream() + .map(k -> new Tuple(k, props.getProperty(k))).sorted() + .collect(Collectors.toList()); } /** @@ -484,29 +439,22 @@ public class EchoProperties extends Task { Document doc = getDocumentBuilder().newDocument(); Element rootElement = doc.createElement(PROPERTIES); - List sorted = sortProperties(props); - + List<Tuple> sorted = sortProperties(props); // output properties - Iterator iten = sorted.iterator(); - while (iten.hasNext()) { - Tuple tuple = (Tuple) iten.next(); + for (Tuple tuple : sorted) { Element propElement = doc.createElement(PROPERTY); propElement.setAttribute(ATTR_NAME, tuple.key); propElement.setAttribute(ATTR_VALUE, tuple.value); rootElement.appendChild(propElement); } - Writer wri = null; - try { - wri = new OutputStreamWriter(os, "UTF8"); + try (Writer wri = new OutputStreamWriter(os, "UTF8")) { wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - (new DOMElementWriter()).write(rootElement, wri, 0, "\t"); + new DOMElementWriter().write(rootElement, wri, 0, "\t"); wri.flush(); } catch (IOException ioe) { throw new BuildException("Unable to write XML file", ioe); - } finally { - FileUtils.close(wri); } } @@ -524,7 +472,6 @@ public class EchoProperties extends Task { String header) throws IOException { try { props.store(os, header); - } catch (IOException ioe) { throw new BuildException(ioe, getLocation()); } finally { @@ -538,6 +485,29 @@ public class EchoProperties extends Task { } } + private OutputStream createOutputStream() throws IOException { + if (destfile == null) { + return new LogOutputStream(this); + } + if (destfile.exists() && destfile.isDirectory()) { + String message = "destfile is a directory!"; + if (failonerror) { + throw new BuildException(message, getLocation()); + } + log(message, Project.MSG_ERR); + return null; + } + if (destfile.exists() && !destfile.canWrite()) { + String message = + "Can not write to the specified destfile!"; + if (failonerror) { + throw new BuildException(message, getLocation()); + } + log(message, Project.MSG_ERR); + return null; + } + return Files.newOutputStream(this.destfile.toPath()); + } /** * Uses the DocumentBuilderFactory to get a DocumentBuilder instance. @@ -552,4 +522,3 @@ public class EchoProperties extends Task { } } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java index 06e1d110d..dd3e107e6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java @@ -19,10 +19,11 @@ package org.apache.tools.ant.taskdefs.optional; import java.io.File; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.StringTokenizer; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import java.util.Vector; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -70,7 +71,7 @@ import org.apache.tools.ant.util.facade.ImplementationSpecificArgument; public class Javah extends Task { - private Vector classes = new Vector(2); + private List<ClassArgument> classes = new Vector<>(2); private String cls; private File destDir; private Path classpath = null; @@ -80,9 +81,8 @@ public class Javah extends Task { private boolean old = false; private boolean stubs = false; private Path bootclasspath; - //private Path extdirs; private FacadeTaskHelper facade = null; - private Vector files = new Vector(); + private Vector<FileSet> files = new Vector<>(); private JavahAdapter nestedAdapter = null; /** @@ -106,7 +106,7 @@ public class Javah extends Task { */ public ClassArgument createClass() { ClassArgument ga = new ClassArgument(); - classes.addElement(ga); + classes.add(ga); return ga; } @@ -117,10 +117,6 @@ public class Javah extends Task { public class ClassArgument { private String name; - /** Constructor for ClassArgument. */ - public ClassArgument() { - } - /** * Set the name attribute. * @param name the name attribute. @@ -152,33 +148,21 @@ public class Javah extends Task { * @since Ant 1.6.3 */ public String[] getClasses() { - ArrayList al = new ArrayList(); + Stream<String> stream = Stream.concat( + files.stream() + .map(fs -> fs.getDirectoryScanner(getProject()) + .getIncludedFiles()) + .flatMap(Stream::of) + .map(s -> s.replace('\\', '.').replace('/', '.') + .replaceFirst("\\.class$", "")), + classes.stream().map(ClassArgument::getName)); + if (cls != null) { - StringTokenizer tok = new StringTokenizer(cls, ",", false); - while (tok.hasMoreTokens()) { - al.add(tok.nextToken().trim()); - } + stream = Stream.concat(Stream.of(cls.split(",")).map(String::trim), + stream); } - if (files.size() > 0) { - for (Enumeration e = files.elements(); e.hasMoreElements();) { - FileSet fs = (FileSet) e.nextElement(); - String[] includedClasses = fs.getDirectoryScanner( - getProject()).getIncludedFiles(); - for (int i = 0; i < includedClasses.length; i++) { - String className = - includedClasses[i].replace('\\', '.').replace('/', '.') - .substring(0, includedClasses[i].length() - 6); - al.add(className); - } - } - } - Enumeration e = classes.elements(); - while (e.hasMoreElements()) { - ClassArgument arg = (ClassArgument) e.nextElement(); - al.add(arg.getName()); - } - return (String[]) al.toArray(new String[al.size()]); + return stream.toArray(String[]::new); } /** @@ -423,8 +407,7 @@ public class Javah extends Task { */ public void add(JavahAdapter adapter) { if (nestedAdapter != null) { - throw new BuildException("Can't have more than one javah" - + " adapter"); + throw new BuildException("Can't have more than one javah adapter"); } nestedAdapter = adapter; } @@ -434,17 +417,22 @@ public class Javah extends Task { * * @throws BuildException is there is a problem in the task execution. */ + @Override public void execute() throws BuildException { // first off, make sure that we've got a srcdir + final Set<Settings> settings = EnumSet.noneOf(Settings.class); - if ((cls == null) && (classes.size() == 0) && (files.size() == 0)) { - throw new BuildException("class attribute must be set!", - getLocation()); + if (cls != null) { + settings.add(Settings.cls); } - - if ((cls != null) && (classes.size() > 0) && (files.size() > 0)) { - throw new BuildException("set class attribute OR class element OR fileset, " - + "not 2 or more of them.", getLocation()); + if (!classes.isEmpty()) { + settings.add(Settings.classes); + } + if (!files.isEmpty()) { + settings.add(Settings.files); + } + if (settings.size() > 1) { + throw new BuildException("Exactly one of " + Settings.values() + " attributes is required", getLocation()); } if (destDir != null) { @@ -459,7 +447,7 @@ public class Javah extends Task { } if (classpath == null) { - classpath = (new Path(getProject())).concatSystemClasspath("last"); + classpath = new Path(getProject()).concatSystemClasspath("last"); } else { classpath = classpath.concatSystemClasspath("ignore"); } @@ -492,22 +480,21 @@ public class Javah extends Task { log("Compilation " + cmd.describeArguments(), Project.MSG_VERBOSE); - StringBuffer niceClassList = new StringBuffer(); String[] c = getClasses(); - for (int i = 0; i < c.length; i++) { - cmd.createArgument().setValue(c[i]); - niceClassList.append(" "); - niceClassList.append(c[i]); - niceClassList.append(StringUtils.LINE_SEP); - } - - StringBuffer prefix = new StringBuffer("Class"); + StringBuilder message = new StringBuilder("Class"); if (c.length > 1) { - prefix.append("es"); + message.append("es"); + } + message.append(" to be compiled:"); + message.append(StringUtils.LINE_SEP); + for (String element : c) { + cmd.createArgument().setValue(element); + message.append(" ").append(element).append(StringUtils.LINE_SEP); } - prefix.append(" to be compiled:"); - prefix.append(StringUtils.LINE_SEP); + log(message.toString(), Project.MSG_VERBOSE); + } - log(prefix.toString() + niceClassList.toString(), Project.MSG_VERBOSE); + private enum Settings { + cls, files, classes; } }
\ No newline at end of file diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java index 81a386fd2..e76197530 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Native2Ascii.java @@ -192,8 +192,8 @@ public class Native2Ascii extends MatchingTask { */ public void add(Native2AsciiAdapter adapter) { if (nestedAdapter != null) { - throw new BuildException("Can't have more than one native2ascii" - + " adapter"); + throw new BuildException( + "Can't have more than one native2ascii adapter"); } nestedAdapter = adapter; } @@ -203,6 +203,7 @@ public class Native2Ascii extends MatchingTask { * * @throws BuildException is there is a problem in the task execution. */ + @Override public void execute() throws BuildException { DirectoryScanner scanner = null; // Scanner to find our inputs @@ -222,11 +223,11 @@ public class Native2Ascii extends MatchingTask { // to be set, so we don't stomp every file. One could still // include a file with the same extension, but .... if (srcDir.equals(destDir) && extension == null && mapper == null) { - throw new BuildException("The ext attribute or a mapper must be set if" - + " src and dest dirs are the same."); + throw new BuildException( + "The ext attribute or a mapper must be set if src and dest dirs are the same."); } - FileNameMapper m = null; + FileNameMapper m; if (mapper == null) { if (extension == null) { m = new IdentityMapper(); @@ -270,8 +271,7 @@ public class Native2Ascii extends MatchingTask { // Make sure we're not about to clobber something if (srcFile.equals(destFile)) { - throw new BuildException("file " + srcFile - + " would overwrite its self"); + throw new BuildException("file %s would overwrite itself", srcFile); } // Make intermediate directories if needed @@ -282,8 +282,8 @@ public class Native2Ascii extends MatchingTask { if (!parentFile.exists() && !(parentFile.mkdirs() || parentFile.isDirectory())) { - throw new BuildException("cannot create parent directory " - + parentName); + throw new BuildException("cannot create parent directory %s", + parentName); } } @@ -310,19 +310,22 @@ public class Native2Ascii extends MatchingTask { private class ExtMapper implements FileNameMapper { + @Override public void setFrom(String s) { } + + @Override public void setTo(String s) { } + @Override public String[] mapFileName(String fileName) { int lastDot = fileName.lastIndexOf('.'); if (lastDot >= 0) { - return new String[] {fileName.substring(0, lastDot) - + extension}; - } else { - return new String[] {fileName + extension}; + return new String[] { + fileName.substring(0, lastDot) + extension }; } + return new String[] { fileName + extension }; } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java index 21440f1e6..9c6da4a32 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/NetRexxC.java @@ -23,11 +23,14 @@ import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; -import java.util.Enumeration; +import java.util.ArrayList; import java.util.Hashtable; +import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; +import java.util.stream.Collectors; +import java.util.stream.Stream; import netrexx.lang.Rexx; @@ -143,8 +146,8 @@ public class NetRexxC extends MatchingTask { static final String MSG_DEPRECATION = "has been deprecated"; // other implementation variables - private Vector compileList = new Vector(); - private Hashtable filecopyList = new Hashtable(); + private Vector<String> compileList = new Vector<>(); + private Hashtable<String, String> filecopyList = new Hashtable<>(); /** * Set whether literals are treated as binary, rather than NetRexx types. @@ -156,7 +159,6 @@ public class NetRexxC extends MatchingTask { this.binary = binary; } - /** * Set the classpath used for NetRexx compilation. * @param classpath the classpath to use. @@ -165,7 +167,6 @@ public class NetRexxC extends MatchingTask { this.classpath = classpath; } - /** * Set whether comments are passed through to the generated java source. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -176,7 +177,6 @@ public class NetRexxC extends MatchingTask { this.comments = comments; } - /** * Set whether error messages come out in compact or verbose format. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -187,7 +187,6 @@ public class NetRexxC extends MatchingTask { this.compact = compact; } - /** * Set whether the NetRexx compiler should compile the generated java code. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -202,7 +201,6 @@ public class NetRexxC extends MatchingTask { } } - /** * Set whether or not compiler messages should be displayed on the 'console'. * Note that this task will rely on the default value for filtering compile messages. @@ -214,7 +212,6 @@ public class NetRexxC extends MatchingTask { this.console = console; } - /** * Whether variable cross references are generated. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -225,7 +222,6 @@ public class NetRexxC extends MatchingTask { this.crossref = crossref; } - /** * Set whether decimal arithmetic should be used for the netrexx code. * Setting this to off will report decimal arithmetic as an error, for @@ -238,7 +234,6 @@ public class NetRexxC extends MatchingTask { this.decimal = decimal; } - /** * Set the destination directory into which the NetRexx source files * should be copied and then compiled. @@ -248,7 +243,6 @@ public class NetRexxC extends MatchingTask { destDir = destDirName; } - /** * Whether diagnostic information about the compile is generated * @param diag a <code>boolean</code> value. @@ -257,7 +251,6 @@ public class NetRexxC extends MatchingTask { this.diag = diag; } - /** * Sets whether variables must be declared explicitly before use. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -268,7 +261,6 @@ public class NetRexxC extends MatchingTask { this.explicit = explicit; } - /** * Whether the generated java code is formatted nicely or left to match * NetRexx line numbers for call stack debugging. @@ -280,7 +272,6 @@ public class NetRexxC extends MatchingTask { this.format = format; } - /** * Whether the generated java code is produced. * This is not implemented yet. @@ -290,7 +281,6 @@ public class NetRexxC extends MatchingTask { log("The attribute java is currently unused.", Project.MSG_WARN); } - /** * Sets whether the generated java source file should be kept after * compilation. The generated files will have an extension of .java.keep, @@ -304,7 +294,6 @@ public class NetRexxC extends MatchingTask { this.keep = keep; } - /** * Whether the compiler text logo is displayed when compiling. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -315,7 +304,6 @@ public class NetRexxC extends MatchingTask { this.logo = logo; } - /** * Whether the generated .java file should be replaced when compiling. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -326,7 +314,6 @@ public class NetRexxC extends MatchingTask { this.replace = replace; } - /** * Sets whether the compiler messages will be written to NetRexxC.log as * well as to the console. @@ -338,7 +325,6 @@ public class NetRexxC extends MatchingTask { this.savelog = savelog; } - /** * Tells the NetRexx compiler to store the class files in the same * directory as the source files. The alternative is the working directory. @@ -350,7 +336,6 @@ public class NetRexxC extends MatchingTask { this.sourcedir = sourcedir; } - /** * Set the source dir to find the source Java files. * @param srcDirName the source directory. @@ -359,7 +344,6 @@ public class NetRexxC extends MatchingTask { srcDir = srcDirName; } - /** * Tells the NetRexx compiler that method calls always need parentheses, * even if no arguments are needed, e.g. <code>aStringVar.getBytes</code> @@ -372,7 +356,6 @@ public class NetRexxC extends MatchingTask { this.strictargs = strictargs; } - /** * Tells the NetRexx compile that assignments must match exactly on type. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -383,7 +366,6 @@ public class NetRexxC extends MatchingTask { this.strictassign = strictassign; } - /** * Specifies whether the NetRexx compiler should be case sensitive or not. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -394,7 +376,6 @@ public class NetRexxC extends MatchingTask { this.strictcase = strictcase; } - /** * Sets whether classes need to be imported explicitly using an <code>import</code> * statement. By default the NetRexx compiler will import certain packages @@ -407,7 +388,6 @@ public class NetRexxC extends MatchingTask { this.strictimport = strictimport; } - /** * Sets whether local properties need to be qualified explicitly using * <code>this</code>. @@ -419,7 +399,6 @@ public class NetRexxC extends MatchingTask { this.strictprops = strictprops; } - /** * Whether the compiler should force catching of exceptions by explicitly * named types. @@ -431,7 +410,6 @@ public class NetRexxC extends MatchingTask { this.strictsignal = strictsignal; } - /** * Sets whether debug symbols should be generated into the class file. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -442,7 +420,6 @@ public class NetRexxC extends MatchingTask { this.symbols = symbols; } - /** * Asks the NetRexx compiler to print compilation times to the console * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -471,12 +448,10 @@ public class NetRexxC extends MatchingTask { */ public void setTrace(String trace) { TraceAttr t = new TraceAttr(); - t.setValue(trace); setTrace(t); } - /** * Tells the NetRexx compiler that the source is in UTF8. * Valid true values are "yes", "on" or "true". Anything else sets the flag to false. @@ -487,7 +462,6 @@ public class NetRexxC extends MatchingTask { this.utf8 = utf8; } - /** * Whether lots of warnings and error messages should be generated * @param verbose the value to set - verbose<level> or noverbose. @@ -496,14 +470,12 @@ public class NetRexxC extends MatchingTask { this.verbose = verbose.getValue(); } - /** * Whether lots of warnings and error messages should be generated * @param verbose the value to set - verbose<level> or noverbose. */ public void setVerbose(String verbose) { VerboseAttr v = new VerboseAttr(); - v.setValue(verbose); setVerbose(v); } @@ -518,7 +490,6 @@ public class NetRexxC extends MatchingTask { this.suppressMethodArgumentNotUsed = suppressMethodArgumentNotUsed; } - /** * Whether the task should suppress the "Private property is defined but * not used" in strictargs-Mode, which can be quite annoying while @@ -529,7 +500,6 @@ public class NetRexxC extends MatchingTask { this.suppressPrivatePropertyNotUsed = suppressPrivatePropertyNotUsed; } - /** * Whether the task should suppress the "Variable is set but not used" in * strictargs-Mode. Be careful with this one! The warning is logged as @@ -540,7 +510,6 @@ public class NetRexxC extends MatchingTask { this.suppressVariableNotUsed = suppressVariableNotUsed; } - /** * Whether the task should suppress the "FooException is in SIGNALS list * but is not signalled within the method", which is sometimes rather @@ -551,7 +520,6 @@ public class NetRexxC extends MatchingTask { this.suppressExceptionNotSignalled = suppressExceptionNotSignalled; } - /** * Tells whether we should filter out any deprecation-messages * of the compiler out. @@ -561,7 +529,6 @@ public class NetRexxC extends MatchingTask { this.suppressDeprecation = suppressDeprecation; } - /** * Tells whether the trailing .keep in nocompile-mode should be removed * so that the resulting java source really ends on .java. @@ -571,12 +538,12 @@ public class NetRexxC extends MatchingTask { this.removeKeepExtension = removeKeepExtension; } - /** * init-Method sets defaults from Properties. That way, when ant is called * with arguments like -Dant.netrexxc.verbose=verbose5 one can easily take * control of all netrexxc-tasks. */ + @Override public void init() { String p; @@ -681,11 +648,11 @@ public class NetRexxC extends MatchingTask { } } - /** * Executes the task - performs the actual compiler call. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { // first off, make sure that we've got a srcdir and destdir @@ -695,7 +662,6 @@ public class NetRexxC extends MatchingTask { // scan source and dest dirs to build up both copy lists and // compile lists - // scanDir(srcDir, destDir); DirectoryScanner ds = getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); @@ -706,7 +672,7 @@ public class NetRexxC extends MatchingTask { copyFilesToDestination(); // compile the source files - if (compileList.size() > 0) { + if (!compileList.isEmpty()) { log("Compiling " + compileList.size() + " source file" + (compileList.size() == 1 ? "" : "s") + " to " + destDir); @@ -717,16 +683,14 @@ public class NetRexxC extends MatchingTask { } } - /** * Scans the directory looking for source files to be compiled and support * files to be copied. */ private void scanDir(File srcDir, File destDir, String[] files) { - for (int i = 0; i < files.length; i++) { - File srcFile = new File(srcDir, files[i]); - File destFile = new File(destDir, files[i]); - String filename = files[i]; + for (String filename : files) { + File srcFile = new File(srcDir, filename); + File destFile = new File(destDir, filename); // if it's a non source file, copy it if a later date than the // dest // if it's a source file, see if the destination class file @@ -749,113 +713,80 @@ public class NetRexxC extends MatchingTask { filecopyList.put(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); compileList.addElement(destFile.getAbsolutePath()); } - } else { - if (srcFile.lastModified() > destFile.lastModified()) { - filecopyList.put(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); - } + } else if (srcFile.lastModified() > destFile.lastModified()) { + filecopyList.put(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); } } } - /** Copy eligible files from the srcDir to destDir */ private void copyFilesToDestination() { - if (filecopyList.size() > 0) { + if (!filecopyList.isEmpty()) { log("Copying " + filecopyList.size() + " file" + (filecopyList.size() == 1 ? "" : "s") + " to " + destDir.getAbsolutePath()); - Enumeration e = filecopyList.keys(); - - while (e.hasMoreElements()) { - String fromFile = (String) e.nextElement(); - String toFile = (String) filecopyList.get(fromFile); - + filecopyList.forEach((fromFile, toFile) -> { try { FileUtils.getFileUtils().copyFile(fromFile, toFile); } catch (IOException ioe) { - String msg = "Failed to copy " + fromFile + " to " + toFile - + " due to " + ioe.getMessage(); - - throw new BuildException(msg, ioe); + throw new BuildException("Failed to copy " + fromFile + + " to " + toFile + " due to " + ioe.getMessage(), ioe); } - } + }); } } - /** * Rename .java.keep files (back) to .java. The netrexxc renames all * .java files to .java.keep if either -keep or -nocompile option is set. */ private void removeKeepExtensions() { - if (compileList.size() > 0) { + if (!compileList.isEmpty()) { log("Removing .keep extension on " + compileList.size() + " file" + (compileList.size() == 1 ? "" : "s")); - Enumeration e = compileList.elements(); - while (e.hasMoreElements()) { - String nrxName = (String) e.nextElement(); - String baseName = nrxName.substring(0, nrxName.lastIndexOf('.')); + compileList.forEach(nrxName -> { + String baseName = + nrxName.substring(0, nrxName.lastIndexOf('.')); File fromFile = new File(baseName + ".java.keep"); File toFile = new File(baseName + ".java"); if (fromFile.renameTo(toFile)) { - log("Successfully renamed " + fromFile + " to " + toFile, Project.MSG_VERBOSE); + log("Successfully renamed " + fromFile + " to " + toFile, + Project.MSG_VERBOSE); } else { log("Failed to rename " + fromFile + " to " + toFile); } - } + }); } } - /** Performs a compile using the NetRexx 1.1.x compiler */ private void doNetRexxCompile() throws BuildException { log("Using NetRexx compiler", Project.MSG_VERBOSE); String classpath = getCompileClasspath(); - StringBuffer compileOptions = new StringBuffer(); // create an array of strings for input to the compiler: one array // comes from the compile options, the other from the compileList String[] compileOptionsArray = getCompileOptionsAsArray(); - String[] fileListArray = new String[compileList.size()]; - Enumeration e = compileList.elements(); - int j = 0; - - while (e.hasMoreElements()) { - fileListArray[j] = (String) e.nextElement(); - j++; - } - // create a single array of arguments for the compiler - String[] compileArgs = new String[compileOptionsArray.length + fileListArray.length]; - - for (int i = 0; i < compileOptionsArray.length; i++) { - compileArgs[i] = compileOptionsArray[i]; - } - for (int i = 0; i < fileListArray.length; i++) { - compileArgs[i + compileOptionsArray.length] = fileListArray[i]; - } // print nice output about what we are doing for the log - compileOptions.append("Compilation args: "); - for (int i = 0; i < compileOptionsArray.length; i++) { - compileOptions.append(compileOptionsArray[i]); - compileOptions.append(" "); - } - log(compileOptions.toString(), Project.MSG_VERBOSE); + log(Stream.of(compileOptionsArray) + .collect(Collectors.joining(" ", "Compilation args: ", "")), + Project.MSG_VERBOSE); - String eol = System.getProperty("line.separator"); - StringBuffer niceSourceList = new StringBuffer("Files to be compiled:" + eol); + log("Files to be compiled:", Project.MSG_VERBOSE); - final int size = compileList.size(); - for (int i = 0; i < size; i++) { - niceSourceList.append(" "); - niceSourceList.append(compileList.elementAt(i).toString()); - niceSourceList.append(eol); - } - - log(niceSourceList.toString(), Project.MSG_VERBOSE); + final String eol = System.getProperty("line.separator"); + log( + compileList.stream().map(s -> " " + s).collect(Collectors.joining(eol)) + , Project.MSG_VERBOSE); + // create a single array of arguments for the compiler + String[] compileArgs = + Stream.concat(Stream.of(compileOptionsArray), compileList.stream()) + .toArray(String[]::new); + // need to set java.class.path property and restore it later // since the NetRexx compiler has no option for the classpath String currentClassPath = System.getProperty("java.class.path"); @@ -865,7 +796,7 @@ public class NetRexxC extends MatchingTask { try { StringWriter out = new StringWriter(); - PrintWriter w = null; + PrintWriter w; int rc = COM.ibm.netrexx.process.NetRexxC.main(new Rexx(compileArgs), w = new PrintWriter(out)); //NOSONAR @@ -873,17 +804,18 @@ public class NetRexxC extends MatchingTask { String ddir = destDir.getAbsolutePath(); boolean doReplace = !(sdir.equals(ddir)); int dlen = ddir.length(); - String l; BufferedReader in = new BufferedReader(new StringReader(out.toString())); log("replacing destdir '" + ddir + "' through sourcedir '" + sdir + "'", Project.MSG_VERBOSE); + + String l; while ((l = in.readLine()) != null) { int idx; while (doReplace && ((idx = l.indexOf(ddir)) != -1)) { // path is mentioned in the message - l = (new StringBuffer(l)).replace(idx, idx + dlen, sdir).toString(); + l = new StringBuilder(l).replace(idx, idx + dlen, sdir).toString(); } // verbose level logging for suppressed messages if (suppressMethodArgumentNotUsed @@ -912,28 +844,26 @@ public class NetRexxC extends MatchingTask { } } if (rc > 1) { - throw new BuildException("Compile failed, messages should " - + "have been provided."); + throw new BuildException( + "Compile failed, messages should have been provided."); } if (w.checkError()) { throw new IOException("Encountered an error"); } } catch (IOException ioe) { - throw new BuildException("Unexpected IOException while " - + "playing with Strings", ioe); + throw new BuildException( + "Unexpected IOException while playing with Strings", ioe); } finally { // need to reset java.class.path property // since the NetRexx compiler has no option for the classpath currentProperties = System.getProperties(); currentProperties.put("java.class.path", currentClassPath); } - } - /** Builds the compilation classpath. */ private String getCompileClasspath() { - StringBuffer classpath = new StringBuffer(); + StringBuilder classpath = new StringBuilder(); // add dest dir to classpath so that previously compiled and // untouched classes are on classpath @@ -945,49 +875,43 @@ public class NetRexxC extends MatchingTask { } // add the system classpath - // addExistingToClasspath(classpath,System.getProperty("java.class.path")); return classpath.toString(); } - /** This */ private String[] getCompileOptionsAsArray() { - Vector options = new Vector(); - - options.addElement(binary ? "-binary" : "-nobinary"); - options.addElement(comments ? "-comments" : "-nocomments"); - options.addElement(compile ? "-compile" : "-nocompile"); - options.addElement(compact ? "-compact" : "-nocompact"); - options.addElement(console ? "-console" : "-noconsole"); - options.addElement(crossref ? "-crossref" : "-nocrossref"); - options.addElement(decimal ? "-decimal" : "-nodecimal"); - options.addElement(diag ? "-diag" : "-nodiag"); - options.addElement(explicit ? "-explicit" : "-noexplicit"); - options.addElement(format ? "-format" : "-noformat"); - options.addElement(keep ? "-keep" : "-nokeep"); - options.addElement(logo ? "-logo" : "-nologo"); - options.addElement(replace ? "-replace" : "-noreplace"); - options.addElement(savelog ? "-savelog" : "-nosavelog"); - options.addElement(sourcedir ? "-sourcedir" : "-nosourcedir"); - options.addElement(strictargs ? "-strictargs" : "-nostrictargs"); - options.addElement(strictassign ? "-strictassign" : "-nostrictassign"); - options.addElement(strictcase ? "-strictcase" : "-nostrictcase"); - options.addElement(strictimport ? "-strictimport" : "-nostrictimport"); - options.addElement(strictprops ? "-strictprops" : "-nostrictprops"); - options.addElement(strictsignal ? "-strictsignal" : "-nostrictsignal"); - options.addElement(symbols ? "-symbols" : "-nosymbols"); - options.addElement(time ? "-time" : "-notime"); - options.addElement("-" + trace); - options.addElement(utf8 ? "-utf8" : "-noutf8"); - options.addElement("-" + verbose); - - String[] results = new String[options.size()]; - - options.copyInto(results); - return results; + List<String> options = new ArrayList<>(); + + options.add(binary ? "-binary" : "-nobinary"); + options.add(comments ? "-comments" : "-nocomments"); + options.add(compile ? "-compile" : "-nocompile"); + options.add(compact ? "-compact" : "-nocompact"); + options.add(console ? "-console" : "-noconsole"); + options.add(crossref ? "-crossref" : "-nocrossref"); + options.add(decimal ? "-decimal" : "-nodecimal"); + options.add(diag ? "-diag" : "-nodiag"); + options.add(explicit ? "-explicit" : "-noexplicit"); + options.add(format ? "-format" : "-noformat"); + options.add(keep ? "-keep" : "-nokeep"); + options.add(logo ? "-logo" : "-nologo"); + options.add(replace ? "-replace" : "-noreplace"); + options.add(savelog ? "-savelog" : "-nosavelog"); + options.add(sourcedir ? "-sourcedir" : "-nosourcedir"); + options.add(strictargs ? "-strictargs" : "-nostrictargs"); + options.add(strictassign ? "-strictassign" : "-nostrictassign"); + options.add(strictcase ? "-strictcase" : "-nostrictcase"); + options.add(strictimport ? "-strictimport" : "-nostrictimport"); + options.add(strictprops ? "-strictprops" : "-nostrictprops"); + options.add(strictsignal ? "-strictsignal" : "-nostrictsignal"); + options.add(symbols ? "-symbols" : "-nosymbols"); + options.add(time ? "-time" : "-notime"); + options.add("-" + trace); + options.add(utf8 ? "-utf8" : "-noutf8"); + options.add("-" + verbose); + + return options.toArray(new String[options.size()]); } - /** * Takes a classpath-like string, and adds each element of this string to * a new classpath, if the components exist. Components that don't exist, @@ -998,7 +922,7 @@ public class NetRexxC extends MatchingTask { * @param target - target classpath * @param source - source classpath to get file objects. */ - private void addExistingToClasspath(StringBuffer target, String source) { + private void addExistingToClasspath(StringBuilder target, String source) { StringTokenizer tok = new StringTokenizer(source, System.getProperty("path.separator"), false); @@ -1013,17 +937,16 @@ public class NetRexxC extends MatchingTask { + f.getAbsolutePath(), Project.MSG_VERBOSE); } } - } - /** * Enumerated class corresponding to the trace attribute. */ public static class TraceAttr extends EnumeratedAttribute { /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[]{"trace", "trace1", "trace2", "notrace"}; + return new String[] { "trace", "trace1", "trace2", "notrace" }; } } @@ -1032,11 +955,10 @@ public class NetRexxC extends MatchingTask { */ public static class VerboseAttr extends EnumeratedAttribute { /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[]{"verbose", "verbose0", "verbose1", - "verbose2", "verbose3", "verbose4", - "verbose5", "noverbose"}; + return new String[] { "verbose", "verbose0", "verbose1", "verbose2", + "verbose3", "verbose4", "verbose5", "noverbose" }; } } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java index 5a3c215cf..32239ce76 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java @@ -31,7 +31,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -139,7 +138,7 @@ public class PropertyFile extends Task { private File propertyfile; private boolean useJDKProperties; - private Vector entries = new Vector(); + private Vector<Entry> entries = new Vector<>(); /* ======================================================================== * @@ -174,10 +173,7 @@ public class PropertyFile extends Task { } private void executeOperation() throws BuildException { - for (Enumeration e = entries.elements(); e.hasMoreElements();) { - Entry entry = (Entry) e.nextElement(); - entry.executeOn(properties); - } + entries.forEach(e -> e.executeOn(properties)); } private void readFile() throws BuildException { @@ -266,7 +262,7 @@ public class PropertyFile extends Task { } private boolean checkParam(File param) { - return !(param == null); + return param != null; } /** @@ -384,8 +380,8 @@ public class PropertyFile extends Task { } else if (type == Type.STRING_TYPE) { executeString(oldValue); } else { - throw new BuildException("Unknown operation type: " - + type); + throw new BuildException("Unknown operation type: %d", + type); } } catch (NullPointerException npe) { // Default to string type @@ -447,7 +443,6 @@ public class PropertyFile extends Task { newValue = fmt.format(currentValue.getTime()); } - /** * Handle operations for type <code>int</code>. * @@ -459,7 +454,6 @@ public class PropertyFile extends Task { int currentValue = DEFAULT_INT_VALUE; int newV = DEFAULT_INT_VALUE; - DecimalFormat fmt = (pattern != null) ? new DecimalFormat(pattern) : new DecimalFormat(); try { @@ -535,15 +529,17 @@ public class PropertyFile extends Task { + "properties (key:" + key + ")"); } if (value == null && defaultValue == null && operation != Operation.DELETE_OPER) { - throw new BuildException("\"value\" and/or \"default\" " - + "attribute must be specified (key:" + key + ")"); + throw new BuildException( + "\"value\" and/or \"default\" attribute must be specified (key: %s)", + key); } if (key == null) { throw new BuildException("key is mandatory"); } if (type == Type.STRING_TYPE && pattern != null) { - throw new BuildException("pattern is not supported for string " - + "properties (key:" + key + ")"); + throw new BuildException( + "pattern is not supported for string properties (key: %s)", + key); } } @@ -582,7 +578,7 @@ public class PropertyFile extends Task { ret = defaultValue; } } else { - ret = (oldValue == null) ? defaultValue : oldValue; + ret = oldValue == null ? defaultValue : oldValue; } return ret; @@ -606,7 +602,7 @@ public class PropertyFile extends Task { /** {@inheritDoc}. */ @Override public String[] getValues() { - return new String[] {"+", "-", "=", "del"}; + return new String[] { "+", "-", "=", "del" }; } /** @@ -617,9 +613,11 @@ public class PropertyFile extends Task { public static int toOperation(String oper) { if ("+".equals(oper)) { return INCREMENT_OPER; - } else if ("-".equals(oper)) { + } + if ("-".equals(oper)) { return DECREMENT_OPER; - } else if ("del".equals(oper)) { + } + if ("del".equals(oper)) { return DELETE_OPER; } return EQUALS_OPER; @@ -642,7 +640,7 @@ public class PropertyFile extends Task { /** {@inheritDoc} */ @Override public String[] getValues() { - return new String[] {"int", "date", "string"}; + return new String[] { "int", "date", "string" }; } /** @@ -653,7 +651,8 @@ public class PropertyFile extends Task { public static int toType(String type) { if ("int".equals(type)) { return INTEGER_TYPE; - } else if ("date".equals(type)) { + } + if ("date".equals(type)) { return DATE_TYPE; } return STRING_TYPE; @@ -677,23 +676,22 @@ public class PropertyFile extends Task { private static final String MONTH = "month"; private static final String YEAR = "year"; - private static final String[] UNITS - = {MILLISECOND, SECOND, MINUTE, HOUR, - DAY, WEEK, MONTH, YEAR }; + private static final String[] UNITS = + { MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR }; - private Map calendarFields = new HashMap(); + private Map<String, Integer> calendarFields = new HashMap<>(); /** no arg constructor */ public Unit() { calendarFields.put(MILLISECOND, - new Integer(Calendar.MILLISECOND)); - calendarFields.put(SECOND, new Integer(Calendar.SECOND)); - calendarFields.put(MINUTE, new Integer(Calendar.MINUTE)); - calendarFields.put(HOUR, new Integer(Calendar.HOUR_OF_DAY)); - calendarFields.put(DAY, new Integer(Calendar.DATE)); - calendarFields.put(WEEK, new Integer(Calendar.WEEK_OF_YEAR)); - calendarFields.put(MONTH, new Integer(Calendar.MONTH)); - calendarFields.put(YEAR, new Integer(Calendar.YEAR)); + Integer.valueOf(Calendar.MILLISECOND)); + calendarFields.put(SECOND, Integer.valueOf(Calendar.SECOND)); + calendarFields.put(MINUTE, Integer.valueOf(Calendar.MINUTE)); + calendarFields.put(HOUR, Integer.valueOf(Calendar.HOUR_OF_DAY)); + calendarFields.put(DAY, Integer.valueOf(Calendar.DATE)); + calendarFields.put(WEEK, Integer.valueOf(Calendar.WEEK_OF_YEAR)); + calendarFields.put(MONTH, Integer.valueOf(Calendar.MONTH)); + calendarFields.put(YEAR, Integer.valueOf(Calendar.YEAR)); } /** @@ -701,9 +699,7 @@ public class PropertyFile extends Task { * @return the calendar value. */ public int getCalendarField() { - String key = getValue().toLowerCase(); - Integer i = (Integer) calendarFields.get(key); - return i.intValue(); + return calendarFields.get(getValue().toLowerCase()).intValue(); } /** {@inheritDoc}. */ diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java index f5357bb9d..afc9a54ab 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ReplaceRegExp.java @@ -27,6 +27,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; +import java.nio.charset.Charset; import java.nio.file.Files; import org.apache.tools.ant.BuildException; @@ -143,7 +144,6 @@ public class ReplaceRegExp extends Task { this.subs = null; } - /** * file for which the regular expression should be replaced; * required unless a nested fileset is supplied. @@ -153,7 +153,6 @@ public class ReplaceRegExp extends Task { this.file = file; } - /** * the regular expression pattern to match in the file(s); * required if no nested <regexp> is used @@ -168,7 +167,6 @@ public class ReplaceRegExp extends Task { regex.setPattern(match); } - /** * The substitution pattern to place in the file(s) in place * of the regular expression. @@ -178,8 +176,8 @@ public class ReplaceRegExp extends Task { public void setReplace(String replace) { if (subs != null) { - throw new BuildException("Only one substitution expression is " - + "allowed"); + throw new BuildException( + "Only one substitution expression is allowed"); } subs = new Substitution(); @@ -205,7 +203,6 @@ public class ReplaceRegExp extends Task { this.flags = flags; } - /** * Process the file(s) one line at a time, executing the replacement * on one line at a time. This is useful if you @@ -219,12 +216,7 @@ public class ReplaceRegExp extends Task { */ @Deprecated public void setByLine(String byline) { - Boolean res = Boolean.valueOf(byline); - - if (res == null) { - res = Boolean.FALSE; - } - this.byline = res.booleanValue(); + this.byline = Boolean.parseBoolean(byline); } /** @@ -297,8 +289,8 @@ public class ReplaceRegExp extends Task { */ public Substitution createSubstitution() { if (subs != null) { - throw new BuildException("Only one substitution expression is " - + "allowed"); + throw new BuildException( + "Only one substitution expression is allowed"); } subs = new Substitution(); @@ -341,7 +333,6 @@ public class ReplaceRegExp extends Task { return res; } - /** * Perform the replacement on a file * @@ -355,13 +346,14 @@ public class ReplaceRegExp extends Task { try { boolean changes = false; + final Charset charset = encoding == null ? Charset.defaultCharset() : Charset.forName(encoding); try (InputStream is = Files.newInputStream(f.toPath()); OutputStream os = Files.newOutputStream(temp.toPath())) { Reader r = null; Writer w = null; try { - r = encoding != null ? new InputStreamReader(is, encoding) : new InputStreamReader(is); - w = encoding != null ? new OutputStreamWriter(os, encoding) : new OutputStreamWriter(os); + r = new InputStreamReader(is, charset); + w = new OutputStreamWriter(os, charset); log("Replacing pattern '" + regex.getPattern(getProject()) + "' with '" + subs.getExpression(getProject()) + "' in '" + f.getPath() + "'" + (byline ? " by line" : "") @@ -372,7 +364,7 @@ public class ReplaceRegExp extends Task { r = new BufferedReader(r); w = new BufferedWriter(w); - StringBuffer linebuf = new StringBuffer(); + StringBuilder linebuf = new StringBuilder(); int c; boolean hasCR = false; @@ -386,7 +378,7 @@ public class ReplaceRegExp extends Task { w, options); w.write('\r'); - linebuf = new StringBuffer(); + linebuf = new StringBuilder(); // hasCR is still true (for the second one) } else { // first CR in this line @@ -402,7 +394,7 @@ public class ReplaceRegExp extends Task { } w.write('\n'); - linebuf = new StringBuffer(); + linebuf = new StringBuilder(); } else { // any other char if ((hasCR) || (c < 0)) { // Mac-style linebreak or EOF (or both) @@ -413,7 +405,7 @@ public class ReplaceRegExp extends Task { hasCR = false; } - linebuf = new StringBuffer(); + linebuf = new StringBuilder(); } if (c >= 0) { @@ -453,7 +445,6 @@ public class ReplaceRegExp extends Task { } } - /** * Execute the task * @@ -469,9 +460,8 @@ public class ReplaceRegExp extends Task { } if (file != null && resources != null) { - throw new BuildException("You cannot supply the 'file' attribute " - + "and resource collections at the same " - + "time."); + throw new BuildException( + "You cannot supply the 'file' attribute and resource collections at the same time."); } int options = RegexpUtil.asOptions(flags); @@ -491,9 +481,7 @@ public class ReplaceRegExp extends Task { if (resources != null) { for (Resource r : resources) { - FileProvider fp = - r.as(FileProvider.class); - File f = fp.getFile(); + File f = r.as(FileProvider.class).getFile(); if (f.exists()) { try { @@ -523,5 +511,3 @@ public class ReplaceRegExp extends Task { return !res.equals(s); } } - - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java b/src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java index d1e945cf6..7ecf35d7f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Rpm.java @@ -110,6 +110,7 @@ public class Rpm extends Task { * * @throws BuildException is there is a problem in the task execution. */ + @Override public void execute() throws BuildException { Commandline toExecute = new Commandline(); @@ -227,7 +228,7 @@ public class Rpm extends Task { * @param sf the spec file name to use. */ public void setSpecFile(String sf) { - if ((sf == null) || (sf.trim().length() == 0)) { + if (sf == null || sf.trim().isEmpty()) { throw new BuildException("You must specify a spec file", getLocation()); } this.specFile = sf; @@ -320,20 +321,20 @@ public class Rpm extends Task { * @since 1.6 */ protected String guessRpmBuildCommand() { - Map/*<String, String>*/ env = Execute.getEnvironmentVariables(); - String path = (String) env.get(PATH1); + Map<String, String> env = Execute.getEnvironmentVariables(); + String path = env.get(PATH1); if (path == null) { - path = (String) env.get(PATH2); + path = env.get(PATH2); if (path == null) { - path = (String) env.get(PATH3); + path = env.get(PATH3); } } if (path != null) { Path p = new Path(getProject(), path); String[] pElements = p.list(); - for (int i = 0; i < pElements.length; i++) { - File f = new File(pElements[i], + for (String pElement : pElements) { + File f = new File(pElement, "rpmbuild" + (Os.isFamily("dos") ? ".exe" : "")); if (f.canRead()) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/SchemaValidate.java b/src/main/org/apache/tools/ant/taskdefs/optional/SchemaValidate.java index e57d6d226..a5db9912e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/SchemaValidate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/SchemaValidate.java @@ -20,7 +20,8 @@ package org.apache.tools.ant.taskdefs.optional; import java.io.File; import java.net.MalformedURLException; import java.util.HashMap; -import java.util.Iterator; +import java.util.Map; +import java.util.stream.Collectors; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; @@ -48,23 +49,6 @@ import org.xml.sax.XMLReader; */ public class SchemaValidate extends XMLValidateTask { - - /** map of all declared schemas; we catch and complain about redefinitions */ - private HashMap schemaLocations = new HashMap(); - - /** full checking of a schema */ - private boolean fullChecking = true; - - /** - * flag to disable DTD support. Best left enabled. - */ - private boolean disableDTD = false; - - /** - * default URL for nonamespace schemas - */ - private SchemaLocation anonymousSchema; - // Error strings /** SAX1 not supported */ public static final String ERROR_SAX_1 = "SAX1 parsers are not supported"; @@ -88,12 +72,29 @@ public class SchemaValidate extends XMLValidateTask { public static final String ERROR_DUPLICATE_SCHEMA = "Duplicate declaration of schema "; + /** map of all declared schemas; we catch and complain about redefinitions */ + private Map<String, SchemaLocation> schemaLocations = new HashMap<>(); + + /** full checking of a schema */ + private boolean fullChecking = true; + + /** + * flag to disable DTD support. Best left enabled. + */ + private boolean disableDTD = false; + + /** + * default URL for nonamespace schemas + */ + private SchemaLocation anonymousSchema; + /** * Called by the project to let the task initialize properly. The default * implementation is a no-op. * * @throws BuildException if something goes wrong with the build */ + @Override public void init() throws BuildException { super.init(); //validating @@ -155,7 +156,7 @@ public class SchemaValidate extends XMLValidateTask { public void addConfiguredSchema(SchemaLocation location) { log("adding schema " + location, Project.MSG_DEBUG); location.validateNamespace(); - SchemaLocation old = (SchemaLocation) schemaLocations.get(location.getNamespace()); + SchemaLocation old = schemaLocations.get(location.getNamespace()); if (old != null && !old.equals(location)) { throw new BuildException(ERROR_DUPLICATE_SCHEMA + location); } @@ -213,6 +214,7 @@ public class SchemaValidate extends XMLValidateTask { * * @throws BuildException if something went wrong */ + @Override protected void initValidator() { super.initValidator(); //validate the parser type @@ -221,7 +223,6 @@ public class SchemaValidate extends XMLValidateTask { } //enable schema - //setFeature(XmlConstants.FEATURE_VALIDATION, false); setFeature(XmlConstants.FEATURE_NAMESPACES, true); if (!enableXercesSchemaValidation() && !enableJAXP12SchemaValidation()) { //couldnt use the xerces or jaxp calls @@ -244,6 +245,7 @@ public class SchemaValidate extends XMLValidateTask { * create our own factory with our own options. * @return a default XML parser */ + @Override protected XMLReader createDefaultReader() { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); @@ -252,9 +254,7 @@ public class SchemaValidate extends XMLValidateTask { try { SAXParser saxParser = factory.newSAXParser(); reader = saxParser.getXMLReader(); - } catch (ParserConfigurationException e) { - throw new BuildException(ERROR_PARSER_CREATION_FAILURE, e); - } catch (SAXException e) { + } catch (ParserConfigurationException | SAXException e) { throw new BuildException(ERROR_PARSER_CREATION_FAILURE, e); } return reader; @@ -265,23 +265,15 @@ public class SchemaValidate extends XMLValidateTask { * property. */ protected void addSchemaLocations() { - Iterator it = schemaLocations.values().iterator(); - StringBuffer buffer = new StringBuffer(); - int count = 0; - while (it.hasNext()) { - if (count > 0) { - buffer.append(' '); - } - SchemaLocation schemaLocation = (SchemaLocation) it.next(); - String tuple = schemaLocation.getURIandLocation(); - buffer.append(tuple); - log("Adding schema " + tuple, Project.MSG_VERBOSE); - count++; + if (!schemaLocations.isEmpty()) { + String joinedValue = schemaLocations.values().stream() + .map(SchemaLocation::getURIandLocation) + .peek( + tuple -> log("Adding schema " + tuple, Project.MSG_VERBOSE)) + .collect(Collectors.joining(" ")); + + setProperty(XmlConstants.PROPERTY_SCHEMA_LOCATION, joinedValue); } - if (count > 0) { - setProperty(XmlConstants.PROPERTY_SCHEMA_LOCATION, buffer.toString()); - } - } /** @@ -289,11 +281,8 @@ public class SchemaValidate extends XMLValidateTask { * @return the schema URL */ protected String getNoNamespaceSchemaURL() { - if (anonymousSchema == null) { - return null; - } else { - return anonymousSchema.getSchemaLocationURL(); - } + return anonymousSchema == null ? null + : anonymousSchema.getSchemaLocationURL(); } /** @@ -317,6 +306,7 @@ public class SchemaValidate extends XMLValidateTask { * * @param fileProcessed number of files processed. */ + @Override protected void onSuccessfulValidation(int fileProcessed) { log(fileProcessed + MESSAGE_FILES_VALIDATED, Project.MSG_VERBOSE); } @@ -350,10 +340,6 @@ public class SchemaValidate extends XMLValidateTask { public static final String ERROR_NO_LOCATION = "No file or URL supplied for the schema "; - /** No arg constructor */ - public SchemaLocation() { - } - /** * Get the namespace. * @return the namespace. @@ -442,11 +428,8 @@ public class SchemaValidate extends XMLValidateTask { */ public String getURIandLocation() throws BuildException { validateNamespace(); - StringBuffer buffer = new StringBuffer(); - buffer.append(namespace); - buffer.append(' '); - buffer.append(getSchemaLocationURL()); - return new String(buffer); + return new StringBuilder(namespace).append(' ') + .append(getSchemaLocationURL()).toString(); } /** @@ -465,7 +448,7 @@ public class SchemaValidate extends XMLValidateTask { * @return true if it is not null or empty */ private boolean isSet(String property) { - return property != null && property.length() != 0; + return property != null && !property.isEmpty(); } /** @@ -474,6 +457,7 @@ public class SchemaValidate extends XMLValidateTask { * @return true iff the objects are considered equal in value */ + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -502,6 +486,7 @@ public class SchemaValidate extends XMLValidateTask { * Generate a hashcode depending on the namespace, url and file name. * @return the hashcode. */ + @Override public int hashCode() { int result; // CheckStyle:MagicNumber OFF @@ -517,8 +502,9 @@ public class SchemaValidate extends XMLValidateTask { * and the like * @return a string representation of the object. */ + @Override public String toString() { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); buffer.append(namespace != null ? namespace : "(anonymous)"); buffer.append(' '); buffer.append(url != null ? (url + " ") : ""); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheck.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheck.java index f6a94b527..a872f4819 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheck.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheck.java @@ -29,12 +29,20 @@ import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.FileSet; - /** * Class common to all check commands (checkout, checkin,checkin default task); * @ant.task ignore="true" */ public class CCMCheck extends Continuus { + /** + * -comment flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "/comment"; + + /** + * -task flag -- associate checkout task with task + */ + public static final String FLAG_TASK = "/task"; private File file = null; private String comment = null; @@ -42,15 +50,10 @@ public class CCMCheck extends Continuus { // CheckStyle:VisibilityModifier OFF - bc - protected Vector filesets = new Vector(); + protected Vector<FileSet> filesets = new Vector<>(); // CheckStyle:VisibilityModifier ON - /** Constructor for CCMCheck. */ - public CCMCheck() { - super(); - } - /** * Get the value of file. * @return value of file. @@ -84,7 +87,6 @@ public class CCMCheck extends Continuus { this.comment = v; } - /** * Get the value of task. * @return value of task. @@ -102,7 +104,6 @@ public class CCMCheck extends Continuus { this.task = v; } - /** * Adds a set of files to copy. * @param set the set of files @@ -120,9 +121,10 @@ public class CCMCheck extends Continuus { * </p> * @throws BuildException on error */ + @Override public void execute() throws BuildException { - if (file == null && filesets.size() == 0) { + if (file == null && filesets.isEmpty()) { throw new BuildException( "Specify at least one source - a file or a fileset."); } @@ -131,7 +133,7 @@ public class CCMCheck extends Continuus { throw new BuildException("CCMCheck cannot be generated for directories"); } - if (file != null && filesets.size() > 0) { + if (file != null && !filesets.isEmpty()) { throw new BuildException("Choose between file and fileset !"); } @@ -140,14 +142,11 @@ public class CCMCheck extends Continuus { return; } - int sizeofFileSet = filesets.size(); - for (int i = 0; i < sizeofFileSet; i++) { - FileSet fs = (FileSet) filesets.elementAt(i); + for (FileSet fs : filesets) { + final File basedir = fs.getDir(getProject()); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); - String[] srcFiles = ds.getIncludedFiles(); - for (int j = 0; j < srcFiles.length; j++) { - File src = new File(fs.getDir(getProject()), srcFiles[j]); - setFile(src); + for (String srcFile : ds.getIncludedFiles()) { + setFile(new File(basedir, srcFile)); doit(); } } @@ -170,12 +169,11 @@ public class CCMCheck extends Continuus { int result = run(commandLine); if (Execute.isFailure(result)) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -195,14 +193,4 @@ public class CCMCheck extends Continuus { } } - /** - * -comment flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "/comment"; - - /** - * -task flag -- associate checkout task with task - */ - public static final String FLAG_TASK = "/task"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckin.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckin.java index ff7472c9a..3f274d712 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckin.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckin.java @@ -36,4 +36,3 @@ public class CCMCheckin extends CCMCheck { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckinDefault.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckinDefault.java index 2fe2a2a12..8bf9fe1b5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckinDefault.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckinDefault.java @@ -25,14 +25,13 @@ package org.apache.tools.ant.taskdefs.optional.ccm; */ public class CCMCheckinDefault extends CCMCheck { + /** The default task */ + public static final String DEFAULT_TASK = "default"; + /** Constructor for CCMCheckinDefault. */ public CCMCheckinDefault() { super(); setCcmAction(COMMAND_CHECKIN); setTask(DEFAULT_TASK); } - - /** The default task */ - public static final String DEFAULT_TASK = "default"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckout.java index 44bbc6bf2..1850cd3ae 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCheckout.java @@ -32,4 +32,3 @@ public class CCMCheckout extends CCMCheck { setCcmAction(COMMAND_CHECKOUT); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCreateTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCreateTask.java index 350d673c7..a3d2d468d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCreateTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMCreateTask.java @@ -38,6 +38,35 @@ import org.apache.tools.ant.util.StringUtils; * @ant.task name="ccmcreatetask" category="scm" */ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { + /** + * /comment -- comments associated to the task + */ + public static final String FLAG_COMMENT = "/synopsis"; + + /** + * /platform flag -- target platform + */ + public static final String FLAG_PLATFORM = "/plat"; + + /** + * /resolver flag + */ + public static final String FLAG_RESOLVER = "/resolver"; + + /** + * /release flag + */ + public static final String FLAG_RELEASE = "/release"; + + /** + * /release flag + */ + public static final String FLAG_SUBSYSTEM = "/subsystem"; + + /** + * -task flag -- associate checkout task with task + */ + public static final String FLAG_TASK = "/task"; private String comment = null; private String platform = null; @@ -63,9 +92,9 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { * </p> * @throws BuildException on error */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); - int result = 0; // build the command line from what we got the format // as specified in the CCM.EXE help @@ -74,10 +103,9 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { checkOptions(commandLine); - result = run(commandLine, this); - if (Execute.isFailure(result)) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + if (Execute.isFailure(run(commandLine, this))) { + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } //create task ok, set this task as the default one @@ -88,15 +116,12 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { log(commandLine.describeCommand(), Project.MSG_DEBUG); - result = run(commandLine2); - if (result != 0) { - String msg = "Failed executing: " + commandLine2.toString(); - throw new BuildException(msg, getLocation()); + if (run(commandLine2) != 0) { + throw new BuildException("Failed executing: " + commandLine2, + getLocation()); } - } - /** * Check the command line options. */ @@ -127,7 +152,6 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { } // end of if () } - /** * Get the value of comment. * @return value of comment. @@ -145,7 +169,6 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { this.comment = v; } - /** * Get the value of platform. * @return value of platform. @@ -163,7 +186,6 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { this.platform = v; } - /** * Get the value of resolver. * @return value of resolver. @@ -181,7 +203,6 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { this.resolver = v; } - /** * Get the value of release. * @return value of release. @@ -216,7 +237,6 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { this.subSystem = v; } - /** * Get the value of task. * @return value of task. @@ -235,71 +255,45 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { this.task = v; } - /** - * /comment -- comments associated to the task - */ - public static final String FLAG_COMMENT = "/synopsis"; - - /** - * /platform flag -- target platform - */ - public static final String FLAG_PLATFORM = "/plat"; - - /** - * /resolver flag - */ - public static final String FLAG_RESOLVER = "/resolver"; - - /** - * /release flag - */ - public static final String FLAG_RELEASE = "/release"; - - /** - * /release flag - */ - public static final String FLAG_SUBSYSTEM = "/subsystem"; - - /** - * -task flag -- associate checkout task with task - */ - public static final String FLAG_TASK = "/task"; - - // implementation of org.apache.tools.ant.taskdefs.ExecuteStreamHandler interface /** * * @throws IOException on error */ + @Override public void start() throws IOException { } /** * */ + @Override public void stop() { } /** * * @param param1 the output stream - * @exception java.io.IOException on error + * @exception IOException on error */ + @Override public void setProcessInputStream(OutputStream param1) throws IOException { } /** * * @param is the input stream - * @exception java.io.IOException on error + * @exception IOException on error */ + @Override public void setProcessErrorStream(InputStream is) throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - String s = reader.readLine(); - if (s != null) { - log("err " + s, Project.MSG_DEBUG); - } // end of if () + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { + String s = reader.readLine(); + if (s != null) { + log("err " + s, Project.MSG_DEBUG); + } // end of if () + } } /** @@ -307,12 +301,11 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { * @param is InputStream * @throws IOException on error */ + @Override public void setProcessOutputStream(InputStream is) throws IOException { - - String buffer = ""; - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - buffer = reader.readLine(); + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(is))) { + String buffer = reader.readLine(); if (buffer != null) { log("buffer:" + buffer, Project.MSG_DEBUG); String taskstring = buffer.substring(buffer.indexOf(' ')).trim(); @@ -323,7 +316,7 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { } catch (NullPointerException npe) { log("error procession stream , null pointer exception", Project.MSG_ERR); log(StringUtils.getStackTrace(npe), Project.MSG_ERR); - throw new BuildException(npe.getClass().getName()); + throw new BuildException(npe); } catch (Exception e) { log("error procession stream " + e.getMessage(), Project.MSG_ERR); throw new BuildException(e.getMessage()); @@ -332,4 +325,3 @@ public class CCMCreateTask extends Continuus implements ExecuteStreamHandler { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMReconfigure.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMReconfigure.java index 28f806459..a45f8bff6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMReconfigure.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/CCMReconfigure.java @@ -28,6 +28,21 @@ import org.apache.tools.ant.types.Commandline; * Task allows to reconfigure a project, recursively or not */ public class CCMReconfigure extends Continuus { + /** + * /recurse -- + */ + public static final String FLAG_RECURSE = "/recurse"; + + /** + * /recurse -- + */ + public static final String FLAG_VERBOSE = "/verbose"; + + + /** + * /project flag -- target project + */ + public static final String FLAG_PROJECT = "/project"; private String ccmProject = null; private boolean recurse = false; @@ -39,7 +54,6 @@ public class CCMReconfigure extends Continuus { setCcmAction(COMMAND_RECONFIGURE); } - /** * Executes the task. * <p> @@ -48,9 +62,9 @@ public class CCMReconfigure extends Continuus { * </p> * @throws BuildException on error */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); - int result = 0; // build the command line from what we got the format // as specified in the CCM.EXE help @@ -59,14 +73,13 @@ public class CCMReconfigure extends Continuus { checkOptions(commandLine); - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result)) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -103,7 +116,6 @@ public class CCMReconfigure extends Continuus { this.ccmProject = v; } - /** * Get the value of recurse. * @return value of recurse. @@ -121,7 +133,6 @@ public class CCMReconfigure extends Continuus { this.recurse = v; } - /** * Get the value of verbose. * @return value of verbose. @@ -138,22 +149,4 @@ public class CCMReconfigure extends Continuus { this.verbose = v; } - - /** - * /recurse -- - */ - public static final String FLAG_RECURSE = "/recurse"; - - /** - * /recurse -- - */ - public static final String FLAG_VERBOSE = "/verbose"; - - - /** - * /project flag -- target project - */ - public static final String FLAG_PROJECT = "/project"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/Continuus.java b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/Continuus.java index 5618dd6aa..845c7bf4c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ccm/Continuus.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ccm/Continuus.java @@ -18,6 +18,8 @@ package org.apache.tools.ant.taskdefs.optional.ccm; +import java.io.IOException; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; @@ -39,6 +41,32 @@ import org.apache.tools.ant.util.FileUtils; * */ public abstract class Continuus extends Task { + /** + * Constant for the thing to execute + */ + private static final String CCM_EXE = "ccm"; + + /** + * The 'CreateTask' command + */ + public static final String COMMAND_CREATE_TASK = "create_task"; + /** + * The 'Checkout' command + */ + public static final String COMMAND_CHECKOUT = "co"; + /** + * The 'Checkin' command + */ + public static final String COMMAND_CHECKIN = "ci"; + /** + * The 'Reconfigure' command + */ + public static final String COMMAND_RECONFIGURE = "reconfigure"; + + /** + * The 'Reconfigure' command + */ + public static final String COMMAND_DEFAULT_TASK = "default_task"; private String ccmDir = ""; private String ccmAction = ""; @@ -60,7 +88,6 @@ public abstract class Continuus extends Task { this.ccmAction = v; } - /** * Set the directory where the ccm executable is located. * @@ -76,7 +103,7 @@ public abstract class Continuus extends Task { */ protected final String getCcmCommand() { String toReturn = ccmDir; - if (!toReturn.equals("") && !toReturn.endsWith("/")) { + if (!("".equals(toReturn) || toReturn.endsWith("/"))) { toReturn += "/"; } @@ -85,7 +112,6 @@ public abstract class Continuus extends Task { return toReturn; } - /** * Run the command. * @param cmd the command line @@ -99,7 +125,7 @@ public abstract class Continuus extends Task { exe.setWorkingDirectory(getProject().getBaseDir()); exe.setCommandline(cmd.getCommandline()); return exe.execute(); - } catch (java.io.IOException e) { + } catch (IOException e) { throw new BuildException(e, getLocation()); } } @@ -113,32 +139,4 @@ public abstract class Continuus extends Task { return run(cmd, new LogStreamHandler(this, Project.MSG_VERBOSE, Project.MSG_WARN)); } - /** - * Constant for the thing to execute - */ - private static final String CCM_EXE = "ccm"; - - /** - * The 'CreateTask' command - */ - public static final String COMMAND_CREATE_TASK = "create_task"; - /** - * The 'Checkout' command - */ - public static final String COMMAND_CHECKOUT = "co"; - /** - * The 'Checkin' command - */ - public static final String COMMAND_CHECKIN = "ci"; - /** - * The 'Reconfigure' command - */ - public static final String COMMAND_RECONFIGURE = "reconfigure"; - - /** - * The 'Reconfigure' command - */ - public static final String COMMAND_DEFAULT_TASK = "default_task"; - - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java index 371d418bd..3e6584814 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckin.java @@ -78,6 +78,41 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCCheckin extends ClearCase { + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + + /** + * -nwarn flag -- suppresses warning messages + */ + public static final String FLAG_NOWARN = "-nwarn"; + + /** + * -ptime flag -- preserves the modification time + */ + public static final String FLAG_PRESERVETIME = "-ptime"; + + /** + * -keep flag -- keeps a copy of the file with a .keep extension + */ + public static final String FLAG_KEEPCOPY = "-keep"; + + /** + * -identical flag -- allows the file to be checked in even if it is identical to the original + */ + public static final String FLAG_IDENTICAL = "-identical"; + private String mComment = null; private String mCfile = null; private boolean mNwarn = false; @@ -92,10 +127,10 @@ public class CCCheckin extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -114,14 +149,12 @@ public class CCCheckin extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, getLocation()); } } - /** * Check the command line options. */ @@ -272,7 +305,6 @@ public class CCCheckin extends ClearCase { return mIdentical; } - /** * Get the 'comment' command * @@ -309,35 +341,5 @@ public class CCCheckin extends ClearCase { } } - - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - /** - * -nwarn flag -- suppresses warning messages - */ - public static final String FLAG_NOWARN = "-nwarn"; - /** - * -ptime flag -- preserves the modification time - */ - public static final String FLAG_PRESERVETIME = "-ptime"; - /** - * -keep flag -- keeps a copy of the file with a .keep extension - */ - public static final String FLAG_KEEPCOPY = "-keep"; - /** - * -identical flag -- allows the file to be checked in even if it is identical to the original - */ - public static final String FLAG_IDENTICAL = "-identical"; - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java index 0eaf09acc..afcdcbc24 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCCheckout.java @@ -94,6 +94,56 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCCheckout extends ClearCase { + /** + * -reserved flag -- check out the file as reserved + */ + public static final String FLAG_RESERVED = "-reserved"; + + /** + * -reserved flag -- check out the file as unreserved + */ + public static final String FLAG_UNRESERVED = "-unreserved"; + + /** + * -out flag -- create a writable file under a different filename + */ + public static final String FLAG_OUT = "-out"; + + /** + * -ndata flag -- checks out the file but does not create an editable file containing its data + */ + public static final String FLAG_NODATA = "-ndata"; + + /** + * -branch flag -- checks out the file on a specified branch + */ + public static final String FLAG_BRANCH = "-branch"; + + /** + * -version flag -- allows checkout of a version that is not main latest + */ + public static final String FLAG_VERSION = "-version"; + + /** + * -nwarn flag -- suppresses warning messages + */ + public static final String FLAG_NOWARN = "-nwarn"; + + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + private boolean mReserved = true; private String mOut = null; private boolean mNdata = false; @@ -111,10 +161,10 @@ public class CCCheckout extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -142,10 +192,10 @@ public class CCCheckout extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -154,7 +204,6 @@ public class CCCheckout extends ClearCase { */ private boolean lsCheckout() { Commandline cmdl = new Commandline(); - String result; // build the command line from what we got the format is // cleartool lsco [options...] [viewpath ...] @@ -167,12 +216,11 @@ public class CCCheckout extends ClearCase { // viewpath cmdl.createArgument().setValue(getViewPath()); - result = runS(cmdl); - - // System.out.println( "lsCheckout: " + result ); + String result = runS(cmdl); - return (result != null && result.length() > 0) ? true : false; + return (result != null && result.length() > 0); } + /** * Check the command line options. */ @@ -189,23 +237,17 @@ public class CCCheckout extends ClearCase { if (getOut() != null) { // -out getOutCommand(cmd); - } else { - if (getNoData()) { - // -ndata - cmd.createArgument().setValue(FLAG_NODATA); - } - + } else if (getNoData()) { + // -ndata + cmd.createArgument().setValue(FLAG_NODATA); } if (getBranch() != null) { // -branch getBranchCommand(cmd); - } else { - if (getVersion()) { - // -version - cmd.createArgument().setValue(FLAG_VERSION); - } - + } else if (getVersion()) { + // -version + cmd.createArgument().setValue(FLAG_VERSION); } if (getNoWarn()) { @@ -216,20 +258,15 @@ public class CCCheckout extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } // viewpath cmd.createArgument().setValue(getViewPath()); - - // Print out info about the notco option - // System.out.println( "Notco: " + (getNotco() ? "yes" : "no") ); } /** @@ -270,7 +307,6 @@ public class CCCheckout extends ClearCase { return mNotco; } - /** * Creates a writable file under a different filename. * @@ -434,7 +470,6 @@ public class CCCheckout extends ClearCase { } } - /** * Get the 'comment' command * @@ -471,46 +506,5 @@ public class CCCheckout extends ClearCase { } } - /** - * -reserved flag -- check out the file as reserved - */ - public static final String FLAG_RESERVED = "-reserved"; - /** - * -reserved flag -- check out the file as unreserved - */ - public static final String FLAG_UNRESERVED = "-unreserved"; - /** - * -out flag -- create a writable file under a different filename - */ - public static final String FLAG_OUT = "-out"; - /** - * -ndata flag -- checks out the file but does not create an editable file containing its data - */ - public static final String FLAG_NODATA = "-ndata"; - /** - * -branch flag -- checks out the file on a specified branch - */ - public static final String FLAG_BRANCH = "-branch"; - /** - * -version flag -- allows checkout of a version that is not main latest - */ - public static final String FLAG_VERSION = "-version"; - /** - * -nwarn flag -- suppresses warning messages - */ - public static final String FLAG_NOWARN = "-nwarn"; - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCLock.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCLock.java index c273554e7..c2e36e94d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCLock.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCLock.java @@ -18,19 +18,19 @@ package org.apache.tools.ant.taskdefs.optional.clearcase; +import java.util.Optional; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.types.Commandline; -/** +/* * TODO: * comment field doesn't include all options yet */ - - /** * Performs a ClearCase Lock command. * @@ -85,6 +85,31 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCLock extends ClearCase { + /** + * -replace flag -- replace existing lock on object(s) + */ + public static final String FLAG_REPLACE = "-replace"; + + /** + * -nusers flag -- list of users to exclude from lock + */ + public static final String FLAG_NUSERS = "-nusers"; + + /** + * -obsolete flag -- mark locked object as obsolete + */ + public static final String FLAG_OBSOLETE = "-obsolete"; + + /** + * -comment flag -- method to use for commenting events + */ + public static final String FLAG_COMMENT = "-comment"; + + /** + * -pname flag -- pathname to lock + */ + public static final String FLAG_PNAME = "-pname"; + private boolean mReplace = false; private boolean mObsolete = false; private String mComment = null; @@ -99,10 +124,10 @@ public class CCLock extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -125,17 +150,17 @@ public class CCLock extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getOpType(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } /** * Check the command line options. */ -private void checkOptions(Commandline cmd) { + private void checkOptions(Commandline cmd) { // ClearCase items if (getReplace()) { // -replace @@ -150,15 +175,15 @@ private void checkOptions(Commandline cmd) { getCommentCommand(cmd); if (getObjselect() == null && getPname() == null) { - throw new BuildException("Should select either an element " - + "(pname) or an object (objselect)"); + throw new BuildException( + "Should select either an element (pname) or an object (objselect)"); } getPnameCommand(cmd); // object selector if (getObjselect() != null) { cmd.createArgument().setValue(getObjselect()); } -} + } /** * If true, replace an existing lock. @@ -289,15 +314,14 @@ private void checkOptions(Commandline cmd) { private void getNusersCommand(Commandline cmd) { if (getNusers() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_NUSERS); - cmd.createArgument().setValue(getNusers()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_NUSERS); + cmd.createArgument().setValue(getNusers()); } /** @@ -309,15 +333,14 @@ private void checkOptions(Commandline cmd) { private void getCommentCommand(Commandline cmd) { if (getComment() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_COMMENT); - cmd.createArgument().setValue(getComment()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_COMMENT); + cmd.createArgument().setValue(getComment()); } /** @@ -329,15 +352,14 @@ private void checkOptions(Commandline cmd) { private void getPnameCommand(Commandline cmd) { if (getPname() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_PNAME); - cmd.createArgument().setValue(getPname()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_PNAME); + cmd.createArgument().setValue(getPname()); } /** @@ -346,33 +368,7 @@ private void checkOptions(Commandline cmd) { * @return String containing the object/pname being worked on */ private String getOpType() { - - if (getPname() != null) { - return getPname(); - } else { - return getObjselect(); - } + return Optional.ofNullable(getPname()).orElseGet(this::getObjselect); } - /** - * -replace flag -- replace existing lock on object(s) - */ - public static final String FLAG_REPLACE = "-replace"; - /** - * -nusers flag -- list of users to exclude from lock - */ - public static final String FLAG_NUSERS = "-nusers"; - /** - * -obsolete flag -- mark locked object as obsolete - */ - public static final String FLAG_OBSOLETE = "-obsolete"; - /** - * -comment flag -- method to use for commenting events - */ - public static final String FLAG_COMMENT = "-comment"; - /** - * -pname flag -- pathname to lock - */ - public static final String FLAG_PNAME = "-pname"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkattr.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkattr.java index 128ea16b7..c428af02d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkattr.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkattr.java @@ -83,6 +83,31 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCMkattr extends ClearCase { + /** + * -replace flag -- replace the existing value of the attribute + */ + public static final String FLAG_REPLACE = "-replace"; + /** + * -recurse flag -- process all subdirectories + */ + public static final String FLAG_RECURSE = "-recurse"; + /** + * -version flag -- attach attribute to specified version + */ + public static final String FLAG_VERSION = "-version"; + /** + * -c flag -- comment to attach to the element + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + private boolean mReplace = false; private boolean mRecurse = false; private String mVersion = null; @@ -98,10 +123,10 @@ public class CCMkattr extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Check for required attributes if (getTypeName() == null) { @@ -131,10 +156,10 @@ public class CCMkattr extends ClearCase { // For debugging // System.out.println(commandLine.toString()); - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -161,13 +186,11 @@ public class CCMkattr extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } if (getTypeName() != null) { @@ -182,7 +205,6 @@ public class CCMkattr extends ClearCase { cmd.createArgument().setValue(getViewPath()); } - /** * Set the replace flag * @@ -309,7 +331,6 @@ public class CCMkattr extends ClearCase { return mTypeValue; } - /** * Get the 'version' command * @@ -397,29 +418,4 @@ public class CCMkattr extends ClearCase { } } - /** - * -replace flag -- replace the existing value of the attribute - */ - public static final String FLAG_REPLACE = "-replace"; - /** - * -recurse flag -- process all subdirectories - */ - public static final String FLAG_RECURSE = "-recurse"; - /** - * -version flag -- attach attribute to specified version - */ - public static final String FLAG_VERSION = "-version"; - /** - * -c flag -- comment to attach to the element - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkbl.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkbl.java index 82c960051..94cb5a10a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkbl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkbl.java @@ -80,6 +80,36 @@ previous baseline.</td> * */ public class CCMkbl extends ClearCase { + + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + /** + * -identical flag -- allows the file to be checked in even if it is identical to the original + */ + public static final String FLAG_IDENTICAL = "-identical"; + /** + * -incremental flag -- baseline to be created is incremental + */ + public static final String FLAG_INCREMENTAL = "-incremental"; + /** + * -full flag -- baseline to be created is full + */ + public static final String FLAG_FULL = "-full"; + /** + * -nlabel -- baseline to be created without a label + */ + public static final String FLAG_NLABEL = "-nlabel"; + private String mComment = null; private String mCfile = null; private String mBaselineRootName = null; @@ -88,7 +118,6 @@ public class CCMkbl extends ClearCase { private boolean mFull = false; private boolean mNlabel = false; - /** * Executes the task. * <p> @@ -96,10 +125,10 @@ public class CCMkbl extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -118,14 +147,13 @@ public class CCMkbl extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getBaselineRootName(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -133,13 +161,11 @@ public class CCMkbl extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } if (getIdentical()) { @@ -162,10 +188,8 @@ public class CCMkbl extends ClearCase { // baseline_root_name cmd.createArgument().setValue(getBaselineRootName()); - } - /** * Set comment string * @@ -221,8 +245,6 @@ public class CCMkbl extends ClearCase { } /** - - /** * Set the nowarn flag * * @param nwarn the status to set the flag to @@ -294,7 +316,6 @@ public class CCMkbl extends ClearCase { return mNlabel; } - /** * Get the 'comment' command * @@ -331,35 +352,4 @@ public class CCMkbl extends ClearCase { } } - - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - /** - * -identical flag -- allows the file to be checked in even if it is identical to the original - */ - public static final String FLAG_IDENTICAL = "-identical"; - /** - * -incremental flag -- baseline to be created is incremental - */ - public static final String FLAG_INCREMENTAL = "-incremental"; - /** - * -full flag -- baseline to be created is full - */ - public static final String FLAG_FULL = "-full"; - /** - * -nlabel -- baseline to be created without a label - */ - public static final String FLAG_NLABEL = "-nlabel"; - - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkdir.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkdir.java index 4c89539fe..09af65e72 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkdir.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkdir.java @@ -63,6 +63,23 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCMkdir extends ClearCase { + /** + * -c flag -- comment to attach to the directory + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the directory + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + /** + * -nco flag -- do not checkout element after creation + */ + public static final String FLAG_NOCHECKOUT = "-nco"; + private String mComment = null; private String mCfile = null; private boolean mNoco = false; @@ -74,10 +91,10 @@ public class CCMkdir extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -96,10 +113,10 @@ public class CCMkdir extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -110,13 +127,11 @@ public class CCMkdir extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } if (getNoCheckout()) { // -nco @@ -180,7 +195,6 @@ public class CCMkdir extends ClearCase { return mNoco; } - /** * Get the 'comment' command * @@ -217,21 +231,4 @@ public class CCMkdir extends ClearCase { } } - /** - * -c flag -- comment to attach to the directory - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the directory - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - /** - * -nco flag -- do not checkout element after creation - */ - public static final String FLAG_NOCHECKOUT = "-nco"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkelem.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkelem.java index 94faa5a6c..72a736aa0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkelem.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMkelem.java @@ -88,6 +88,43 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCMkelem extends ClearCase { + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + /** + * -nwarn flag -- suppresses warning messages + */ + public static final String FLAG_NOWARN = "-nwarn"; + /** + * -ptime flag -- preserves the modification time on checkin + */ + public static final String FLAG_PRESERVETIME = "-ptime"; + /** + * -nco flag -- do not checkout element after creation + */ + public static final String FLAG_NOCHECKOUT = "-nco"; + /** + * -ci flag -- checkin element after creation + */ + public static final String FLAG_CHECKIN = "-ci"; + /** + * -master flag -- change mastership of main branch to current site + */ + public static final String FLAG_MASTER = "-master"; + /** + * -eltype flag -- element type to use during creation + */ + public static final String FLAG_ELTYPE = "-eltype"; + private String mComment = null; private String mCfile = null; private boolean mNwarn = false; @@ -104,10 +141,10 @@ public class CCMkelem extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -126,14 +163,13 @@ public class CCMkelem extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -141,13 +177,11 @@ public class CCMkelem extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } if (getNoWarn()) { @@ -329,7 +363,6 @@ public class CCMkelem extends ClearCase { return mEltype; } - /** * Get the 'comment' command * @@ -384,41 +417,4 @@ public class CCMkelem extends ClearCase { } } - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - /** - * -nwarn flag -- suppresses warning messages - */ - public static final String FLAG_NOWARN = "-nwarn"; - /** - * -ptime flag -- preserves the modification time on checkin - */ - public static final String FLAG_PRESERVETIME = "-ptime"; - /** - * -nco flag -- do not checkout element after creation - */ - public static final String FLAG_NOCHECKOUT = "-nco"; - /** - * -ci flag -- checkin element after creation - */ - public static final String FLAG_CHECKIN = "-ci"; - /** - * -master flag -- change mastership of main branch to current site - */ - public static final String FLAG_MASTER = "-master"; - /** - * -eltype flag -- element type to use during creation - */ - public static final String FLAG_ELTYPE = "-eltype"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklabel.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklabel.java index e3d288df5..c75dc6d56 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklabel.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklabel.java @@ -82,6 +82,31 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCMklabel extends ClearCase { + /** + * -replace flag -- replace another label of the same type + */ + public static final String FLAG_REPLACE = "-replace"; + /** + * -recurse flag -- process all subdirectories + */ + public static final String FLAG_RECURSE = "-recurse"; + /** + * -version flag -- attach label to specified version + */ + public static final String FLAG_VERSION = "-version"; + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + private boolean mReplace = false; private boolean mRecurse = false; private String mVersion = null; @@ -97,10 +122,10 @@ public class CCMklabel extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Check for required attributes if (getTypeName() == null) { @@ -124,10 +149,10 @@ public class CCMklabel extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -154,13 +179,11 @@ public class CCMklabel extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } if (getTypeName() != null) { @@ -172,7 +195,6 @@ public class CCMklabel extends ClearCase { cmd.createArgument().setValue(getViewPath()); } - /** * Set the replace flag * @@ -299,7 +321,6 @@ public class CCMklabel extends ClearCase { return mVOB; } - /** * Get the 'version' command * @@ -361,10 +382,9 @@ public class CCMklabel extends ClearCase { * without the type-name */ private void getTypeCommand(Commandline cmd) { - String typenm = null; if (getTypeName() != null) { - typenm = getTypeName(); + String typenm = getTypeName(); if (getVOB() != null) { typenm += "@" + getVOB(); } @@ -372,31 +392,4 @@ public class CCMklabel extends ClearCase { } } - - /** - * -replace flag -- replace another label of the same type - */ - public static final String FLAG_REPLACE = "-replace"; - /** - * -recurse flag -- process all subdirectories - */ - public static final String FLAG_RECURSE = "-recurse"; - /** - * -version flag -- attach label to specified version - */ - public static final String FLAG_VERSION = "-version"; - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklbtype.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklbtype.java index 7bb7192e8..87e213755 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklbtype.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCMklbtype.java @@ -94,6 +94,39 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCMklbtype extends ClearCase { + /** + * -replace flag -- replace existing label definition of the same type + */ + public static final String FLAG_REPLACE = "-replace"; + /** + * -global flag -- creates a label type that is global to the VOB or to VOBs that use this VOB + */ + public static final String FLAG_GLOBAL = "-global"; + /** + * -ordinary flag -- creates a label type that can be used only in the current VOB + */ + public static final String FLAG_ORDINARY = "-ordinary"; + /** + * -pbranch flag -- allows label type to be used once per branch + */ + public static final String FLAG_PBRANCH = "-pbranch"; + /** + * -shared flag -- sets the way mastership is checked by ClearCase + */ + public static final String FLAG_SHARED = "-shared"; + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + private String mTypeName = null; private String mVOB = null; private String mComment = null; @@ -111,9 +144,9 @@ public class CCMklbtype extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); - int result = 0; // Check for required attributes if (getTypeName() == null) { @@ -132,14 +165,13 @@ public class CCMklbtype extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getTypeSpecifier(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -152,11 +184,9 @@ public class CCMklbtype extends ClearCase { if (getOrdinary()) { // -ordinary cmd.createArgument().setValue(FLAG_ORDINARY); - } else { - if (getGlobal()) { - // -global - cmd.createArgument().setValue(FLAG_GLOBAL); - } + } else if (getGlobal()) { + // -global + cmd.createArgument().setValue(FLAG_GLOBAL); } if (getPbranch()) { @@ -172,20 +202,17 @@ public class CCMklbtype extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } // type-name@vob cmd.createArgument().setValue(getTypeSpecifier()); } - /** * Set type-name string * @@ -348,7 +375,6 @@ public class CCMklbtype extends ClearCase { return mCfile; } - /** * Get the 'comment' command * @@ -392,49 +418,11 @@ public class CCMklbtype extends ClearCase { * specified, otherwise an empty string */ private String getTypeSpecifier() { - String typenm = null; - - typenm = getTypeName(); + String typenm = getTypeName(); if (getVOB() != null) { typenm += "@" + getVOB(); } - return typenm; } - - /** - * -replace flag -- replace existing label definition of the same type - */ - public static final String FLAG_REPLACE = "-replace"; - /** - * -global flag -- creates a label type that is global to the VOB or to VOBs that use this VOB - */ - public static final String FLAG_GLOBAL = "-global"; - /** - * -ordinary flag -- creates a label type that can be used only in the current VOB - */ - public static final String FLAG_ORDINARY = "-ordinary"; - /** - * -pbranch flag -- allows label type to be used once per branch - */ - public static final String FLAG_PBRANCH = "-pbranch"; - /** - * -shared flag -- sets the way mastership is checked by ClearCase - */ - public static final String FLAG_SHARED = "-shared"; - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCRmtype.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCRmtype.java index cef0c3a57..c699de126 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCRmtype.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCRmtype.java @@ -86,6 +86,31 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCRmtype extends ClearCase { + /** + * -ignore flag -- ignore pre-trigger operations when removing a trigger type + */ + public static final String FLAG_IGNORE = "-ignore"; + /** + * -rmall flag -- removes all instances of a type and the type object itself + */ + public static final String FLAG_RMALL = "-rmall"; + /** + * -force flag -- suppresses confirmation prompts + */ + public static final String FLAG_FORCE = "-force"; + /** + * -c flag -- comment to attach to the file + */ + public static final String FLAG_COMMENT = "-c"; + /** + * -cfile flag -- file containing a comment to attach to the file + */ + public static final String FLAG_COMMENTFILE = "-cfile"; + /** + * -nc flag -- no comment is specified + */ + public static final String FLAG_NOCOMMENT = "-nc"; + private String mTypeKind = null; private String mTypeName = null; private String mVOB = null; @@ -101,9 +126,9 @@ public class CCRmtype extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); - int result = 0; // Check for required attributes if (getTypeKind() == null) { @@ -125,14 +150,13 @@ public class CCRmtype extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getTypeSpecifier(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -149,13 +173,11 @@ public class CCRmtype extends ClearCase { if (getComment() != null) { // -c getCommentCommand(cmd); + } else if (getCommentFile() != null) { + // -cfile + getCommentFileCommand(cmd); } else { - if (getCommentFile() != null) { - // -cfile - getCommentFileCommand(cmd); - } else { - cmd.createArgument().setValue(FLAG_NOCOMMENT); - } + cmd.createArgument().setValue(FLAG_NOCOMMENT); } // type-kind:type-name @@ -297,10 +319,9 @@ public class CCRmtype extends ClearCase { private String getTypeSpecifier() { String tkind = getTypeKind(); String tname = getTypeName(); - String typeSpec = null; // Return the type-selector - typeSpec = tkind + ":" + tname; + String typeSpec = tkind + ":" + tname; if (getVOB() != null) { typeSpec += "@" + getVOB(); } @@ -343,31 +364,4 @@ public class CCRmtype extends ClearCase { } } - - /** - * -ignore flag -- ignore pre-trigger operations when removing a trigger type - */ - public static final String FLAG_IGNORE = "-ignore"; - /** - * -rmall flag -- removes all instances of a type and the type object itself - */ - public static final String FLAG_RMALL = "-rmall"; - /** - * -force flag -- suppresses confirmation prompts - */ - public static final String FLAG_FORCE = "-force"; - /** - * -c flag -- comment to attach to the file - */ - public static final String FLAG_COMMENT = "-c"; - /** - * -cfile flag -- file containing a comment to attach to the file - */ - public static final String FLAG_COMMENTFILE = "-cfile"; - /** - * -nc flag -- no comment is specified - */ - public static final String FLAG_NOCOMMENT = "-nc"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java index 3c00e1af1..266c0984c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnCheckout.java @@ -53,6 +53,15 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCUnCheckout extends ClearCase { + /** + * -keep flag -- keep a copy of the file with .keep extension + */ + public static final String FLAG_KEEPCOPY = "-keep"; + /** + * -rm flag -- remove the copy of the file + */ + public static final String FLAG_RM = "-rm"; + private boolean mKeep = false; /** @@ -62,10 +71,10 @@ public class CCUnCheckout extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -84,14 +93,13 @@ public class CCUnCheckout extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } - /** * Check the command line options. */ @@ -127,15 +135,4 @@ public class CCUnCheckout extends ClearCase { return mKeep; } - - /** - * -keep flag -- keep a copy of the file with .keep extension - */ - public static final String FLAG_KEEPCOPY = "-keep"; - /** - * -rm flag -- remove the copy of the file - */ - public static final String FLAG_RM = "-rm"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnlock.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnlock.java index 4ca3e8905..dbb5f12af 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnlock.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUnlock.java @@ -18,12 +18,14 @@ package org.apache.tools.ant.taskdefs.optional.clearcase; +import java.util.Optional; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.types.Commandline; -/** +/* * TODO: * comment field doesn't include all options yet */ @@ -68,6 +70,15 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCUnlock extends ClearCase { + /** + * -comment flag -- method to use for commenting events + */ + public static final String FLAG_COMMENT = "-comment"; + /** + * -pname flag -- pathname to lock + */ + public static final String FLAG_PNAME = "-pname"; + private String mComment = null; private String mPname = null; @@ -78,10 +89,10 @@ public class CCUnlock extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -104,10 +115,10 @@ public class CCUnlock extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getOpType(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -119,8 +130,8 @@ public class CCUnlock extends ClearCase { getCommentCommand(cmd); if (getObjSelect() == null && getPname() == null) { - throw new BuildException("Should select either an element " - + "(pname) or an object (objselect)"); + throw new BuildException( + "Should select either an element (pname) or an object (objselect)"); } getPnameCommand(cmd); // object selector @@ -203,15 +214,14 @@ public class CCUnlock extends ClearCase { private void getCommentCommand(Commandline cmd) { if (getComment() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_COMMENT); - cmd.createArgument().setValue(getComment()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_COMMENT); + cmd.createArgument().setValue(getComment()); } /** @@ -223,15 +233,14 @@ public class CCUnlock extends ClearCase { private void getPnameCommand(Commandline cmd) { if (getPname() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_PNAME); - cmd.createArgument().setValue(getPname()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_PNAME); + cmd.createArgument().setValue(getPname()); } /** @@ -240,21 +249,7 @@ public class CCUnlock extends ClearCase { * @return String containing the object/pname being worked on */ private String getOpType() { - - if (getPname() != null) { - return getPname(); - } else { - return getObjSelect(); - } + return Optional.ofNullable(getPname()).orElseGet(this::getObjSelect); } - /** - * -comment flag -- method to use for commenting events - */ - public static final String FLAG_COMMENT = "-comment"; - /** - * -pname flag -- pathname to lock - */ - public static final String FLAG_PNAME = "-pname"; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java index 712efdcae..96afe8d74 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/CCUpdate.java @@ -80,6 +80,35 @@ import org.apache.tools.ant.types.Commandline; * */ public class CCUpdate extends ClearCase { + /** + * -graphical flag -- display graphical dialog during update operation + */ + public static final String FLAG_GRAPHICAL = "-graphical"; + /** + * -log flag -- file to log status to + */ + public static final String FLAG_LOG = "-log"; + /** + * -overwrite flag -- overwrite hijacked files + */ + public static final String FLAG_OVERWRITE = "-overwrite"; + /** + * -noverwrite flag -- do not overwrite hijacked files + */ + public static final String FLAG_NOVERWRITE = "-noverwrite"; + /** + * -rename flag -- rename hijacked files with .keep extension + */ + public static final String FLAG_RENAME = "-rename"; + /** + * -ctime flag -- modified time is written as the current time + */ + public static final String FLAG_CURRENTTIME = "-ctime"; + /** + * -ptime flag -- modified time is written as the VOB time + */ + public static final String FLAG_PRESERVETIME = "-ptime"; + private boolean mGraphical = false; private boolean mOverwrite = false; private boolean mRename = false; @@ -94,10 +123,10 @@ public class CCUpdate extends ClearCase { * to execute the command line. * @throws BuildException if the command fails and failonerr is set to true */ + @Override public void execute() throws BuildException { Commandline commandLine = new Commandline(); Project aProj = getProject(); - int result = 0; // Default the viewpath to basedir if it is not specified if (getViewPath() == null) { @@ -120,10 +149,10 @@ public class CCUpdate extends ClearCase { getProject().log("Ignoring any errors that occur for: " + getViewPathBasename(), Project.MSG_VERBOSE); } - result = run(commandLine); + int result = run(commandLine); if (Execute.isFailure(result) && getFailOnErr()) { - String msg = "Failed executing: " + commandLine.toString(); - throw new BuildException(msg, getLocation()); + throw new BuildException("Failed executing: " + commandLine, + getLocation()); } } @@ -139,24 +168,20 @@ public class CCUpdate extends ClearCase { if (getOverwrite()) { // -overwrite cmd.createArgument().setValue(FLAG_OVERWRITE); + } else if (getRename()) { + // -rename + cmd.createArgument().setValue(FLAG_RENAME); } else { - if (getRename()) { - // -rename - cmd.createArgument().setValue(FLAG_RENAME); - } else { - // -noverwrite - cmd.createArgument().setValue(FLAG_NOVERWRITE); - } + // -noverwrite + cmd.createArgument().setValue(FLAG_NOVERWRITE); } if (getCurrentTime()) { // -ctime cmd.createArgument().setValue(FLAG_CURRENTTIME); - } else { - if (getPreserveTime()) { - // -ptime - cmd.createArgument().setValue(FLAG_PRESERVETIME); - } + } else if (getPreserveTime()) { + // -ptime + cmd.createArgument().setValue(FLAG_PRESERVETIME); } // -log logname @@ -278,7 +303,6 @@ public class CCUpdate extends ClearCase { return mLog; } - /** * Get the 'log' command * @@ -287,45 +311,14 @@ public class CCUpdate extends ClearCase { private void getLogCommand(Commandline cmd) { if (getLog() == null) { return; - } else { - /* Had to make two separate commands here because if a space is - inserted between the flag and the value, it is treated as a - Windows filename with a space and it is enclosed in double - quotes ("). This breaks clearcase. - */ - cmd.createArgument().setValue(FLAG_LOG); - cmd.createArgument().setValue(getLog()); } + /* Had to make two separate commands here because if a space is + inserted between the flag and the value, it is treated as a + Windows filename with a space and it is enclosed in double + quotes ("). This breaks clearcase. + */ + cmd.createArgument().setValue(FLAG_LOG); + cmd.createArgument().setValue(getLog()); } - /** - * -graphical flag -- display graphical dialog during update operation - */ - public static final String FLAG_GRAPHICAL = "-graphical"; - /** - * -log flag -- file to log status to - */ - public static final String FLAG_LOG = "-log"; - /** - * -overwrite flag -- overwrite hijacked files - */ - public static final String FLAG_OVERWRITE = "-overwrite"; - /** - * -noverwrite flag -- do not overwrite hijacked files - */ - public static final String FLAG_NOVERWRITE = "-noverwrite"; - /** - * -rename flag -- rename hijacked files with .keep extension - */ - public static final String FLAG_RENAME = "-rename"; - /** - * -ctime flag -- modified time is written as the current time - */ - public static final String FLAG_CURRENTTIME = "-ctime"; - /** - * -ptime flag -- modified time is written as the VOB time - */ - public static final String FLAG_PRESERVETIME = "-ptime"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java index 5a537eb85..eba0e9a6c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/clearcase/ClearCase.java @@ -19,6 +19,7 @@ package org.apache.tools.ant.taskdefs.optional.clearcase; import java.io.File; +import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -29,8 +30,6 @@ import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.util.FileUtils; - - /** * A base class for creating tasks for executing commands on ClearCase. * <p> @@ -46,11 +45,73 @@ import org.apache.tools.ant.util.FileUtils; * */ public abstract class ClearCase extends Task { + /** + * Constant for the thing to execute + */ + private static final String CLEARTOOL_EXE = "cleartool"; + /** + * The 'Update' command + */ + public static final String COMMAND_UPDATE = "update"; + /** + * The 'Checkout' command + */ + public static final String COMMAND_CHECKOUT = "checkout"; + /** + * The 'Checkin' command + */ + public static final String COMMAND_CHECKIN = "checkin"; + /** + * The 'UndoCheckout' command + */ + public static final String COMMAND_UNCHECKOUT = "uncheckout"; + /** + * The 'Lock' command + */ + public static final String COMMAND_LOCK = "lock"; + /** + * The 'Unlock' command + */ + public static final String COMMAND_UNLOCK = "unlock"; + /** + * The 'Mkbl' command + */ + public static final String COMMAND_MKBL = "mkbl"; + /** + * The 'Mklabel' command + */ + public static final String COMMAND_MKLABEL = "mklabel"; + /** + * The 'Mklbtype' command + */ + public static final String COMMAND_MKLBTYPE = "mklbtype"; + /** + * The 'Rmtype' command + */ + public static final String COMMAND_RMTYPE = "rmtype"; + /** + * The 'LsCheckout' command + */ + public static final String COMMAND_LSCO = "lsco"; + /** + * The 'Mkelem' command + */ + public static final String COMMAND_MKELEM = "mkelem"; + /** + * The 'Mkattr' command + */ + public static final String COMMAND_MKATTR = "mkattr"; + /** + * The 'Mkdir' command + */ + public static final String COMMAND_MKDIR = "mkdir"; + private String mClearToolDir = ""; private String mviewPath = null; private String mobjSelect = null; private int pcnt = 0; private boolean mFailonerr = true; + /** * Set the directory where the cleartool executable is located. * @@ -67,7 +128,7 @@ public abstract class ClearCase extends Task { */ protected final String getClearToolCommand() { String toReturn = mClearToolDir; - if (!toReturn.equals("") && !toReturn.endsWith("/")) { + if (!("".equals(toReturn) || toReturn.endsWith("/"))) { toReturn += "/"; } @@ -129,13 +190,13 @@ public abstract class ClearCase extends Task { protected int run(Commandline cmd) { try { Project aProj = getProject(); - Execute exe - = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN)); + Execute exe = new Execute( + new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN)); exe.setAntRun(aProj); exe.setWorkingDirectory(aProj.getBaseDir()); exe.setCommandline(cmd.getCommandline()); return exe.execute(); - } catch (java.io.IOException e) { + } catch (IOException e) { throw new BuildException(e, getLocation()); } } @@ -157,6 +218,7 @@ public abstract class ClearCase extends Task { return getProject().getProperty(outV); } + /** * If true, command will throw an exception on failure. * @@ -177,66 +239,4 @@ public abstract class ClearCase extends Task { return mFailonerr; } - /** - * Constant for the thing to execute - */ - private static final String CLEARTOOL_EXE = "cleartool"; - /** - * The 'Update' command - */ - public static final String COMMAND_UPDATE = "update"; - /** - * The 'Checkout' command - */ - public static final String COMMAND_CHECKOUT = "checkout"; - /** - * The 'Checkin' command - */ - public static final String COMMAND_CHECKIN = "checkin"; - /** - * The 'UndoCheckout' command - */ - public static final String COMMAND_UNCHECKOUT = "uncheckout"; - /** - * The 'Lock' command - */ - public static final String COMMAND_LOCK = "lock"; - /** - * The 'Unlock' command - */ - public static final String COMMAND_UNLOCK = "unlock"; - /** - * The 'Mkbl' command - */ - public static final String COMMAND_MKBL = "mkbl"; - /** - * The 'Mklabel' command - */ - public static final String COMMAND_MKLABEL = "mklabel"; - /** - * The 'Mklbtype' command - */ - public static final String COMMAND_MKLBTYPE = "mklbtype"; - /** - * The 'Rmtype' command - */ - public static final String COMMAND_RMTYPE = "rmtype"; - /** - * The 'LsCheckout' command - */ - public static final String COMMAND_LSCO = "lsco"; - /** - * The 'Mkelem' command - */ - public static final String COMMAND_MKELEM = "mkelem"; - /** - * The 'Mkattr' command - */ - public static final String COMMAND_MKATTR = "mkattr"; - /** - * The 'Mkdir' command - */ - public static final String COMMAND_MKDIR = "mkdir"; - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java index 8f0a57975..3c8d82b33 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/AntAnalyzer.java @@ -20,10 +20,11 @@ package org.apache.tools.ant.taskdefs.optional.depend; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.Enumeration; -import java.util.Hashtable; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -37,11 +38,6 @@ import org.apache.tools.ant.util.depend.AbstractAnalyzer; * */ public class AntAnalyzer extends AbstractAnalyzer { - /** - * Default constructor - */ - public AntAnalyzer() { - } /** * Determine the dependencies of the configured root classes. @@ -51,31 +47,27 @@ public class AntAnalyzer extends AbstractAnalyzer { * @param classes a vector to be populated with the names of the * dependency classes. */ + @Override protected void determineDependencies(Vector<File> files, Vector<String> classes) { // we get the root classes and build up a set of // classes upon which they depend - Hashtable<String, String> dependencies = new Hashtable<String, String>(); - Hashtable<File, File> containers = new Hashtable<File, File>(); - Hashtable<String, String> toAnalyze = new Hashtable<String, String>(); - for (Enumeration<String> e = getRootClasses(); e.hasMoreElements();) { - String classname = e.nextElement(); - toAnalyze.put(classname, classname); - } + Set<String> toAnalyze = new HashSet<>(Collections.list(getRootClasses())); int count = 0; int maxCount = isClosureRequired() ? MAX_LOOPS : 1; - Hashtable<String, String> analyzedDeps = null; - while (toAnalyze.size() != 0 && count++ < maxCount) { - analyzedDeps = new Hashtable<String, String>(); - for (Enumeration<String> e = toAnalyze.keys(); e.hasMoreElements();) { - String classname = e.nextElement(); - dependencies.put(classname, classname); + Set<String> dependencies = new HashSet<>(); + Set<File> containers = new HashSet<>(); + Set<String> analyzedDeps = null; + while (!toAnalyze.isEmpty() && count++ < maxCount) { + analyzedDeps = new HashSet<>(); + for (String classname : toAnalyze) { + dependencies.add(classname); try { File container = getClassContainer(classname); if (container == null) { continue; } - containers.put(container, container); + containers.add(container); ZipFile zipFile = null; InputStream inStream = null; @@ -93,7 +85,7 @@ public class AntAnalyzer extends AbstractAnalyzer { ClassFile classFile = new ClassFile(); classFile.read(inStream); for (String dependency : classFile.getClassRefs()) { - analyzedDeps.put(dependency, dependency); + analyzedDeps.add(dependency); } } finally { FileUtils.close(inStream); @@ -107,27 +99,20 @@ public class AntAnalyzer extends AbstractAnalyzer { toAnalyze.clear(); // now recover all the dependencies collected and add to the list. - for (String className : analyzedDeps.values()) { - if (!dependencies.containsKey(className)) { - toAnalyze.put(className, className); + for (String className : analyzedDeps) { + if (!dependencies.contains(className)) { + toAnalyze.add(className); } } } // pick up the last round of dependencies that were determined - for (String className : analyzedDeps.values()) { - dependencies.put(className, className); - } + dependencies.addAll(analyzedDeps); files.removeAllElements(); - for (File f : containers.keySet()) { - files.add(f); - } - + files.addAll(containers); classes.removeAllElements(); - for (String dependency :dependencies.keySet()) { - classes.add(dependency); - } + classes.addAll(dependencies); } /** @@ -135,9 +120,9 @@ public class AntAnalyzer extends AbstractAnalyzer { * * @return true if the analyzer provides dependency file information. */ + @Override protected boolean supportsFileDependencies() { return true; } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java index 858ce03e2..49f8a2755 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFile.java @@ -59,8 +59,8 @@ public class ClassFile { DataInputStream classStream = new DataInputStream(stream); if (classStream.readInt() != CLASS_MAGIC) { - throw new ClassFormatError("No Magic Code Found " - + "- probably not a Java class file."); + throw new ClassFormatError( + "No Magic Code Found - probably not a Java class file."); } // right we have a good looking class file. @@ -81,7 +81,6 @@ public class ClassFile { className = classInfo.getClassName(); } - /** * Get the classes which this class references. * @@ -89,7 +88,7 @@ public class ClassFile { */ public Vector<String> getClassRefs() { - Vector<String> classRefs = new Vector<String>(); + Vector<String> classRefs = new Vector<>(); final int size = constantPool.size(); for (int i = 0; i < size; ++i) { @@ -118,4 +117,3 @@ public class ClassFile { return ClassFileUtils.convertSlashName(className); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileIterator.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileIterator.java index 92fc191b0..0af757986 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileIterator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileIterator.java @@ -17,11 +17,14 @@ */ package org.apache.tools.ant.taskdefs.optional.depend; +import java.util.Iterator; +import java.util.NoSuchElementException; + /** * Iterator interface for iterating over a set of class files * */ -public interface ClassFileIterator { +public interface ClassFileIterator extends Iterable<ClassFile> { /** * Get the next class file in the iteration @@ -29,5 +32,33 @@ public interface ClassFileIterator { * @return the next class file in the iteration */ ClassFile getNextClassFile(); -} + + @Override + default Iterator<ClassFile> iterator() { + + return new Iterator<ClassFile>() { + ClassFile next; + { + next = getNextClassFile(); + } + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public ClassFile next() { + if (next == null) { + throw new NoSuchElementException(); + } + try { + return next; + } finally { + next = getNextClassFile(); + } + } + + }; + } +} diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileUtils.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileUtils.java index c6eec6cc5..273b563ca 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileUtils.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/ClassFileUtils.java @@ -49,4 +49,3 @@ public class ClassFileUtils { return dotName.replace('.', '/'); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java index f46af0afa..c08b089bc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/Depend.java @@ -23,10 +23,18 @@ import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.io.PrintWriter; import java.net.URL; +import java.util.ArrayList; import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; @@ -37,6 +45,9 @@ import org.apache.tools.ant.taskdefs.rmic.DefaultRmicAdapter; import org.apache.tools.ant.taskdefs.rmic.WLRmic; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; +import org.apache.tools.ant.types.ResourceCollection; +import org.apache.tools.ant.types.resources.Difference; +import org.apache.tools.ant.types.resources.FileProvider; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.depend.DependencyAnalyzer; @@ -74,26 +85,23 @@ public class Depend extends MatchingTask { /** The directory which contains the dependency cache. */ private File cache; - /** The list of source paths derived from the srcPath field. */ - private String[] srcPathList; - /** * A map which gives for every class a list of the class which it * affects. */ - private Hashtable affectedClassMap; + private Map<String, Map<String, ClassFileInfo>> affectedClassMap; /** A map which gives information about a class */ - private Hashtable classFileInfoMap; + private Map<String, ClassFileInfo> classFileInfoMap; /** * A map which gives the list of jars and classes from the classpath * that a class depends upon */ - private Hashtable classpathDependencies; + private Map<String, Set<File>> classpathDependencies; /** The list of classes which are out of date. */ - private Hashtable outOfDateClasses; + private Map<String, String> outOfDateClasses; /** * indicates that the dependency relationships should be extended beyond @@ -182,29 +190,24 @@ public class Depend extends MatchingTask { * @return a collection of class dependencies * @exception IOException if the dependency file cannot be read */ - private Hashtable readCachedDependencies(File depFile) throws IOException { - Hashtable dependencyMap = new Hashtable(); + private Map<String, List<String>> readCachedDependencies(File depFile) throws IOException { + Map<String, List<String>> dependencyMap = new HashMap<>(); - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(depFile)); - String line = null; - Vector dependencyList = null; - String className = null; - int prependLength = CLASSNAME_PREPEND.length(); + int prependLength = CLASSNAME_PREPEND.length(); + + try (BufferedReader in = new BufferedReader(new FileReader(depFile))) { + List<String> dependencyList = null; + String line; while ((line = in.readLine()) != null) { if (line.startsWith(CLASSNAME_PREPEND)) { - dependencyList = new Vector(); - className = line.substring(prependLength); - dependencyMap.put(className, dependencyList); + String className = line.substring(prependLength); + dependencyList = dependencyMap.computeIfAbsent(className, + k -> new ArrayList<>()); } else if (dependencyList != null) { - dependencyList.addElement(line); + dependencyList.add(line); } } - } finally { - FileUtils.close(in); } - return dependencyMap; } @@ -214,32 +217,18 @@ public class Depend extends MatchingTask { * @param dependencyMap the map of dependencies to be written out. * @exception IOException if the dependency file cannot be written out. */ - private void writeCachedDependencies(Hashtable dependencyMap) + private void writeCachedDependencies(Map<String, List<String>> dependencyMap) throws IOException { if (cache != null) { - BufferedWriter pw = null; - try { - cache.mkdirs(); - File depFile = new File(cache, CACHE_FILE_NAME); - - pw = new BufferedWriter(new FileWriter(depFile)); - Enumeration e = dependencyMap.keys(); - while (e.hasMoreElements()) { - String className = (String) e.nextElement(); - - pw.write(CLASSNAME_PREPEND + className); - pw.newLine(); - - Vector dependencyList - = (Vector) dependencyMap.get(className); - int size = dependencyList.size(); - for (int x = 0; x < size; x++) { - pw.write(String.valueOf(dependencyList.elementAt(x))); - pw.newLine(); - } + cache.mkdirs(); + File depFile = new File(cache, CACHE_FILE_NAME); + try (PrintWriter pw = + new PrintWriter(new BufferedWriter(new FileWriter(depFile)))) { + for (Map.Entry<String, List<String>> e : dependencyMap + .entrySet()) { + pw.printf("%s%s%n", CLASSNAME_PREPEND, e.getKey()); + e.getValue().forEach(pw::println); } - } finally { - FileUtils.close(pw); } } } @@ -253,28 +242,16 @@ public class Depend extends MatchingTask { if (dependClasspath == null) { return null; } - - String[] destPathElements = destPath.list(); - String[] classpathElements = dependClasspath.list(); - String checkPath = ""; - for (int i = 0; i < classpathElements.length; ++i) { - String element = classpathElements[i]; - boolean inDestPath = false; - for (int j = 0; j < destPathElements.length && !inDestPath; ++j) { - inDestPath = destPathElements[j].equals(element); - } - if (!inDestPath) { - if (checkPath.length() == 0) { - checkPath = element; - } else { - checkPath += ":" + element; - } - } - } - - Path p = null; - if (checkPath.length() > 0) { - p = new Path(getProject(), checkPath); + Difference diff = new Difference(); + diff.add(destPath); + diff.add(dependClasspath); + + Path p; + if (diff.isEmpty()) { + p = null; + } else { + p = new Path(getProject()); + p.add(diff); } log("Classpath without dest dir is " + p, Project.MSG_DEBUG); @@ -300,11 +277,11 @@ public class Depend extends MatchingTask { * files cannot be read or written */ private void determineDependencies() throws IOException { - affectedClassMap = new Hashtable(); - classFileInfoMap = new Hashtable(); + affectedClassMap = new HashMap<>(); + classFileInfoMap = new HashMap<>(); boolean cacheDirty = false; - Hashtable dependencyMap = new Hashtable(); + Map<String, List<String>> dependencyMap = new HashMap<>(); File cacheFile = null; boolean cacheFileExists = true; long cacheLastModified = Long.MAX_VALUE; @@ -318,13 +295,11 @@ public class Depend extends MatchingTask { dependencyMap = readCachedDependencies(cacheFile); } } - Enumeration classfileEnum = getClassFiles(destPath).elements(); - while (classfileEnum.hasMoreElements()) { - ClassFileInfo info = (ClassFileInfo) classfileEnum.nextElement(); + for (ClassFileInfo info : getClassFiles()) { log("Adding class info for " + info.className, Project.MSG_DEBUG); classFileInfoMap.put(info.className, info); - Vector dependencyList = null; + List<String> dependencyList = null; if (cache != null) { // try to read the dependency info from the map if it is @@ -333,7 +308,7 @@ public class Depend extends MatchingTask { && cacheLastModified > info.absoluteFile.lastModified()) { // depFile exists and is newer than the class file // need to get dependency list from the map. - dependencyList = (Vector) dependencyMap.get(info.className); + dependencyList = dependencyMap.get(info.className); } } @@ -343,11 +318,11 @@ public class Depend extends MatchingTask { analyzer.addRootClass(info.className); analyzer.addClassPath(destPath); analyzer.setClosure(false); - dependencyList = new Vector(); - Enumeration depEnum = analyzer.getClassDependencies(); + dependencyList = new ArrayList<>(); + Enumeration<String> depEnum = analyzer.getClassDependencies(); while (depEnum.hasMoreElements()) { - Object o = depEnum.nextElement(); - dependencyList.addElement(o); + String o = depEnum.nextElement(); + dependencyList.add(o); log("Class " + info.className + " depends on " + o, Project.MSG_DEBUG); } @@ -357,18 +332,10 @@ public class Depend extends MatchingTask { // This class depends on each class in the dependency list. For each // one of those, add this class into their affected classes list - Enumeration depEnum = dependencyList.elements(); - while (depEnum.hasMoreElements()) { - String dependentClass = (String) depEnum.nextElement(); - - Hashtable affectedClasses - = (Hashtable) affectedClassMap.get(dependentClass); - if (affectedClasses == null) { - affectedClasses = new Hashtable(); - affectedClassMap.put(dependentClass, affectedClasses); - } - - affectedClasses.put(info.className, info); + for (String dependentClass : dependencyList) { + affectedClassMap + .computeIfAbsent(dependentClass, k -> new HashMap<>()) + .put(info.className, info); log(dependentClass + " affects " + info.className, Project.MSG_DEBUG); } @@ -378,21 +345,19 @@ public class Depend extends MatchingTask { Path checkPath = getCheckClassPath(); if (checkPath != null) { // now determine which jars each class depends upon - classpathDependencies = new Hashtable(); + classpathDependencies = new HashMap<>(); try (AntClassLoader loader = getProject().createClassLoader(checkPath)) { - Hashtable classpathFileCache = new Hashtable(); + Map<String, Object> classpathFileCache = new HashMap<>(); Object nullFileMarker = new Object(); - for (Enumeration e = dependencyMap.keys(); e.hasMoreElements();) { - String className = (String) e.nextElement(); + for (Map.Entry<String, List<String>> e : dependencyMap.entrySet()) { + String className = e.getKey(); log("Determining classpath dependencies for " + className, Project.MSG_DEBUG); - Vector dependencyList = (Vector) dependencyMap.get(className); - Hashtable dependencies = new Hashtable(); + List<String> dependencyList = e.getValue(); + Set<File> dependencies = new HashSet<>(); classpathDependencies.put(className, dependencies); - Enumeration e2 = dependencyList.elements(); - while (e2.hasMoreElements()) { - String dependency = (String) e2.nextElement(); + for (String dependency : dependencyList) { log("Looking for " + dependency, Project.MSG_DEBUG); Object classpathFileObject = classpathFileCache.get(dependency); @@ -405,22 +370,23 @@ public class Depend extends MatchingTask { = loader.getResource(dependency.replace('.', '/') + ".class"); log("URL is " + classURL, Project.MSG_DEBUG); if (classURL != null) { - if (classURL.getProtocol().equals("jar")) { + if ("jar".equals(classURL.getProtocol())) { String jarFilePath = classURL.getFile(); int classMarker = jarFilePath.indexOf('!'); jarFilePath = jarFilePath.substring(0, classMarker); if (jarFilePath.startsWith("file:")) { classpathFileObject = new File( - FileUtils.getFileUtils().fromURI(jarFilePath)); + FileUtils.getFileUtils() + .fromURI(jarFilePath)); } else { throw new IOException( - "Bizarre nested path in jar: protocol: " - + jarFilePath); + "Bizarre nested path in jar: protocol: " + + jarFilePath); } - } else if (classURL.getProtocol().equals("file")) { + } else if ("file".equals(classURL.getProtocol())) { classpathFileObject = new File( - FileUtils.getFileUtils() - .fromURI(classURL.toExternalForm())); + FileUtils.getFileUtils().fromURI( + classURL.toExternalForm())); } log("Class " + className + " depends on " + classpathFileObject @@ -437,7 +403,7 @@ public class Depend extends MatchingTask { File jarFile = (File) classpathFileObject; log("Adding a classpath dependency on " + jarFile, Project.MSG_DEBUG); - dependencies.put(jarFile, jarFile); + dependencies.add(jarFile); } } } @@ -460,11 +426,9 @@ public class Depend extends MatchingTask { */ private int deleteAllAffectedFiles() { int count = 0; - for (Enumeration e = outOfDateClasses.elements(); e.hasMoreElements();) { - String className = (String) e.nextElement(); + for (String className : outOfDateClasses.keySet()) { count += deleteAffectedFiles(className); - ClassFileInfo classInfo - = (ClassFileInfo) classFileInfoMap.get(className); + ClassFileInfo classInfo = classFileInfoMap.get(className); if (classInfo != null && classInfo.absoluteFile.exists()) { if (classInfo.sourceFile == null) { warnOutOfDateButNotDeleted(classInfo, className, className); @@ -487,14 +451,13 @@ public class Depend extends MatchingTask { private int deleteAffectedFiles(String className) { int count = 0; - Hashtable affectedClasses = (Hashtable) affectedClassMap.get(className); + Map<String, ClassFileInfo> affectedClasses = affectedClassMap.get(className); if (affectedClasses == null) { return count; } - for (Enumeration e = affectedClasses.keys(); e.hasMoreElements();) { - String affectedClass = (String) e.nextElement(); - ClassFileInfo affectedClassInfo - = (ClassFileInfo) affectedClasses.get(affectedClass); + for (Map.Entry<String, ClassFileInfo> e : affectedClasses.entrySet()) { + String affectedClass = e.getKey(); + ClassFileInfo affectedClassInfo = e.getValue(); if (!affectedClassInfo.absoluteFile.exists()) { continue; @@ -516,16 +479,16 @@ public class Depend extends MatchingTask { // without closure we may delete an inner class but not the // top level class which would not trigger a recompile. - if (affectedClass.indexOf("$") == -1) { + if (affectedClass.indexOf('$') == -1) { continue; } // need to delete the main class String topLevelClassName - = affectedClass.substring(0, affectedClass.indexOf("$")); + = affectedClass.substring(0, affectedClass.indexOf('$')); log("Top level class = " + topLevelClassName, Project.MSG_VERBOSE); ClassFileInfo topLevelClassInfo - = (ClassFileInfo) classFileInfoMap.get(topLevelClassName); + = classFileInfoMap.get(topLevelClassName); if (topLevelClassInfo != null && topLevelClassInfo.absoluteFile.exists()) { log("Deleting file " @@ -569,8 +532,8 @@ public class Depend extends MatchingTask { log("The class " + affectedClass + " in file " + affectedClassInfo.absoluteFile.getPath() + " is out of date due to " + className - + " but has not been deleted because its source file" - + " could not be determined", level); + + " but has not been deleted because its source file could not be determined", + level); affectedClassInfo.isUserWarned = true; } @@ -598,75 +561,48 @@ public class Depend extends MatchingTask { log("Reverse Dependency Dump for " + affectedClassMap.size() + " classes:", Project.MSG_DEBUG); - Enumeration classEnum = affectedClassMap.keys(); - while (classEnum.hasMoreElements()) { - String className = (String) classEnum.nextElement(); + affectedClassMap.forEach((className, affectedClasses) -> { log(" Class " + className + " affects:", Project.MSG_DEBUG); - Hashtable affectedClasses - = (Hashtable) affectedClassMap.get(className); - Enumeration affectedClassEnum = affectedClasses.keys(); - while (affectedClassEnum.hasMoreElements()) { - String affectedClass = (String) affectedClassEnum.nextElement(); - ClassFileInfo info - = (ClassFileInfo) affectedClasses.get(affectedClass); - log(" " + affectedClass + " in " - + info.absoluteFile.getPath(), Project.MSG_DEBUG); - } - } + affectedClasses.forEach((affectedClass, info) -> log( + " " + affectedClass + " in " + info.absoluteFile.getPath(), + Project.MSG_DEBUG)); + }); if (classpathDependencies != null) { log("Classpath file dependencies (Forward):", Project.MSG_DEBUG); - Enumeration classpathEnum = classpathDependencies.keys(); - while (classpathEnum.hasMoreElements()) { - String className = (String) classpathEnum.nextElement(); + classpathDependencies.forEach((className, dependencies) -> { log(" Class " + className + " depends on:", Project.MSG_DEBUG); - Hashtable dependencies - = (Hashtable) classpathDependencies.get(className); - - Enumeration classpathFileEnum = dependencies.elements(); - while (classpathFileEnum.hasMoreElements()) { - File classpathFile = (File) classpathFileEnum.nextElement(); - log(" " + classpathFile.getPath(), Project.MSG_DEBUG); - } - } + dependencies.forEach(f -> log(" " + f.getPath(), Project.MSG_DEBUG)); + }); } } private void determineOutOfDateClasses() { - outOfDateClasses = new Hashtable(); - for (int i = 0; i < srcPathList.length; i++) { - File srcDir = getProject().resolveFile(srcPathList[i]); - if (srcDir.exists()) { - DirectoryScanner ds = this.getDirectoryScanner(srcDir); - String[] files = ds.getIncludedFiles(); - scanDir(srcDir, files); - } - } + outOfDateClasses = new HashMap<>(); + directories(srcPath).forEach(srcDir -> { + DirectoryScanner ds = this.getDirectoryScanner(srcDir); + scanDir(srcDir, ds.getIncludedFiles()); + }); // now check classpath file dependencies if (classpathDependencies == null) { return; } - Enumeration classpathDepsEnum = classpathDependencies.keys(); - while (classpathDepsEnum.hasMoreElements()) { - String className = (String) classpathDepsEnum.nextElement(); + for (Map.Entry<String, Set<File>> e : classpathDependencies.entrySet()) { + String className = e.getKey(); if (outOfDateClasses.containsKey(className)) { continue; } - ClassFileInfo info - = (ClassFileInfo) classFileInfoMap.get(className); + ClassFileInfo info = classFileInfoMap.get(className); // if we have no info about the class - it may have been deleted already and we // are using cached info. if (info != null) { - Hashtable dependencies - = (Hashtable) classpathDependencies.get(className); - for (Enumeration e2 = dependencies.elements(); e2.hasMoreElements();) { - File classpathFile = (File) e2.nextElement(); - if (classpathFile.lastModified() - > info.absoluteFile.lastModified()) { + for (File classpathFile : e.getValue()) { + if (classpathFile.lastModified() > info.absoluteFile + .lastModified()) { log("Class " + className + " is out of date with respect to " + classpathFile, Project.MSG_DEBUG); @@ -683,6 +619,7 @@ public class Depend extends MatchingTask { * * @exception BuildException Thrown in case of an unrecoverable error. */ + @Override public void execute() throws BuildException { try { long start = System.currentTimeMillis(); @@ -691,8 +628,7 @@ public class Depend extends MatchingTask { getLocation()); } - srcPathList = srcPath.list(); - if (srcPathList.length == 0) { + if (!directories(srcPath).findAny().isPresent()) { throw new BuildException("srcdir attribute must be non-empty", getLocation()); } @@ -702,8 +638,8 @@ public class Depend extends MatchingTask { } if (cache != null && cache.exists() && !cache.isDirectory()) { - throw new BuildException("The cache, if specified, must " - + "point to a directory"); + throw new BuildException( + "The cache, if specified, must point to a directory"); } if (cache != null && !cache.exists()) { @@ -743,50 +679,38 @@ public class Depend extends MatchingTask { * checked. */ protected void scanDir(File srcDir, String[] files) { - - for (int i = 0; i < files.length; i++) { - File srcFile = new File(srcDir, files[i]); - if (files[i].endsWith(".java")) { + for (String f : files) { + File srcFile = new File(srcDir, f); + if (f.endsWith(".java")) { String filePath = srcFile.getPath(); String className = filePath.substring(srcDir.getPath().length() + 1, filePath.length() - ".java".length()); className = ClassFileUtils.convertSlashName(className); ClassFileInfo info - = (ClassFileInfo) classFileInfoMap.get(className); + = classFileInfoMap.get(className); if (info == null) { // there was no class file. add this class to the list outOfDateClasses.put(className, className); - } else { - if (srcFile.lastModified() - > info.absoluteFile.lastModified()) { - outOfDateClasses.put(className, className); - } + } else if (srcFile.lastModified() > info.absoluteFile + .lastModified()) { + outOfDateClasses.put(className, className); } } } } - /** * Get the list of class files we are going to analyse. * - * @param classLocations a path structure containing all the directories - * where classes can be found. * @return a vector containing the classes to analyse. */ - private Vector getClassFiles(Path classLocations) { + private List<ClassFileInfo> getClassFiles() { // break the classLocations into its components. - String[] classLocationsList = classLocations.list(); + List<ClassFileInfo> classFileList = new ArrayList<>(); - Vector classFileList = new Vector(); - - for (int i = 0; i < classLocationsList.length; ++i) { - File dir = new File(classLocationsList[i]); - if (dir.isDirectory()) { - addClassFiles(classFileList, dir, dir); - } - } + directories(destPath) + .forEach(dir -> addClassFiles(classFileList, dir, dir)); return classFileList; } @@ -800,21 +724,17 @@ public class Depend extends MatchingTask { */ private File findSourceFile(String classname, File sourceFileKnownToExist) { String sourceFilename; - int innerIndex = classname.indexOf("$"); + int innerIndex = classname.indexOf('$'); if (innerIndex != -1) { sourceFilename = classname.substring(0, innerIndex) + ".java"; } else { sourceFilename = classname + ".java"; } - // search the various source path entries - for (int i = 0; i < srcPathList.length; ++i) { - File sourceFile = new File(srcPathList[i], sourceFilename); - if (sourceFile.equals(sourceFileKnownToExist) || sourceFile.exists()) { - return sourceFile; - } - } - return null; + return directories(srcPath) + .map(d -> new File(d, sourceFilename)).filter(Predicate + .<File> isEqual(sourceFileKnownToExist).or(File::exists)) + .findFirst().orElse(null); } /** @@ -829,36 +749,34 @@ public class Depend extends MatchingTask { * the absolute class name from the relative position in the * source tree */ - private void addClassFiles(Vector classFileList, File dir, File root) { - String[] filesInDir = dir.list(); + private void addClassFiles(List<ClassFileInfo> classFileList, File dir, File root) { + File[] children = dir.listFiles(); - if (filesInDir == null) { + if (children == null) { return; } - int length = filesInDir.length; int rootLength = root.getPath().length(); File sourceFileKnownToExist = null; // speed optimization - for (int i = 0; i < length; ++i) { - File file = new File(dir, filesInDir[i]); - if (filesInDir[i].endsWith(".class")) { + for (File file : children) { + if (file.getName().endsWith(".class")) { ClassFileInfo info = new ClassFileInfo(); info.absoluteFile = file; - String relativeName = file.getPath().substring( - rootLength + 1, - file.getPath().length() - ".class".length()); + + String relativeName = file.getPath().substring(rootLength + 1, + file.getPath().length() - ".class".length()); + info.className = ClassFileUtils.convertSlashName(relativeName); - info.sourceFile = sourceFileKnownToExist = findSourceFile( - relativeName, sourceFileKnownToExist); - classFileList.addElement(info); + info.sourceFile = sourceFileKnownToExist = + findSourceFile(relativeName, sourceFileKnownToExist); + classFileList.add(info); } else { addClassFiles(classFileList, file, root); } } } - /** * Set the directories path to find the Java source files. * @@ -907,5 +825,10 @@ public class Depend extends MatchingTask { public void setDump(boolean dump) { this.dump = dump; } -} + private Stream<File> directories(ResourceCollection rc) { + return rc.stream().map(r -> r.as(FileProvider.class)) + .filter(Objects::nonNull).map(FileProvider::getFile) + .filter(File::isDirectory); + } +} diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java index 4401f1cab..71379188f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/DirectoryIterator.java @@ -19,11 +19,14 @@ package org.apache.tools.ant.taskdefs.optional.depend; import java.io.File; import java.io.IOException; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.Iterator; +import java.util.List; import java.io.InputStream; import java.nio.file.Files; -import java.util.Enumeration; -import java.util.Stack; -import java.util.Vector; /** * An iterator which iterates through the contents of a java directory. The @@ -37,7 +40,7 @@ public class DirectoryIterator implements ClassFileIterator { * This is a stack of current iterators supporting the depth first * traversal of the directory tree. */ - private Stack enumStack; + private Deque<Iterator<File>> enumStack; /** * The current directory iterator. As directories encounter lower level @@ -46,7 +49,7 @@ public class DirectoryIterator implements ClassFileIterator { * directory. This implements a depth first traversal of the directory * namespace. */ - private Enumeration currentEnum; + private Iterator<File> currentIterator; /** * Creates a directory iterator. The directory iterator is created to @@ -64,12 +67,8 @@ public class DirectoryIterator implements ClassFileIterator { public DirectoryIterator(File rootDirectory, boolean changeInto) throws IOException { super(); - - enumStack = new Stack(); - - Vector filesInRoot = getDirectoryEntries(rootDirectory); - - currentEnum = filesInRoot.elements(); + enumStack = new ArrayDeque<>(); + currentIterator = getDirectoryEntries(rootDirectory).iterator(); } /** @@ -80,21 +79,12 @@ public class DirectoryIterator implements ClassFileIterator { * @return a vector containing File objects for each entry in the * directory. */ - private Vector getDirectoryEntries(File directory) { - Vector files = new Vector(); - - // File[] filesInDir = directory.listFiles(); - String[] filesInDir = directory.list(); - - if (filesInDir != null) { - int length = filesInDir.length; - - for (int i = 0; i < length; ++i) { - files.addElement(new File(directory, filesInDir[i])); - } + private List<File> getDirectoryEntries(File directory) { + File[] filesInDir = directory.listFiles(); + if (filesInDir == null) { + return Collections.emptyList(); } - - return files; + return Arrays.asList(filesInDir); } /** @@ -111,25 +101,25 @@ public class DirectoryIterator implements ClassFileIterator { * * @return the next ClassFile in the iteration. */ + @Override public ClassFile getNextClassFile() { ClassFile nextElement = null; try { while (nextElement == null) { - if (currentEnum.hasMoreElements()) { - File element = (File) currentEnum.nextElement(); + if (currentIterator.hasNext()) { + File element = currentIterator.next(); if (element.isDirectory()) { // push the current iterator onto the stack and then // iterate through this directory. - enumStack.push(currentEnum); + enumStack.push(currentIterator); - Vector files = getDirectoryEntries(element); + List<File> files = getDirectoryEntries(element); - currentEnum = files.elements(); + currentIterator = files.iterator(); } else { - // we have a file. create a stream for it try (InputStream inFileStream = Files.newInputStream(element.toPath())) { @@ -145,13 +135,11 @@ public class DirectoryIterator implements ClassFileIterator { } } } + } else // this iterator is exhausted. Can we pop one off the stack + if (enumStack.isEmpty()) { + break; } else { - // this iterator is exhausted. Can we pop one off the stack - if (enumStack.empty()) { - break; - } else { - currentEnum = (Enumeration) enumStack.pop(); - } + currentIterator = enumStack.pop(); } } } catch (IOException e) { @@ -162,4 +150,3 @@ public class DirectoryIterator implements ClassFileIterator { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/JarFileIterator.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/JarFileIterator.java index c468b952a..cc2d60df4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/JarFileIterator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/JarFileIterator.java @@ -41,7 +41,6 @@ public class JarFileIterator implements ClassFileIterator { */ public JarFileIterator(InputStream stream) throws IOException { super(); - jarStream = new ZipInputStream(stream); } @@ -50,6 +49,7 @@ public class JarFileIterator implements ClassFileIterator { * * @return a ClassFile object describing the class from the jar */ + @Override public ClassFile getNextClassFile() { ZipEntry jarEntry; ClassFile nextElement = null; @@ -69,7 +69,6 @@ public class JarFileIterator implements ClassFileIterator { nextElement = javaClass; } else { - jarEntry = jarStream.getNextEntry(); } } @@ -83,9 +82,7 @@ public class JarFileIterator implements ClassFileIterator { throw new BuildException("Problem reading JAR file: " + text); } - return nextElement; } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java index 8abbfc829..a870fc773 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ClassCPInfo.java @@ -54,6 +54,7 @@ public class ClassCPInfo extends ConstantPoolEntry { * @exception IOException thrown if there is a problem reading the entry * from the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { index = cpStream.readUnsignedShort(); className = "unresolved"; @@ -64,6 +65,7 @@ public class ClassCPInfo extends ConstantPoolEntry { * * @return string representation of this constant pool entry */ + @Override public String toString() { return "Class Constant Pool Entry for " + className + "[" + index + "]"; } @@ -74,6 +76,7 @@ public class ClassCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool with which to resolve the * class. */ + @Override public void resolve(ConstantPool constantPool) { className = ((Utf8CPInfo) constantPool.getEntry(index)).getValue(); @@ -90,4 +93,3 @@ public class ClassCPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantCPInfo.java index 6103422e1..1865c071e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantCPInfo.java @@ -60,4 +60,3 @@ public abstract class ConstantCPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java index 9bec0ed32..ec7ed64e3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPool.java @@ -23,6 +23,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * The constant pool of a Java class. The constant pool is a collection of @@ -343,16 +345,11 @@ public class ConstantPool { * * @return the constant pool entries as strings */ + @Override public String toString() { - StringBuilder sb = new StringBuilder("\n"); - final int size = entries.size(); - - for (int i = 0; i < size; ++i) { - sb.append('[').append(i).append("] = ").append(getEntry(i)).append('\n'); - } - - return sb.toString(); + return IntStream.range(0, entries.size()) + .mapToObj(i -> String.format("[%d] = %s", i, getEntry(i))) + .collect(Collectors.joining("\n", "\n", "\n")); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPoolEntry.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPoolEntry.java index 26a0d094c..b639fa9ae 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPoolEntry.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/ConstantPoolEntry.java @@ -115,72 +115,57 @@ public abstract class ConstantPoolEntry { */ public static ConstantPoolEntry readEntry(DataInputStream cpStream) throws IOException { - ConstantPoolEntry cpInfo = null; int cpTag = cpStream.readUnsignedByte(); + ConstantPoolEntry cpInfo; switch (cpTag) { case CONSTANT_UTF8: cpInfo = new Utf8CPInfo(); - break; case CONSTANT_INTEGER: cpInfo = new IntegerCPInfo(); - break; case CONSTANT_FLOAT: cpInfo = new FloatCPInfo(); - break; case CONSTANT_LONG: cpInfo = new LongCPInfo(); - break; case CONSTANT_DOUBLE: cpInfo = new DoubleCPInfo(); - break; case CONSTANT_CLASS: cpInfo = new ClassCPInfo(); - break; case CONSTANT_STRING: cpInfo = new StringCPInfo(); - break; case CONSTANT_FIELDREF: cpInfo = new FieldRefCPInfo(); - break; case CONSTANT_METHODREF: cpInfo = new MethodRefCPInfo(); - break; case CONSTANT_INTERFACEMETHODREF: cpInfo = new InterfaceMethodRefCPInfo(); - break; case CONSTANT_NAMEANDTYPE: cpInfo = new NameAndTypeCPInfo(); - break; case CONSTANT_METHODHANDLE: cpInfo = new MethodHandleCPInfo(); - break; case CONSTANT_METHODTYPE: cpInfo = new MethodTypeCPInfo(); - break; case CONSTANT_INVOKEDYNAMIC: cpInfo = new InvokeDynamicCPInfo(); - break; default: throw new ClassFormatError("Invalid Constant Pool entry Type " + cpTag); } - cpInfo.read(cpStream); return cpInfo; @@ -239,4 +224,3 @@ public abstract class ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/DoubleCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/DoubleCPInfo.java index a21c0d66b..5f28999a5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/DoubleCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/DoubleCPInfo.java @@ -41,8 +41,9 @@ public class DoubleCPInfo extends ConstantCPInfo { * @exception IOException if there is a problem reading the entry from the * stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { - setValue(new Double(cpStream.readDouble())); + setValue(Double.valueOf(cpStream.readDouble())); } /** @@ -50,9 +51,9 @@ public class DoubleCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "Double Constant Pool Entry: " + getValue(); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java index 06c0925d5..1367b6299 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FieldRefCPInfo.java @@ -49,6 +49,7 @@ public class FieldRefCPInfo extends ConstantPoolEntry { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { classIndex = cpStream.readUnsignedShort(); nameAndTypeIndex = cpStream.readUnsignedShort(); @@ -61,6 +62,7 @@ public class FieldRefCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { ClassCPInfo fieldClass = (ClassCPInfo) constantPool.getEntry(classIndex); @@ -85,18 +87,14 @@ public class FieldRefCPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; - if (isResolved()) { - value = "Field : Class = " + fieldClassName + ", name = " - + fieldName + ", type = " + fieldType; - } else { - value = "Field : Class index = " + classIndex - + ", name and type index = " + nameAndTypeIndex; + return "Field : Class = " + fieldClassName + ", name = " + fieldName + + ", type = " + fieldType; } - - return value; + return "Field : Class index = " + classIndex + + ", name and type index = " + nameAndTypeIndex; } /** @@ -127,4 +125,3 @@ public class FieldRefCPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FloatCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FloatCPInfo.java index 532b67256..d9bf46599 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FloatCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/FloatCPInfo.java @@ -39,8 +39,9 @@ public class FloatCPInfo extends ConstantCPInfo { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { - setValue(new Float(cpStream.readFloat())); + setValue(Float.valueOf(cpStream.readFloat())); } /** @@ -48,9 +49,9 @@ public class FloatCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "Float Constant Pool Entry: " + getValue(); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/IntegerCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/IntegerCPInfo.java index 3beaa8cd0..a3ecdaad8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/IntegerCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/IntegerCPInfo.java @@ -39,8 +39,9 @@ public class IntegerCPInfo extends ConstantCPInfo { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { - setValue(new Integer(cpStream.readInt())); + setValue(Integer.valueOf(cpStream.readInt())); } /** @@ -48,9 +49,9 @@ public class IntegerCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "Integer Constant Pool Entry: " + getValue(); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java index fbc23c1c8..4f7246cb0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InterfaceMethodRefCPInfo.java @@ -55,6 +55,7 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { classIndex = cpStream.readUnsignedShort(); nameAndTypeIndex = cpStream.readUnsignedShort(); @@ -67,6 +68,7 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { ClassCPInfo interfaceMethodClass = (ClassCPInfo) constantPool.getEntry(classIndex); @@ -91,19 +93,16 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; - if (isResolved()) { - value = "InterfaceMethod : Class = " + interfaceMethodClassName + return "InterfaceMethod : Class = " + interfaceMethodClassName + ", name = " + interfaceMethodName + ", type = " + interfaceMethodType; - } else { - value = "InterfaceMethod : Class index = " + classIndex - + ", name and type index = " + nameAndTypeIndex; - } + } + return "InterfaceMethod : Class index = " + classIndex + + ", name and type index = " + nameAndTypeIndex; - return value; } /** @@ -134,4 +133,3 @@ public class InterfaceMethodRefCPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InvokeDynamicCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InvokeDynamicCPInfo.java index 3795db752..176b99ac8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InvokeDynamicCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/InvokeDynamicCPInfo.java @@ -32,7 +32,7 @@ public class InvokeDynamicCPInfo extends ConstantCPInfo { private int nameAndTypeIndex; /** the name and type CP info pointed to */ private NameAndTypeCPInfo nameAndTypeCPInfo; - /** */ + /** Constructor. */ public InvokeDynamicCPInfo() { super(CONSTANT_INVOKEDYNAMIC, 1); @@ -46,6 +46,7 @@ public class InvokeDynamicCPInfo extends ConstantCPInfo { * @exception java.io.IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { bootstrapMethodAttrIndex = cpStream.readUnsignedShort(); nameAndTypeIndex = cpStream.readUnsignedShort(); @@ -56,16 +57,14 @@ public class InvokeDynamicCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; if (isResolved()) { - value = "Name = " + nameAndTypeCPInfo.getName() + ", type = " + nameAndTypeCPInfo.getType(); - } else { - value = "BootstrapMethodAttrIndex inx = " + bootstrapMethodAttrIndex - + "NameAndType index = " + nameAndTypeIndex; + return "Name = " + nameAndTypeCPInfo.getName() + ", type = " + + nameAndTypeCPInfo.getType(); } - - return value; + return "BootstrapMethodAttrIndex inx = " + bootstrapMethodAttrIndex + + "NameAndType index = " + nameAndTypeIndex; } /** * Resolve this constant pool entry with respect to its dependents in @@ -74,6 +73,7 @@ public class InvokeDynamicCPInfo extends ConstantCPInfo { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { nameAndTypeCPInfo = (NameAndTypeCPInfo) constantPool.getEntry(nameAndTypeIndex); @@ -82,4 +82,3 @@ public class InvokeDynamicCPInfo extends ConstantCPInfo { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/LongCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/LongCPInfo.java index e854f04ff..9e57a39b3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/LongCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/LongCPInfo.java @@ -39,8 +39,9 @@ public class LongCPInfo extends ConstantCPInfo { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { - setValue(new Long(cpStream.readLong())); + setValue(Long.valueOf(cpStream.readLong())); } /** @@ -48,9 +49,9 @@ public class LongCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "Long Constant Pool Entry: " + getValue(); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodHandleCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodHandleCPInfo.java index e11e3aabd..e304d4170 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodHandleCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodHandleCPInfo.java @@ -36,22 +36,23 @@ public class MethodHandleCPInfo extends ConstantPoolEntry { * signature of the method */ private int nameAndTypeIndex; + public enum ReferenceKind { - REF_getField(1), - REF_getStatic(2), - REF_putField(3), - REF_putStatic(4), - REF_invokeVirtual(5), - REF_invokeStatic(6), - REF_invokeSpecial(7), - REF_newInvokeSpecial(8), - REF_invokeInterface(9); - private final int referenceKind; - ReferenceKind(int referenceKind) { - this.referenceKind = referenceKind; - } + REF_getField, + REF_getStatic, + REF_putField, + REF_putStatic, + REF_invokeVirtual, + REF_invokeStatic, + REF_invokeSpecial, + REF_newInvokeSpecial, + REF_invokeInterface; + public int value() { + return ordinal() + 1; + } } + /** Constructor. */ public MethodHandleCPInfo() { super(CONSTANT_METHODHANDLE, 1); @@ -65,9 +66,9 @@ public class MethodHandleCPInfo extends ConstantPoolEntry { * @exception java.io.IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { referenceKind = ReferenceKind.values()[cpStream.readUnsignedByte() - 1]; - referenceIndex = cpStream.readUnsignedShort(); } @@ -76,17 +77,13 @@ public class MethodHandleCPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; - if (isResolved()) { - value = "MethodHandle : " + reference.toString(); - } else { - value = "MethodHandle : Reference kind = " + referenceKind - + "Reference index = " + referenceIndex; + return "MethodHandle : " + reference.toString(); } - - return value; + return "MethodHandle : Reference kind = " + referenceKind + + "Reference index = " + referenceIndex; } /** @@ -96,12 +93,11 @@ public class MethodHandleCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { reference = constantPool.getEntry(referenceIndex); reference.resolve(constantPool); super.resolve(constantPool); } - } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java index 6b3352127..b90169f91 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodRefCPInfo.java @@ -52,6 +52,7 @@ public class MethodRefCPInfo extends ConstantPoolEntry { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { classIndex = cpStream.readUnsignedShort(); nameAndTypeIndex = cpStream.readUnsignedShort(); @@ -62,18 +63,14 @@ public class MethodRefCPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; - if (isResolved()) { - value = "Method : Class = " + methodClassName + ", name = " - + methodName + ", type = " + methodType; - } else { - value = "Method : Class index = " + classIndex - + ", name and type index = " + nameAndTypeIndex; + return "Method : Class = " + methodClassName + ", name = " + + methodName + ", type = " + methodType; } - - return value; + return "Method : Class index = " + classIndex + + ", name and type index = " + nameAndTypeIndex; } /** @@ -83,6 +80,7 @@ public class MethodRefCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { ClassCPInfo methodClass = (ClassCPInfo) constantPool.getEntry(classIndex); @@ -130,4 +128,3 @@ public class MethodRefCPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java index d3c35cee1..7b6f9a68b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/MethodTypeCPInfo.java @@ -30,6 +30,7 @@ public class MethodTypeCPInfo extends ConstantCPInfo { private int methodDescriptorIndex; /** the value of the method descriptor pointed to */ private String methodDescriptor; + /** Constructor. */ public MethodTypeCPInfo() { super(CONSTANT_METHODTYPE, 1); @@ -63,6 +64,7 @@ public class MethodTypeCPInfo extends ConstantCPInfo { methodDescriptor = methodClass.getValue(); super.resolve(constantPool); } + /** * Print a readable version of the constant pool entry. * @@ -70,13 +72,10 @@ public class MethodTypeCPInfo extends ConstantCPInfo { */ @Override public String toString() { - if (!isResolved()) { - return "MethodDescriptorIndex: " + methodDescriptorIndex; - } else { + if (isResolved()) { return "MethodDescriptor: " + methodDescriptor; - } + return "MethodDescriptorIndex: " + methodDescriptorIndex; } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java index 47f454d25..761808b1c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/NameAndTypeCPInfo.java @@ -25,6 +25,20 @@ import java.io.IOException; * */ public class NameAndTypeCPInfo extends ConstantPoolEntry { + /** the name component of this entry */ + private String name; + /** the type component of this entry */ + private String type; + /** + * the index into the constant pool at which the name component's string + * value is stored + */ + private int nameIndex; + /** + * the index into the constant pool where the type descriptor string is + * stored. + */ + private int descriptorIndex; /** Constructor. */ public NameAndTypeCPInfo() { @@ -39,6 +53,7 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { nameIndex = cpStream.readUnsignedShort(); descriptorIndex = cpStream.readUnsignedShort(); @@ -49,17 +64,13 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { - String value; - if (isResolved()) { - value = "Name = " + name + ", type = " + type; - } else { - value = "Name index = " + nameIndex - + ", descriptor index = " + descriptorIndex; + return "Name = " + name + ", type = " + type; } - - return value; + return "Name index = " + nameIndex + ", descriptor index = " + + descriptorIndex; } /** @@ -69,6 +80,7 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { name = ((Utf8CPInfo) constantPool.getEntry(nameIndex)).getValue(); type = ((Utf8CPInfo) constantPool.getEntry(descriptorIndex)).getValue(); @@ -94,19 +106,4 @@ public class NameAndTypeCPInfo extends ConstantPoolEntry { return type; } - /** the name component of this entry */ - private String name; - /** the type component of this entry */ - private String type; - /** - * the index into the constant pool at which the name component's string - * value is stored - */ - private int nameIndex; - /** - * the index into the constant pool where the type descriptor string is - * stored. - */ - private int descriptorIndex; } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java index bc9ee24b3..750340362 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/StringCPInfo.java @@ -26,6 +26,8 @@ import java.io.IOException; * */ public class StringCPInfo extends ConstantCPInfo { + /** the index into the constant pool containing the string's content */ + private int index; /** Constructor. */ public StringCPInfo() { @@ -40,9 +42,9 @@ public class StringCPInfo extends ConstantCPInfo { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { index = cpStream.readUnsignedShort(); - setValue("unresolved"); } @@ -51,6 +53,7 @@ public class StringCPInfo extends ConstantCPInfo { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "String Constant Pool Entry for " + getValue() + "[" + index + "]"; @@ -63,12 +66,11 @@ public class StringCPInfo extends ConstantCPInfo { * @param constantPool the constant pool of which this entry is a member * and against which this entry is to be resolved. */ + @Override public void resolve(ConstantPool constantPool) { setValue(((Utf8CPInfo) constantPool.getEntry(index)).getValue()); super.resolve(constantPool); } - /** the index into the constant pool containing the string's content */ - private int index; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/Utf8CPInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/Utf8CPInfo.java index 5471ccdeb..724bc9f9f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/Utf8CPInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/depend/constantpool/Utf8CPInfo.java @@ -41,6 +41,7 @@ public class Utf8CPInfo extends ConstantPoolEntry { * @exception IOException if there is a problem reading the entry from * the stream. */ + @Override public void read(DataInputStream cpStream) throws IOException { value = cpStream.readUTF(); } @@ -50,6 +51,7 @@ public class Utf8CPInfo extends ConstantPoolEntry { * * @return the string representation of this constant pool entry. */ + @Override public String toString() { return "UTF8 Value = " + value; } @@ -64,4 +66,3 @@ public class Utf8CPInfo extends ConstantPoolEntry { } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java index 4eefaebfe..c1e57995e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandDeploymentTool.java @@ -26,16 +26,18 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collection; import java.util.Hashtable; -import java.util.Iterator; -import java.util.Vector; - +import java.util.List; +import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.ExecTask; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.ExecuteStreamHandler; import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.taskdefs.optional.ejb.EjbJar.DTDLocation; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.Path; @@ -78,19 +80,18 @@ import org.apache.tools.ant.types.Path; public class BorlandDeploymentTool extends GenericDeploymentTool implements ExecuteStreamHandler { /** Borland 1.1 ejb id */ - public static final String PUBLICID_BORLAND_EJB - = "-//Inprise Corporation//DTD Enterprise JavaBeans 1.1//EN"; + public static final String PUBLICID_BORLAND_EJB = + "-//Inprise Corporation//DTD Enterprise JavaBeans 1.1//EN"; - protected static final String DEFAULT_BAS45_EJB11_DTD_LOCATION - = "/com/inprise/j2ee/xml/dtds/ejb-jar.dtd"; + protected static final String DEFAULT_BAS45_EJB11_DTD_LOCATION = + "/com/inprise/j2ee/xml/dtds/ejb-jar.dtd"; - protected static final String DEFAULT_BAS_DTD_LOCATION - = "/com/inprise/j2ee/xml/dtds/ejb-inprise.dtd"; + protected static final String DEFAULT_BAS_DTD_LOCATION = + "/com/inprise/j2ee/xml/dtds/ejb-inprise.dtd"; protected static final String BAS_DD = "ejb-inprise.xml"; protected static final String BES_DD = "ejb-borland.xml"; - /** Java2iiop executable **/ protected static final String JAVA2IIOP = "java2iiop"; @@ -114,13 +115,13 @@ public class BorlandDeploymentTool extends GenericDeploymentTool /** Borland Enterprise Server = version 5 */ static final int BES = 5; + /** Borland Application Server or Inprise Application Server = version 4 */ static final int BAS = 4; /** borland appserver version 4 or 5 */ private int version = BAS; - /** * Instance variable that determines whether it is necessary to verify the * produced jar @@ -128,7 +129,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool private boolean verify = true; private String verifyArgs = ""; - private Hashtable genfiles = new Hashtable(); + private Map<String, File> genfiles = new Hashtable<>(); /** * set the debug mode for java2iiop (default false) @@ -146,7 +147,6 @@ public class BorlandDeploymentTool extends GenericDeploymentTool this.verify = verify; } - /** * Setter used to store the suffix for the generated borland jar file. * @param inString the string to use as the suffix. @@ -155,7 +155,6 @@ public class BorlandDeploymentTool extends GenericDeploymentTool this.jarSuffix = inString; } - /** * sets some additional args to send to verify command * @param args additional command line parameters @@ -173,7 +172,6 @@ public class BorlandDeploymentTool extends GenericDeploymentTool this.borlandDTD = inString; } - /** * setter used to store whether the task will include the generate client task. * (see : BorlandGenerateClient task) @@ -200,7 +198,6 @@ public class BorlandDeploymentTool extends GenericDeploymentTool this.java2iioparams = params; } - /** * Get the borland descriptor handler. * @param srcDir the source directory. @@ -209,8 +206,9 @@ public class BorlandDeploymentTool extends GenericDeploymentTool protected DescriptorHandler getBorlandDescriptorHandler(final File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir) { + @Override protected void processElement() { - if (currentElement.equals("type-storage")) { + if ("type-storage".equals(currentElement)) { // Get the filename of vendor specific descriptor String fileNameWithMETA = currentText; //trim the META_INF\ off of the file name @@ -226,8 +224,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool handler.registerDTD(PUBLICID_BORLAND_EJB, borlandDTD == null ? DEFAULT_BAS_DTD_LOCATION : borlandDTD); - for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); + for (DTDLocation dtdLocation : getConfig().dtdLocations) { handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; @@ -239,14 +236,15 @@ public class BorlandDeploymentTool extends GenericDeploymentTool * @param ejbFiles the map to add the files to. * @param ddPrefix the prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { //choose the right vendor DD if (!(version == BES || version == BAS)) { throw new BuildException("version " + version + " is not supported"); } - String dd = (version == BES ? BES_DD : BAS_DD); + String dd = (version == BES) ? BES_DD : BAS_DD; log("vendor file : " + ddPrefix + dd, Project.MSG_DEBUG); @@ -266,6 +264,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool * Get the vendor specific name of the Jar that will be output. The modification date * of this jar will be checked against the dependent bean classes. */ + @Override File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + jarSuffix); } @@ -294,8 +293,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool private void verifyBorlandJarV5(File sourceJar) { log("verify BES " + sourceJar, Project.MSG_INFO); try { - ExecTask execTask = null; - execTask = new ExecTask(getTask()); + ExecTask execTask = new ExecTask(getTask()); execTask.setDir(new File(".")); execTask.setExecutable("iastool"); //classpath @@ -315,9 +313,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool execTask.execute(); } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling generateclient Details: " - + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while calling generateclient Details: ", e); } } @@ -354,7 +350,6 @@ public class BorlandDeploymentTool extends GenericDeploymentTool } } - /** * Generate the client jar corresponding to the jar file passed as parameter * the method uses the BorlandGenerateClient task. @@ -364,7 +359,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool getTask().getProject().addTaskDefinition("internal_bas_generateclient", org.apache.tools.ant.taskdefs.optional.ejb.BorlandGenerateClient.class); - org.apache.tools.ant.taskdefs.optional.ejb.BorlandGenerateClient gentask = null; + BorlandGenerateClient gentask; log("generate client for " + sourceJar, Project.MSG_INFO); try { Project project = getTask().getProject(); @@ -381,9 +376,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool gentask.execute(); } catch (Exception e) { //TO DO : delete the file if it is not a valid file. - String msg = "Exception while calling " + VERIFY + " Details: " - + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while calling " + VERIFY, e); } } @@ -392,10 +385,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool * Add all the generate class file into the ejb files * @param ithomes : iterator on home class */ - private void buildBorlandStubs(Iterator ithomes) { - Execute execTask = null; - - execTask = new Execute(this); + private void buildBorlandStubs(Collection<String> ithomes) { + Execute execTask = new Execute(this); Project project = getTask().getProject(); execTask.setAntRun(project); execTask.setWorkingDirectory(project.getBaseDir()); @@ -419,16 +410,14 @@ public class BorlandDeploymentTool extends GenericDeploymentTool commandline.createArgument().setLine(java2iioparams); } - //root dir commandline.createArgument().setValue("-root_dir"); commandline.createArgument().setValue(getConfig().srcDir.getAbsolutePath()); //compiling order commandline.createArgument().setValue("-compile"); //add the home class - while (ithomes.hasNext()) { - commandline.createArgument().setValue(ithomes.next().toString()); - } + ithomes.stream().map(Object::toString) + .forEach(v -> commandline.createArgument().setValue(v)); try { log("Calling java2iiop", Project.MSG_VERBOSE); @@ -436,11 +425,11 @@ public class BorlandDeploymentTool extends GenericDeploymentTool execTask.setCommandline(commandline.getCommandline()); int result = execTask.execute(); if (Execute.isFailure(result)) { - String msg = "Failed executing java2iiop (ret code is " - + result + ")"; - throw new BuildException(msg, getTask().getLocation()); + throw new BuildException( + "Failed executing java2iiop (ret code is " + result + ")", + getTask().getLocation()); } - } catch (java.io.IOException e) { + } catch (IOException e) { log("java2iiop exception :" + e.getMessage(), Project.MSG_ERR); throw new BuildException(e, getTask().getLocation()); } @@ -456,13 +445,13 @@ public class BorlandDeploymentTool extends GenericDeploymentTool * @param publicId the id to use. * @throws BuildException if there is an error. */ - protected void writeJar(String baseName, File jarFile, Hashtable files, String publicId) + @Override + protected void writeJar(String baseName, File jarFile, Hashtable<String, File> files, String publicId) throws BuildException { //build the home classes list. - Vector homes = new Vector(); - Iterator it = files.keySet().iterator(); - while (it.hasNext()) { - String clazz = (String) it.next(); + List<String> homes = new ArrayList<>(); + + for (String clazz : files.keySet()) { if (clazz.endsWith("Home.class")) { //remove .class extension String home = toClass(clazz); @@ -471,7 +460,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool } } - buildBorlandStubs(homes.iterator()); + buildBorlandStubs(homes); //add the gen files to the collection files.putAll(genfiles); @@ -494,9 +483,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool */ private String toClass(String filename) { //remove the .class - String classname = filename.substring(0, filename.lastIndexOf(".class")); - classname = classname.replace('\\', '.'); - return classname; + return filename.substring(0, filename.lastIndexOf(".class")) + .replace('\\', '.').replace('/', '.'); } /** @@ -505,28 +493,35 @@ public class BorlandDeploymentTool extends GenericDeploymentTool */ private String toClassFile(String filename) { //remove the .class - String classfile = filename.substring(0, filename.lastIndexOf(".java")); - classfile = classfile + ".class"; - return classfile; + return filename.replaceFirst("\\.java$", ".class"); } // implementation of org.apache.tools.ant.taskdefs.ExecuteStreamHandler interface /** {@inheritDoc}. */ - public void start() throws IOException { } + @Override + public void start() throws IOException { + } + /** {@inheritDoc}. */ - public void stop() { } + @Override + public void stop() { + } + /** {@inheritDoc}. */ - public void setProcessInputStream(OutputStream param1) throws IOException { } + @Override + public void setProcessInputStream(OutputStream param1) throws IOException { + } /** * Set the output stream of the process. * @param is the input stream. * @throws IOException if there is an error. */ + @Override public void setProcessOutputStream(InputStream is) throws IOException { - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(is))) { String javafile; while ((javafile = reader.readLine()) != null) { if (javafile.endsWith(".java")) { @@ -536,10 +531,8 @@ public class BorlandDeploymentTool extends GenericDeploymentTool genfiles.put(key, new File(classfile)); } } - reader.close(); } catch (Exception e) { - String msg = "Exception while parsing java2iiop output. Details: " + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while parsing java2iiop output.", e); } } @@ -548,6 +541,7 @@ public class BorlandDeploymentTool extends GenericDeploymentTool * @param is the input stream. * @throws IOException if there is an error. */ + @Override public void setProcessErrorStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String s = reader.readLine(); @@ -556,4 +550,3 @@ public class BorlandDeploymentTool extends GenericDeploymentTool } } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java index dd46269d1..87925e4e7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/BorlandGenerateClient.java @@ -133,7 +133,6 @@ public class BorlandGenerateClient extends Task { createClasspath().setRefid(r); } - /** * Do the work. * @@ -141,6 +140,7 @@ public class BorlandGenerateClient extends Task { * * @exception BuildException if something goes wrong with the build */ + @Override public void execute() throws BuildException { if (ejbjarfile == null || ejbjarfile.isDirectory()) { throw new BuildException("invalid ejb jar file."); @@ -162,13 +162,12 @@ public class BorlandGenerateClient extends Task { if (!(version == BorlandDeploymentTool.BES || version == BorlandDeploymentTool.BAS)) { - throw new BuildException("version " + version - + " is not supported"); + throw new BuildException("version %d is not supported", version); } log("client jar file is " + clientjarfile); - if (mode.equalsIgnoreCase(FORK_MODE)) { + if (FORK_MODE.equalsIgnoreCase(mode)) { executeFork(); } else { executeJava(); @@ -182,15 +181,14 @@ public class BorlandGenerateClient extends Task { protected void executeJava() throws BuildException { try { if (version == BorlandDeploymentTool.BES) { - throw new BuildException("java mode is supported only for " - + "previous version <=" + BorlandDeploymentTool.BAS); + throw new BuildException( + "java mode is supported only for previous version <= %d", + BorlandDeploymentTool.BAS); } log("mode : java"); - Java execTask = null; - execTask = new Java(this); - + Java execTask = new Java(this); execTask.setDir(new File(".")); execTask.setClassname("com.inprise.server.commandline.EJBUtilities"); //classpath @@ -218,8 +216,7 @@ public class BorlandGenerateClient extends Task { } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling generateclient Details: " + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while calling generateclient", e); } } @@ -227,7 +224,7 @@ public class BorlandGenerateClient extends Task { * launch the generate client using system api. * @throws BuildException if there is an error. */ - protected void executeFork() throws BuildException { + protected void executeFork() throws BuildException { if (version == BorlandDeploymentTool.BAS) { executeForkV4(); } @@ -240,13 +237,11 @@ public class BorlandGenerateClient extends Task { * launch the generate client using system api. * @throws BuildException if there is an error. */ - protected void executeForkV4() throws BuildException { + protected void executeForkV4() throws BuildException { try { - log("mode : fork " + BorlandDeploymentTool.BAS, Project.MSG_DEBUG); ExecTask execTask = new ExecTask(this); - execTask.setDir(new File(".")); execTask.setExecutable("iastool"); execTask.createArg().setValue("generateclient"); @@ -267,24 +262,19 @@ public class BorlandGenerateClient extends Task { execTask.execute(); } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling generateclient Details: " - + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while calling generateclient", e); } - } /** * launch the generate client using system api. * @throws BuildException if there is an error. */ - protected void executeForkV5() throws BuildException { + protected void executeForkV5() throws BuildException { try { log("mode : fork " + BorlandDeploymentTool.BES, Project.MSG_DEBUG); ExecTask execTask = new ExecTask(this); - execTask.setDir(new File(".")); - execTask.setExecutable("iastool"); if (debug) { execTask.createArg().setValue("-debug"); @@ -303,11 +293,8 @@ public class BorlandGenerateClient extends Task { execTask.execute(); } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling generateclient Details: " - + e.toString(); - throw new BuildException(msg, e); + throw new BuildException("Exception while calling generateclient", e); } - } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java index a987b92db..4e75eefe9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.java @@ -24,6 +24,7 @@ import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Hashtable; +import java.util.Map; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; @@ -94,20 +95,20 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * put into the jar file, mapped to File objects Accessed by the SAX * parser call-back method characters(). */ - protected Hashtable ejbFiles = null; + protected Hashtable<String, File> ejbFiles = null; /** * Instance variable that stores the value found in the <ejb-name> element */ protected String ejbName = null; - private Hashtable fileDTDs = new Hashtable(); + private Map<String, File> fileDTDs = new Hashtable<>(); - private Hashtable resourceDTDs = new Hashtable(); + private Map<String, String> resourceDTDs = new Hashtable<>(); private boolean inEJBRef = false; - private Hashtable urlDTDs = new Hashtable(); + private Map<String, URL> urlDTDs = new Hashtable<>(); // CheckStyle:VisibilityModifier OFF - bc /** @@ -174,7 +175,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { /** * Resolve the entity. - * @see org.xml.sax.EntityResolver#resolveEntity(String, String). + * @see org.xml.sax.EntityResolver#resolveEntity(String, String) * @param publicId The public identifier, or <code>null</code> * if none is available. * @param systemId The system identifier provided in the XML @@ -182,11 +183,12 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * @return an inputsource for this identifier * @throws SAXException if there is a problem. */ + @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { this.publicId = publicId; - File dtdFile = (File) fileDTDs.get(publicId); + File dtdFile = fileDTDs.get(publicId); if (dtdFile != null) { try { owningTask.log("Resolved " + publicId + " to local file " @@ -197,7 +199,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { } } - String dtdResourceName = (String) resourceDTDs.get(publicId); + String dtdResourceName = resourceDTDs.get(publicId); if (dtdResourceName != null) { InputStream is = this.getClass().getResourceAsStream(dtdResourceName); if (is != null) { @@ -207,7 +209,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { } } - URL dtdUrl = (URL) urlDTDs.get(publicId); + URL dtdUrl = urlDTDs.get(publicId); if (dtdUrl != null) { try { InputStream is = dtdUrl.openStream(); @@ -229,8 +231,8 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * Getter method that returns the set of files to include in the EJB jar. * @return the map of files */ - public Hashtable getFiles() { - return (ejbFiles == null) ? new Hashtable() : ejbFiles; + public Hashtable<String, File> getFiles() { + return ejbFiles == null ? new Hashtable<>() : ejbFiles; } /** @@ -254,13 +256,13 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * instance variables to ensure safe operation. * @throws SAXException on error */ + @Override public void startDocument() throws SAXException { - this.ejbFiles = new Hashtable(DEFAULT_HASH_TABLE_SIZE, 1); + this.ejbFiles = new Hashtable<>(DEFAULT_HASH_TABLE_SIZE, 1); this.currentElement = null; inEJBRef = false; } - /** * SAX parser call-back method that is invoked when a new element is entered * into. Used to store the context (attribute name) in the currentAttribute @@ -269,26 +271,26 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * @param attrs Attributes associated to the element. * @throws SAXException on error */ + @Override public void startElement(String name, AttributeList attrs) throws SAXException { this.currentElement = name; currentText = ""; - if (name.equals(EJB_REF) || name.equals(EJB_LOCAL_REF)) { + if (EJB_REF.equals(name) || EJB_LOCAL_REF.equals(name)) { inEJBRef = true; - } else if (parseState == STATE_LOOKING_EJBJAR && name.equals(EJB_JAR)) { + } else if (parseState == STATE_LOOKING_EJBJAR && EJB_JAR.equals(name)) { parseState = STATE_IN_EJBJAR; - } else if (parseState == STATE_IN_EJBJAR && name.equals(ENTERPRISE_BEANS)) { + } else if (parseState == STATE_IN_EJBJAR && ENTERPRISE_BEANS.equals(name)) { parseState = STATE_IN_BEANS; - } else if (parseState == STATE_IN_BEANS && name.equals(SESSION_BEAN)) { + } else if (parseState == STATE_IN_BEANS && SESSION_BEAN.equals(name)) { parseState = STATE_IN_SESSION; - } else if (parseState == STATE_IN_BEANS && name.equals(ENTITY_BEAN)) { + } else if (parseState == STATE_IN_BEANS && ENTITY_BEAN.equals(name)) { parseState = STATE_IN_ENTITY; - } else if (parseState == STATE_IN_BEANS && name.equals(MESSAGE_BEAN)) { + } else if (parseState == STATE_IN_BEANS && MESSAGE_BEAN.equals(name)) { parseState = STATE_IN_MESSAGE; } } - /** * SAX parser call-back method that is invoked when an element is exited. * Used to blank out (set to the empty string, not nullify) the name of @@ -299,6 +301,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * in this implementation. * @throws SAXException on error */ + @Override public void endElement(String name) throws SAXException { processElement(); currentText = ""; @@ -334,13 +337,12 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { * char array where the current data terminates. * @throws SAXException on error */ + @Override public void characters(char[] ch, int start, int length) throws SAXException { - currentText += new String(ch, start, length); } - /** * Called when an endelement is seen. * This may be overridden in derived classes. @@ -355,15 +357,14 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { return; } - if (currentElement.equals(HOME_INTERFACE) - || currentElement.equals(REMOTE_INTERFACE) - || currentElement.equals(LOCAL_INTERFACE) - || currentElement.equals(LOCAL_HOME_INTERFACE) - || currentElement.equals(BEAN_CLASS) - || currentElement.equals(PK_CLASS)) { + if (HOME_INTERFACE.equals(currentElement) + || REMOTE_INTERFACE.equals(currentElement) + || LOCAL_INTERFACE.equals(currentElement) + || LOCAL_HOME_INTERFACE.equals(currentElement) + || BEAN_CLASS.equals(currentElement) + || PK_CLASS.equals(currentElement)) { // Get the filename into a String object - File classFile = null; String className = currentText.trim(); // If it's a primitive wrapper then we shouldn't try and put @@ -374,8 +375,7 @@ public class DescriptorHandler extends org.xml.sax.HandlerBase { // name, create the File object and add it to the Hashtable. className = className.replace('.', File.separatorChar); className += ".class"; - classFile = new File(srcDir, className); - ejbFiles.put(className, classFile); + ejbFiles.put(className, new File(srcDir, className)); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.java index 6ed8e34a2..2a1d70d13 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.java @@ -18,14 +18,11 @@ package org.apache.tools.ant.taskdefs.optional.ejb; - - import javax.xml.parsers.SAXParser; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; - /** * The interface to implement for deployment tools. */ diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java index e9b7ed429..f582091fc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/EjbJar.java @@ -21,7 +21,6 @@ package org.apache.tools.ant.taskdefs.optional.ejb; // Standard java imports import java.io.File; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import javax.xml.parsers.ParserConfigurationException; @@ -103,12 +102,12 @@ public class EjbJar extends MatchingTask { /** * A Fileset of support classes */ - public List supportFileSets = new ArrayList(); + public List<FileSet> supportFileSets = new ArrayList<>(); /** * The list of configured DTD locations */ - public ArrayList dtdLocations = new ArrayList(); + public ArrayList<DTDLocation> dtdLocations = new ArrayList<>(); /** * The naming scheme used to determine the generated jar name @@ -162,8 +161,10 @@ public class EjbJar extends MatchingTask { * * @return an array of the values of this attribute class. */ + @Override public String[] getValues() { - return new String[] {EJB_NAME, DIRECTORY, DESCRIPTOR, BASEJARNAME}; + return new String[] { EJB_NAME, DIRECTORY, DESCRIPTOR, + BASEJARNAME }; } } @@ -178,20 +179,21 @@ public class EjbJar extends MatchingTask { /** 2.0 value */ public static final String CMP2_0 = "2.0"; /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[]{ + return new String[] { CMP1_0, CMP2_0, }; } } + /** * The config which is built by this task and used by the various deployment * tools to access the configuration of the ejbjar task */ private Config config = new Config(); - /** * Stores a handle to the directory to put the Jar files in. This is * only used by the generic deployment descriptor tool which is created @@ -207,7 +209,7 @@ public class EjbJar extends MatchingTask { private String cmpVersion = CMPVersion.CMP1_0; /** The list of deployment tools we are going to run. */ - private ArrayList deploymentTools = new ArrayList(); + private List<EJBDeploymentTool> deploymentTools = new ArrayList<>(); /** * Add a deployment tool to the list of deployment tools that will be @@ -348,7 +350,6 @@ public class EjbJar extends MatchingTask { return supportFileSet; } - /** * Set the Manifest file to use when jarring. As of EJB 1.1, manifest * files are no longer used to configure the EJB. However, they still @@ -409,10 +410,10 @@ public class EjbJar extends MatchingTask { if (config.namingScheme == null) { config.namingScheme = new NamingScheme(); config.namingScheme.setValue(NamingScheme.BASEJARNAME); - } else if (!config.namingScheme.getValue().equals(NamingScheme.BASEJARNAME)) { - throw new BuildException("The basejarname attribute is not " - + "compatible with the " - + config.namingScheme.getValue() + " naming scheme"); + } else if (!NamingScheme.BASEJARNAME.equals(config.namingScheme.getValue())) { + throw new BuildException( + "The basejarname attribute is not compatible with the %s naming scheme", + config.namingScheme.getValue()); } } @@ -424,11 +425,11 @@ public class EjbJar extends MatchingTask { */ public void setNaming(NamingScheme namingScheme) { config.namingScheme = namingScheme; - if (!config.namingScheme.getValue().equals(NamingScheme.BASEJARNAME) + if (!NamingScheme.BASEJARNAME.equals(config.namingScheme.getValue()) && config.baseJarName != null) { - throw new BuildException("The basejarname attribute is not " - + "compatible with the " - + config.namingScheme.getValue() + " naming scheme"); + throw new BuildException( + "The basejarname attribute is not compatible with the %s naming scheme", + config.namingScheme.getValue()); } } @@ -546,10 +547,10 @@ public class EjbJar extends MatchingTask { if (config.namingScheme == null) { config.namingScheme = new NamingScheme(); config.namingScheme.setValue(NamingScheme.DESCRIPTOR); - } else if (config.namingScheme.getValue().equals(NamingScheme.BASEJARNAME) + } else if (NamingScheme.BASEJARNAME.equals(config.namingScheme.getValue()) && config.baseJarName == null) { - throw new BuildException("The basejarname attribute must " - + "be specified with the basejarname naming scheme"); + throw new BuildException( + "The basejarname attribute must be specified with the basejarname naming scheme"); } } @@ -568,10 +569,11 @@ public class EjbJar extends MatchingTask { * encountered that cannot be recovered from, to signal to ant * that a major problem occurred within this task. */ + @Override public void execute() throws BuildException { validateConfig(); - if (deploymentTools.size() == 0) { + if (deploymentTools.isEmpty()) { GenericDeploymentTool genericTool = new GenericDeploymentTool(); genericTool.setTask(this); genericTool.setDestdir(destDir); @@ -579,8 +581,7 @@ public class EjbJar extends MatchingTask { deploymentTools.add(genericTool); } - for (Iterator i = deploymentTools.iterator(); i.hasNext();) { - EJBDeploymentTool tool = (EJBDeploymentTool) i.next(); + for (EJBDeploymentTool tool : deploymentTools) { tool.configure(config); tool.validateConfigured(); } @@ -591,7 +592,6 @@ public class EjbJar extends MatchingTask { saxParserFactory.setValidating(true); SAXParser saxParser = saxParserFactory.newSAXParser(); - DirectoryScanner ds = getDirectoryScanner(config.descriptorDir); ds.scan(); String[] files = ds.getIncludedFiles(); @@ -601,30 +601,18 @@ public class EjbJar extends MatchingTask { // Loop through the files. Each file represents one deployment // descriptor, and hence one bean in our model. - for (int index = 0; index < files.length; ++index) { + for (String file : files) { // process the deployment descriptor in each tool - for (Iterator i = deploymentTools.iterator(); i.hasNext();) { - EJBDeploymentTool tool = (EJBDeploymentTool) i.next(); - tool.processDescriptor(files[index], saxParser); + for (EJBDeploymentTool tool : deploymentTools) { + tool.processDescriptor(file, saxParser); } } } catch (SAXException se) { - String msg = "SAXException while creating parser." - + " Details: " - + se.getMessage(); - throw new BuildException(msg, se); + throw new BuildException("SAXException while creating parser.", se); } catch (ParserConfigurationException pce) { - String msg = "ParserConfigurationException while creating parser. " - + "Details: " + pce.getMessage(); - throw new BuildException(msg, pce); + throw new BuildException( + "ParserConfigurationException while creating parser. ", pce); } } // end of execute() } - - - - - - - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java index 7de0ba309..16bde5d80 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/GenericDeploymentTool.java @@ -24,7 +24,6 @@ import java.nio.file.Files; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.Set; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; @@ -37,9 +36,9 @@ import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.optional.ejb.EjbJar.DTDLocation; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.depend.DependencyAnalyzer; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -118,7 +117,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { /** * Set of files have been loaded into the EJB jar */ - private Set addedfiles; + private Set<String> addedfiles; /** * Handler used to parse the EJB XML descriptor @@ -130,11 +129,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { */ private DependencyAnalyzer dependencyAnalyzer; - /** No arg constructor */ - public GenericDeploymentTool() { - } - - /** * Set the destination directory; required. * @param inDir the destination directory. @@ -152,12 +146,12 @@ public class GenericDeploymentTool implements EJBDeploymentTool { return destDir; } - /** * Set the task which owns this tool * * @param task the Task to which this deployment tool is associated. */ + @Override public void setTask(Task task) { this.task = task; } @@ -234,7 +228,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { combinedPath.append(config.classpath); } } - return combinedPath; } @@ -277,9 +270,10 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } try { - Class analyzerClass = Class.forName(analyzerClassName); - dependencyAnalyzer - = (DependencyAnalyzer) analyzerClass.newInstance(); + Class<? extends DependencyAnalyzer> analyzerClass = + Class.forName(analyzerClassName) + .asSubclass(DependencyAnalyzer.class); + dependencyAnalyzer = analyzerClass.newInstance(); dependencyAnalyzer.addClassPath(new Path(task.getProject(), config.srcDir.getPath())); dependencyAnalyzer.addClassPath(config.classpath); @@ -296,12 +290,12 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } } - /** * Configure this tool for use in the ejbjar task. * * @param config the configuration from the surrounding ejbjar task. */ + @Override public void configure(EjbJar.Config config) { this.config = config; @@ -326,12 +320,11 @@ public class GenericDeploymentTool implements EJBDeploymentTool { File inputFile, String logicalFilename) throws BuildException { - InputStream iStream = null; - try { - if (!addedfiles.contains(logicalFilename)) { - iStream = Files.newInputStream(inputFile.toPath()); + if (!addedfiles.contains(logicalFilename)) { + try (InputStream iStream = Files.newInputStream(inputFile.toPath())) { // Create the zip entry and add it to the jar file - ZipEntry zipEntry = new ZipEntry(logicalFilename.replace('\\', '/')); + ZipEntry zipEntry = + new ZipEntry(logicalFilename.replace('\\', '/')); jStream.putNextEntry(zipEntry); // Create the file input stream, and buffer everything over @@ -345,15 +338,12 @@ public class GenericDeploymentTool implements EJBDeploymentTool { //add it to list of files in jar addedfiles.add(logicalFilename); - } - } catch (IOException ioe) { - log("WARNING: IOException while adding entry " - + logicalFilename + " to jarfile from " - + inputFile.getPath() + " " + ioe.getClass().getName() - + "-" + ioe.getMessage(), Project.MSG_WARN); - } finally { - // Close up the file input stream for the class file - FileUtils.close(iStream); + } catch (IOException ioe) { + log("WARNING: IOException while adding entry " + logicalFilename + + " to jarfile from " + inputFile.getPath() + " " + + ioe.getClass().getName() + "-" + ioe.getMessage(), + Project.MSG_WARN); + } } } @@ -368,8 +358,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { registerKnownDTDs(h); // register any DTDs supplied by the user - for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); + for (DTDLocation dtdLocation : getConfig().dtdLocations) { h.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return h; @@ -387,6 +376,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } /** {@inheritDoc}. */ + @Override public void processDescriptor(String descriptorFileName, SAXParser saxParser) { checkConfiguration(descriptorFileName, saxParser); @@ -395,7 +385,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { handler = getDescriptorHandler(config.srcDir); // Retrive the files to be added to JAR from EJB descriptor - Hashtable ejbFiles = parseEjbFiles(descriptorFileName, saxParser); + Hashtable<String, File> ejbFiles = parseEjbFiles(descriptorFileName, saxParser); // Add any support classes specified in the build file addSupportClasses(ejbFiles); @@ -410,8 +400,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { ejbFiles.put(MANIFEST, manifestFile); } - - // First the regular deployment descriptor ejbFiles.put(META_DIR + EJB_DD, new File(config.descriptorDir, descriptorFileName)); @@ -436,7 +424,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { File jarFile = getVendorOutputJarFile(baseName); - // Check to see if we need a build and start doing the work! if (needToRebuild(ejbFiles, jarFile)) { // Log that we are going to build... @@ -450,27 +437,23 @@ public class GenericDeploymentTool implements EJBDeploymentTool { // Use helper method to write the jarfile String publicId = getPublicId(); writeJar(baseName, jarFile, ejbFiles, publicId); - } else { // Log that the file is up to date... log(jarFile.toString() + " is up to date.", Project.MSG_VERBOSE); } - } catch (SAXException se) { - String msg = "SAXException while parsing '" - + descriptorFileName - + "'. This probably indicates badly-formed XML." - + " Details: " - + se.getMessage(); - throw new BuildException(msg, se); + throw new BuildException( + "SAXException while parsing '" + descriptorFileName + + "'. This probably indicates badly-formed XML." + + " Details: " + se.getMessage(), + se); } catch (IOException ioe) { - String msg = "IOException while parsing'" - + descriptorFileName - + "'. This probably indicates that the descriptor" - + " doesn't exist. Details: " - + ioe.getMessage(); - throw new BuildException(msg, ioe); + throw new BuildException( + "IOException while parsing'" + descriptorFileName + + "'. This probably indicates that the descriptor" + + " doesn't exist. Details: " + ioe.getMessage(), + ioe); } } @@ -488,7 +471,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { */ protected void checkConfiguration(String descriptorFileName, SAXParser saxParser) throws BuildException { - /* * For the GenericDeploymentTool, do nothing. Vendor specific * subclasses should throw a BuildException if the configuration is @@ -511,28 +493,17 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @throws IOException An IOException from the parser, possibly from a * the byte stream or character stream */ - protected Hashtable parseEjbFiles(String descriptorFileName, SAXParser saxParser) + protected Hashtable<String, File> parseEjbFiles(String descriptorFileName, SAXParser saxParser) throws IOException, SAXException { - InputStream descriptorStream = null; - Hashtable ejbFiles = null; - - try { - - /* Parse the ejb deployment descriptor. While it may not - * look like much, we use a SAXParser and an inner class to - * get hold of all the classfile names for the descriptor. - */ - descriptorStream - = Files.newInputStream(new File(config.descriptorDir, descriptorFileName).toPath()); + /* Parse the ejb deployment descriptor. While it may not + * look like much, we use a SAXParser and an inner class to + * get hold of all the classfile names for the descriptor. + */ + try (InputStream descriptorStream = Files.newInputStream( + new File(config.descriptorDir, descriptorFileName).toPath())) { saxParser.parse(new InputSource(descriptorStream), handler); - - ejbFiles = handler.getFiles(); - - } finally { - FileUtils.close(descriptorStream); + return handler.getFiles(); } - - return ejbFiles; } /** @@ -542,22 +513,18 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @param ejbFiles Hashtable of EJB classes (and other) files that will be * added to the completed JAR file */ - protected void addSupportClasses(Hashtable ejbFiles) { + protected void addSupportClasses(Hashtable<String, File> ejbFiles) { // add in support classes if any Project project = task.getProject(); - for (Iterator i = config.supportFileSets.iterator(); i.hasNext();) { - FileSet supportFileSet = (FileSet) i.next(); + for (FileSet supportFileSet : config.supportFileSets) { File supportBaseDir = supportFileSet.getDir(project); DirectoryScanner supportScanner = supportFileSet.getDirectoryScanner(project); - supportScanner.scan(); - String[] supportFiles = supportScanner.getIncludedFiles(); - for (int j = 0; j < supportFiles.length; ++j) { - ejbFiles.put(supportFiles[j], new File(supportBaseDir, supportFiles[j])); + for (String supportFile : supportScanner.getIncludedFiles()) { + ejbFiles.put(supportFile, new File(supportBaseDir, supportFile)); } } } - /** * Using the EJB descriptor file name passed from the <code>ejbjar</code> * task, this method returns the "basename" which will be used to name the @@ -573,14 +540,14 @@ public class GenericDeploymentTool implements EJBDeploymentTool { String baseName = ""; // Work out what the base name is - if (config.namingScheme.getValue().equals(EjbJar.NamingScheme.BASEJARNAME)) { + if (EjbJar.NamingScheme.BASEJARNAME.equals(config.namingScheme.getValue())) { String canonicalDescriptor = descriptorFileName.replace('\\', '/'); int index = canonicalDescriptor.lastIndexOf('/'); if (index != -1) { baseName = descriptorFileName.substring(0, index + 1); } baseName += config.baseJarName; - } else if (config.namingScheme.getValue().equals(EjbJar.NamingScheme.DESCRIPTOR)) { + } else if (EjbJar.NamingScheme.DESCRIPTOR.equals(config.namingScheme.getValue())) { int lastSeparatorIndex = descriptorFileName.lastIndexOf(File.separator); int endBaseName = -1; if (lastSeparatorIndex != -1) { @@ -593,10 +560,11 @@ public class GenericDeploymentTool implements EJBDeploymentTool { if (endBaseName != -1) { baseName = descriptorFileName.substring(0, endBaseName); } else { - throw new BuildException("Unable to determine jar name " - + "from descriptor \"" + descriptorFileName + "\""); + throw new BuildException( + "Unable to determine jar name from descriptor \"%s\"", + descriptorFileName); } - } else if (config.namingScheme.getValue().equals(EjbJar.NamingScheme.DIRECTORY)) { + } else if (EjbJar.NamingScheme.DIRECTORY.equals(config.namingScheme.getValue())) { File descriptorFile = new File(config.descriptorDir, descriptorFileName); String path = descriptorFile.getAbsolutePath(); int lastSeparatorIndex @@ -609,9 +577,8 @@ public class GenericDeploymentTool implements EJBDeploymentTool { if (dirSeparatorIndex != -1) { dirName = dirName.substring(dirSeparatorIndex + 1); } - baseName = dirName; - } else if (config.namingScheme.getValue().equals(EjbJar.NamingScheme.EJB_NAME)) { + } else if (EjbJar.NamingScheme.EJB_NAME.equals(config.namingScheme.getValue())) { baseName = handler.getEjbName(); } return baseName; @@ -651,11 +618,10 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @param ejbFiles a hashtable entryname -> file. * @param ddPrefix a prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { // nothing to add for generic tool. } - /** * Get the vendor specific name of the Jar that will be output. The modification date * of this jar will be checked against the dependent bean classes. @@ -680,16 +646,13 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @return boolean indicating whether or not the <code>jarFile</code> * is up to date */ - protected boolean needToRebuild(Hashtable ejbFiles, File jarFile) { + protected boolean needToRebuild(Hashtable<String, File> ejbFiles, File jarFile) { if (jarFile.exists()) { long lastBuild = jarFile.lastModified(); - Iterator fileIter = ejbFiles.values().iterator(); - // Loop through the files seeing if any has been touched // more recently than the destination jar. - while (fileIter.hasNext()) { - File currentFile = (File) fileIter.next(); + for (File currentFile : ejbFiles.values()) { if (lastBuild < currentFile.lastModified()) { log("Build needed because " + currentFile.getPath() + " is out of date", Project.MSG_VERBOSE); @@ -698,7 +661,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } return false; } - return true; } @@ -730,7 +692,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { if (manifestFile.exists()) { return manifestFile; } - if (config.manifest != null) { return config.manifest; } @@ -747,17 +708,15 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @param publicId the id to use. * @throws BuildException if there is a problem. */ - protected void writeJar(String baseName, File jarfile, Hashtable files, + protected void writeJar(String baseName, File jarfile, Hashtable<String, File> files, String publicId) throws BuildException { - - JarOutputStream jarStream = null; + // clean the addedfiles set + if (addedfiles == null) { + addedfiles = new HashSet<>(); + } else { + addedfiles.clear(); + } try { - // clean the addedfiles set - if (addedfiles == null) { - addedfiles = new HashSet(); - } else { - addedfiles.clear(); - } /* If the jarfile already exists then whack it and recreate it. * Should probably think of a more elegant way to handle this @@ -773,18 +732,18 @@ public class GenericDeploymentTool implements EJBDeploymentTool { InputStream in = null; Manifest manifest = null; try { - File manifestFile = (File) files.get(MANIFEST); + File manifestFile = files.get(MANIFEST); if (manifestFile != null && manifestFile.exists()) { in = Files.newInputStream(manifestFile.toPath()); } else { String defaultManifest = "/org/apache/tools/ant/defaultManifest.mf"; in = this.getClass().getResourceAsStream(defaultManifest); if (in == null) { - throw new BuildException("Could not find " - + "default manifest: " + defaultManifest); + throw new BuildException( + "Could not find default manifest: %s", + defaultManifest); } } - manifest = new Manifest(in); } catch (IOException e) { throw new BuildException ("Unable to read manifest", e, getLocation()); @@ -796,46 +755,43 @@ public class GenericDeploymentTool implements EJBDeploymentTool { // Create the streams necessary to write the jarfile - jarStream = new JarOutputStream(Files.newOutputStream(jarfile.toPath()), manifest); - jarStream.setMethod(JarOutputStream.DEFLATED); + try (JarOutputStream jarStream = new JarOutputStream( + Files.newOutputStream(jarfile.toPath()), manifest)) { + jarStream.setMethod(JarOutputStream.DEFLATED); - // Loop through all the class files found and add them to the jar - for (Iterator entryIterator = files.keySet().iterator(); entryIterator.hasNext();) { - String entryName = (String) entryIterator.next(); - if (entryName.equals(MANIFEST)) { - continue; - } - - File entryFile = (File) files.get(entryName); - - log("adding file '" + entryName + "'", - Project.MSG_VERBOSE); - - addFileToJar(jarStream, entryFile, entryName); - - // See if there are any inner classes for this class and add them in if there are - InnerClassFilenameFilter flt = new InnerClassFilenameFilter(entryFile.getName()); - File entryDir = entryFile.getParentFile(); - String[] innerfiles = entryDir.list(flt); - if (innerfiles != null) { - for (int i = 0, n = innerfiles.length; i < n; i++) { - - //get and clean up innerclass name - int entryIndex = entryName.lastIndexOf(entryFile.getName()) - 1; - if (entryIndex < 0) { - entryName = innerfiles[i]; - } else { - entryName = entryName.substring(0, entryIndex) - + File.separatorChar + innerfiles[i]; - } - // link the file - entryFile = new File(config.srcDir, entryName); - - log("adding innerclass file '" + entryName + "'", + // Loop through all the class files found and add them to the jar + for (String entryName : files.keySet()) { + if (entryName.equals(MANIFEST)) { + continue; + } + File entryFile = files.get(entryName); + log("adding file '" + entryName + "'", Project.MSG_VERBOSE); + addFileToJar(jarStream, entryFile, entryName); + + // See if there are any inner classes for this class and add them in if there are + InnerClassFilenameFilter flt = + new InnerClassFilenameFilter(entryFile.getName()); + File entryDir = entryFile.getParentFile(); + String[] innerfiles = entryDir.list(flt); + if (innerfiles != null) { + for (String innerfile : innerfiles) { + //get and clean up innerclass name + int entryIndex = + entryName.lastIndexOf(entryFile.getName()) - 1; + if (entryIndex < 0) { + entryName = innerfile; + } else { + entryName = entryName.substring(0, entryIndex) + + File.separatorChar + innerfile; + } + // link the file + entryFile = new File(config.srcDir, entryName); + + log("adding innerclass file '" + entryName + "'", Project.MSG_VERBOSE); - addFileToJar(jarStream, entryFile, entryName); - + addFileToJar(jarStream, entryFile, entryName); + } } } } @@ -845,8 +801,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { + "'. Details: " + ioe.getMessage(); throw new BuildException(msg, ioe); - } finally { - FileUtils.close(jarStream); } } // end of writeJar @@ -856,7 +810,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @param checkEntries files, that are extracted from the deployment descriptor * @throws BuildException if there is a problem. */ - protected void checkAndAddDependants(Hashtable checkEntries) + protected void checkAndAddDependants(Hashtable<String, File> checkEntries) throws BuildException { if (dependencyAnalyzer == null) { @@ -865,9 +819,7 @@ public class GenericDeploymentTool implements EJBDeploymentTool { dependencyAnalyzer.reset(); - Iterator i = checkEntries.keySet().iterator(); - while (i.hasNext()) { - String entryName = (String) i.next(); + for (String entryName : checkEntries.keySet()) { if (entryName.endsWith(".class")) { String className = entryName.substring(0, entryName.length() - ".class".length()); @@ -878,10 +830,10 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } } - Enumeration e = dependencyAnalyzer.getClassDependencies(); + Enumeration<String> e = dependencyAnalyzer.getClassDependencies(); while (e.hasMoreElements()) { - String classname = (String) e.nextElement(); + String classname = e.nextElement(); String location = classname.replace('.', File.separatorChar) + ".class"; File classFile = new File(config.srcDir, location); @@ -893,7 +845,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { } } - /** * Returns a Classloader object which parses the passed in generic EjbJar classpath. * The loader is used to dynamically load classes from javax.ejb.* and the classes @@ -904,7 +855,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { if (classpathLoader != null) { return classpathLoader; } - Path combinedClasspath = getCombinedClasspath(); // only generate a new ClassLoader if we have a classpath @@ -915,7 +865,6 @@ public class GenericDeploymentTool implements EJBDeploymentTool { classpathLoader = getTask().getProject().createClassLoader(combinedClasspath); } - return classpathLoader; } @@ -925,11 +874,12 @@ public class GenericDeploymentTool implements EJBDeploymentTool { * @throws BuildException If the Deployment Tool's configuration isn't * valid */ + @Override public void validateConfigured() throws BuildException { if ((destDir == null) || (!destDir.isDirectory())) { - String msg = "A valid destination directory must be specified " - + "using the \"destdir\" attribute."; - throw new BuildException(msg, getLocation()); + throw new BuildException( + "A valid destination directory must be specified using the \"destdir\" attribute.", + getLocation()); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java index cbc8526aa..181720f78 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetDeploymentTool.java @@ -21,12 +21,12 @@ package org.apache.tools.ant.taskdefs.optional.ejb; import java.io.File; import java.io.IOException; import java.util.Hashtable; -import java.util.Iterator; import javax.xml.parsers.SAXParser; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.optional.ejb.EjbJar.DTDLocation; import org.xml.sax.SAXException; /** @@ -107,7 +107,7 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * we may determine the name of the EJB JAR file using this display-name, * but this has not be implemented yet. */ - private String displayName; + private String displayName; /* * Regardless of the name of the iAS-specific EJB descriptor file, it will @@ -202,25 +202,26 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { int startOfName = descriptorFileName.lastIndexOf(File.separatorChar) + 1; String stdXml = descriptorFileName.substring(startOfName); if (stdXml.equals(EJB_DD) && (getConfig().baseJarName == null)) { - String msg = "No name specified for the completed JAR file. The EJB" - + " descriptor should be prepended with the JAR " - + "name or it should be specified using the " - + "attribute \"basejarname\" in the \"ejbjar\" task."; - throw new BuildException(msg, getLocation()); + throw new BuildException( + "No name specified for the completed JAR file. The EJB" + + " descriptor should be prepended with the JAR " + + "name or it should be specified using the " + + "attribute \"basejarname\" in the \"ejbjar\" task.", + getLocation()); } File iasDescriptor = new File(getConfig().descriptorDir, getIasDescriptorName()); if ((!iasDescriptor.exists()) || (!iasDescriptor.isFile())) { - String msg = "The iAS-specific EJB descriptor (" - + iasDescriptor + ") was not found."; - throw new BuildException(msg, getLocation()); + throw new BuildException("The iAS-specific EJB descriptor (" + + iasDescriptor + ") was not found.", getLocation()); } if ((iashome != null) && (!iashome.isDirectory())) { - String msg = "If \"iashome\" is specified, it must be a valid " - + "directory (it was set to " + iashome + ")."; - throw new BuildException(msg, getLocation()); + throw new BuildException( + "If \"iashome\" is specified, it must be a valid directory (it was set to " + + iashome + ").", + getLocation()); } } @@ -240,10 +241,10 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * exception */ @Override - protected Hashtable parseEjbFiles(String descriptorFileName, + protected Hashtable<String, File> parseEjbFiles(String descriptorFileName, SAXParser saxParser) throws IOException, SAXException { - Hashtable files; + Hashtable<String, File> files; /* Build and populate an instance of the ejbc utility */ IPlanetEjbc ejbc = new IPlanetEjbc( @@ -260,12 +261,9 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { ejbc.setIasHomeDir(iashome); } if (getConfig().dtdLocations != null) { - for (Iterator i = getConfig().dtdLocations.iterator(); - i.hasNext();) { - EjbJar.DTDLocation dtdLocation = - (EjbJar.DTDLocation) i.next(); + for (DTDLocation dtdLocation : getConfig().dtdLocations) { ejbc.registerDTD(dtdLocation.getPublicId(), - dtdLocation.getLocation()); + dtdLocation.getLocation()); } } @@ -292,7 +290,7 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { int endOfCmp = cmpDescriptors[i].lastIndexOf('/'); String cmpDescriptor = cmpDescriptors[i].substring(endOfCmp + 1); - File cmpFile = new File(baseDir, relativePath + cmpDescriptor); + File cmpFile = new File(baseDir, relativePath + cmpDescriptor); if (!cmpFile.exists()) { throw new BuildException("The CMP descriptor file (" + cmpFile + ") could not be found.", getLocation()); @@ -300,7 +298,6 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { files.put(cmpDescriptors[i], cmpFile); } } - return files; } @@ -313,7 +310,7 @@ public class IPlanetDeploymentTool extends GenericDeploymentTool { * @param ddPrefix not used */ @Override - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { ejbFiles.put(META_DIR + IAS_DD, new File(getConfig().descriptorDir, getIasDescriptorName())); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java index 5a6656f4e..c15a07a54 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbc.java @@ -23,10 +23,12 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.time.Instant; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Date; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; @@ -34,6 +36,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; @@ -42,8 +46,6 @@ import org.xml.sax.AttributeList; import org.xml.sax.HandlerBase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; - -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.StringUtils; /** @@ -114,7 +116,7 @@ public class IPlanetEjbc { * (relative to the destination directory). The value for the Hashtable is * a File object which reference the actual class file. */ - private Hashtable ejbFiles = new Hashtable(); + private Hashtable<String, File> ejbFiles = new Hashtable<>(); /* Value of the display-name element read from the standard EJB descriptor */ private String displayName; @@ -150,15 +152,11 @@ public class IPlanetEjbc { * Parse the classpath into it's individual elements and store the * results in the "classpathElements" instance variable. */ - List elements = new ArrayList(); if (classpath != null) { StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator); - while (st.hasMoreTokens()) { - elements.add(st.nextToken()); - } - classpathElements - = (String[]) elements.toArray(new String[elements.size()]); + final int count = st.countTokens(); + classpathElements = Collections.list(st).toArray(new String[count]); } } @@ -217,7 +215,7 @@ public class IPlanetEjbc { * * @return The list of EJB files processed by the ejbc utility. */ - public Hashtable getEjbFiles() { + public Hashtable<String, File> getEjbFiles() { return ejbFiles; } @@ -236,16 +234,8 @@ public class IPlanetEjbc { * @return An array of CMP descriptors. */ public String[] getCmpDescriptors() { - List returnList = new ArrayList(); - - EjbInfo[] ejbs = handler.getEjbs(); - - for (int i = 0; i < ejbs.length; i++) { - List descriptors = (List) ejbs[i].getCmpDescriptors(); - returnList.addAll(descriptors); - } - - return (String[]) returnList.toArray(new String[returnList.size()]); + return Stream.of(handler.getEjbs()).map(EjbInfo::getCmpDescriptors) + .flatMap(Collection::stream).toArray(String[]::new); } /** @@ -274,13 +264,13 @@ public class IPlanetEjbc { iasDescriptor = new File(args[args.length - 1]); for (int i = 0; i < args.length - 2; i++) { - if (args[i].equals("-classpath")) { + if ("-classpath".equals(args[i])) { classpath = args[++i]; - } else if (args[i].equals("-d")) { + } else if ("-d".equals(args[i])) { destDirectory = new File(args[++i]); - } else if (args[i].equals("-debug")) { + } else if ("-debug".equals(args[i])) { debug = true; - } else if (args[i].equals("-keepsource")) { + } else if ("-keepsource".equals(args[i])) { retainSource = true; } else { usage(); @@ -383,22 +373,17 @@ public class IPlanetEjbc { EjbInfo[] ejbs = getEjbs(); // Returns list of EJBs for processing - for (int i = 0; i < ejbs.length; i++) { + for (EjbInfo ejb : ejbs) { log("EJBInfo..."); - log(ejbs[i].toString()); + log(ejb.toString()); } - for (int i = 0; i < ejbs.length; i++) { - EjbInfo ejb = ejbs[i]; - + for (EjbInfo ejb : ejbs) { ejb.checkConfiguration(destDirectory); // Throws EjbcException if (ejb.mustBeRecompiled(destDirectory)) { log(ejb.getName() + " must be recompiled using ejbc."); - - String[] arguments = buildArgumentList(ejb); - callEjbc(arguments); - + callEjbc(buildArgumentList(ejb)); } else { log(ejb.getName() + " is up to date."); } @@ -412,11 +397,6 @@ public class IPlanetEjbc { */ private void callEjbc(String[] arguments) { - /* Concatenate all of the command line arguments into a single String */ - StringBuffer args = new StringBuffer(); - for (int i = 0; i < arguments.length; i++) { - args.append(arguments[i]).append(" "); - } /* If an iAS home directory is specified, prepend it to the commmand */ String command; @@ -428,6 +408,9 @@ public class IPlanetEjbc { } command += "ejbc "; + /* Concatenate all of the command line arguments into a single String */ + String args = Stream.of(arguments).collect(Collectors.joining(" ")); + log(command + args); /* @@ -498,18 +481,14 @@ public class IPlanetEjbc { * XML descriptor (it may wrap another exception) */ private EjbInfo[] getEjbs() throws IOException, SAXException { - EjbInfo[] ejbs = null; /* * The EJB information is gathered from the standard XML EJB descriptor * and the iAS-specific XML EJB descriptor using a SAX parser. */ - parser.parse(stdDescriptor, handler); parser.parse(iasDescriptor, handler); - ejbs = handler.getEjbs(); - - return ejbs; + return handler.getEjbs(); } /** @@ -522,7 +501,7 @@ public class IPlanetEjbc { */ private String[] buildArgumentList(EjbInfo ejb) { - List arguments = new ArrayList(); + List<String> arguments = new ArrayList<>(); /* OPTIONAL COMMAND LINE PARAMETERS */ @@ -566,7 +545,7 @@ public class IPlanetEjbc { arguments.add(ejb.getImplementation().getQualifiedClassName()); /* Convert the List into an Array and return it */ - return (String[]) arguments.toArray(new String[arguments.size()]); + return arguments.toArray(new String[arguments.size()]); } /** @@ -591,6 +570,7 @@ public class IPlanetEjbc { * */ public class EjbcException extends Exception { + private static final long serialVersionUID = 1L; /** * Constructs an exception with the given descriptive message. @@ -631,10 +611,10 @@ public class IPlanetEjbc { * remote copies of these DTDs cannot be accessed. The key for the Map * is the DTDs public ID and the value is the local location for the DTD */ - private Map resourceDtds = new HashMap(); - private Map fileDtds = new HashMap(); + private Map<String, String> resourceDtds = new HashMap<>(); + private Map<String, String> fileDtds = new HashMap<>(); - private Map ejbs = new HashMap(); // List of EJBs found in XML + private Map<String, EjbInfo> ejbs = new HashMap<>(); // List of EJBs found in XML private EjbInfo currentEjb; // One item within the Map private boolean iasDescriptor = false; // Is doc iAS or EJB descriptor @@ -660,7 +640,7 @@ public class IPlanetEjbc { * parsing. */ public EjbInfo[] getEjbs() { - return (EjbInfo[]) ejbs.values().toArray(new EjbInfo[ejbs.size()]); + return ejbs.values().toArray(new EjbInfo[ejbs.size()]); } /** @@ -713,35 +693,30 @@ public class IPlanetEjbc { * @param publicId The DTD's public identifier. * @param systemId The location of the DTD, as found in the XML document. */ + @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputStream inputStream = null; - try { - /* Search the resource Map and (if not found) file Map */ - - String location = (String) resourceDtds.get(publicId); + String location = resourceDtds.get(publicId); if (location != null) { inputStream = ClassLoader.getSystemResource(location).openStream(); } else { - location = (String) fileDtds.get(publicId); + location = fileDtds.get(publicId); if (location != null) { // closed when the InputSource is closed inputStream = Files.newInputStream(Paths.get(location)); //NOSONAR } } } catch (IOException e) { - return super.resolveEntity(publicId, systemId); } - if (inputStream == null) { return super.resolveEntity(publicId, systemId); - } else { - return new InputSource(inputStream); } + return new InputSource(inputStream); } /** @@ -752,6 +727,7 @@ public class IPlanetEjbc { * (if any). * @throws SAXException If the parser cannot process the document. */ + @Override public void startElement(String name, AttributeList atts) throws SAXException { @@ -764,13 +740,13 @@ public class IPlanetEjbc { /* A new element has started, so reset the text being captured */ currentText = ""; - if (currentLoc.equals("\\ejb-jar")) { + if ("\\ejb-jar".equals(currentLoc)) { iasDescriptor = false; - } else if (currentLoc.equals("\\ias-ejb-jar")) { + } else if ("\\ias-ejb-jar".equals(currentLoc)) { iasDescriptor = true; } - if ((name.equals("session")) || (name.equals("entity"))) { + if (("session".equals(name)) || ("entity".equals(name))) { ejbType = name; } } @@ -784,9 +760,9 @@ public class IPlanetEjbc { * @param len The number of characters found in the document. * @throws SAXException If the parser cannot process the document. */ + @Override public void characters(char[] ch, int start, int len) throws SAXException { - currentText += new String(ch).substring(start, start + len); } @@ -796,6 +772,7 @@ public class IPlanetEjbc { * @param name String name of the element. * @throws SAXException If the parser cannot process the document. */ + @Override public void endElement(String name) throws SAXException { /* @@ -831,30 +808,30 @@ public class IPlanetEjbc { */ private void stdCharacters(String value) { - if (currentLoc.equals("\\ejb-jar\\display-name")) { + if ("\\ejb-jar\\display-name".equals(currentLoc)) { displayName = value; return; } String base = "\\ejb-jar\\enterprise-beans\\" + ejbType; - if (currentLoc.equals(base + "\\ejb-name")) { - currentEjb = (EjbInfo) ejbs.get(value); + if ((base + "\\ejb-name").equals(currentLoc)) { + currentEjb = ejbs.get(value); if (currentEjb == null) { currentEjb = new EjbInfo(value); ejbs.put(value, currentEjb); } - } else if (currentLoc.equals(base + "\\home")) { + } else if ((base + "\\home").equals(currentLoc)) { currentEjb.setHome(value); - } else if (currentLoc.equals(base + "\\remote")) { + } else if ((base + "\\remote").equals(currentLoc)) { currentEjb.setRemote(value); - } else if (currentLoc.equals(base + "\\ejb-class")) { + } else if ((base + "\\ejb-class").equals(currentLoc)) { currentEjb.setImplementation(value); - } else if (currentLoc.equals(base + "\\prim-key-class")) { + } else if ((base + "\\prim-key-class").equals(currentLoc)) { currentEjb.setPrimaryKey(value); - } else if (currentLoc.equals(base + "\\session-type")) { + } else if ((base + "\\session-type").equals(currentLoc)) { currentEjb.setBeantype(value); - } else if (currentLoc.equals(base + "\\persistence-type")) { + } else if ((base + "\\persistence-type").equals(currentLoc)) { currentEjb.setCmp(value); } } @@ -872,18 +849,19 @@ public class IPlanetEjbc { private void iasCharacters(String value) { String base = "\\ias-ejb-jar\\enterprise-beans\\" + ejbType; - if (currentLoc.equals(base + "\\ejb-name")) { - currentEjb = (EjbInfo) ejbs.get(value); + if ((base + "\\ejb-name").equals(currentLoc)) { + currentEjb = ejbs.get(value); if (currentEjb == null) { currentEjb = new EjbInfo(value); ejbs.put(value, currentEjb); } - } else if (currentLoc.equals(base + "\\iiop")) { + } else if ((base + "\\iiop").equals(currentLoc)) { currentEjb.setIiop(value); - } else if (currentLoc.equals(base + "\\failover-required")) { + } else if ((base + "\\failover-required").equals(currentLoc)) { currentEjb.setHasession(value); - } else if (currentLoc.equals(base + "\\persistence-manager" - + "\\properties-file-location")) { + } else if ((base + + "\\persistence-manager\\properties-file-location") + .equals(currentLoc)) { currentEjb.addCmpDescriptor(value); } } @@ -904,7 +882,7 @@ public class IPlanetEjbc { private boolean cmp = false; // Does this EJB support CMP? private boolean iiop = false; // Does this EJB support IIOP? private boolean hasession = false; // Does this EJB require failover? - private List cmpDescriptors = new ArrayList(); // CMP descriptor list + private List<String> cmpDescriptors = new ArrayList<>(); // CMP descriptor list /** * Construct a new EJBInfo object with the given name. @@ -926,9 +904,8 @@ public class IPlanetEjbc { if (name == null) { if (implementation == null) { return "[unnamed]"; - } else { - return implementation.getClassName(); } + return implementation.getClassName(); } return name; } @@ -1002,7 +979,7 @@ public class IPlanetEjbc { } public void setCmp(String cmp) { - setCmp(cmp.equals("Container")); + setCmp("Container".equals(cmp)); } public boolean getCmp() { @@ -1014,7 +991,7 @@ public class IPlanetEjbc { } public void setIiop(String iiop) { - setIiop(iiop.equals("true")); + setIiop(Boolean.parseBoolean(iiop)); } public boolean getIiop() { @@ -1026,7 +1003,7 @@ public class IPlanetEjbc { } public void setHasession(String hasession) { - setHasession(hasession.equals("true")); + setHasession(Boolean.parseBoolean(hasession)); } public boolean getHasession() { @@ -1037,7 +1014,7 @@ public class IPlanetEjbc { cmpDescriptors.add(descriptor); } - public List getCmpDescriptors() { + public List<String> getCmpDescriptors() { return cmpDescriptors; } @@ -1054,53 +1031,52 @@ public class IPlanetEjbc { /* Check that the specified instance variables are valid */ if (home == null) { - throw new EjbcException("A home interface was not found " - + "for the " + name + " EJB."); + throw new EjbcException( + "A home interface was not found for the " + name + " EJB."); } if (remote == null) { - throw new EjbcException("A remote interface was not found " - + "for the " + name + " EJB."); + throw new EjbcException( + "A remote interface was not found for the " + name + + " EJB."); } if (implementation == null) { - throw new EjbcException("An EJB implementation class was not " - + "found for the " + name + " EJB."); + throw new EjbcException( + "An EJB implementation class was not found for the " + name + + " EJB."); } if ((!beantype.equals(ENTITY_BEAN)) - && (!beantype.equals(STATELESS_SESSION)) - && (!beantype.equals(STATEFUL_SESSION))) { - throw new EjbcException("The beantype found (" + beantype + ") " - + "isn't valid in the " + name + " EJB."); + && (!beantype.equals(STATELESS_SESSION)) + && (!beantype.equals(STATEFUL_SESSION))) { + throw new EjbcException("The beantype found (" + beantype + + ") isn't valid in the " + name + " EJB."); } if (cmp && (!beantype.equals(ENTITY_BEAN))) { - System.out.println("CMP stubs and skeletons may not be generated" - + " for a Session Bean -- the \"cmp\" attribute will be" - + " ignoredfor the " + name + " EJB."); + System.out.println( + "CMP stubs and skeletons may not be generated for a Session Bean -- the \"cmp\" attribute will be ignoredfor the " + + name + " EJB."); } if (hasession && (!beantype.equals(STATEFUL_SESSION))) { - System.out.println("Highly available stubs and skeletons may " - + "only be generated for a Stateful Session Bean -- the " - + "\"hasession\" attribute will be ignored for the " - + name + " EJB."); + System.out.println( + "Highly available stubs and skeletons may only be generated for a Stateful Session Bean -- the \"hasession\" attribute will be ignored for the " + + name + " EJB."); } /* Check that the EJB "source" classes all exist */ if (!remote.getClassFile(buildDir).exists()) { throw new EjbcException("The remote interface " - + remote.getQualifiedClassName() + " could not be " - + "found."); + + remote.getQualifiedClassName() + " could not be found."); } if (!home.getClassFile(buildDir).exists()) { throw new EjbcException("The home interface " - + home.getQualifiedClassName() + " could not be " - + "found."); + + home.getQualifiedClassName() + " could not be found."); } if (!implementation.getClassFile(buildDir).exists()) { throw new EjbcException("The EJB implementation class " - + implementation.getQualifiedClassName() + " could " - + "not be found."); + + implementation.getQualifiedClassName() + + " could not be found."); } } @@ -1149,9 +1125,8 @@ public class IPlanetEjbc { remoteFile = remote.getClassFile(buildDir); modified = remoteFile.lastModified(); if (modified == -1) { - System.out.println("The class " - + remote.getQualifiedClassName() + " couldn't " - + "be found on the classpath"); + System.out.println("The class " + remote.getQualifiedClassName() + + " couldn't be found on the classpath"); return -1; } latestModified = modified; @@ -1160,9 +1135,8 @@ public class IPlanetEjbc { homeFile = home.getClassFile(buildDir); modified = homeFile.lastModified(); if (modified == -1) { - System.out.println("The class " - + home.getQualifiedClassName() + " couldn't be " - + "found on the classpath"); + System.out.println("The class " + home.getQualifiedClassName() + + " couldn't be found on the classpath"); return -1; } latestModified = Math.max(latestModified, modified); @@ -1172,9 +1146,9 @@ public class IPlanetEjbc { pkFile = primaryKey.getClassFile(buildDir); modified = pkFile.lastModified(); if (modified == -1) { - System.out.println("The class " - + primaryKey.getQualifiedClassName() + "couldn't be " - + "found on the classpath"); + System.out.println( + "The class " + primaryKey.getQualifiedClassName() + + "couldn't be found on the classpath"); return -1; } latestModified = Math.max(latestModified, modified); @@ -1237,7 +1211,7 @@ public class IPlanetEjbc { */ private long destClassesModified(File destDir) { String[] classnames = classesToGenerate(); // List of all stubs & skels - long destClassesModified = new Date().getTime(); // Earliest mod time + long destClassesModified = Instant.now().toEpochMilli(); // Earliest mod time boolean allClassesFound = true; // Has each been found? /* @@ -1245,7 +1219,6 @@ public class IPlanetEjbc { * determine (if all exist) which file has the most recent timestamp */ for (int i = 0; i < classnames.length; i++) { - String pathToClass = classnames[i].replace('.', File.separatorChar) + ".class"; File classFile = new File(destDir, pathToClass); @@ -1266,7 +1239,7 @@ public class IPlanetEjbc { } } - return (allClassesFound) ? destClassesModified : -1; + return allClassesFound ? destClassesModified : -1; } /** @@ -1330,6 +1303,7 @@ public class IPlanetEjbc { * * @return A String representing the EjbInfo instance. */ + @Override public String toString() { String s = "EJB name: " + name + "\n\r home: " + home @@ -1341,7 +1315,7 @@ public class IPlanetEjbc { + "\n\r iiop: " + iiop + "\n\r hasession: " + hasession; - Iterator i = cmpDescriptors.iterator(); + Iterator<String> i = cmpDescriptors.iterator(); while (i.hasNext()) { s += "\n\r CMP Descriptor: " + i.next(); } @@ -1446,6 +1420,7 @@ public class IPlanetEjbc { * * @return String representing the fully qualified class name. */ + @Override public String toString() { return getQualifiedClassName(); } @@ -1477,18 +1452,16 @@ public class IPlanetEjbc { * Reads text from the input stream and redirects it to standard output * using a separate thread. */ + @Override public void run() { - BufferedReader reader = new BufferedReader( - new InputStreamReader(stream)); - String text; - try { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(stream))) { + String text; while ((text = reader.readLine()) != null) { System.out.println(text); } } catch (IOException e) { e.printStackTrace(); //NOSONAR - } finally { - FileUtils.close(reader); } } } // End of RedirectOutput inner class diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbcTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbcTask.java index ee5dc854b..147e5d5ea 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbcTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/IPlanetEjbcTask.java @@ -188,6 +188,7 @@ public class IPlanetEjbcTask extends Task { * Does the work. * @throws BuildException if there is a problem. */ + @Override public void execute() throws BuildException { checkConfiguration(); @@ -202,41 +203,42 @@ public class IPlanetEjbcTask extends Task { private void checkConfiguration() throws BuildException { if (ejbdescriptor == null) { - String msg = "The standard EJB descriptor must be specified using " - + "the \"ejbdescriptor\" attribute."; + String msg = + "The standard EJB descriptor must be specified using the \"ejbdescriptor\" attribute."; throw new BuildException(msg, getLocation()); } if ((!ejbdescriptor.exists()) || (!ejbdescriptor.isFile())) { String msg = "The standard EJB descriptor (" + ejbdescriptor - + ") was not found or isn't a file."; + + ") was not found or isn't a file."; throw new BuildException(msg, getLocation()); } if (iasdescriptor == null) { - String msg = "The iAS-speific XML descriptor must be specified using" - + " the \"iasdescriptor\" attribute."; + String msg = + "The iAS-speific XML descriptor must be specified using the \"iasdescriptor\" attribute."; throw new BuildException(msg, getLocation()); } if ((!iasdescriptor.exists()) || (!iasdescriptor.isFile())) { String msg = "The iAS-specific XML descriptor (" + iasdescriptor - + ") was not found or isn't a file."; + + ") was not found or isn't a file."; throw new BuildException(msg, getLocation()); } if (dest == null) { - String msg = "The destination directory must be specified using " - + "the \"dest\" attribute."; + String msg = + "The destination directory must be specified using the \"dest\" attribute."; throw new BuildException(msg, getLocation()); } if ((!dest.exists()) || (!dest.isDirectory())) { - String msg = "The destination directory (" + dest + ") was not " - + "found or isn't a directory."; + String msg = "The destination directory (" + dest + + ") was not found or isn't a directory."; throw new BuildException(msg, getLocation()); } if ((iashome != null) && (!iashome.isDirectory())) { - String msg = "If \"iashome\" is specified, it must be a valid " - + "directory (it was set to " + iashome + ")."; + String msg = + "If \"iashome\" is specified, it must be a valid directory (it was set to " + + iashome + ")."; throw new BuildException(msg, getLocation()); } } @@ -248,21 +250,13 @@ public class IPlanetEjbcTask extends Task { * @throws BuildException If the parser cannot be created or configured. */ private SAXParser getParser() throws BuildException { - - SAXParser saxParser = null; try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); - saxParser = saxParserFactory.newSAXParser(); - } catch (SAXException e) { - String msg = "Unable to create a SAXParser: " + e.getMessage(); - throw new BuildException(msg, e, getLocation()); - } catch (ParserConfigurationException e) { - String msg = "Unable to create a SAXParser: " + e.getMessage(); - throw new BuildException(msg, e, getLocation()); + return saxParserFactory.newSAXParser(); + } catch (SAXException | ParserConfigurationException e) { + throw new BuildException("Unable to create a SAXParser: " + e.getMessage(), e, getLocation()); } - - return saxParser; } /** @@ -284,21 +278,23 @@ public class IPlanetEjbcTask extends Task { if (iashome != null) { ejbc.setIasHomeDir(iashome); } - try { ejbc.execute(); } catch (IOException e) { - String msg = "An IOException occurred while trying to read the XML " - + "descriptor file: " + e.getMessage(); - throw new BuildException(msg, e, getLocation()); + throw new BuildException( + "An IOException occurred while trying to read the XML descriptor file: " + + e.getMessage(), + e, getLocation()); } catch (SAXException e) { - String msg = "A SAXException occurred while trying to read the XML " - + "descriptor file: " + e.getMessage(); - throw new BuildException(msg, e, getLocation()); + throw new BuildException( + "A SAXException occurred while trying to read the XML descriptor file: " + + e.getMessage(), + e, getLocation()); } catch (IPlanetEjbc.EjbcException e) { - String msg = "An exception occurred while trying to run the ejbc " - + "utility: " + e.getMessage(); - throw new BuildException(msg, e, getLocation()); + throw new BuildException( + "An exception occurred while trying to run the ejbc utility: " + + e.getMessage(), + e, getLocation()); } } @@ -309,13 +305,9 @@ public class IPlanetEjbcTask extends Task { * @return Path The classpath to be used for EJBc. */ private Path getClasspath() { - Path cp = null; if (classpath == null) { - cp = (new Path(getProject())).concatSystemClasspath("last"); - } else { - cp = classpath.concatSystemClasspath("ignore"); - } - - return cp; + return new Path(getProject()).concatSystemClasspath("last"); + } + return classpath.concatSystemClasspath("ignore"); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java index e92d98796..b27eaa395 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/InnerClassFilenameFilter.java @@ -44,11 +44,9 @@ public class InnerClassFilenameFilter implements FilenameFilter { * @param filename the filename to filter on. * @return true if the filename is an inner class of the base class. */ + @Override public boolean accept(File dir, String filename) { - if ((filename.lastIndexOf(".") != filename.lastIndexOf(".class")) - || (filename.indexOf(baseClassName + "$") != 0)) { - return false; - } - return true; + return filename.lastIndexOf('.') == filename.lastIndexOf(".class") + && filename.indexOf(baseClassName + "$") == 0; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JbossDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JbossDeploymentTool.java index 79f4574ef..c3a48ecae 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JbossDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JbossDeploymentTool.java @@ -53,14 +53,14 @@ public class JbossDeploymentTool extends GenericDeploymentTool { * @param ejbFiles the hashtable of files to populate. * @param ddPrefix the prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { File jbossDD = new File(getConfig().descriptorDir, ddPrefix + JBOSS_DD); if (jbossDD.exists()) { ejbFiles.put(META_DIR + JBOSS_DD, jbossDD); } else { - log("Unable to locate jboss deployment descriptor. " - + "It was expected to be in " + jbossDD.getPath(), - Project.MSG_WARN); + log("Unable to locate jboss deployment descriptor. It was expected to be in " + + jbossDD.getPath(), Project.MSG_WARN); return; } String descriptorFileName = JBOSS_CMP10D; @@ -73,8 +73,7 @@ public class JbossDeploymentTool extends GenericDeploymentTool { if (jbossCMPD.exists()) { ejbFiles.put(META_DIR + descriptorFileName, jbossCMPD); } else { - log("Unable to locate jboss cmp descriptor. " - + "It was expected to be in " + log("Unable to locate jboss cmp descriptor. It was expected to be in " + jbossCMPD.getPath(), Project.MSG_VERBOSE); return; } @@ -84,15 +83,15 @@ public class JbossDeploymentTool extends GenericDeploymentTool { * Get the vendor specific name of the Jar that will be output. The modification date * of this jar will be checked against the dependent bean classes. */ + @Override File getVendorOutputJarFile(String baseName) { if (getDestDir() == null && getParent().getDestdir() == null) { throw new BuildException("DestDir not specified"); } if (getDestDir() == null) { return new File(getParent().getDestdir(), baseName + jarSuffix); - } else { - return new File(getDestDir(), baseName + jarSuffix); } + return new File(getDestDir(), baseName + jarSuffix); } /** @@ -102,6 +101,7 @@ public class JbossDeploymentTool extends GenericDeploymentTool { * valid * @since ant 1.6 */ + @Override public void validateConfigured() throws BuildException { } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java index 0d9bd1330..71c08604d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/JonasDeploymentTool.java @@ -20,9 +20,9 @@ package org.apache.tools.ant.taskdefs.optional.ejb; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.Enumeration; +import java.util.Arrays; import java.util.Hashtable; - +import java.util.List; import javax.xml.parsers.SAXParser; import org.apache.tools.ant.AntClassLoader; @@ -330,6 +330,7 @@ public class JonasDeploymentTool extends GenericDeploymentTool { /* ------------- */ /** {@inheritDoc}. */ + @Override public void processDescriptor(String aDescriptorName, SAXParser saxParser) { descriptorName = aDescriptorName; @@ -347,7 +348,8 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ - protected void writeJar(String baseName, File jarfile, Hashtable ejbFiles, String publicId) + @Override + protected void writeJar(String baseName, File jarfile, Hashtable<String, File> ejbFiles, String publicId) throws BuildException { // create the generic jar first @@ -367,10 +369,11 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { - // JOnAS-specific descriptor deployment - jonasDescriptorName = getJonasDescriptorName(); + // JOnAS-specific descriptor deployment + jonasDescriptorName = getJonasDescriptorName(); File jonasDD = new File(getConfig().descriptorDir, jonasDescriptorName); if (jonasDD.exists()) { @@ -382,6 +385,7 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ + @Override protected File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + suffix); } @@ -459,6 +463,7 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ + @Override protected String getJarBaseName(String descriptorFileName) { String baseName = null; @@ -500,6 +505,7 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** {@inheritDoc}. */ + @Override protected void registerKnownDTDs(DescriptorHandler handler) { handler.registerDTD(EJB_JAR_1_1_PUBLIC_ID, jonasroot + File.separator + "xml" + File.separator + EJB_JAR_1_1_DTD); @@ -519,15 +525,12 @@ public class JonasDeploymentTool extends GenericDeploymentTool { * @param ejbFiles the hashtable. */ private void addGenICGeneratedFiles( - File genericJarFile, Hashtable ejbFiles) { - Java genicTask = null; // GenIC task - String genicClass = null; // GenIC class (3 are supported for various - // versions + File genericJarFile, Hashtable<String, File> ejbFiles) { if (nogenic) { return; } - genicTask = new Java(getTask()); + Java genicTask = new Java(getTask()); // GenIC task genicTask.setTaskName("genic"); genicTask.setFork(true); @@ -554,13 +557,8 @@ public class JonasDeploymentTool extends GenericDeploymentTool { genicTask.createArg().setValue("-d"); genicTask.createArg().setFile(outputdir); - // work around a bug of GenIC 2.5 - String key; - File f; - Enumeration keys = ejbFiles.keys(); - while (keys.hasMoreElements()) { - key = (String) keys.nextElement(); - f = new File(outputdir + File.separator + key); + for (String key : ejbFiles.keySet()) { + File f = new File(outputdir + File.separator + key); f.getParentFile().mkdirs(); } log("Worked around a bug of GenIC 2.5.", Project.MSG_VERBOSE); @@ -582,15 +580,18 @@ public class JonasDeploymentTool extends GenericDeploymentTool { log("Using classpath: " + classpath.toString(), Project.MSG_VERBOSE); genicTask.setClasspath(classpath); + String genicClass; // GenIC class (3 are supported for various + // versions + // work around a bug of GenIC 2.5 + // class name (search in the classpath provided for the ejbjar element) genicClass = getGenicClassName(classpath); if (genicClass == null) { log("Cannot find GenIC class in classpath.", Project.MSG_ERR); throw new BuildException("GenIC class not found, please check the classpath."); - } else { - log("Using '" + genicClass + "' GenIC class." , Project.MSG_VERBOSE); - genicTask.setClassname(genicClass); - } + } + log("Using '" + genicClass + "' GenIC class." , Project.MSG_VERBOSE); + genicTask.setClassname(genicClass); // keepgenerated if (keepgenerated) { @@ -731,33 +732,38 @@ public class JonasDeploymentTool extends GenericDeploymentTool { * @param saxParser not used. * @throws BuildException if there is an error. */ + @Override protected void checkConfiguration(String descriptorFileName, SAXParser saxParser) throws BuildException { // jonasroot if (jonasroot == null) { - throw new BuildException("The jonasroot attribut is not set."); - } else if (!jonasroot.isDirectory()) { - throw new BuildException("The jonasroot attribut '" + jonasroot - + "' is not a valid directory."); + throw new BuildException("The jonasroot attribute is not set."); + } + if (!jonasroot.isDirectory()) { + throw new BuildException( + "The jonasroot attribute '%s' is not a valid directory.", + jonasroot); } // orb - if (orb != null && !orb.equals(RMI_ORB) && !orb.equals(JEREMIE_ORB) - && !orb.equals(DAVID_ORB)) { - throw new BuildException("The orb attribut '" + orb - + "' is not valid (must be either " - + RMI_ORB + ", " + JEREMIE_ORB + " or " + DAVID_ORB + ")."); + final List<String> validOrbs = + Arrays.asList(RMI_ORB, JEREMIE_ORB, DAVID_ORB); + + if (orb != null && !validOrbs.contains(orb)) { + throw new BuildException( + "The orb attribute '%s' is not valid (must be one of %s.", orb, + validOrbs); } // additionalargs - if (additionalargs != null && additionalargs.equals("")) { - throw new BuildException("Empty additionalargs attribut."); + if (additionalargs != null && additionalargs.isEmpty()) { + throw new BuildException("Empty additionalargs attribute."); } // javac - if (javac != null && javac.equals("")) { - throw new BuildException("Empty javac attribut."); + if (javac != null && javac.isEmpty()) { + throw new BuildException("Empty javac attribute."); } } @@ -776,17 +782,15 @@ public class JonasDeploymentTool extends GenericDeploymentTool { } /** - * Delete a file. If the file is a directory, delete recursivly all the + * Delete a file. If the file is a directory, delete recursively all the * files inside. * * @param aFile file to delete. */ private void deleteAllFiles(File aFile) { if (aFile.isDirectory()) { - File[] someFiles = aFile.listFiles(); - - for (int i = 0; i < someFiles.length; i++) { - deleteAllFiles(someFiles[i]); + for (File child : aFile.listFiles()) { + deleteAllFiles(child); } } aFile.delete(); @@ -800,22 +804,19 @@ public class JonasDeploymentTool extends GenericDeploymentTool { * @param rootDir the current sub-directory to scan. * @param hashtable the hashtable where to add the files. */ - private void addAllFiles(File file, String rootDir, Hashtable hashtable) { - + private void addAllFiles(File file, String rootDir, Hashtable<String, File> hashtable) { if (!file.exists()) { throw new IllegalArgumentException(); } - String newRootDir; if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - if (rootDir.length() > 0) { - newRootDir = rootDir + File.separator + files[i].getName(); + for (File child : file.listFiles()) { + if (rootDir.isEmpty()) { + newRootDir = child.getName(); } else { - newRootDir = files[i].getName(); + newRootDir = rootDir + File.separator + child.getName(); } - addAllFiles(files[i], newRootDir, hashtable); + addAllFiles(child, newRootDir, hashtable); } } else { hashtable.put(rootDir, file); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java index cc1bd90aa..4b0116d2b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicDeploymentTool.java @@ -23,7 +23,7 @@ import java.io.InputStream; import java.nio.file.Files; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Iterator; +import java.util.List; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -36,7 +36,9 @@ import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.taskdefs.optional.ejb.EjbJar.DTDLocation; import org.apache.tools.ant.types.Environment; +import org.apache.tools.ant.types.Environment.Variable; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.FileUtils; import org.xml.sax.InputSource; @@ -140,7 +142,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { private Path wlClasspath = null; /** System properties for the JVM. */ - private Vector sysprops = new Vector(); + private List<Variable> sysprops = new Vector<>(); /** * The weblogic.StdoutSeverityLevel to use when running the JVM that @@ -159,7 +161,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { sysprops.add(sysp); } - /** * Get the classpath to the weblogic classpaths. * @return the classpath to configure. @@ -181,7 +182,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.outputDir = outputDir; } - /** * Optional classpath to WL6.0. * Weblogic 6.0 will give a warning if the home and remote interfaces @@ -196,7 +196,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.wlClasspath = wlClasspath; } - /** * The compiler (switch <code>-compiler</code>) to use; optional. * This allows for the selection of a different compiler @@ -213,7 +212,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.compiler = compiler; } - /** * Set the rebuild flag to false to only update changes in the jar rather * than rerunning ejbc; optional, default true. @@ -229,7 +227,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.alwaysRebuild = rebuild; } - /** * Sets the weblogic.StdoutSeverityLevel to use when running the JVM that * executes ejbc; optional. Set to 16 to avoid the warnings about EJB Home and @@ -240,7 +237,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.jvmDebugLevel = jvmDebugLevel; } - /** * Get the debug level. * @return the jvm debug level (may be null). @@ -249,8 +245,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { return jvmDebugLevel; } - - /** * Setter used to store the suffix for the generated weblogic jar file. * @@ -260,7 +254,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.jarSuffix = inString; } - /** * controls whether the generic file used as input to * ejbc is retained; defaults to false @@ -271,7 +264,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.keepGeneric = inValue; } - /** * Controls whether weblogic will keep the generated Java * files used to build the class files added to the @@ -280,10 +272,9 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { * @param inValue either 'true' or 'false' */ public void setKeepgenerated(String inValue) { - this.keepgenerated = Boolean.valueOf(inValue).booleanValue(); + this.keepgenerated = Boolean.parseBoolean(inValue); } - /** * Any optional extra arguments pass to the weblogic.ejbc * tool. @@ -293,7 +284,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.additionalArgs = args; } - /** * Set any additional arguments to pass to the weblogic JVM; optional. * @param args the arguments to be passed to the JVM @@ -315,7 +305,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.ejbcClass = ejbcClass; } - /** * Get the ejbc compiler class. * @return the name of the ejbc compiler class. @@ -324,7 +313,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { return ejbcClass; } - /** * <b>Deprecated</b>. Defines the location of the ejb-jar DTD in * the weblogic class hierarchy. Should not be needed, and the @@ -336,7 +324,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { setEJBdtd(inString); } - /** * <b>Deprecated</b>. Defines the location of weblogic DTD in * the weblogic class hierarchy. Should not be needed, and the @@ -348,7 +335,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.weblogicDTD = inString; } - /** * <b>Deprecated</b>. Defines the location of Sun's EJB DTD in * the weblogic class hierarchy. Should not be needed, and the @@ -360,7 +346,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.ejb11DTD = inString; } - /** * Set the value of the oldCMP scheme. This is an antonym for newCMP * @ant.attribute ignore="true' @@ -370,7 +355,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.newCMP = !oldCMP; } - /** * If this is set to true, the new method for locating * CMP descriptors will be used; optional, default false. @@ -387,7 +371,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.newCMP = newCMP; } - /** * Do not EJBC the jar after it has been put together; * optional, default false @@ -397,11 +380,11 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { this.noEJBC = noEJBC; } - /** * Register the DTDs. * @param handler the handler to use. */ + @Override protected void registerKnownDTDs(DescriptorHandler handler) { // register all the known DTDs handler.registerDTD(PUBLICID_EJB11, DEFAULT_WL51_EJB11_DTD_LOCATION); @@ -410,7 +393,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { handler.registerDTD(PUBLICID_EJB20, DEFAULT_WL60_EJB20_DTD_LOCATION); } - /** * Get the weblogic descriptor handler. * @param srcDir the source directory. @@ -419,8 +401,9 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { protected DescriptorHandler getWeblogicDescriptorHandler(final File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir) { + @Override protected void processElement() { - if (currentElement.equals("type-storage")) { + if ("type-storage".equals(currentElement)) { // Get the filename of vendor specific descriptor String fileNameWithMETA = currentText; //trim the META_INF\ off of the file name @@ -441,44 +424,39 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { handler.registerDTD(PUBLICID_WEBLOGIC_EJB510, weblogicDTD); handler.registerDTD(PUBLICID_WEBLOGIC_EJB600, weblogicDTD); - for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); - + for (DTDLocation dtdLocation : getConfig().dtdLocations) { handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; } - /** * Add any vendor specific files which should be included in the EJB Jar. * @param ejbFiles the hash table to be populated. * @param ddPrefix the prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { File weblogicDD = new File(getConfig().descriptorDir, ddPrefix + WL_DD); if (weblogicDD.exists()) { ejbFiles.put(META_DIR + WL_DD, weblogicDD); } else { - log("Unable to locate weblogic deployment descriptor. " - + "It was expected to be in " + log("Unable to locate weblogic deployment descriptor. It was expected to be in " + weblogicDD.getPath(), Project.MSG_WARN); return; } if (!newCMP) { log("The old method for locating CMP files has been DEPRECATED.", Project.MSG_VERBOSE); - log("Please adjust your weblogic descriptor and set " - + "newCMP=\"true\" to use the new CMP descriptor " - + "inclusion mechanism. ", Project.MSG_VERBOSE); + log("Please adjust your weblogic descriptor and set newCMP=\"true\" to use the new CMP descriptor inclusion mechanism. ", + Project.MSG_VERBOSE); // The the weblogic cmp deployment descriptor File weblogicCMPDD = new File(getConfig().descriptorDir, ddPrefix + WL_CMP_DD); if (weblogicCMPDD.exists()) { - ejbFiles.put(META_DIR + WL_CMP_DD, - weblogicCMPDD); + ejbFiles.put(META_DIR + WL_CMP_DD, weblogicCMPDD); } } else { // now that we have the weblogic descriptor, we parse the file @@ -486,7 +464,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { // this could be the weblogic-cmp-rdbms.xml or any other O/R // mapping tool descriptors. try { - File ejbDescriptor = (File) ejbFiles.get(META_DIR + EJB_DD); + File ejbDescriptor = ejbFiles.get(META_DIR + EJB_DD); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); @@ -495,36 +473,29 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { DescriptorHandler handler = getWeblogicDescriptorHandler(ejbDescriptor.getParentFile()); - saxParser.parse(new InputSource(Files.newInputStream(weblogicDD.toPath())), - handler); - - Hashtable ht = handler.getFiles(); - Enumeration e = ht.keys(); - - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - - ejbFiles.put(key, ht.get(key)); + try (InputStream in = Files.newInputStream(weblogicDD.toPath())) { + saxParser.parse(new InputSource(in), handler); } + handler.getFiles().forEach(ejbFiles::put); } catch (Exception e) { - String msg = "Exception while adding Vendor specific files: " + e.toString(); - - throw new BuildException(msg, e); + throw new BuildException( + "Exception while adding Vendor specific files: " + + e.toString(), + e); } } } - /** * Get the vendor specific name of the Jar that will be output. The * modification date of this jar will be checked against the dependent * bean classes. */ + @Override File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + jarSuffix); } - /** * Helper method invoked by execute() for each WebLogic jar to be built. * Encapsulates the logic of constructing a java task for calling @@ -535,7 +506,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { * jarfile. */ private void buildWeblogicJar(File sourceJar, File destJar, String publicId) { - Java javaTask = null; if (noEJBC) { try { @@ -552,17 +522,11 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { String ejbcClassName = ejbcClass; try { - javaTask = new Java(getTask()); + Java javaTask = new Java(getTask()); javaTask.setTaskName("ejbc"); javaTask.createJvmarg().setLine(additionalJvmArgs); - if (!(sysprops.isEmpty())) { - for (Enumeration en = sysprops.elements(); en.hasMoreElements();) { - Environment.Variable entry - = (Environment.Variable) en.nextElement(); - javaTask.addSysproperty(entry); - } - } + sysprops.forEach(javaTask::addSysproperty); if (getJvmDebugLevel() != null) { javaTask.createJvmarg().setLine(" -Dweblogic.StdoutSeverityLevel=" + jvmDebugLevel); @@ -592,20 +556,18 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { String buildCompiler = getTask().getProject().getProperty("build.compiler"); - if (buildCompiler != null && buildCompiler.equals("jikes")) { + if ("jikes".equals(buildCompiler)) { javaTask.createArg().setValue("-compiler"); javaTask.createArg().setValue("jikes"); } - } else { - if (!compiler.equals(DEFAULT_COMPILER)) { - javaTask.createArg().setValue("-compiler"); - javaTask.createArg().setLine(compiler); - } + } else if (!DEFAULT_COMPILER.equals(compiler)) { + javaTask.createArg().setValue("-compiler"); + javaTask.createArg().setLine(compiler); } Path combinedClasspath = getCombinedClasspath(); - if (wlClasspath != null && combinedClasspath != null - && combinedClasspath.toString().trim().length() > 0) { + if (!(wlClasspath == null || combinedClasspath == null + || combinedClasspath.toString().trim().isEmpty())) { javaTask.createArg().setValue("-classpath"); javaTask.createArg().setPath(combinedClasspath); } @@ -636,14 +598,11 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { } } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling " + ejbcClassName - + ". Details: " + e.toString(); - - throw new BuildException(msg, e); + throw new BuildException("Exception while calling " + ejbcClassName + + ". Details: " + e.toString(), e); } } - /** * Method used to encapsulate the writing of the JAR file. Iterates over * the filenames/java.io.Files in the Hashtable stored on the instance @@ -654,7 +613,8 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { * @param publicId the id to use. * @throws BuildException if there is a problem. */ - protected void writeJar(String baseName, File jarFile, Hashtable files, + @Override + protected void writeJar(String baseName, File jarFile, Hashtable<String, File> files, String publicId) throws BuildException { // need to create a generic jar first. File genericJarFile = super.getVendorOutputJarFile(baseName); @@ -671,16 +631,15 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { } } - /** * Called to validate that the tool parameters have been configured. * @throws BuildException if there is an error. */ + @Override public void validateConfigured() throws BuildException { super.validateConfigured(); } - /** * Helper method to check to see if a weblogic EBJ1.1 jar needs to be * rebuilt using ejbc. Called from writeJar it sees if the "Bean" classes @@ -726,35 +685,33 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { genericJar = new JarFile(genericJarFile); wlJar = new JarFile(weblogicJarFile); - Hashtable genericEntries = new Hashtable(); - Hashtable wlEntries = new Hashtable(); - Hashtable replaceEntries = new Hashtable(); + Hashtable<String, JarEntry> genericEntries = new Hashtable<>(); + Hashtable<String, JarEntry> wlEntries = new Hashtable<>(); + Hashtable<String, JarEntry> replaceEntries = new Hashtable<>(); //get the list of generic jar entries - for (Enumeration e = genericJar.entries(); e.hasMoreElements();) { - JarEntry je = (JarEntry) e.nextElement(); - + for (Enumeration<JarEntry> e = genericJar.entries(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); genericEntries.put(je.getName().replace('\\', '/'), je); } //get the list of weblogic jar entries - for (Enumeration e = wlJar.entries(); e.hasMoreElements();) { - JarEntry je = (JarEntry) e.nextElement(); - + for (Enumeration<JarEntry> e = wlJar.entries(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); wlEntries.put(je.getName(), je); } //Cycle Through generic and make sure its in weblogic genericLoader = getClassLoaderFromJar(genericJarFile); - for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) { - String filepath = (String) e.nextElement(); + for (Enumeration<String> e = genericEntries.keys(); e.hasMoreElements();) { + String filepath = e.nextElement(); if (wlEntries.containsKey(filepath)) { // File name/path match // Check files see if same - JarEntry genericEntry = (JarEntry) genericEntries.get(filepath); - JarEntry wlEntry = (JarEntry) wlEntries.get(filepath); + JarEntry genericEntry = genericEntries.get(filepath); + JarEntry wlEntry = wlEntries.get(filepath); if ((genericEntry.getCrc() != wlEntry.getCrc()) || (genericEntry.getSize() != wlEntry.getSize())) { @@ -768,7 +725,7 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { classname = classname.substring(0, classname.lastIndexOf(".class")); - Class genclass = genericLoader.loadClass(classname); + Class<?> genclass = genericLoader.loadClass(classname); if (genclass.isInterface()) { //Interface changed rebuild jar. @@ -776,19 +733,17 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { + " has changed", Project.MSG_VERBOSE); rebuild = true; break; - } else { - //Object class Changed update it. - replaceEntries.put(filepath, genericEntry); - } - } else { - // is it the manifest. If so ignore it - if (!genericEntry.getName().equals("META-INF/MANIFEST.MF")) { - //File other then class changed rebuild - log("Non class file " + genericEntry.getName() - + " has changed", Project.MSG_VERBOSE); - rebuild = true; - break; } + //Object class Changed update it. + replaceEntries.put(filepath, genericEntry); + } else if (!genericEntry.getName() + .equals("META-INF/MANIFEST.MF")) { + // it is the manifest, so ignore it + //File other then class changed rebuild + log("Non class file " + genericEntry.getName() + + " has changed", Project.MSG_VERBOSE); + rebuild = true; + break; } } } else { @@ -812,11 +767,8 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { newJarStream.setLevel(0); //Copy files from old weblogic jar - for (Enumeration e = wlEntries.elements(); e.hasMoreElements();) { - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - int bytesRead; - InputStream is; - JarEntry je = (JarEntry) e.nextElement(); + for (Enumeration<JarEntry> e = wlEntries.elements(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); if (je.getCompressedSize() == -1 || je.getCompressedSize() == je.getSize()) { @@ -825,12 +777,13 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { newJarStream.setLevel(JAR_COMPRESS_LEVEL); } + InputStream is; // Update with changed Bean class if (replaceEntries.containsKey(je.getName())) { log("Updating Bean class from generic Jar " + je.getName(), Project.MSG_VERBOSE); // Use the entry from the generic jar - je = (JarEntry) replaceEntries.get(je.getName()); + je = replaceEntries.get(je.getName()); is = genericJar.getInputStream(je); } else { //use fle from original weblogic jar @@ -839,6 +792,8 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { } newJarStream.putNextEntry(new JarEntry(je.getName())); + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { newJarStream.write(buffer, 0, bytesRead); } @@ -878,11 +833,11 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { } if (genericLoader != null && genericLoader instanceof AntClassLoader) { + @SuppressWarnings("resource") AntClassLoader loader = (AntClassLoader) genericLoader; loader.cleanup(); } } - return rebuild; } @@ -905,7 +860,6 @@ public class WeblogicDeploymentTool extends GenericDeploymentTool { if (classpath != null) { lookupPath.append(classpath); } - return getTask().getProject().createClassLoader(lookupPath); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java index 0752bbec7..15edf4687 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WeblogicTOPLinkDeploymentTool.java @@ -62,14 +62,17 @@ public class WeblogicTOPLinkDeploymentTool extends WeblogicDeploymentTool { * @param srcDir the source file. * @return the descriptor handler. */ + @Override protected DescriptorHandler getDescriptorHandler(File srcDir) { DescriptorHandler handler = super.getDescriptorHandler(srcDir); if (toplinkDTD != null) { - handler.registerDTD("-//The Object People, Inc.//" - + "DTD TOPLink for WebLogic CMP 2.5.1//EN", toplinkDTD); + handler.registerDTD( + "-//The Object People, Inc.//DTD TOPLink for WebLogic CMP 2.5.1//EN", + toplinkDTD); } else { - handler.registerDTD("-//The Object People, Inc.//" - + "DTD TOPLink for WebLogic CMP 2.5.1//EN", TL_DTD_LOC); + handler.registerDTD( + "-//The Object People, Inc.//DTD TOPLink for WebLogic CMP 2.5.1//EN", + TL_DTD_LOC); } return handler; } @@ -80,21 +83,20 @@ public class WeblogicTOPLinkDeploymentTool extends WeblogicDeploymentTool { * @param ejbFiles the hashtable to add files to. * @param ddPrefix the prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String ddPrefix) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String ddPrefix) { super.addVendorFiles(ejbFiles, ddPrefix); // Then the toplink deployment descriptor // Setup a naming standard here?. - File toplinkDD = new File(getConfig().descriptorDir, ddPrefix + toplinkDescriptor); if (toplinkDD.exists()) { ejbFiles.put(META_DIR + toplinkDescriptor, toplinkDD); } else { - log("Unable to locate toplink deployment descriptor. " - + "It was expected to be in " + log("Unable to locate toplink deployment descriptor. It was expected to be in " + toplinkDD.getPath(), Project.MSG_WARN); } } @@ -103,11 +105,12 @@ public class WeblogicTOPLinkDeploymentTool extends WeblogicDeploymentTool { * Called to validate that the tool parameters have been configured. * @throws BuildException if there is an error. */ + @Override public void validateConfigured() throws BuildException { super.validateConfigured(); if (toplinkDescriptor == null) { - throw new BuildException("The toplinkdescriptor attribute must " - + "be specified"); + throw new BuildException( + "The toplinkdescriptor attribute must be specified"); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java index 63caf5075..6acdc4781 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ejb/WebsphereDeploymentTool.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Iterator; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -32,6 +31,7 @@ import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.taskdefs.optional.ejb.EjbJar.DTDLocation; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.FileUtils; @@ -148,7 +148,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { return wasClasspath.createPath(); } - /** * Set the websphere classpath. * @param wasClasspath the websphere classpath. @@ -157,7 +156,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.wasClasspath = wasClasspath; } - /** Sets the DB Vendor for the Entity Bean mapping ; optional. * <p> * Valid options can be obtained by running the following command: @@ -177,7 +175,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.dbVendor = dbvendor; } - /** * Sets the name of the Database to create; optional. * @@ -187,7 +184,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.dbName = dbName; } - /** * Sets the name of the schema to create; optional. * @@ -197,7 +193,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.dbSchema = dbSchema; } - /** * Flag, default false, to only generate the deployment * code, do not run RMIC or Javac @@ -208,7 +203,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.codegen = codegen; } - /** * Flag, default true, to only output error messages. * @@ -218,7 +212,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.quiet = quiet; } - /** * Flag to disable the validation steps; optional, default false. * @@ -228,7 +221,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.novalidate = novalidate; } - /** * Flag to disable warning and informational messages; optional, default false. * @@ -238,7 +230,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.nowarn = nowarn; } - /** * Flag to disable informational messages; optional, default false. * @@ -248,7 +239,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.noinform = noinform; } - /** * Flag to enable internal tracing when set, optional, default false. * @@ -276,7 +266,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { use35MappingRules = attr; } - /** * Set the rebuild flag to false to only update changes in the jar rather * than rerunning ejbdeploy; optional, default true. @@ -286,7 +275,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.alwaysRebuild = rebuild; } - /** * String value appended to the basename of the deployment * descriptor to create the filename of the WebLogic EJB @@ -297,7 +285,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.jarSuffix = inString; } - /** * This controls whether the generic file used as input to * ejbdeploy is retained; optional, default false. @@ -307,7 +294,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.keepGeneric = inValue; } - /** * Decide, whether ejbdeploy should be called or not; * optional, default true. @@ -318,7 +304,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.ejbdeploy = ejbdeploy; } - /** * Setter used to store the location of the Sun's Generic EJB DTD. This * can be a file on the system or a resource on the classpath. @@ -329,7 +314,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.ejb11DTD = inString; } - /** * Set the value of the oldCMP scheme. This is an antonym for newCMP * @ant.attribute ignore="true" @@ -339,7 +323,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.newCMP = !oldCMP; } - /** * Set the value of the newCMP scheme. The old CMP scheme locates the * websphere CMP descriptor based on the naming convention where the @@ -353,7 +336,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.newCMP = newCMP; } - /** * The directory, where ejbdeploy will write temporary files; * optional, defaults to '_ejbdeploy_temp'. @@ -363,24 +345,20 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { this.tempdir = tempdir; } - /** {@inheritDoc}. */ + @Override protected DescriptorHandler getDescriptorHandler(File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir); // register all the DTDs, both the ones that are known and // any supplied by the user handler.registerDTD(PUBLICID_EJB11, ejb11DTD); - for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); - + for (DTDLocation dtdLocation : getConfig().dtdLocations) { handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } - return handler; } - /** * Get a description handler. * @param srcDir the source directory. @@ -389,13 +367,12 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { protected DescriptorHandler getWebsphereDescriptorHandler(final File srcDir) { DescriptorHandler handler = new DescriptorHandler(getTask(), srcDir) { + @Override protected void processElement() { } }; - for (Iterator i = getConfig().dtdLocations.iterator(); i.hasNext();) { - EjbJar.DTDLocation dtdLocation = (EjbJar.DTDLocation) i.next(); - + for (DTDLocation dtdLocation : getConfig().dtdLocations) { handler.registerDTD(dtdLocation.getPublicId(), dtdLocation.getLocation()); } return handler; @@ -407,9 +384,10 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { * @param ejbFiles a hashtable entryname -> file. * @param baseName a prefix to use. */ - protected void addVendorFiles(Hashtable ejbFiles, String baseName) { + @Override + protected void addVendorFiles(Hashtable<String, File> ejbFiles, String baseName) { - String ddPrefix = (usingBaseJarName() ? "" : baseName); + String ddPrefix = usingBaseJarName() ? "" : baseName; String dbPrefix = (dbVendor == null) ? "" : dbVendor + "-"; // Get the Extensions document @@ -419,8 +397,7 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { ejbFiles.put(META_DIR + WAS_EXT, websphereEXT); } else { - log("Unable to locate websphere extensions. " - + "It was expected to be in " + log("Unable to locate websphere extensions. It was expected to be in " + websphereEXT.getPath(), Project.MSG_VERBOSE); } @@ -430,17 +407,15 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { ejbFiles.put(META_DIR + WAS_BND, websphereBND); } else { - log("Unable to locate websphere bindings. " - + "It was expected to be in " + log("Unable to locate websphere bindings. It was expected to be in " + websphereBND.getPath(), Project.MSG_VERBOSE); } if (!newCMP) { log("The old method for locating CMP files has been DEPRECATED.", Project.MSG_VERBOSE); - log("Please adjust your websphere descriptor and set " - + "newCMP=\"true\" to use the new CMP descriptor " - + "inclusion mechanism. ", Project.MSG_VERBOSE); + log("Please adjust your websphere descriptor and set newCMP=\"true\" to use the new CMP descriptor inclusion mechanism. ", + Project.MSG_VERBOSE); } else { // We attempt to put in the MAP and Schema files of CMP beans try { @@ -468,25 +443,24 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } // Theres nothing else to see here...keep moving sonny } catch (Exception e) { - String msg = "Exception while adding Vendor specific files: " - + e.toString(); - - throw new BuildException(msg, e); + throw new BuildException( + "Exception while adding Vendor specific files: " + + e.toString(), + e); } } } - /** * Get the vendor specific name of the Jar that will be output. The * modification date of this jar will be checked against the dependent * bean classes. */ + @Override File getVendorOutputJarFile(String baseName) { return new File(getDestDir(), baseName + jarSuffix); } - /** * Gets the options for the EJB Deploy operation * @@ -494,7 +468,7 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { */ protected String getOptions() { // Set the options - StringBuffer options = new StringBuffer(); + StringBuilder options = new StringBuilder(); if (dbVendor != null) { options.append(" -dbvendor ").append(dbVendor); @@ -542,7 +516,6 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { return options.toString(); } - /** * Helper method invoked by execute() for each websphere jar to be built. * Encapsulates the logic of constructing a java task for calling @@ -603,15 +576,16 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } } catch (Exception e) { // Have to catch this because of the semantics of calling main() - String msg = "Exception while calling ejbdeploy. Details: " + e.toString(); - - throw new BuildException(msg, e); + throw new BuildException( + "Exception while calling ejbdeploy. Details: " + e.toString(), + e); } } /** {@inheritDoc}. */ - protected void writeJar(String baseName, File jarFile, Hashtable files, String publicId) - throws BuildException { + @Override + protected void writeJar(String baseName, File jarFile, + Hashtable<String, File> files, String publicId) throws BuildException { if (ejbdeploy) { // create the -generic.jar, if required File genericJarFile = super.getVendorOutputJarFile(baseName); @@ -633,24 +607,23 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } } - /** * Called to validate that the tool parameters have been configured. * @throws BuildException if there is an error. */ + @Override public void validateConfigured() throws BuildException { super.validateConfigured(); if (ejbdeploy) { String home = getTask().getProject().getProperty("websphere.home"); if (home == null) { - throw new BuildException("The 'websphere.home' property must " - + "be set when 'ejbdeploy=true'"); + throw new BuildException( + "The 'websphere.home' property must be set when 'ejbdeploy=true'"); } websphereHome = getTask().getProject().resolveFile(home); } } - /** * Helper method to check to see if a websphere EBJ1.1 jar needs to be * rebuilt using ejbdeploy. Called from writeJar it sees if the "Bean" @@ -696,34 +669,32 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { genericJar = new JarFile(genericJarFile); wasJar = new JarFile(websphereJarFile); - Hashtable genericEntries = new Hashtable(); - Hashtable wasEntries = new Hashtable(); - Hashtable replaceEntries = new Hashtable(); + Hashtable<String, JarEntry> genericEntries = new Hashtable<>(); + Hashtable<String, JarEntry> wasEntries = new Hashtable<>(); + Hashtable<String, JarEntry> replaceEntries = new Hashtable<>(); //get the list of generic jar entries - for (Enumeration e = genericJar.entries(); e.hasMoreElements();) { - JarEntry je = (JarEntry) e.nextElement(); - + for (Enumeration<JarEntry> e = genericJar.entries(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); genericEntries.put(je.getName().replace('\\', '/'), je); } //get the list of websphere jar entries - for (Enumeration e = wasJar.entries(); e.hasMoreElements();) { - JarEntry je = (JarEntry) e.nextElement(); - + for (Enumeration<JarEntry> e = wasJar.entries(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); wasEntries.put(je.getName(), je); } //Cycle Through generic and make sure its in websphere genericLoader = getClassLoaderFromJar(genericJarFile); - for (Enumeration e = genericEntries.keys(); e.hasMoreElements();) { - String filepath = (String) e.nextElement(); + for (Enumeration<String> e = genericEntries.keys(); e.hasMoreElements();) { + String filepath = e.nextElement(); if (wasEntries.containsKey(filepath)) { // File name/path match // Check files see if same - JarEntry genericEntry = (JarEntry) genericEntries.get(filepath); - JarEntry wasEntry = (JarEntry) wasEntries.get(filepath); + JarEntry genericEntry = genericEntries.get(filepath); + JarEntry wasEntry = wasEntries.get(filepath); if ((genericEntry.getCrc() != wasEntry.getCrc()) || (genericEntry.getSize() != wasEntry.getSize())) { @@ -735,7 +706,7 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { classname = classname.substring(0, classname.lastIndexOf(".class")); - Class genclass = genericLoader.loadClass(classname); + Class<?> genclass = genericLoader.loadClass(classname); if (genclass.isInterface()) { //Interface changed rebuild jar. @@ -743,14 +714,13 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { + " has changed", Project.MSG_VERBOSE); rebuild = true; break; - } else { - //Object class Changed update it. - replaceEntries.put(filepath, genericEntry); } + //Object class Changed update it. + replaceEntries.put(filepath, genericEntry); } else { // is it the manifest. If so ignore it if (!genericEntry.getName().equals("META-INF/MANIFEST.MF")) { - //File other then class changed rebuild + //File other then class changed rebuild log("Non class file " + genericEntry.getName() + " has changed", Project.MSG_VERBOSE); rebuild = true; @@ -779,11 +749,8 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { newJarStream.setLevel(0); //Copy files from old websphere jar - for (Enumeration e = wasEntries.elements(); e.hasMoreElements();) { - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - int bytesRead; - InputStream is; - JarEntry je = (JarEntry) e.nextElement(); + for (Enumeration<JarEntry> e = wasEntries.elements(); e.hasMoreElements();) { + JarEntry je = e.nextElement(); if (je.getCompressedSize() == -1 || je.getCompressedSize() == je.getSize()) { @@ -792,12 +759,13 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { newJarStream.setLevel(JAR_COMPRESS_LEVEL); } + InputStream is; // Update with changed Bean class if (replaceEntries.containsKey(je.getName())) { log("Updating Bean class from generic Jar " + je.getName(), Project.MSG_VERBOSE); // Use the entry from the generic jar - je = (JarEntry) replaceEntries.get(je.getName()); + je = replaceEntries.get(je.getName()); is = genericJar.getInputStream(je); } else { //use fle from original websphere jar @@ -806,6 +774,8 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } newJarStream.putNextEntry(new JarEntry(je.getName())); + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { newJarStream.write(buffer, 0, bytesRead); } @@ -819,17 +789,15 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { rebuild = true; } } catch (ClassNotFoundException cnfe) { - String cnfmsg = "ClassNotFoundException while processing ejb-jar file" - + ". Details: " - + cnfe.getMessage(); - - throw new BuildException(cnfmsg, cnfe); + throw new BuildException( + "ClassNotFoundException while processing ejb-jar file. Details: " + + cnfe.getMessage(), + cnfe); } catch (IOException ioe) { - String msg = "IOException while processing ejb-jar file " - + ". Details: " - + ioe.getMessage(); - - throw new BuildException(msg, ioe); + throw new BuildException( + "IOException while processing ejb-jar file . Details: " + + ioe.getMessage(), + ioe); } finally { // need to close files and perhaps rename output FileUtils.close(genericJar); @@ -846,15 +814,14 @@ public class WebsphereDeploymentTool extends GenericDeploymentTool { } if (genericLoader != null && genericLoader instanceof AntClassLoader) { + @SuppressWarnings("resource") AntClassLoader loader = (AntClassLoader) genericLoader; loader.cleanup(); } } - return rebuild; } - /** * Helper method invoked by isRebuildRequired to get a ClassLoader for a * Jar File passed to it. diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatability.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatability.java index 2c06daf17..1d748e451 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatability.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatability.java @@ -51,6 +51,7 @@ public final class Compatability { * * @return the name of compatibility level */ + @Override public String toString() { return name; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatibility.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatibility.java index bb28cd6b4..5c3240dcb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatibility.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Compatibility.java @@ -51,6 +51,7 @@ public final class Compatibility { * * @return the name of compatibility level */ + @Override public String toString() { return name; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Extension.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Extension.java index d13d2f4e3..a0c7e9d6e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Extension.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Extension.java @@ -18,11 +18,12 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; +import java.util.List; +import java.util.Objects; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.Manifest; +import java.util.stream.Stream; import org.apache.tools.ant.util.DeweyDecimal; import org.apache.tools.ant.util.StringUtils; @@ -187,31 +188,13 @@ public final class Extension { */ public static Extension[] getAvailable(final Manifest manifest) { if (null == manifest) { - return new Extension[ 0 ]; + return new Extension[0]; } - - final ArrayList results = new ArrayList(); - - final Attributes mainAttributes = manifest.getMainAttributes(); - if (null != mainAttributes) { - final Extension extension = getExtension("", mainAttributes); - if (null != extension) { - results.add(extension); - } - } - - final Map entries = manifest.getEntries(); - final Iterator keys = entries.keySet().iterator(); - while (keys.hasNext()) { - final String key = (String) keys.next(); - final Attributes attributes = (Attributes) entries.get(key); - final Extension extension = getExtension("", attributes); - if (null != extension) { - results.add(extension); - } - } - - return (Extension[]) results.toArray(new Extension[results.size()]); + return Stream + .concat(Stream.of(manifest.getMainAttributes()), + manifest.getEntries().values().stream()) + .map(attrs -> getExtension("", attrs)).filter(Objects::nonNull) + .toArray(Extension[]::new); } /** @@ -491,10 +474,11 @@ public final class Extension { * * @return string representation of object. */ + @Override public String toString() { final String brace = ": "; - final StringBuffer sb = new StringBuffer(EXTENSION_NAME.toString()); + final StringBuilder sb = new StringBuilder(EXTENSION_NAME.toString()); sb.append(brace); sb.append(extensionName); sb.append(StringUtils.LINE_SEP); @@ -567,22 +551,17 @@ public final class Extension { */ private static Extension[] getListed(final Manifest manifest, final Attributes.Name listKey) { - final ArrayList results = new ArrayList(); + final List<Extension> results = new ArrayList<>(); final Attributes mainAttributes = manifest.getMainAttributes(); if (null != mainAttributes) { getExtension(mainAttributes, results, listKey); } - final Map entries = manifest.getEntries(); - final Iterator keys = entries.keySet().iterator(); - while (keys.hasNext()) { - final String key = (String) keys.next(); - final Attributes attributes = (Attributes) entries.get(key); - getExtension(attributes, results, listKey); - } + manifest.getEntries().values() + .forEach(attributes -> getExtension(attributes, results, listKey)); - return (Extension[]) results.toArray(new Extension[results.size()]); + return results.toArray(new Extension[results.size()]); } /** @@ -595,18 +574,14 @@ public final class Extension { * or OPTIONAL_EXTENSION_LIST */ private static void getExtension(final Attributes attributes, - final ArrayList required, + final List<Extension> required, final Attributes.Name listKey) { final String names = attributes.getValue(listKey); if (null == names) { return; } - - final String[] extensions = split(names, " "); - for (int i = 0; i < extensions.length; i++) { - final String prefix = extensions[ i ] + "-"; - final Extension extension = getExtension(prefix, attributes); - + for (final String prefix : split(names, " ")) { + final Extension extension = getExtension(prefix + "-", attributes); if (null != extension) { required.add(extension); } @@ -623,10 +598,10 @@ public final class Extension { private static String[] split(final String string, final String onToken) { final StringTokenizer tokenizer = new StringTokenizer(string, onToken); - final String[] result = new String[ tokenizer.countTokens() ]; + final String[] result = new String[tokenizer.countTokens()]; for (int i = 0; i < result.length; i++) { - result[ i ] = tokenizer.nextToken(); + result[i] = tokenizer.nextToken(); } return result; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionAdapter.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionAdapter.java index b3cfddc2f..47478214e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionAdapter.java @@ -150,6 +150,7 @@ public class ExtensionAdapter extends DataType { * @param reference the reference to which this instance is associated * @exception BuildException if this instance already has been configured. */ + @Override public void setRefid(final Reference reference) throws BuildException { if (null != extensionName @@ -183,8 +184,7 @@ public class ExtensionAdapter extends DataType { } dieOnCircularReference(); if (null == extensionName) { - final String message = "Extension is missing name."; - throw new BuildException(message); + throw new BuildException("Extension is missing name."); } String specificationVersionString = null; @@ -209,7 +209,8 @@ public class ExtensionAdapter extends DataType { * @return the extension in a string. * @see java.lang.Object#toString() */ + @Override public String toString() { - return "{" + toExtension().toString() + "}"; + return "{" + toExtension() + "}"; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java index 5aba37c9f..286802768 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionSet.java @@ -19,7 +19,7 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; +import java.util.List; import java.util.Stack; import org.apache.tools.ant.BuildException; @@ -39,12 +39,12 @@ public class ExtensionSet /** * ExtensionAdapter objects representing extensions. */ - private final ArrayList extensions = new ArrayList(); + private final List<ExtensionAdapter> extensions = new ArrayList<>(); /** * Filesets specifying all the extensions wanted. */ - private final ArrayList extensionsFilesets = new ArrayList(); + private final List<FileSet> extensionsFilesets = new ArrayList<>(); /** * Adds an extension that this library requires. @@ -98,9 +98,9 @@ public class ExtensionSet return ((ExtensionSet) getCheckedRef()).toExtensions(proj); } dieOnCircularReference(); - final ArrayList extensionsList = ExtensionUtil.toExtensions(extensions); + final List<Extension> extensionsList = ExtensionUtil.toExtensions(extensions); ExtensionUtil.extractExtensions(proj, extensionsList, extensionsFilesets); - return (Extension[]) extensionsList.toArray(new Extension[extensionsList.size()]); + return extensionsList.toArray(new Extension[extensionsList.size()]); } /** @@ -123,7 +123,7 @@ public class ExtensionSet } @Override - protected synchronized void dieOnCircularReference(Stack stk, Project p) + protected synchronized void dieOnCircularReference(Stack<Object> stk, Project p) throws BuildException { if (isChecked()) { return; @@ -131,12 +131,11 @@ public class ExtensionSet if (isReference()) { super.dieOnCircularReference(stk, p); } else { - for (Iterator i = extensions.iterator(); i.hasNext();) { - pushAndInvokeCircularReferenceCheck((ExtensionAdapter) i.next(), - stk, p); + for (ExtensionAdapter extensionAdapter : extensions) { + pushAndInvokeCircularReferenceCheck(extensionAdapter, stk, p); } - for (Iterator i = extensionsFilesets.iterator(); i.hasNext();) { - pushAndInvokeCircularReferenceCheck((FileSet) i.next(), stk, p); + for (FileSet fileSet : extensionsFilesets) { + pushAndInvokeCircularReferenceCheck(fileSet, stk, p); } setChecked(true); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java index 00d4599f4..7f951d969 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtensionUtil.java @@ -20,16 +20,15 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.jar.JarFile; import java.util.jar.Manifest; +import java.util.stream.Collectors; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.util.FileUtils; /** * A set of useful methods relating to extensions. @@ -49,19 +48,10 @@ public final class ExtensionUtil { * @param adapters the list of ExtensionAdapterss to add to convert * @throws BuildException if an error occurs */ - static ArrayList toExtensions(final List adapters) + static ArrayList<Extension> toExtensions(final List<? extends ExtensionAdapter> adapters) throws BuildException { - final ArrayList results = new ArrayList(); - - final int size = adapters.size(); - for (int i = 0; i < size; i++) { - final ExtensionAdapter adapter = - (ExtensionAdapter) adapters.get(i); - final Extension extension = adapter.toExtension(); - results.add(extension); - } - - return results; + return adapters.stream().map(ExtensionAdapter::toExtension) + .collect(Collectors.toCollection(ArrayList::new)); } /** @@ -72,14 +62,12 @@ public final class ExtensionUtil { * @throws BuildException if an error occurs */ static void extractExtensions(final Project project, - final List libraries, - final List fileset) + final List<Extension> libraries, + final List<FileSet> fileset) throws BuildException { if (!fileset.isEmpty()) { - final Extension[] extensions = getExtensions(project, - fileset); - for (int i = 0; i < extensions.length; i++) { - libraries.add(extensions[ i ]); + for (Extension extension : getExtensions(project, fileset)) { + libraries.add(extension); } } } @@ -92,13 +80,11 @@ public final class ExtensionUtil { * @throws BuildException if failing to scan libraries */ private static Extension[] getExtensions(final Project project, - final List libraries) + final List<FileSet> libraries) throws BuildException { - final ArrayList extensions = new ArrayList(); - final Iterator iterator = libraries.iterator(); - while (iterator.hasNext()) { - final FileSet fileSet = (FileSet) iterator.next(); - + final List<Extension> extensions = new ArrayList<>(); + + for (FileSet fileSet : libraries) { boolean includeImpl = true; boolean includeURL = true; @@ -116,7 +102,7 @@ public final class ExtensionUtil { loadExtensions(file, extensions, includeImpl, includeURL); } } - return (Extension[]) extensions.toArray(new Extension[extensions.size()]); + return extensions.toArray(new Extension[extensions.size()]); } /** @@ -127,23 +113,17 @@ public final class ExtensionUtil { * @throws BuildException if there is an error */ private static void loadExtensions(final File file, - final List extensionList, + final List<Extension> extensionList, final boolean includeImpl, final boolean includeURL) throws BuildException { - JarFile jarFile = null; - try { - jarFile = new JarFile(file); - final Extension[] extensions = - Extension.getAvailable(jarFile.getManifest()); - for (int i = 0; i < extensions.length; i++) { - final Extension extension = extensions[ i ]; + try (JarFile jarFile = new JarFile(file)) { + for (Extension extension : Extension + .getAvailable(jarFile.getManifest())) { addExtension(extensionList, extension, includeImpl, includeURL); } } catch (final Exception e) { throw new BuildException(e.getMessage(), e); - } finally { - FileUtils.close(jarFile); } } @@ -158,7 +138,7 @@ public final class ExtensionUtil { * @param includeImpl false to exclude implementation details * @param includeURL false to exclude implementation URL */ - private static void addExtension(final List extensionList, + private static void addExtension(final List<Extension> extensionList, final Extension originalExtension, final boolean includeImpl, final boolean includeURL) { @@ -205,18 +185,14 @@ public final class ExtensionUtil { */ static Manifest getManifest(final File file) throws BuildException { - JarFile jarFile = null; - try { - jarFile = new JarFile(file); + try (JarFile jarFile = new JarFile(file)) { Manifest m = jarFile.getManifest(); if (m == null) { - throw new BuildException(file + " doesn't have a MANIFEST"); + throw new BuildException("%s doesn't have a MANIFEST", file); } return m; } catch (final IOException ioe) { throw new BuildException(ioe.getMessage(), ioe); - } finally { - FileUtils.close(jarFile); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtraAttribute.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtraAttribute.java index d52bec419..21d1144f5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtraAttribute.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/ExtraAttribute.java @@ -73,11 +73,11 @@ public class ExtraAttribute { */ public void validate() throws BuildException { if (null == name) { - final String message = "Missing name from parameter."; - throw new BuildException(message); - } else if (null == value) { - final String message = "Missing value from parameter " + name + "."; - throw new BuildException(message); + throw new BuildException("Missing name from parameter."); + } + if (null == value) { + throw new BuildException( + "Missing value from parameter " + name + "."); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibAvailableTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibAvailableTask.java index cebcf0d5e..84ba74add 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibAvailableTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibAvailableTask.java @@ -18,11 +18,12 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.io.File; -import java.util.Iterator; +import java.util.List; import java.util.Vector; -import java.util.jar.Manifest; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; /** @@ -40,7 +41,7 @@ public class JarLibAvailableTask extends Task { * Filesets specifying all the librarys * to display information about. */ - private final Vector extensionFileSets = new Vector(); + private final List<ExtensionSet> extensionFileSets = new Vector<>(); /** * The name of the property to set if extension is available. @@ -77,9 +78,8 @@ public class JarLibAvailableTask extends Task { */ public void addConfiguredExtension(final ExtensionAdapter extension) { if (null != requiredExtension) { - final String message = "Can not specify extension to " - + "search for multiple times."; - throw new BuildException(message); + throw new BuildException( + "Can not specify extension to search for multiple times."); } requiredExtension = extension; } @@ -90,7 +90,7 @@ public class JarLibAvailableTask extends Task { * @param extensionSet a set of extensions to search in. */ public void addConfiguredExtensionSet(final ExtensionSet extensionSet) { - extensionFileSets.addElement(extensionSet); + extensionFileSets.add(extensionSet); } /** @@ -98,35 +98,24 @@ public class JarLibAvailableTask extends Task { * * @throws BuildException if something goes wrong. */ + @Override public void execute() throws BuildException { validate(); - final Extension test = requiredExtension.toExtension(); + final Project prj = getProject(); + final Stream<Extension> extensions; // Check if list of files to check has been specified if (!extensionFileSets.isEmpty()) { - final Iterator iterator = extensionFileSets.iterator(); - while (iterator.hasNext()) { - final ExtensionSet extensionSet - = (ExtensionSet) iterator.next(); - final Extension[] extensions = - extensionSet.toExtensions(getProject()); - for (int i = 0; i < extensions.length; i++) { - final Extension extension = extensions[ i ]; - if (extension.isCompatibleWith(test)) { - getProject().setNewProperty(propertyName, "true"); - } - } - } + extensions = extensionFileSets.stream() + .map(xset -> xset.toExtensions(prj)).flatMap(Stream::of); } else { - final Manifest manifest = ExtensionUtil.getManifest(libraryFile); - final Extension[] extensions = Extension.getAvailable(manifest); - for (int i = 0; i < extensions.length; i++) { - final Extension extension = extensions[ i ]; - if (extension.isCompatibleWith(test)) { - getProject().setNewProperty(propertyName, "true"); - } - } + extensions = Stream.of( + Extension.getAvailable(ExtensionUtil.getManifest(libraryFile))); + } + final Extension test = requiredExtension.toExtension(); + if (extensions.anyMatch(x -> x.isCompatibleWith(test))) { + prj.setNewProperty(propertyName, "true"); } } @@ -137,21 +126,16 @@ public class JarLibAvailableTask extends Task { */ private void validate() throws BuildException { if (null == requiredExtension) { - final String message = "Extension element must be specified."; - throw new BuildException(message); + throw new BuildException("Extension element must be specified."); } - - if (null == libraryFile && extensionFileSets.isEmpty()) { - final String message = "File attribute not specified."; - throw new BuildException(message); - } - if (null != libraryFile && !libraryFile.exists()) { - final String message = "File '" + libraryFile + "' does not exist."; - throw new BuildException(message); - } - if (null != libraryFile && !libraryFile.isFile()) { - final String message = "\'" + libraryFile + "\' is not a file."; - throw new BuildException(message); + if (null == libraryFile) { + if (extensionFileSets.isEmpty()) { + throw new BuildException("File attribute not specified."); + } + } else if (!libraryFile.exists()) { + throw new BuildException("File '%s' does not exist.", libraryFile); + } else if (!libraryFile.isFile()) { + throw new BuildException("'%s' is not a file.", libraryFile); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibDisplayTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibDisplayTask.java index da12cd020..0f316573f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibDisplayTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibDisplayTask.java @@ -18,7 +18,7 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.io.File; -import java.util.Iterator; +import java.util.List; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -49,7 +49,7 @@ public class JarLibDisplayTask extends Task { * Filesets specifying all the librarys * to display information about. */ - private final Vector libraryFileSets = new Vector(); + private final List<FileSet> libraryFileSets = new Vector<>(); /** * The JAR library to display information for. @@ -66,7 +66,7 @@ public class JarLibDisplayTask extends Task { * @param fileSet a set of files about which library data will be displayed. */ public void addFileset(final FileSet fileSet) { - libraryFileSets.addElement(fileSet); + libraryFileSets.add(fileSet); } /** @@ -74,26 +74,23 @@ public class JarLibDisplayTask extends Task { * * @throws BuildException if the task fails. */ + @Override public void execute() throws BuildException { validate(); final LibraryDisplayer displayer = new LibraryDisplayer(); // Check if list of files to check has been specified - if (!libraryFileSets.isEmpty()) { - final Iterator iterator = libraryFileSets.iterator(); - while (iterator.hasNext()) { - final FileSet fileSet = (FileSet) iterator.next(); - final DirectoryScanner scanner - = fileSet.getDirectoryScanner(getProject()); + if (libraryFileSets.isEmpty()) { + displayer.displayLibrary(libraryFile); + } else { + for (FileSet fileSet : libraryFileSets) { + final DirectoryScanner scanner = + fileSet.getDirectoryScanner(getProject()); final File basedir = scanner.getBasedir(); - final String[] files = scanner.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - final File file = new File(basedir, files[ i ]); - displayer.displayLibrary(file); + for (String filename : scanner.getIncludedFiles()) { + displayer.displayLibrary(new File(basedir, filename)); } } - } else { - displayer.displayLibrary(libraryFile); } } @@ -103,17 +100,14 @@ public class JarLibDisplayTask extends Task { * @throws BuildException if invalid parameters found */ private void validate() throws BuildException { - if (null == libraryFile && libraryFileSets.isEmpty()) { - final String message = "File attribute not specified."; - throw new BuildException(message); - } - if (null != libraryFile && !libraryFile.exists()) { - final String message = "File '" + libraryFile + "' does not exist."; - throw new BuildException(message); - } - if (null != libraryFile && !libraryFile.isFile()) { - final String message = "\'" + libraryFile + "\' is not a file."; - throw new BuildException(message); + if (null == libraryFile) { + if (libraryFileSets.isEmpty()) { + throw new BuildException("File attribute not specified."); + } + } else if (!libraryFile.exists()) { + throw new BuildException("File '%s' does not exist.", libraryFile); + } else if (!libraryFile.isFile()) { + throw new BuildException("'%s' is not a file.", libraryFile); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibManifestTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibManifestTask.java index a5105e24b..6e5329448 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibManifestTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibManifestTask.java @@ -22,15 +22,17 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Iterator; +import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.MagicNames; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; -import org.apache.tools.ant.util.FileUtils; /** * Generates a manifest that declares all the dependencies. @@ -72,19 +74,19 @@ public final class JarLibManifestTask extends Task { * ExtensionAdapter objects representing * dependencies required by library. */ - private final ArrayList dependencies = new ArrayList(); + private final List<ExtensionSet> dependencies = new ArrayList<>(); /** * ExtensionAdapter objects representing optional * dependencies required by library. */ - private final ArrayList optionals = new ArrayList(); + private final List<ExtensionSet> optionals = new ArrayList<>(); /** * Extra attributes the user specifies for main section * in manifest. */ - private final ArrayList extraAttributes = new ArrayList(); + private final List<ExtraAttribute> extraAttributes = new ArrayList<>(); /** * The location where generated manifest is placed. @@ -106,7 +108,8 @@ public final class JarLibManifestTask extends Task { public void addConfiguredExtension(final ExtensionAdapter extensionAdapter) throws BuildException { if (null != extension) { - throw new BuildException("Can not have multiple extensions defined in one library."); + throw new BuildException( + "Can not have multiple extensions defined in one library."); } extension = extensionAdapter.toExtension(); } @@ -143,6 +146,7 @@ public final class JarLibManifestTask extends Task { * * @throws BuildException if the task fails. */ + @Override public void execute() throws BuildException { validate(); @@ -160,13 +164,13 @@ public final class JarLibManifestTask extends Task { } //Add all the dependency data to manifest for dependencies - final ArrayList depends = toExtensions(dependencies); + final List<Extension> depends = toExtensions(dependencies); appendExtensionList(attributes, Extension.EXTENSION_LIST, "lib", depends.size()); appendLibraryList(attributes, "lib", depends); // Add all the dependency data to manifest for "optional" //dependencies - final ArrayList option = toExtensions(optionals); + final List<Extension> option = toExtensions(optionals); appendExtensionList(attributes, Extension.OPTIONAL_EXTENSION_LIST, "opt", option.size()); appendLibraryList(attributes, "opt", option); @@ -188,7 +192,7 @@ public final class JarLibManifestTask extends Task { throw new BuildException("Destfile attribute not specified."); } if (destFile.exists() && !destFile.isFile()) { - throw new BuildException(destFile + " is not a file."); + throw new BuildException("%s is not a file.", destFile); } } @@ -199,12 +203,8 @@ public final class JarLibManifestTask extends Task { * attributes to */ private void appendExtraAttributes(final Attributes attributes) { - final Iterator iterator = extraAttributes.iterator(); - while (iterator.hasNext()) { - final ExtraAttribute attribute = - (ExtraAttribute) iterator.next(); - attributes.putValue(attribute.getName(), - attribute.getValue()); + for (ExtraAttribute attribute : extraAttributes) { + attributes.putValue(attribute.getName(), attribute.getValue()); } } @@ -215,13 +215,9 @@ public final class JarLibManifestTask extends Task { * @throws IOException if error writing file */ private void writeManifest(final Manifest manifest) throws IOException { - OutputStream output = null; - try { - output = Files.newOutputStream(destFile.toPath()); + try (OutputStream output = Files.newOutputStream(destFile.toPath())) { manifest.write(output); output.flush(); - } finally { - FileUtils.close(output); } } @@ -237,12 +233,11 @@ public final class JarLibManifestTask extends Task { * @throws BuildException if an error occurs */ private void appendLibraryList(final Attributes attributes, final String listPrefix, - final ArrayList extensions) throws BuildException { + final List<Extension> extensions) throws BuildException { final int size = extensions.size(); for (int i = 0; i < size; i++) { - final Extension ext = (Extension) extensions.get(i); - final String prefix = listPrefix + i + "-"; - Extension.addExtension(ext, prefix, attributes); + Extension.addExtension(extensions.get(i), listPrefix + i + "-", + attributes); } } @@ -259,15 +254,10 @@ public final class JarLibManifestTask extends Task { */ private void appendExtensionList(final Attributes attributes, final Attributes.Name extensionKey, final String listPrefix, final int size) { - final StringBuffer sb = new StringBuffer(); - for (int i = 0; i < size; i++) { - sb.append(listPrefix); - sb.append(i); - sb.append(' '); - } //add in something like //"Extension-List: javahelp java3d" - attributes.put(extensionKey, sb.toString()); + attributes.put(extensionKey, IntStream.range(0, size) + .mapToObj(i -> listPrefix + i).collect(Collectors.joining(" "))); } /** @@ -276,17 +266,10 @@ public final class JarLibManifestTask extends Task { * @param extensionSets the list of ExtensionSets to add to list * @throws BuildException if an error occurs */ - private ArrayList toExtensions(final ArrayList extensionSets) throws BuildException { - final ArrayList results = new ArrayList(); - - final int size = extensionSets.size(); - for (int i = 0; i < size; i++) { - final ExtensionSet set = (ExtensionSet) extensionSets.get(i); - final Extension[] extensions = set.toExtensions(getProject()); - for (int j = 0; j < extensions.length; j++) { - results.add(extensions[ j ]); - } - } - return results; + private List<Extension> toExtensions(final List<ExtensionSet> extensionSets) + throws BuildException { + final Project prj = getProject(); + return extensionSets.stream().map(xset -> xset.toExtensions(prj)) + .flatMap(Stream::of).collect(Collectors.toList()); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibResolveTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibResolveTask.java index c13194fa9..5cdc32fc6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibResolveTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibResolveTask.java @@ -19,6 +19,7 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.io.File; import java.util.ArrayList; +import java.util.List; import java.util.jar.Manifest; import org.apache.tools.ant.BuildException; @@ -49,7 +50,7 @@ public class JarLibResolveTask extends Task { /** * The set of resolvers to use to attempt to locate library. */ - private final ArrayList resolvers = new ArrayList(); + private final List<ExtensionResolver> resolvers = new ArrayList<>(); /** * Flag to indicate that you should check that @@ -132,9 +133,8 @@ public class JarLibResolveTask extends Task { */ public void addConfiguredExtension(final ExtensionAdapter extension) { if (null != requiredExtension) { - final String message = "Can not specify extension to " - + "resolve multiple times."; - throw new BuildException(message); + throw new BuildException( + "Can not specify extension to resolve multiple times."); } requiredExtension = extension.toExtension(); } @@ -144,6 +144,7 @@ public class JarLibResolveTask extends Task { * * @throws BuildException if the task fails. */ + @Override public void execute() throws BuildException { validate(); @@ -160,28 +161,26 @@ public class JarLibResolveTask extends Task { return; } - final int size = resolvers.size(); - for (int i = 0; i < size; i++) { - final ExtensionResolver resolver = - (ExtensionResolver) resolvers.get(i); - + for (ExtensionResolver resolver : resolvers) { getProject().log("Searching for extension using Resolver:" + resolver, Project.MSG_VERBOSE); - try { - final File file = resolver.resolve(requiredExtension, getProject()); + final File file = + resolver.resolve(requiredExtension, getProject()); try { checkExtension(file); return; } catch (final BuildException be) { - final String message = "File " + file + " returned by " - + "resolver failed to satisfy extension due to: " + be.getMessage(); - getProject().log(message, Project.MSG_WARN); + getProject().log("File " + file + " returned by " + + "resolver failed to satisfy extension due to: " + + be.getMessage(), Project.MSG_WARN); } } catch (final BuildException be) { - final String message = "Failed to resolve extension to file " + "using resolver " - + resolver + " due to: " + be; - getProject().log(message, Project.MSG_WARN); + getProject() + .log( + "Failed to resolve extension to file " + + "using resolver " + resolver + " due to: " + be, + Project.MSG_WARN); } } missingExtension(); @@ -210,10 +209,10 @@ public class JarLibResolveTask extends Task { */ private void checkExtension(final File file) { if (!file.exists()) { - throw new BuildException("File " + file + " does not exist"); + throw new BuildException("File %s does not exist", file); } if (!file.isFile()) { - throw new BuildException("File " + file + " is not a file"); + throw new BuildException("File %s is not a file", file); } if (!checkExtension) { getProject().log("Setting property to " + file @@ -223,9 +222,7 @@ public class JarLibResolveTask extends Task { getProject().log("Checking file " + file + " to see if it satisfies extension", Project.MSG_VERBOSE); final Manifest manifest = ExtensionUtil.getManifest(file); - final Extension[] extensions = Extension.getAvailable(manifest); - for (int i = 0; i < extensions.length; i++) { - final Extension extension = extensions[ i ]; + for (final Extension extension : Extension.getAvailable(manifest)) { if (extension.isCompatibleWith(requiredExtension)) { setLibraryProperty(file); return; @@ -256,13 +253,10 @@ public class JarLibResolveTask extends Task { */ private void validate() throws BuildException { if (null == propertyName) { - final String message = "Property attribute must be specified."; - throw new BuildException(message); + throw new BuildException("Property attribute must be specified."); } - if (null == requiredExtension) { - final String message = "Extension element must be specified."; - throw new BuildException(message); + throw new BuildException("Extension element must be specified."); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibFileSet.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibFileSet.java index b21719e58..bade00f32 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibFileSet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibFileSet.java @@ -25,8 +25,7 @@ import org.apache.tools.ant.types.FileSet; * how they are to be handled when building manifests. * */ -public class LibFileSet - extends FileSet { +public class LibFileSet extends FileSet { /** * Flag indicating whether should include the * "Implementation-URL" attribute in manifest. diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java index b0ee4f819..d3eb0566b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/LibraryDisplayer.java @@ -20,6 +20,8 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.io.File; import java.text.ParseException; import java.util.jar.Manifest; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; @@ -72,32 +74,28 @@ class LibraryDisplayer { if (0 != available.length) { System.out.println("Extensions Supported By Library:"); for (int i = 0; i < available.length; i++) { - final Extension extension = available[ i ]; - System.out.println(extension.toString()); + System.out.println(available[i]); } } if (0 != required.length) { System.out.println("Extensions Required By Library:"); for (int i = 0; i < required.length; i++) { - final Extension extension = required[ i ]; - System.out.println(extension.toString()); + System.out.println(required[i]); } } if (0 != options.length) { System.out.println("Extensions that will be used by Library if present:"); for (int i = 0; i < options.length; i++) { - final Extension extension = options[ i ]; - System.out.println(extension.toString()); + System.out.println(options[i]); } } if (0 != specifications.length) { System.out.println("Specifications Supported By Library:"); for (int i = 0; i < specifications.length; i++) { - final Specification specification = specifications[ i ]; - displaySpecification(specification); + displaySpecification(specifications[i]); } } } @@ -138,12 +136,9 @@ class LibraryDisplayer { private void displaySpecification(final Specification specification) { final String[] sections = specification.getSections(); if (null != sections) { - final StringBuffer sb = new StringBuffer("Sections: "); - for (int i = 0; i < sections.length; i++) { - sb.append(" "); - sb.append(sections[ i ]); - } - System.out.println(sb); + System.out.print("Sections: "); + System.out + .println(Stream.of(sections).collect(Collectors.joining(" "))); } System.out.println(specification.toString()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Specification.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Specification.java index 1e4bb7b30..ea8405ce3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/Specification.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/Specification.java @@ -19,11 +19,14 @@ package org.apache.tools.ant.taskdefs.optional.extension; import java.text.ParseException; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.jar.Attributes; import java.util.jar.Manifest; +import java.util.stream.Stream; import org.apache.tools.ant.util.DeweyDecimal; import org.apache.tools.ant.util.StringUtils; @@ -167,25 +170,17 @@ public final class Specification { public static Specification[] getSpecifications(final Manifest manifest) throws ParseException { if (null == manifest) { - return new Specification[ 0 ]; + return new Specification[0]; } + final List<Specification> results = new ArrayList<>(); - final ArrayList results = new ArrayList(); - - final Map entries = manifest.getEntries(); - final Iterator keys = entries.keySet().iterator(); - while (keys.hasNext()) { - final String key = (String) keys.next(); - final Attributes attributes = (Attributes) entries.get(key); - final Specification specification - = getSpecification(key, attributes); - if (null != specification) { - results.add(specification); - } + for (Map.Entry<String, Attributes> e : manifest.getEntries() + .entrySet()) { + Optional.ofNullable(getSpecification(e.getKey(), e.getValue())) + .ifPresent(results::add); } - - final ArrayList trimmedResults = removeDuplicates(results); - return (Specification[]) trimmedResults.toArray(new Specification[trimmedResults.size()]); + return removeDuplicates(results) + .toArray(new Specification[removeDuplicates(results).size()]); } /** @@ -239,10 +234,10 @@ public final class Specification { this.specificationVersion = new DeweyDecimal(specificationVersion); } catch (final NumberFormatException nfe) { - final String error = "Bad specification version format '" - + specificationVersion + "' in '" + specificationTitle - + "'. (Reason: " + nfe + ")"; - throw new IllegalArgumentException(error); + throw new IllegalArgumentException( + "Bad specification version format '" + specificationVersion + + "' in '" + specificationTitle + "'. (Reason: " + nfe + + ")"); } } @@ -253,13 +248,7 @@ public final class Specification { if (null == this.specificationTitle) { throw new NullPointerException("specificationTitle"); } - - String[] copy = null; - if (null != sections) { - copy = new String[ sections.length ]; - System.arraycopy(sections, 0, copy, 0, sections.length); - } - this.sections = copy; + this.sections = sections == null ? null : sections.clone(); } /** @@ -324,12 +313,7 @@ public final class Specification { * or null if relevant to no sections. */ public String[] getSections() { - if (null == sections) { - return null; - } - final String[] newSections = new String[ sections.length ]; - System.arraycopy(sections, 0, newSections, 0, sections.length); - return newSections; + return sections == null ? null : sections.clone(); } /** @@ -390,7 +374,7 @@ public final class Specification { * @return true if the specification is compatible with this specification */ public boolean isCompatibleWith(final Specification other) { - return (COMPATIBLE == getCompatibilityWith(other)); + return COMPATIBLE == getCompatibilityWith(other); } /** @@ -398,11 +382,12 @@ public final class Specification { * * @return string representation of object. */ + @Override public String toString() { final String brace = ": "; - final StringBuffer sb - = new StringBuffer(SPECIFICATION_TITLE.toString()); + final StringBuilder sb + = new StringBuilder(SPECIFICATION_TITLE.toString()); sb.append(brace); sb.append(specificationTitle); sb.append(StringUtils.LINE_SEP); @@ -441,7 +426,6 @@ public final class Specification { sb.append(implementationVendor); sb.append(StringUtils.LINE_SEP); } - return sb.toString(); } @@ -467,30 +451,24 @@ public final class Specification { * @param list the array of results to trim * @return an array list with all duplicates removed */ - private static ArrayList removeDuplicates(final ArrayList list) { - final ArrayList results = new ArrayList(); - final ArrayList sections = new ArrayList(); - while (list.size() > 0) { - final Specification specification = (Specification) list.remove(0); - final Iterator iterator = list.iterator(); - while (iterator.hasNext()) { - final Specification other = (Specification) iterator.next(); + private static List<Specification> removeDuplicates(final List<Specification> list) { + final List<Specification> results = new ArrayList<>(); + final List<String> sections = new ArrayList<>(); + while (!list.isEmpty()) { + final Specification specification = list.remove(0); + for (final Iterator<Specification> iterator = + list.iterator(); iterator.hasNext();) { + final Specification other = iterator.next(); if (isEqual(specification, other)) { - final String[] otherSections = other.getSections(); - if (null != otherSections) { - sections.addAll(Arrays.asList(otherSections)); - } + Optional.ofNullable(other.getSections()) + .ifPresent(s -> Collections.addAll(sections, s)); iterator.remove(); } } - - final Specification merged = - mergeInSections(specification, sections); - results.add(merged); + results.add(mergeInSections(specification, sections)); //Reset list of sections sections.clear(); } - return results; } @@ -522,22 +500,23 @@ public final class Specification { * @return the merged specification */ private static Specification mergeInSections(final Specification specification, - final ArrayList sectionsToAdd) { - if (0 == sectionsToAdd.size()) { + final List<String> sectionsToAdd) { + if (sectionsToAdd.isEmpty()) { return specification; } - sectionsToAdd.addAll(Arrays.asList(specification.getSections())); - - final String[] sections = - (String[]) sectionsToAdd.toArray(new String[sectionsToAdd.size()]); + Stream<String> sections = + Stream + .concat( + Optional.ofNullable(specification.getSections()) + .map(Stream::of).orElse(Stream.empty()), + sectionsToAdd.stream()); return new Specification(specification.getSpecificationTitle(), specification.getSpecificationVersion().toString(), specification.getSpecificationVendor(), specification.getImplementationTitle(), specification.getImplementationVersion(), - specification.getImplementationVendor(), - sections); + specification.getImplementationVendor(), sections.toArray(String[]::new)); } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/AntResolver.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/AntResolver.java index 6284679fc..b174455c3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/AntResolver.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/AntResolver.java @@ -66,6 +66,7 @@ public class AntResolver implements ExtensionResolver { * @return the file resolved * @throws BuildException if the file cannot be resolved */ + @Override public File resolve(final Extension extension, final Project project) throws BuildException { validate(); @@ -111,6 +112,7 @@ public class AntResolver implements ExtensionResolver { * Returns a string representation * @return the string representation */ + @Override public String toString() { return "Ant[" + antfile + "==>" + destfile + "]"; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/LocationResolver.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/LocationResolver.java index e2fec0229..8d3e9bc3f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/LocationResolver.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/LocationResolver.java @@ -46,19 +46,19 @@ public class LocationResolver implements ExtensionResolver { * @return the file resolved * @throws BuildException if no location is set */ + @Override public File resolve(final Extension extension, final Project project) throws BuildException { if (null == location) { - final String message = "No location specified for resolver"; - throw new BuildException(message); + throw new BuildException("No location specified for resolver"); } - return project.resolveFile(location); } /** * Returns a string representation of the Location * @return the string representation */ + @Override public String toString() { return "Location[" + location + "]"; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/URLResolver.java b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/URLResolver.java index d693b8995..7e3dca534 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/URLResolver.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/extension/resolvers/URLResolver.java @@ -66,6 +66,7 @@ public class URLResolver implements ExtensionResolver { * @return file the file resolved * @throws BuildException if the URL is invalid */ + @Override public File resolve(final Extension extension, final Project project) throws BuildException { validate(); @@ -110,16 +111,15 @@ public class URLResolver implements ExtensionResolver { */ private void validate() { if (null == url) { - final String message = "Must specify URL"; - throw new BuildException(message); + throw new BuildException("Must specify URL"); } - if (null == destdir && null == destfile) { - final String message = "Must specify destination file or directory"; - throw new BuildException(message); - } else if (null != destdir && null != destfile) { - final String message = "Must not specify both destination file or directory"; - throw new BuildException(message); + throw new BuildException( + "Must specify destination file or directory"); + } + if (null != destdir && null != destfile) { + throw new BuildException( + "Must not specify both destination file or directory"); } } @@ -127,6 +127,7 @@ public class URLResolver implements ExtensionResolver { * Returns a string representation of the URL * @return the string representation */ + @Override public String toString() { return "URL[" + url + "]"; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java index 685468ad5..42e2be18b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/i18n/Translate.java @@ -23,11 +23,12 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.util.Hashtable; +import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -138,12 +139,12 @@ public class Translate extends MatchingTask { /** * Vector to hold source file sets. */ - private Vector filesets = new Vector(); + private List<FileSet> filesets = new Vector<>(); /** * Holds key value pairs loaded from resource bundle file */ - private Hashtable resourceMap = new Hashtable(); + private Map<String, String> resourceMap = new Hashtable<>(); /** * Used to resolve file names. @@ -269,7 +270,7 @@ public class Translate extends MatchingTask { * @param set the fileset to be added */ public void addFileset(FileSet set) { - filesets.addElement(set); + filesets.add(set); } /** @@ -281,6 +282,7 @@ public class Translate extends MatchingTask { * <li>endtoken</li> * </ul> */ + @Override public void execute() throws BuildException { if (bundle == null) { throw new BuildException("The bundle attribute must be set.", @@ -319,7 +321,7 @@ public class Translate extends MatchingTask { if (!toDir.exists()) { toDir.mkdirs(); } else if (toDir.isFile()) { - throw new BuildException(toDir + " is not a directory"); + throw new BuildException("%s is not a directory", toDir); } if (srcEncoding == null) { @@ -362,23 +364,18 @@ public class Translate extends MatchingTask { Locale locale = new Locale(bundleLanguage, bundleCountry, bundleVariant); + String language = locale.getLanguage().length() > 0 ? "_" + locale.getLanguage() : ""; String country = locale.getCountry().length() > 0 ? "_" + locale.getCountry() : ""; String variant = locale.getVariant().length() > 0 ? "_" + locale.getVariant() : ""; - String bundleFile = bundle + language + country + variant; - processBundle(bundleFile, BUNDLE_SPECIFIED_LANGUAGE_COUNTRY_VARIANT, false); - - bundleFile = bundle + language + country; - processBundle(bundleFile, BUNDLE_SPECIFIED_LANGUAGE_COUNTRY, false); - - bundleFile = bundle + language; - processBundle(bundleFile, BUNDLE_SPECIFIED_LANGUAGE, false); - - bundleFile = bundle; - processBundle(bundleFile, BUNDLE_NOMATCH, false); + + processBundle(bundle + language + country + variant, BUNDLE_SPECIFIED_LANGUAGE_COUNTRY_VARIANT, false); + processBundle(bundle + language + country, BUNDLE_SPECIFIED_LANGUAGE_COUNTRY, false); + processBundle(bundle + language, BUNDLE_SPECIFIED_LANGUAGE, false); + processBundle(bundle, BUNDLE_NOMATCH, false); //Load default locale bundle files //using default file encoding scheme. @@ -392,14 +389,9 @@ public class Translate extends MatchingTask { ? "_" + locale.getVariant() : ""; bundleEncoding = System.getProperty("file.encoding"); - bundleFile = bundle + language + country + variant; - processBundle(bundleFile, BUNDLE_DEFAULT_LANGUAGE_COUNTRY_VARIANT, false); - - bundleFile = bundle + language + country; - processBundle(bundleFile, BUNDLE_DEFAULT_LANGUAGE_COUNTRY, false); - - bundleFile = bundle + language; - processBundle(bundleFile, BUNDLE_DEFAULT_LANGUAGE, true); + processBundle(bundle + language + country + variant, BUNDLE_DEFAULT_LANGUAGE_COUNTRY_VARIANT, false); + processBundle(bundle + language + country, BUNDLE_DEFAULT_LANGUAGE_COUNTRY, false); + processBundle(bundle + language, BUNDLE_DEFAULT_LANGUAGE, true); } /** @@ -431,11 +423,9 @@ public class Translate extends MatchingTask { * are not overwritten. Bundle's encoding scheme is used. */ private void loadResourceMap(InputStream ins) throws BuildException { - try { - BufferedReader in = null; - InputStreamReader isr = new InputStreamReader(ins, bundleEncoding); - in = new BufferedReader(isr); - String line = null; + try (BufferedReader in = + new BufferedReader(new InputStreamReader(ins, bundleEncoding))) { + String line; while ((line = in.readLine()) != null) { //So long as the line isn't empty and isn't a comment... if (line.trim().length() > 1 && '#' != line.charAt(0) && '!' != line.charAt(0)) { @@ -475,9 +465,6 @@ public class Translate extends MatchingTask { } } } - if (in != null) { - in.close(); - } } catch (IOException ioe) { throw new BuildException(ioe.getMessage(), getLocation()); } @@ -497,9 +484,7 @@ public class Translate extends MatchingTask { */ private void translate() throws BuildException { int filesProcessed = 0; - final int size = filesets.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) filesets.elementAt(i); + for (FileSet fs : filesets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); for (int j = 0; j < srcFiles.length; j++) { @@ -549,18 +534,14 @@ public class Translate extends MatchingTask { } private void translateOneFile(File src, File dest) throws IOException { - BufferedWriter out = null; - BufferedReader in = null; - try { - OutputStream fos = Files.newOutputStream(dest.toPath()); - out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding)); - InputStream fis = Files.newInputStream(src.toPath()); - in = new BufferedReader(new InputStreamReader(fis, srcEncoding)); - String line; + try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter( + Files.newOutputStream(dest.toPath()), destEncoding)); + BufferedReader in = new BufferedReader(new InputStreamReader( + Files.newInputStream(src.toPath()), srcEncoding))) { LineTokenizer lineTokenizer = new LineTokenizer(); lineTokenizer.setIncludeDelims(true); - line = lineTokenizer.getToken(in); - while ((line) != null) { + String line = lineTokenizer.getToken(in); + while (line != null) { // 2003-02-21 new replace algorithm by tbee (tbee@tbee.org) // because it wasn't able to replace something like "@aaa;@bbb;" @@ -602,7 +583,7 @@ public class Translate extends MatchingTask { } else { // find the replace string if (resourceMap.containsKey(token)) { - replace = (String) resourceMap.get(token); + replace = resourceMap.get(token); } else { log("Replacement string missing for: " + token, Project.MSG_VERBOSE); @@ -625,9 +606,6 @@ public class Translate extends MatchingTask { out.write(line); line = lineTokenizer.getToken(in); } - } finally { - FileUtils.close(in); - FileUtils.close(out); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java b/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java index 5cef00933..53b234b05 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/image/Image.java @@ -28,7 +28,6 @@ import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.FileSet; @@ -39,7 +38,6 @@ import org.apache.tools.ant.types.optional.image.Rotate; import org.apache.tools.ant.types.optional.image.Scale; import org.apache.tools.ant.types.optional.image.TransformOperation; import org.apache.tools.ant.util.FileNameMapper; -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.IdentityMapper; import org.apache.tools.ant.util.StringUtils; @@ -60,9 +58,9 @@ import com.sun.media.jai.codec.FileSeekableStream; */ public class Image extends MatchingTask { // CheckStyle:VisibilityModifier OFF - bc - protected Vector instructions = new Vector(); + protected Vector<ImageOperation> instructions = new Vector<>(); protected boolean overwrite = false; - protected Vector filesets = new Vector(); + protected Vector<FileSet> filesets = new Vector<>(); protected File srcDir = null; protected File destDir = null; @@ -85,7 +83,7 @@ public class Image extends MatchingTask { * @param set the FileSet to add. */ public void addFileset(FileSet set) { - filesets.addElement(set); + filesets.add(set); } /** @@ -230,9 +228,7 @@ public class Image extends MatchingTask { continue; } - for (int j = 0; j < dstNames.length; ++j){ - - final String dstName = dstNames[j]; + for (String dstName : dstNames) { final File dstFile = new File(dstDir, dstName).getAbsoluteFile(); if (dstFile.exists()){ @@ -271,6 +267,7 @@ public class Image extends MatchingTask { * @param file The file to be processed. * @deprecated this method isn't used anymore */ + @Deprecated public void processFile(File file) { processFile(file, new File(destDir == null ? srcDir : destDir, file.getName())); @@ -287,14 +284,10 @@ public class Image extends MatchingTask { try { log("Processing File: " + file.getAbsolutePath()); - FileSeekableStream input = null; PlanarImage image = null; - try { - input = new FileSeekableStream(file); + try (FileSeekableStream input = new FileSeekableStream(file)) { image = JAI.create("stream", input); - final int size = instructions.size(); - for (int i = 0; i < size; i++) { - Object instr = instructions.elementAt(i); + for (ImageOperation instr : instructions) { if (instr instanceof TransformOperation) { image = ((TransformOperation) instr) .executeTransformOperation(image); @@ -302,33 +295,25 @@ public class Image extends MatchingTask { log("Not a TransformOperation: " + instr); } } - } finally { - FileUtils.close(input); } File dstParent = newFile.getParentFile(); if (!dstParent.isDirectory() && !(dstParent.mkdirs() || dstParent.isDirectory())) { - throw new BuildException("Failed to create parent directory " - + dstParent); + throw new BuildException("Failed to create parent directory %s", + dstParent); } if ((overwrite && newFile.exists()) && (!newFile.equals(file))) { newFile.delete(); } - OutputStream stream = null; - try { - stream = Files.newOutputStream(newFile.toPath()); - + try (OutputStream stream = Files.newOutputStream(newFile.toPath())) { JAI.create("encode", image, stream, - str_encoding.toUpperCase(Locale.ENGLISH), - null); + str_encoding.toUpperCase(Locale.ENGLISH), null); stream.flush(); - } finally { - FileUtils.close(stream); } - } catch (IOException err) { + } catch (IOException | RuntimeException err) { if (!file.equals(newFile)){ newFile.delete(); } @@ -337,15 +322,6 @@ public class Image extends MatchingTask { } else { throw new BuildException(err); } - } catch (java.lang.RuntimeException rerr) { - if (!file.equals(newFile)){ - newFile.delete(); - } - if (!failonerror) { - log("Error processing file: " + rerr); - } else { - throw new BuildException(rerr); - } } } @@ -353,6 +329,7 @@ public class Image extends MatchingTask { * Executes the Task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { validateAttributes(); @@ -363,29 +340,20 @@ public class Image extends MatchingTask { int writeCount = 0; // build mapper - final FileNameMapper mapper; - if (mapperElement==null){ - mapper = new IdentityMapper(); - } else { - mapper = mapperElement.getImplementation(); - } + final FileNameMapper mapper = mapperElement == null + ? new IdentityMapper() : mapperElement.getImplementation(); // deal with specified srcDir if (srcDir != null) { - final DirectoryScanner ds = super.getDirectoryScanner(srcDir); - - final String[] files = ds.getIncludedFiles(); - writeCount += processDir(srcDir, files, dest, mapper); + writeCount += processDir(srcDir, + super.getDirectoryScanner(srcDir).getIncludedFiles(), dest, + mapper); } // deal with the filesets - final int size = filesets.size(); - for (int i = 0; i < size; i++) { - final FileSet fs = (FileSet) filesets.elementAt(i); - final DirectoryScanner ds = - fs.getDirectoryScanner(getProject()); - final String[] files = ds.getIncludedFiles(); - final File fromDir = fs.getDir(getProject()); - writeCount += processDir(fromDir, files, dest, mapper); + for (FileSet fs : filesets) { + writeCount += processDir(fs.getDir(getProject()), + fs.getDirectoryScanner(getProject()).getIncludedFiles(), + dest, mapper); } if (writeCount>0){ @@ -406,16 +374,16 @@ public class Image extends MatchingTask { * @throws BuildException on error. */ protected void validateAttributes() throws BuildException { - if (srcDir == null && filesets.size() == 0) { - throw new BuildException("Specify at least one source" - + "--a srcDir or a fileset."); + if (srcDir == null && filesets.isEmpty()) { + throw new BuildException( + "Specify at least one source--a srcDir or a fileset."); } if (srcDir == null && destDir == null) { throw new BuildException("Specify the destDir, or the srcDir."); } - if (str_encoding.equalsIgnoreCase("jpg")) { + if ("jpg".equalsIgnoreCase(str_encoding)) { str_encoding = "JPEG"; - } else if (str_encoding.equalsIgnoreCase("tif")) { + } else if ("tif".equalsIgnoreCase(str_encoding)) { str_encoding = "TIFF"; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java index fdbde749f..21d847829 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/AbstractHotDeploymentTool.java @@ -87,13 +87,14 @@ public abstract class AbstractHotDeploymentTool implements HotDeploymentTool { * base class. Subclasses should check attributes accordingly. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ + @Override public void validateAttributes() throws BuildException { if (task.getAction() == null) { throw new BuildException("The \"action\" attribute must be set"); } if (!isActionValid()) { - throw new BuildException("Invalid action \"" + task.getAction() + "\" passed"); + throw new BuildException("Invalid action \"%s\" passed", task.getAction()); } if (classpath == null) { @@ -102,17 +103,11 @@ public abstract class AbstractHotDeploymentTool implements HotDeploymentTool { } /** - * Perform the actual deployment. - * It's up to the subclasses to implement the actual behavior. - * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. - */ - public abstract void deploy() throws BuildException; - - /** * Sets the parent task. * @param task a ServerDeploy object representing the parent task. * @ant.attribute ignore="true" */ + @Override public void setTask(ServerDeploy task) { this.task = task; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java index 5a5abbab6..1cb0a7eec 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/GenericHotDeploymentTool.java @@ -70,8 +70,9 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool { * For this generic implementation, the only valid action is "deploy" * @return true if the "action" attribute is valid, false if not. */ + @Override protected boolean isActionValid() { - return (getTask().getAction().equals(VALID_ACTIONS[0])); + return getTask().getAction().equals(VALID_ACTIONS[0]); } /** @@ -79,6 +80,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool { * @param task An ServerDeploy object representing the parent task. * @ant.attribute ignored="true" */ + @Override public void setTask(ServerDeploy task) { super.setTask(task); java = new Java(task); @@ -90,6 +92,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool { * supplied classpath, classname, JVM args, and command line arguments. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ + @Override public void deploy() throws BuildException { java.setClassname(className); java.setClasspath(getClasspath()); @@ -103,6 +106,7 @@ public class GenericHotDeploymentTool extends AbstractHotDeploymentTool { * Ensures the className and arguments attribute have been set. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ + @Override public void validateAttributes() throws BuildException { super.validateAttributes(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/JonasHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/JonasHotDeploymentTool.java index c7a33a191..6e7f11882 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/JonasHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/JonasHotDeploymentTool.java @@ -53,8 +53,8 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements /** * All the valid actions that weblogic.deploy permits * */ - private static final String[] VALID_ACTIONS - = {ACTION_DELETE, ACTION_DEPLOY, ACTION_LIST, ACTION_UNDEPLOY, ACTION_UPDATE}; + private static final String[] VALID_ACTIONS = { ACTION_DELETE, + ACTION_DEPLOY, ACTION_LIST, ACTION_UNDEPLOY, ACTION_UPDATE }; /** * Description of the Field @@ -76,7 +76,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements */ private int davidPort; - /** * Set the host for the David ORB; required if * ORB==david. @@ -87,7 +86,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements davidHost = inValue; } - /** * Set the port for the David ORB; required if * ORB==david. @@ -98,7 +96,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements davidPort = inValue; } - /** * set the jonas root directory (-Dinstall.root=). This * element is required. @@ -109,7 +106,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements jonasroot = inValue; } - /** * * Choose your ORB : RMI, JEREMIE, DAVID, ...; optional. @@ -124,14 +120,13 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements orb = inValue; } - /** * gets the classpath field. * *@return A Path representing the "classpath" attribute. */ + @Override public Path getClasspath() { - Path aClassPath = super.getClasspath(); if (aClassPath == null) { @@ -147,7 +142,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements return aClassPath; } - /** * Validates the passed in attributes. <p> * @@ -161,6 +155,7 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements *@exception BuildException Description * of Exception */ + @Override public void validateAttributes() throws BuildException { // super.validateAttributes(); // don't want to call this method @@ -172,7 +167,7 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements } if (!isActionValid()) { - throw new BuildException("Invalid action \"" + action + "\" passed"); + throw new BuildException("Invalid action \"%s\" passed", action); } if (getClassName() == null) { @@ -213,9 +208,9 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements java.createArg().setLine("-n " + getServer()); } - if (action.equals(ACTION_DEPLOY) - || action.equals(ACTION_UPDATE) - || action.equals("redeploy")) { + if (ACTION_DEPLOY.equals(action) + || ACTION_UPDATE.equals(action) + || "redeploy".equals(action)) { java.createArg().setLine("-a " + getTask().getSource()); } else if (action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) { java.createArg().setLine("-r " + getTask().getSource()); @@ -224,7 +219,6 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements } } - /** * Determines if the action supplied is valid. <p> * @@ -234,19 +228,17 @@ public class JonasHotDeploymentTool extends GenericHotDeploymentTool implements *@return true if the action attribute is valid, false if * not. */ + @Override protected boolean isActionValid() { - boolean valid = false; - String action = getTask().getAction(); - for (int i = 0; i < VALID_ACTIONS.length; i++) { - if (action.equals(VALID_ACTIONS[i])) { - valid = true; - break; + for (String validAction : VALID_ACTIONS) { + if (action.equals(validAction)) { + return true; } } - - return valid; + // TODO what about redeploy, mentioned in #validateAttribute + return false; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/ServerDeploy.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/ServerDeploy.java index 8965b8e88..7947a7b81 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/ServerDeploy.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/ServerDeploy.java @@ -19,7 +19,7 @@ package org.apache.tools.ant.taskdefs.optional.j2ee; import java.io.File; -import java.util.Enumeration; +import java.util.List; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -44,7 +44,7 @@ public class ServerDeploy extends Task { private File source; /** The vendor specific tool for deploying the component **/ - private Vector vendorTools = new Vector(); + private List<AbstractHotDeploymentTool> vendorTools = new Vector<>(); /////////////////////////////////////////////////////////////////////////// // @@ -60,7 +60,7 @@ public class ServerDeploy extends Task { */ public void addGeneric(GenericHotDeploymentTool tool) { tool.setTask(this); - vendorTools.addElement(tool); + vendorTools.add(tool); } /** @@ -71,7 +71,7 @@ public class ServerDeploy extends Task { */ public void addWeblogic(WebLogicHotDeploymentTool tool) { tool.setTask(this); - vendorTools.addElement(tool); + vendorTools.add(tool); } /** @@ -82,7 +82,7 @@ public class ServerDeploy extends Task { */ public void addJonas(JonasHotDeploymentTool tool) { tool.setTask(this); - vendorTools.addElement(tool); + vendorTools.add(tool); } @@ -100,10 +100,9 @@ public class ServerDeploy extends Task { * @exception org.apache.tools.ant.BuildException if the attributes * are invalid or incomplete, or a failure occurs in the deployment process. */ + @Override public void execute() throws BuildException { - for (Enumeration e = vendorTools.elements(); - e.hasMoreElements();) { - HotDeploymentTool tool = (HotDeploymentTool) e.nextElement(); + for (HotDeploymentTool tool : vendorTools) { tool.validateAttributes(); tool.deploy(); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java index da8750927..e186dcb46 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/j2ee/WebLogicHotDeploymentTool.java @@ -59,6 +59,7 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool * tools is executed. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ + @Override public void deploy() { Java java = new Java(getTask()); java.setFork(true); @@ -79,6 +80,7 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool * be supplied. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete */ + @Override public void validateAttributes() throws BuildException { super.validateAttributes(); @@ -92,22 +94,22 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool // check for missing application on deploy & update if ((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) && application == null) { - throw new BuildException("The application attribute must be set " - + "if action = " + action); + throw new BuildException( + "The application attribute must be set if action = %s", action); } // check for missing source on deploy & update if ((action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) && getTask().getSource() == null) { - throw new BuildException("The source attribute must be set if " - + "action = " + action); + throw new BuildException( + "The source attribute must be set if action = %s", action); } // check for missing application on delete & undeploy if ((action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) && application == null) { - throw new BuildException("The application attribute must be set if " - + "action = " + action); + throw new BuildException( + "The application attribute must be set if action = %s", action); } } @@ -119,17 +121,17 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool */ public String getArguments() throws BuildException { String action = getTask().getAction(); - String args = null; if (action.equals(ACTION_DEPLOY) || action.equals(ACTION_UPDATE)) { - args = buildDeployArgs(); - } else if (action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) { - args = buildUndeployArgs(); - } else if (action.equals(ACTION_LIST)) { - args = buildListArgs(); + return buildDeployArgs(); } - - return args; + if (action.equals(ACTION_DELETE) || action.equals(ACTION_UNDEPLOY)) { + return buildUndeployArgs(); + } + if (action.equals(ACTION_LIST)) { + return buildListArgs(); + } + return null; } /** @@ -137,19 +139,16 @@ public class WebLogicHotDeploymentTool extends AbstractHotDeploymentTool * <p>Valid actions are contained in the static array VALID_ACTIONS * @return true if the action attribute is valid, false if not. */ + @Override protected boolean isActionValid() { - boolean valid = false; - String action = getTask().getAction(); - for (int i = 0; i < VALID_ACTIONS.length; i++) { - if (action.equals(VALID_ACTIONS[i])) { - valid = true; - break; + for (String validAction : VALID_ACTIONS) { + if (action.equals(validAction)) { + return true; } } - - return valid; + return false; } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJDoc.java b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJDoc.java index a4dc0f484..d3aff0840 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJDoc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJDoc.java @@ -20,8 +20,8 @@ package org.apache.tools.ant.taskdefs.optional.javacc; import java.io.File; import java.io.IOException; -import java.util.Enumeration; import java.util.Hashtable; +import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -44,7 +44,7 @@ public class JJDoc extends Task { private static final String TEXT = "TEXT"; private static final String ONE_TABLE = "ONE_TABLE"; - private final Hashtable optionalAttrs = new Hashtable(); + private final Map<String, Object> optionalAttrs = new Hashtable<>(); private String outputFile = null; private boolean plainText = false; @@ -65,7 +65,7 @@ public class JJDoc extends Task { * @param plainText a <code>boolean</code> value. */ public void setText(boolean plainText) { - optionalAttrs.put(TEXT, plainText ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(TEXT, Boolean.valueOf(plainText)); this.plainText = plainText; } @@ -74,7 +74,7 @@ public class JJDoc extends Task { * @param oneTable a <code>boolean</code> value. */ public void setOnetable(boolean oneTable) { - optionalAttrs.put(ONE_TABLE, oneTable ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(ONE_TABLE, Boolean.valueOf(oneTable)); } /** @@ -124,19 +124,15 @@ public class JJDoc extends Task { * Do the task. * @throws BuildException if there is an error. */ + @Override public void execute() throws BuildException { // load command line with optional attributes - Enumeration iter = optionalAttrs.keys(); - while (iter.hasMoreElements()) { - String name = (String) iter.nextElement(); - Object value = optionalAttrs.get(name); - cmdl.createArgument() - .setValue("-" + name + ":" + value.toString()); - } + optionalAttrs.forEach((name, value) -> cmdl.createArgument() + .setValue("-" + name + ":" + value.toString())); if (targetFile == null || !targetFile.isFile()) { - throw new BuildException("Invalid target: " + targetFile); + throw new BuildException("Invalid target: %s", targetFile); } if (outputFile != null) { @@ -195,8 +191,8 @@ public class JJDoc extends Task { suffix = DEFAULT_SUFFIX_TEXT; } - if ((optionalOutputFile == null) || optionalOutputFile.equals("")) { - int filePos = javaccFile.lastIndexOf("/"); + if ((optionalOutputFile == null) || optionalOutputFile.isEmpty()) { + int filePos = javaccFile.lastIndexOf('/'); if (filePos >= 0) { javaccFile = javaccFile.substring(filePos + 1); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java index f5d126eed..e3bca20cc 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java @@ -20,8 +20,8 @@ package org.apache.tools.ant.taskdefs.optional.javacc; import java.io.File; import java.io.IOException; -import java.util.Enumeration; import java.util.Hashtable; +import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -54,7 +54,7 @@ public class JJTree extends Task { private static final String VISITOR_EXCEPTION = "VISITOR_EXCEPTION"; private static final String NODE_PREFIX = "NODE_PREFIX"; - private final Hashtable optionalAttrs = new Hashtable(); + private final Map<String, Object> optionalAttrs = new Hashtable<>(); private String outputFile = null; @@ -74,7 +74,7 @@ public class JJTree extends Task { * @param buildNodeFiles a <code>boolean</code> value. */ public void setBuildnodefiles(boolean buildNodeFiles) { - optionalAttrs.put(BUILD_NODE_FILES, buildNodeFiles ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(BUILD_NODE_FILES, Boolean.valueOf(buildNodeFiles)); } /** @@ -82,7 +82,7 @@ public class JJTree extends Task { * @param multi a <code>boolean</code> value. */ public void setMulti(boolean multi) { - optionalAttrs.put(MULTI, multi ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(MULTI, Boolean.valueOf(multi)); } /** @@ -90,7 +90,7 @@ public class JJTree extends Task { * @param nodeDefaultVoid a <code>boolean</code> value. */ public void setNodedefaultvoid(boolean nodeDefaultVoid) { - optionalAttrs.put(NODE_DEFAULT_VOID, nodeDefaultVoid ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(NODE_DEFAULT_VOID, Boolean.valueOf(nodeDefaultVoid)); } /** @@ -98,7 +98,7 @@ public class JJTree extends Task { * @param nodeFactory a <code>boolean</code> value. */ public void setNodefactory(boolean nodeFactory) { - optionalAttrs.put(NODE_FACTORY, nodeFactory ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(NODE_FACTORY, Boolean.valueOf(nodeFactory)); } /** @@ -106,7 +106,7 @@ public class JJTree extends Task { * @param nodeScopeHook a <code>boolean</code> value. */ public void setNodescopehook(boolean nodeScopeHook) { - optionalAttrs.put(NODE_SCOPE_HOOK, nodeScopeHook ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(NODE_SCOPE_HOOK, Boolean.valueOf(nodeScopeHook)); } /** @@ -114,7 +114,7 @@ public class JJTree extends Task { * @param nodeUsesParser a <code>boolean</code> value. */ public void setNodeusesparser(boolean nodeUsesParser) { - optionalAttrs.put(NODE_USES_PARSER, nodeUsesParser ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(NODE_USES_PARSER, Boolean.valueOf(nodeUsesParser)); } /** @@ -122,7 +122,7 @@ public class JJTree extends Task { * @param staticParser a <code>boolean</code> value. */ public void setStatic(boolean staticParser) { - optionalAttrs.put(STATIC, staticParser ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(STATIC, Boolean.valueOf(staticParser)); } /** @@ -130,7 +130,7 @@ public class JJTree extends Task { * @param visitor a <code>boolean</code> value. */ public void setVisitor(boolean visitor) { - optionalAttrs.put(VISITOR, visitor ? Boolean.TRUE : Boolean.FALSE); + optionalAttrs.put(VISITOR, Boolean.valueOf(visitor)); } /** @@ -214,21 +214,18 @@ public class JJTree extends Task { * Run the task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { // load command line with optional attributes - Enumeration iter = optionalAttrs.keys(); - while (iter.hasMoreElements()) { - String name = (String) iter.nextElement(); - Object value = optionalAttrs.get(name); - cmdl.createArgument().setValue("-" + name + ":" + value.toString()); - } + optionalAttrs.forEach((name, value) -> cmdl.createArgument() + .setValue("-" + name + ":" + value.toString())); if (targetFile == null || !targetFile.isFile()) { - throw new BuildException("Invalid target: " + targetFile); + throw new BuildException("Invalid target: %s", targetFile); } - File javaFile = null; + File javaFile; // use the directory containing the target as the output directory if (outputDirectory == null) { @@ -305,8 +302,8 @@ public class JJTree extends Task { outputDir); String jjtreeFile = destFile.getAbsolutePath().replace('\\', '/'); - if ((optionalOutputFile == null) || optionalOutputFile.equals("")) { - int filePos = jjtreeFile.lastIndexOf("/"); + if ((optionalOutputFile == null) || optionalOutputFile.isEmpty()) { + int filePos = jjtreeFile.lastIndexOf('/'); if (filePos >= 0) { jjtreeFile = jjtreeFile.substring(filePos + 1); @@ -328,7 +325,7 @@ public class JJTree extends Task { } } - if ((outputDir == null) || outputDir.equals("")) { + if ((outputDir == null) || outputDir.isEmpty()) { outputDir = getDefaultOutputDirectory(); } @@ -363,17 +360,17 @@ public class JJTree extends Task { String root = getRoot(new File(destFile)).getAbsolutePath(); - if ((root.length() > 1) + if (root.length() > 1 && destFile.startsWith(root.substring(0, root.length() - 1))) { - throw new BuildException("Drive letter in 'outputfile' not " - + "supported: " + destFile); + throw new BuildException( + "Drive letter in 'outputfile' not supported: %s", destFile); } return destFile; } private String makeOutputFileRelative(String destFile) { - StringBuffer relativePath = new StringBuffer(); + StringBuilder relativePath = new StringBuilder(); String defaultOutputDirectory = getDefaultOutputDirectory(); int nextPos = defaultOutputDirectory.indexOf('/'); int startPos = nextPos + 1; @@ -388,10 +385,7 @@ public class JJTree extends Task { startPos = nextPos + 1; } } - - relativePath.append(destFile); - - return relativePath.toString(); + return relativePath.append(destFile).toString(); } private String getDefaultOutputDirectory() { @@ -410,7 +404,6 @@ public class JJTree extends Task { while (root.getParent() != null) { root = root.getParentFile(); } - return root; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java index 86713da27..c35db1bbd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JavaCC.java @@ -20,8 +20,8 @@ package org.apache.tools.ant.taskdefs.optional.javacc; import java.io.File; import java.io.InputStream; -import java.util.Enumeration; import java.util.Hashtable; +import java.util.Map; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; @@ -64,7 +64,7 @@ public class JavaCC extends Task { private static final String KEEP_LINE_COLUMN = "KEEP_LINE_COLUMN"; private static final String JDK_VERSION = "JDK_VERSION"; - private final Hashtable optionalAttrs = new Hashtable(); + private final Map<String, Object> optionalAttrs = new Hashtable<>(); // required attributes private File outputDirectory = null; @@ -79,19 +79,19 @@ public class JavaCC extends Task { protected static final String[] ARCHIVE_LOCATIONS = //NOSONAR new String[] { - "JavaCC.zip", - "bin/lib/JavaCC.zip", - "bin/lib/javacc.jar", - "javacc.jar", // used by jpackage for JavaCC 3.x - }; + "JavaCC.zip", + "bin/lib/JavaCC.zip", + "bin/lib/javacc.jar", + "javacc.jar", // used by jpackage for JavaCC 3.x + }; protected static final int[] ARCHIVE_LOCATIONS_VS_MAJOR_VERSION = //NOSONAR new int[] { - 1, - 2, - 3, - 3, - }; + 1, + 2, + 3, + 3, + }; protected static final String COM_PACKAGE = "COM.sun.labs."; protected static final String COM_JAVACC_CLASS = "javacc.Main"; @@ -331,19 +331,16 @@ public class JavaCC extends Task { * Run the task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { // load command line with optional attributes - Enumeration iter = optionalAttrs.keys(); - while (iter.hasMoreElements()) { - String name = (String) iter.nextElement(); - Object value = optionalAttrs.get(name); - cmdl.createArgument().setValue("-" + name + ":" + value.toString()); - } + optionalAttrs.forEach((name, value) -> cmdl.createArgument() + .setValue("-" + name + ":" + value)); // check the target is a file if (targetFile == null || !targetFile.isFile()) { - throw new BuildException("Invalid target: " + targetFile); + throw new BuildException("Invalid target: %s", targetFile); } // use the directory containing the target as the output directory @@ -523,8 +520,9 @@ public class JavaCC extends Task { } } - throw new BuildException("Could not find a path to JavaCC.zip " - + "or javacc.jar from '" + home + "'."); + throw new BuildException( + "Could not find a path to JavaCC.zip or javacc.jar from '%s'.", + home); } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javah/JavahAdapterFactory.java b/src/main/org/apache/tools/ant/taskdefs/optional/javah/JavahAdapterFactory.java index 481a97d3c..2244e5b26 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javah/JavahAdapterFactory.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javah/JavahAdapterFactory.java @@ -42,7 +42,8 @@ public class JavahAdapterFactory { public static String getDefault() { if (JavaEnvUtils.isKaffe()) { return Kaffeh.IMPLEMENTATION_NAME; - } else if (JavaEnvUtils.isGij()) { + } + if (JavaEnvUtils.isGij()) { return Gcjh.IMPLEMENTATION_NAME; } return ForkingJavah.IMPLEMENTATION_NAME; @@ -84,20 +85,23 @@ public class JavahAdapterFactory { if ((JavaEnvUtils.isKaffe() && choice == null) || Kaffeh.IMPLEMENTATION_NAME.equals(choice)) { return new Kaffeh(); - } else if ((JavaEnvUtils.isGij() && choice == null) + } + if ((JavaEnvUtils.isGij() && choice == null) || Gcjh.IMPLEMENTATION_NAME.equals(choice)) { return new Gcjh(); - } else if (ForkingJavah.IMPLEMENTATION_NAME.equals(choice)) { + } + if (ForkingJavah.IMPLEMENTATION_NAME.equals(choice)) { return new ForkingJavah(); - } else if (SunJavah.IMPLEMENTATION_NAME.equals(choice)) { + } + if (SunJavah.IMPLEMENTATION_NAME.equals(choice)) { return new SunJavah(); - } else if (choice != null) { + } + if (choice != null) { return resolveClassName(choice, // Memory leak in line below log.getProject() .createClassLoader(classpath)); } - return new ForkingJavah(); } @@ -113,7 +117,7 @@ public class JavahAdapterFactory { private static JavahAdapter resolveClassName(String className, ClassLoader loader) throws BuildException { - return (JavahAdapter) ClasspathUtils.newInstance(className, + return ClasspathUtils.newInstance(className, loader != null ? loader : JavahAdapterFactory.class.getClassLoader(), JavahAdapter.class); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/javah/SunJavah.java b/src/main/org/apache/tools/ant/taskdefs/optional/javah/SunJavah.java index 7911b1773..dbfd05c36 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/javah/SunJavah.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/javah/SunJavah.java @@ -44,10 +44,11 @@ public class SunJavah implements JavahAdapter { * @throws BuildException if there is an error. * @since Ant 1.6.3 */ + @Override public boolean compile(Javah javah) throws BuildException { Commandline cmd = setupJavahCommand(javah); ExecuteJava ej = new ExecuteJava(); - Class c = null; + Class<?> c; try { try { // first search for the "old" javah class in 1.4.2 tools.jar diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java index c608583b1..abc52e319 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java @@ -24,9 +24,12 @@ import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.Map; -import java.util.Vector; - +import java.util.Optional; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; @@ -42,6 +45,8 @@ import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.LoaderUtils; +import jdepend.textui.JDepend; + /** * Runs JDepend tests. * @@ -53,7 +58,6 @@ import org.apache.tools.ant.util.LoaderUtils; * */ public class JDependTask extends Task { - //private CommandlineJava commandline = new CommandlineJava(); // required attributes private Path sourcesPath; // Deprecated! @@ -71,7 +75,7 @@ public class JDependTask extends Task { private String format = "text"; private PatternSet defaultPatterns = new PatternSet(); - private static Constructor packageFilterC; + private static Constructor<?> packageFilterC; private static Method setFilter; private boolean includeRuntime = false; @@ -79,13 +83,12 @@ public class JDependTask extends Task { static { try { - Class packageFilter = + Class<?> packageFilter = Class.forName("jdepend.framework.PackageFilter"); packageFilterC = - packageFilter.getConstructor(new Class[] {java.util.Collection.class}); + packageFilter.getConstructor(Collection.class); setFilter = - jdepend.textui.JDepend.class.getDeclaredMethod("setFilter", - new Class[] {packageFilter}); + JDepend.class.getDeclaredMethod("setFilter", packageFilter); } catch (Throwable t) { if (setFilter == null) { packageFilterC = null; @@ -189,6 +192,7 @@ public class JDependTask extends Task { * @return a source path * @deprecated since 1.6.x. */ + @Deprecated public Path createSourcespath() { if (sourcesPath == null) { sourcesPath = new Path(getProject()); @@ -201,6 +205,7 @@ public class JDependTask extends Task { * @return the sources path * @deprecated since 1.6.x. */ + @Deprecated public Path getSourcespath() { return sourcesPath; } @@ -320,11 +325,12 @@ public class JDependTask extends Task { * @see EnumeratedAttribute */ public static class FormatAttribute extends EnumeratedAttribute { - private String [] formats = new String[]{"xml", "text"}; + private String[] formats = new String[] { "xml", "text" }; /** * @return the enumerated values */ + @Override public String[] getValues() { return formats; } @@ -368,11 +374,11 @@ public class JDependTask extends Task { File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource); - if (f != null) { + if (f == null) { + log("Couldn\'t find " + resource, Project.MSG_DEBUG); + } else { log("Found " + f.getAbsolutePath(), Project.MSG_DEBUG); runtimeClasses.createPath().setLocation(f); - } else { - log("Couldn\'t find " + resource, Project.MSG_DEBUG); } } @@ -381,31 +387,29 @@ public class JDependTask extends Task { * * @exception BuildException if an error occurs */ + @Override public void execute() throws BuildException { CommandlineJava commandline = new CommandlineJava(); if ("text".equals(format)) { commandline.setClassname("jdepend.textui.JDepend"); - } else - if ("xml".equals(format)) { - commandline.setClassname("jdepend.xmlui.JDepend"); - } + } else if ("xml".equals(format)) { + commandline.setClassname("jdepend.xmlui.JDepend"); + } if (jvm != null) { commandline.setVm(jvm); } if (getSourcespath() == null && getClassespath() == null) { throw new BuildException("Missing classespath required argument"); - } else if (getClassespath() == null) { - String msg = - "sourcespath is deprecated in JDepend >= 2.5 " - + "- please convert to classespath"; - log(msg); + } + if (getClassespath() == null) { + log("sourcespath is deprecated in JDepend >= 2.5 - please convert to classespath"); } // execute the test and get the return code - int exitValue = JDependTask.ERRORS; + int exitValue; boolean wasKilled = false; if (!getFork()) { exitValue = executeInVM(commandline); @@ -426,11 +430,10 @@ public class JDependTask extends Task { String errorMessage = "JDepend FAILED" + (wasKilled ? " - Timed out" : ""); - if (getHaltonerror()) { + if (getHaltonerror()) { throw new BuildException(errorMessage, getLocation()); - } else { - log(errorMessage, Project.MSG_ERR); } + log(errorMessage, Project.MSG_ERR); } } @@ -471,15 +474,10 @@ public class JDependTask extends Task { log("Output to be stored in " + getOutputFile().getPath()); } - try { - if (getClassespath() != null) { - // This is the new, better way - use classespath instead - // of sourcespath. The code is currently the same - you - // need class files in a directory to use this or jar files. - String[] cP = getClassespath().list(); - for (int i = 0; i < cP.length; i++) { - File f = new File(cP[i]); + getWorkingPath().ifPresent(path -> { + for (String filepath : path.list()) { + File f = new File(filepath); // not necessary as JDepend would fail, but why loose // some time? if (!f.exists()) { @@ -500,48 +498,17 @@ public class JDependTask extends Task { throw new BuildException(msg); } } - - } else if (getSourcespath() != null) { - - // This is the old way and is deprecated - classespath is - // the right way to do this and is above - String[] sP = getSourcespath().list(); - for (int i = 0; i < sP.length; i++) { - File f = new File(sP[i]); - - // not necessary as JDepend would fail, but why loose - // some time? - if (!f.exists() || !f.isDirectory()) { - String msg = "\"" - + f.getPath() - + "\" does not represent a valid" - + " directory. JDepend would fail."; - log(msg); - throw new BuildException(msg); - } - try { - jdepend.addDirectory(f.getPath()); - } catch (IOException e) { - String msg = - "JDepend Failed when adding a source directory: " - + e.getMessage(); - log(msg); - throw new BuildException(msg); - } - } - } + }); // This bit turns <exclude> child tags into patters to ignore String[] patterns = defaultPatterns.getExcludePatterns(getProject()); if (patterns != null && patterns.length > 0) { if (setFilter != null) { - Vector v = new Vector(); - for (int i = 0; i < patterns.length; i++) { - v.addElement(patterns[i]); - } + List<String> v = new ArrayList<>(); + Collections.addAll(v, patterns); try { - Object o = packageFilterC.newInstance(new Object[] {v}); - setFilter.invoke(jdepend, new Object[] {o}); + Object o = packageFilterC.newInstance(v); + setFilter.invoke(jdepend, o); } catch (Throwable e) { log("excludes will be ignored as JDepend doesn't like me: " + e.getMessage(), Project.MSG_WARN); @@ -554,8 +521,8 @@ public class JDependTask extends Task { jdepend.analyze(); if (pw != null && pw.checkError()) { - throw new IOException("Encountered an error writing JDepend" - + " output"); + throw new IOException( + "Encountered an error writing JDepend output"); } } catch (IOException ex) { throw new BuildException(ex); @@ -566,7 +533,6 @@ public class JDependTask extends Task { return SUCCESS; } - /** * Execute the task by forking a new JVM. The command will block until * it finishes. To know if the process was destroyed or not, use the @@ -594,8 +560,8 @@ public class JDependTask extends Task { } if (includeRuntime) { - Map/*<String, String>*/ env = Execute.getEnvironmentVariables(); - String cp = (String) env.get("CLASSPATH"); + Map<String, String> env = Execute.getEnvironmentVariables(); + String cp = env.get("CLASSPATH"); if (cp != null) { commandline.createClasspath(getProject()).createPath() .append(new Path(getProject(), cp)); @@ -615,42 +581,20 @@ public class JDependTask extends Task { // we have to find a cleaner way to put this output } - if (getSourcespath() != null) { - // This is deprecated - use classespath in the future - String[] sP = getSourcespath().list(); - for (int i = 0; i < sP.length; i++) { - File f = new File(sP[i]); - + getWorkingPath().ifPresent(path -> { + for (String filepath : path.list()) { + File f = new File(filepath); + // not necessary as JDepend would fail, but why loose // some time? if (!f.exists() || !f.isDirectory()) { - throw new BuildException("\"" + f.getPath() - + "\" does not represent a valid" - + " directory. JDepend would" - + " fail."); - } - commandline.createArgument().setValue(f.getPath()); - } - } - - if (getClassespath() != null) { - // This is the new way - use classespath - code is the - // same for now - String[] cP = getClassespath().list(); - for (int i = 0; i < cP.length; i++) { - File f = new File(cP[i]); - // not necessary as JDepend would fail, but why loose - // some time? - if (!f.exists()) { - throw new BuildException("\"" + f.getPath() - + "\" does not represent a valid" - + " file or directory. JDepend would" - + " fail."); + throw new BuildException( + "\"%s\" does not represent a valid directory. JDepend would fail.", + f.getPath()); } commandline.createArgument().setValue(f.getPath()); } - } - + }); Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN), watchdog); execute.setCommandline(commandline.getCommandline()); @@ -681,4 +625,17 @@ public class JDependTask extends Task { } return new ExecuteWatchdog(getTimeout().longValue()); } + + private Optional<Path> getWorkingPath() { + Optional<Path> result = Optional.ofNullable(getClassespath()); + if (result.isPresent()) { + return result; + } + result = Optional.ofNullable(getSourcespath()); + if (result.isPresent()) { + log("nested sourcespath is deprecated; please use classespath"); + } + return result; + } + } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java index 20e9fc510..7609c2f56 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java @@ -49,8 +49,8 @@ class ConstantPool { super(); int count = data.readUnsignedShort(); - types = new byte [ count ]; - values = new Object [ count ]; + types = new byte[count]; + values = new Object[count]; // read in all constant pool entries. for (int i = 1; i < count; i++) { byte type = data.readByte(); @@ -64,33 +64,33 @@ class ConstantPool { break; case INTEGER : - values[i] = new Integer(data.readInt()); + values[i] = Integer.valueOf(data.readInt()); break; case FLOAT : - values[i] = new Float(data.readFloat()); + values[i] = Float.valueOf(data.readFloat()); break; case LONG : - values[i] = new Long(data.readLong()); + values[i] = Long.valueOf(data.readLong()); ++i; break; case DOUBLE : - values[i] = new Double(data.readDouble()); + values[i] = Double.valueOf(data.readDouble()); ++i; break; case CLASS : case STRING : - values[i] = new Integer(data.readUnsignedShort()); + values[i] = Integer.valueOf(data.readUnsignedShort()); break; case FIELDREF : case METHODREF : case INTERFACEMETHODREF : case NAMEANDTYPE : - values[i] = new Integer(data.readInt()); + values[i] = Integer.valueOf(data.readInt()); break; default: // Do nothing @@ -133,7 +133,6 @@ public class ClassNameReader extends Object { return className; } - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java index f5767e671..4e4b0aaaf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java @@ -54,11 +54,19 @@ import org.apache.tools.ant.types.Path; */ public class JlinkTask extends MatchingTask { + private File outfile = null; + + private Path mergefiles = null; + + private Path addfiles = null; + + private boolean compress = false; + /** * The output file for this run of jlink. Usually a jar or zip file. * @param outfile the output file */ - public void setOutfile(File outfile) { + public void setOutfile(File outfile) { this.outfile = outfile; } @@ -67,7 +75,7 @@ public class JlinkTask extends MatchingTask { * be merged into the output. * @return a path to be configured */ - public Path createMergefiles() { + public Path createMergefiles() { if (this.mergefiles == null) { this.mergefiles = new Path(getProject()); } @@ -78,7 +86,7 @@ public class JlinkTask extends MatchingTask { * Sets the files to be merged into the output. * @param mergefiles a path */ - public void setMergefiles(Path mergefiles) { + public void setMergefiles(Path mergefiles) { if (this.mergefiles == null) { this.mergefiles = mergefiles; } else { @@ -91,7 +99,7 @@ public class JlinkTask extends MatchingTask { * be added to the output. * @return a path to be configured */ - public Path createAddfiles() { + public Path createAddfiles() { if (this.addfiles == null) { this.addfiles = new Path(getProject()); } @@ -102,7 +110,7 @@ public class JlinkTask extends MatchingTask { * Sets the files to be added into the output. * @param addfiles a path */ - public void setAddfiles(Path addfiles) { + public void setAddfiles(Path addfiles) { if (this.addfiles == null) { this.addfiles = addfiles; } else { @@ -114,7 +122,7 @@ public class JlinkTask extends MatchingTask { * Defines whether or not the output should be compacted. * @param compress a <code>boolean</code> value */ - public void setCompress(boolean compress) { + public void setCompress(boolean compress) { this.compress = compress; } @@ -122,15 +130,16 @@ public class JlinkTask extends MatchingTask { * Does the adding and merging. * @throws BuildException on error */ - public void execute() throws BuildException { + @Override + public void execute() throws BuildException { //Be sure everything has been set. if (outfile == null) { - throw new BuildException("outfile attribute is required! " - + "Please set."); + throw new BuildException( + "outfile attribute is required! Please set."); } if (!haveAddFiles() && !haveMergeFiles()) { - throw new BuildException("addfiles or mergefiles required! " - + "Please set."); + throw new BuildException( + "addfiles or mergefiles required! Please set."); } log("linking: " + outfile.getPath()); log("compression: " + compress, Project.MSG_VERBOSE); @@ -161,23 +170,6 @@ public class JlinkTask extends MatchingTask { } private boolean haveEntries(Path p) { - if (p == null) { - return false; - } - if (p.size() > 0) { - return true; - } - return false; + return !(p == null || p.isEmpty()); } - - private File outfile = null; - - private Path mergefiles = null; - - private Path addfiles = null; - - private boolean compress = false; - } - - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java index 4f3cff928..0d4895cd4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java @@ -29,6 +29,7 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Enumeration; +import java.util.List; import java.util.Vector; import java.util.zip.CRC32; import java.util.zip.Deflater; @@ -37,8 +38,6 @@ import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -import org.apache.tools.ant.util.FileUtils; - // CheckStyle:TypeNameCheck OFF - bc /** * jlink links together multiple .jar files. @@ -49,9 +48,9 @@ public class jlink { private String outfile = null; - private Vector mergefiles = new Vector(VECTOR_INIT_SIZE); + private List<String> mergefiles = new Vector<>(VECTOR_INIT_SIZE); - private Vector addfiles = new Vector(VECTOR_INIT_SIZE); + private List<String> addfiles = new Vector<>(VECTOR_INIT_SIZE); private boolean compression = false; @@ -71,7 +70,6 @@ public class jlink { this.outfile = outfile; } - /** * Adds a file to be merged into the output. * @param fileToMerge the file to merge into the output. @@ -80,10 +78,9 @@ public class jlink { if (fileToMerge == null) { return; } - mergefiles.addElement(fileToMerge); + mergefiles.add(fileToMerge); } - /** Adds a file to be added into the output. * @param fileToAdd the file to add to the output. */ @@ -91,38 +88,35 @@ public class jlink { if (fileToAdd == null) { return; } - addfiles.addElement(fileToAdd); + addfiles.add(fileToAdd); } - /** * Adds several files to be merged into the output. * @param filesToMerge an array of files to merge into the output. */ - public void addMergeFiles(String[] filesToMerge) { + public void addMergeFiles(String... filesToMerge) { if (filesToMerge == null) { return; } - for (int i = 0; i < filesToMerge.length; i++) { - addMergeFile(filesToMerge[i]); + for (String element : filesToMerge) { + addMergeFile(element); } } - /** - * Adds several file to be added into the output. + * Adds several files to be added into the output. * @param filesToAdd an array of files to add to the output. */ - public void addAddFiles(String[] filesToAdd) { + public void addAddFiles(String... filesToAdd) { if (filesToAdd == null) { return; } - for (int i = 0; i < filesToAdd.length; i++) { - addAddFile(filesToAdd[i]); + for (String element : filesToAdd) { + addAddFile(element); } } - /** * Determines whether output will be compressed. * @param compress if true use compression. @@ -131,7 +125,6 @@ public class jlink { this.compression = compress; } - /** * Performs the linking of files. Addfiles are added to the output as-is. * For example, a jar file is added to the output as a jar file. However, @@ -145,48 +138,40 @@ public class jlink { * @throws Exception on error. */ public void link() throws Exception { //NOSONAR - ZipOutputStream output = new ZipOutputStream(Files.newOutputStream(Paths.get(outfile))); + try (ZipOutputStream output = + new ZipOutputStream(Files.newOutputStream(Paths.get(outfile)))) { - if (compression) { - output.setMethod(ZipOutputStream.DEFLATED); - output.setLevel(Deflater.DEFAULT_COMPRESSION); - } else { - output.setMethod(ZipOutputStream.STORED); - } - - Enumeration merges = mergefiles.elements(); - - while (merges.hasMoreElements()) { - String path = (String) merges.nextElement(); - File f = new File(path); - - if (f.getName().endsWith(".jar") || f.getName().endsWith(".zip")) { - //Do the merge - mergeZipJarContents(output, f); + if (compression) { + output.setMethod(ZipOutputStream.DEFLATED); + output.setLevel(Deflater.DEFAULT_COMPRESSION); } else { - //Add this file to the addfiles Vector and add it - //later at the top level of the output file. - addAddFile(path); + output.setMethod(ZipOutputStream.STORED); } - } - - Enumeration adds = addfiles.elements(); - - while (adds.hasMoreElements()) { - String name = (String) adds.nextElement(); - File f = new File(name); + for (String path : mergefiles) { + File f = new File(path); + + if (f.getName().endsWith(".jar") + || f.getName().endsWith(".zip")) { + //Do the merge + mergeZipJarContents(output, f); + } else { + //Add this file to the addfiles Vector and add it + //later at the top level of the output file. + addAddFile(path); + } + } + for (String name : addfiles) { + File f = new File(name); - if (f.isDirectory()) { - //System.out.println("in jlink: adding directory contents of " + f.getPath()); - addDirContents(output, f, f.getName() + '/', compression); - } else { - addFile(output, f, "", compression); + if (f.isDirectory()) { + addDirContents(output, f, f.getName() + '/', compression); + } else { + addFile(output, f, "", compression); + } } } - FileUtils.close(output); } - /** * The command line entry point for jlink. * @param args an array of arguments @@ -212,7 +197,6 @@ public class jlink { } } - /* * Actually performs the merging of f into the output. * f should be a zip or jar file. @@ -223,10 +207,10 @@ public class jlink { return; } try (ZipFile zipf = new ZipFile(f)) { - Enumeration entries = zipf.entries(); + Enumeration<? extends ZipEntry> entries = zipf.entries(); while (entries.hasMoreElements()) { - ZipEntry inputEntry = (ZipEntry) entries.nextElement(); + ZipEntry inputEntry = entries.nextElement(); //Ignore manifest entries. They're bound to cause conflicts between //files that are being merged. User should supply their own //manifest file when doing the merge. @@ -244,33 +228,29 @@ public class jlink { //entry from another mergefile was called "com". //In that case, just ignore the error and go on to the //next entry. - String mess = ex.getMessage(); - - if (mess.indexOf("duplicate") >= 0) { + if (ex.getMessage().indexOf("duplicate") >= 0) { //It was the duplicate entry. continue; - } else { - // I hate to admit it, but we don't know what happened - // here. Throw the Exception. - throw ex; } + // I hate to admit it, but we don't know what happened + // here. Throw the Exception. + throw ex; } - InputStream in = zipf.getInputStream(inputEntry); - int len = buffer.length; - int count = -1; + try (InputStream in = zipf.getInputStream(inputEntry)) { + int len = buffer.length; + int count = -1; - while ((count = in.read(buffer, 0, len)) > 0) { - output.write(buffer, 0, count); + while ((count = in.read(buffer, 0, len)) > 0) { + output.write(buffer, 0, count); + } + output.closeEntry(); } - in.close(); - output.closeEntry(); } } } } - /* * Adds contents of a directory to the output. */ @@ -290,7 +270,6 @@ public class jlink { } } - /* * Gets the name of an entry in the file. This is the real name * which for a class is the name of the package with the class @@ -301,9 +280,7 @@ public class jlink { if (!name.endsWith(".class")) { // see if the file is in fact a .class file, and determine its actual name. - InputStream input = null; - try { - input = Files.newInputStream(file.toPath()); + try (InputStream input = Files.newInputStream(file.toPath())) { String className = ClassNameReader.getClassName(input); if (className != null) { @@ -311,13 +288,12 @@ public class jlink { } } catch (IOException ioe) { //do nothing - } finally { - FileUtils.close(input); } } - System.out.println("From " + file.getPath() + " and prefix " + prefix - + ", creating entry " + prefix + name); - return (prefix + name); + System.out.printf( + "From %1$s and prefix %2$s, creating entry %2$s%3$s%n", + file.getPath(), prefix, name); + return prefix + name; } @@ -337,12 +313,9 @@ public class jlink { if (!compress) { entry.setCrc(calcChecksum(file)); } - InputStream input = Files.newInputStream(file.toPath()); - - addToOutputStream(output, input, entry); + addToOutputStream(output, Files.newInputStream(file.toPath()), entry); } - /* * A convenience method that several other methods might call. */ @@ -356,7 +329,7 @@ public class jlink { return; } - int numBytes = -1; + int numBytes; while ((numBytes = input.read(buffer)) > 0) { output.write(buffer, 0, numBytes); @@ -365,7 +338,6 @@ public class jlink { input.close(); } - /* * A method that does the work on a given entry in a mergefile. * The big deal is to set the right parameters in the ZipEntry @@ -387,11 +359,9 @@ public class jlink { String name = inputEntry.getName(); if (!(inputEntry.isDirectory() || name.endsWith(".class"))) { - try { - InputStream input = zip.getInputStream(zip.getEntry(name)); + try (InputStream input = zip.getInputStream(zip.getEntry(name))) { String className = ClassNameReader.getClassName(input); - input.close(); if (className != null) { name = className.replace('.', '/') + ".class"; } @@ -416,18 +386,15 @@ public class jlink { return outputEntry; } - /* * Necessary in the case where you add a entry that * is not compressed. */ private long calcChecksum(File f) throws IOException { - BufferedInputStream in = new BufferedInputStream(Files.newInputStream(f.toPath())); - - return calcChecksum(in); + return calcChecksum( + new BufferedInputStream(Files.newInputStream(f.toPath()))); } - /* * Necessary in the case where you add a entry that * is not compressed. @@ -435,18 +402,15 @@ public class jlink { private long calcChecksum(InputStream in) throws IOException { CRC32 crc = new CRC32(); int len = buffer.length; - int count = -1; - int haveRead = 0; + int count; while ((count = in.read(buffer, 0, len)) > 0) { - haveRead += count; crc.update(buffer, 0, count); } in.close(); return crc.getValue(); } - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java index 609938c95..d8637152f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java @@ -27,19 +27,18 @@ import java.io.File; */ public class Jasper41Mangler implements JspMangler { - /** * map from a jsp file to a java filename; does not do packages * * @param jspFile file * @return java filename */ + @Override public String mapJspToJavaName(File jspFile) { String jspUri = jspFile.getAbsolutePath(); int start = jspUri.lastIndexOf(File.separatorChar) + 1; int end = jspUri.length(); - StringBuffer modifiedClassName; - modifiedClassName = new StringBuffer(jspUri.length() - start); + StringBuilder modifiedClassName = new StringBuilder(jspUri.length() - start); if (!Character.isJavaIdentifierStart(jspUri.charAt(start)) || jspUri.charAt(start) == '_') { // If the first char is not a start of Java identifier or is _ @@ -78,7 +77,6 @@ public class Jasper41Mangler implements JspMangler { // CheckStyle:MagicNumber ON } - /** * taking in the substring representing the path relative to the source dir * return a new string representing the destination path @@ -86,6 +84,7 @@ public class Jasper41Mangler implements JspMangler { * @return null as this is not implemented. * @todo */ + @Override public String mapPath(String path) { return null; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java index 9832e3e00..4af9f3d4e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java @@ -19,8 +19,7 @@ package org.apache.tools.ant.taskdefs.optional.jsp; import java.io.File; -import java.util.Date; -import java.util.Enumeration; +import java.time.Instant; import java.util.Vector; import org.apache.tools.ant.AntClassLoader; @@ -80,8 +79,8 @@ public class JspC extends MatchingTask { private boolean mapped; private int verbose = 0; // CheckStyle:VisibilityModifier OFF - bc - protected Vector compileList = new Vector(); - Vector javaFiles = new Vector(); + protected Vector<String> compileList = new Vector<>(); + Vector<File> javaFiles = new Vector<>(); /** * flag to control action on execution trouble @@ -209,6 +208,7 @@ public class JspC extends MatchingTask { public String getIeplugin() { return iepluginid; } + /** * Java Plugin CLASSID for Internet Explorer * @param iepluginid the id to use. @@ -272,7 +272,6 @@ public class JspC extends MatchingTask { return uriroot; } - /** * Set the classpath to be used for this compilation. * @param cp the path to be used. @@ -413,7 +412,7 @@ public class JspC extends MatchingTask { * get the list of files to compile * @return the list of files. */ - public Vector getCompileList() { + public Vector<String> getCompileList() { return compileList; } @@ -422,6 +421,7 @@ public class JspC extends MatchingTask { * have changed and hand them off to a jsp compiler * @throws BuildException on error. */ + @Override public void execute() throws BuildException { @@ -496,7 +496,7 @@ public class JspC extends MatchingTask { log("compiling " + compileList.size() + " files", Project.MSG_VERBOSE); - if (compileList.size() > 0) { + if (!compileList.isEmpty()) { log("Compiling " + compileList.size() + " source file" + (compileList.size() == 1 ? "" : "s") @@ -504,12 +504,10 @@ public class JspC extends MatchingTask { + dest); doCompilation(compiler); + } else if (filecount == 0) { + log("there were no files to compile", Project.MSG_INFO); } else { - if (filecount == 0) { - log("there were no files to compile", Project.MSG_INFO); - } else { - log("all files are up to date", Project.MSG_VERBOSE); - } + log("all files are up to date", Project.MSG_VERBOSE); } } } @@ -519,15 +517,11 @@ public class JspC extends MatchingTask { * this is destDir or it id destDir + the package name */ private File getActualDestDir() { - File dest = null; if (packageName == null) { - dest = destDir; - } else { - String path = destDir.getPath() + File.separatorChar - + packageName.replace('.', File.separatorChar); - dest = new File(path); + return destDir; } - return dest; + return new File(destDir.getPath() + File.separatorChar + + packageName.replace('.', File.separatorChar)); } /** @@ -542,9 +536,8 @@ public class JspC extends MatchingTask { if (!compiler.execute()) { if (failOnError) { throw new BuildException(FAIL_MSG, getLocation()); - } else { - log(FAIL_MSG, Project.MSG_ERR); } + log(FAIL_MSG, Project.MSG_ERR); } } @@ -566,23 +559,19 @@ public class JspC extends MatchingTask { protected void scanDir(File srcDir, File dest, JspMangler mangler, String[] files) { - long now = (new Date()).getTime(); + long now = Instant.now().toEpochMilli(); - for (int i = 0; i < files.length; i++) { - String filename = files[i]; + for (String filename : files) { File srcFile = new File(srcDir, filename); File javaFile = mapToJavaFile(mangler, srcFile, srcDir, dest); if (javaFile == null) { continue; } - if (srcFile.lastModified() > now) { log("Warning: file modified in the future: " + filename, Project.MSG_WARN); } - boolean shouldCompile = false; - shouldCompile = isCompileNeeded(srcFile, javaFile); - if (shouldCompile) { + if (isCompileNeeded(srcFile, javaFile)) { compileList.addElement(srcFile.getAbsolutePath()); javaFiles.addElement(javaFile); } @@ -612,26 +601,21 @@ public class JspC extends MatchingTask { log("Compiling " + srcFile.getPath() + " because java file " + javaFile.getPath() + " does not exist", Project.MSG_VERBOSE); - } else { - if (srcFile.lastModified() > javaFile.lastModified()) { - shouldCompile = true; - log("Compiling " + srcFile.getPath() - + " because it is out of date with respect to " - + javaFile.getPath(), - Project.MSG_VERBOSE); - } else { - if (javaFile.length() == 0) { - shouldCompile = true; - log("Compiling " + srcFile.getPath() - + " because java file " + javaFile.getPath() - + " is empty", Project.MSG_VERBOSE); - } - } + } else if (srcFile.lastModified() > javaFile.lastModified()) { + shouldCompile = true; + log("Compiling " + srcFile.getPath() + + " because it is out of date with respect to " + + javaFile.getPath(), + Project.MSG_VERBOSE); + } else if (javaFile.length() == 0) { + shouldCompile = true; + log("Compiling " + srcFile.getPath() + + " because java file " + javaFile.getPath() + + " is empty", Project.MSG_VERBOSE); } return shouldCompile; } - /** * get a filename from our jsp file. * @param mangler the jsp filename manager. @@ -647,7 +631,6 @@ public class JspC extends MatchingTask { return null; } String javaFileName = mangler.mapJspToJavaName(srcFile); - // String srcFileDir=srcFile.getParent(); return new File(dest, javaFileName); } @@ -658,9 +641,7 @@ public class JspC extends MatchingTask { */ public void deleteEmptyJavaFiles() { if (javaFiles != null) { - Enumeration e = javaFiles.elements(); - while (e.hasMoreElements()) { - File file = (File) e.nextElement(); + for (File file : javaFiles) { if (file.exists() && file.length() == 0) { log("deleting empty output file " + file); file.delete(); @@ -694,9 +675,6 @@ public class JspC extends MatchingTask { public void setBaseDir(File directory) { this.directory = directory; } - //end inner class } - - //end class } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java index 850c6bca9..4cde0791c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java @@ -58,6 +58,7 @@ public class JspNameMangler implements JspMangler { * @param jspFile file * @return java filename */ + @Override public String mapJspToJavaName(File jspFile) { return mapJspToBaseName(jspFile) + ".java"; } @@ -70,20 +71,19 @@ public class JspNameMangler implements JspMangler { * @return exensionless potentially remapped name */ private String mapJspToBaseName(File jspFile) { - String className; - className = stripExtension(jspFile); + String className = stripExtension(jspFile); // since we don't mangle extensions like the servlet does, // we need to check for keywords as class names - for (int i = 0; i < keywords.length; ++i) { - if (className.equals(keywords[i])) { + for (String keyword : keywords) { + if (className.equals(keyword)) { className += "%"; break; } } // Fix for invalid characters. If you think of more add to the list. - StringBuffer modifiedClassName = new StringBuffer(className.length()); + StringBuilder modifiedClassName = new StringBuilder(className.length()); // first char is more restrictive than the rest char firstChar = className.charAt(0); if (Character.isJavaIdentifierStart(firstChar)) { @@ -148,6 +148,7 @@ public class JspNameMangler implements JspMangler { * @param path not used * @return null always. */ + @Override public String mapPath(String path) { return null; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/WLJspc.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/WLJspc.java index 45a427ad5..779b01b93 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/WLJspc.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/WLJspc.java @@ -19,7 +19,8 @@ package org.apache.tools.ant.taskdefs.optional.jsp; //apache/ant imports import java.io.File; -import java.util.Date; +import java.time.Instant; +import java.util.List; import java.util.StringTokenizer; import java.util.Vector; @@ -98,21 +99,22 @@ public class WLJspc extends MatchingTask { //private String compilerPath; //fully qualified name for the compiler executable private String pathToPackage = ""; - private Vector filesToDo = new Vector(); + private List<String> filesToDo = new Vector<>(); /** * Run the task. * @throws BuildException if there is an error. */ + @Override public void execute() throws BuildException { if (!destinationDirectory.isDirectory()) { - throw new BuildException("destination directory " - + destinationDirectory.getPath() + " is not valid"); + throw new BuildException("destination directory %s is not valid", + destinationDirectory.getPath()); } if (!sourceDirectory.isDirectory()) { - throw new BuildException("src directory " - + sourceDirectory.getPath() + " is not valid"); + throw new BuildException("src directory %s is not valid", + sourceDirectory.getPath()); } if (destinationPackage == null) { @@ -120,7 +122,6 @@ public class WLJspc extends MatchingTask { getLocation()); } - pathToPackage = this.destinationPackage.replace('.', File.separatorChar); // get all the files in the sourceDirectory @@ -146,8 +147,6 @@ public class WLJspc extends MatchingTask { String[] args = new String[12]; // CheckStyle:MagicNumber ON - File jspFile = null; - String parents = ""; int j = 0; //TODO this array stuff is a remnant of prev trials.. gotta remove. args[j++] = "-d"; @@ -168,24 +167,21 @@ public class WLJspc extends MatchingTask { this.scanDir(files); log("Compiling " + filesToDo.size() + " JSP files"); - final int size = filesToDo.size(); - for (int i = 0; i < size; i++) { + for (String filename : filesToDo) { //TODO // All this to get package according to weblogic standards // Can be written better... this is too hacky! - // Careful.. similar code in scanDir , but slightly different!! - String filename = (String) filesToDo.elementAt(i); - jspFile = new File(filename); + // Careful.. similar code in scanDir, but slightly different!! + File jspFile = new File(filename); args[j] = "-package"; - parents = jspFile.getParent(); - if ((parents != null) && (!("").equals(parents))) { - parents = this.replaceString(parents, File.separator, "_."); - args[j + 1] = destinationPackage + "." + "_" + parents; - } else { + String parents = jspFile.getParent(); + if (parents == null || "".equals(parents)) { args[j + 1] = destinationPackage; + } else { + parents = this.replaceString(parents, File.separator, "_."); + args[j + 1] = destinationPackage + "." + "_" + parents; } - args[j + 2] = sourceDirectory + File.separator + filename; helperTask.clearArgs(); @@ -202,8 +198,6 @@ public class WLJspc extends MatchingTask { } } - - /** * Set the classpath to be used for this compilation. * @param classpath the classpath to use. @@ -234,7 +228,6 @@ public class WLJspc extends MatchingTask { * @param dirName the directory containg the source jsp's */ public void setSrc(File dirName) { - sourceDirectory = dirName; } @@ -245,7 +238,6 @@ public class WLJspc extends MatchingTask { * @param dirName the directory containg the source jsp's */ public void setDest(File dirName) { - destinationDirectory = dirName; } @@ -255,7 +247,6 @@ public class WLJspc extends MatchingTask { * @param packageName the package name for the classes */ public void setPackage(String packageName) { - destinationPackage = packageName; } @@ -265,52 +256,48 @@ public class WLJspc extends MatchingTask { * @param files the files to scan. */ protected void scanDir(String[] files) { - - long now = (new Date()).getTime(); - File jspFile = null; - String parents = null; - String pack = ""; - for (int i = 0; i < files.length; i++) { - File srcFile = new File(this.sourceDirectory, files[i]); + long now = Instant.now().toEpochMilli(); + for (String file : files) { + File srcFile = new File(this.sourceDirectory, file); //TODO // All this to convert source to destination directory according // to weblogic standards Can be written better... this is too hacky! - jspFile = new File(files[i]); - parents = jspFile.getParent(); + File jspFile = new File(file); + String parents = jspFile.getParent(); - if ((parents != null) && (!("").equals(parents))) { + String pack; + if (parents == null || "".equals(parents)) { + pack = pathToPackage; + } else { parents = this.replaceString(parents, File.separator, "_/"); pack = pathToPackage + File.separator + "_" + parents; - } else { - pack = pathToPackage; } String filePath = pack + File.separator + "_"; - int startingIndex = files[i].lastIndexOf(File.separator) != -1 - ? files[i].lastIndexOf(File.separator) + 1 : 0; - int endingIndex = files[i].indexOf(".jsp"); + int startingIndex = file.lastIndexOf(File.separator) != -1 + ? file.lastIndexOf(File.separator) + 1 : 0; + int endingIndex = file.indexOf(".jsp"); if (endingIndex == -1) { - log("Skipping " + files[i] + ". Not a JSP", + log("Skipping " + file + ". Not a JSP", Project.MSG_VERBOSE); continue; } - filePath += files[i].substring(startingIndex, endingIndex); + filePath += file.substring(startingIndex, endingIndex); filePath += ".class"; File classFile = new File(this.destinationDirectory, filePath); if (srcFile.lastModified() > now) { log("Warning: file modified in the future: " - + files[i], Project.MSG_WARN); + + file, Project.MSG_WARN); } if (srcFile.lastModified() > classFile.lastModified()) { - filesToDo.addElement(files[i]); - log("Recompiling File " + files[i], Project.MSG_VERBOSE); + filesToDo.add(file); + log("Recompiling File " + file, Project.MSG_VERBOSE); } } } - /** * Replace occurrences of a string with a replacement string. * @param inpString the string to convert. @@ -321,9 +308,8 @@ public class WLJspc extends MatchingTask { protected String replaceString(String inpString, String escapeChars, String replaceChars) { String localString = ""; - int numTokens = 0; StringTokenizer st = new StringTokenizer(inpString, escapeChars, true); - numTokens = st.countTokens(); + int numTokens = st.countTokens(); for (int i = 0; i < numTokens; i++) { String test = st.nextToken(); test = (test.equals(escapeChars) ? replaceChars : test); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/DefaultJspCompilerAdapter.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/DefaultJspCompilerAdapter.java index 5c4d0e3b5..303ef6f37 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/DefaultJspCompilerAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/DefaultJspCompilerAdapter.java @@ -19,8 +19,8 @@ package org.apache.tools.ant.taskdefs.optional.jsp.compilers; import java.io.File; -import java.util.Enumeration; import java.util.Vector; +import java.util.stream.Collectors; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.optional.jsp.JspC; @@ -35,7 +35,7 @@ import org.apache.tools.ant.types.CommandlineJava; public abstract class DefaultJspCompilerAdapter implements JspCompilerAdapter { - private static String lSep = System.getProperty("line.separator"); + private static String lSep = System.lineSeparator(); /** * Logs the compilation parameters, adds the files to compile and logs the @@ -45,27 +45,18 @@ public abstract class DefaultJspCompilerAdapter * @param cmd the command line used */ protected void logAndAddFilesToCompile(JspC jspc, - Vector compileList, + Vector<String> compileList, CommandlineJava cmd) { jspc.log("Compilation " + cmd.describeJavaCommand(), Project.MSG_VERBOSE); - StringBuffer niceSourceList = new StringBuffer("File"); - if (compileList.size() != 1) { - niceSourceList.append("s"); - } - niceSourceList.append(" to be compiled:"); - - niceSourceList.append(lSep); - - Enumeration e = compileList.elements(); - while (e.hasMoreElements()) { - String arg = (String) e.nextElement(); - cmd.createArgument().setValue(arg); - niceSourceList.append(" "); - niceSourceList.append(arg); - niceSourceList.append(lSep); - } + StringBuilder niceSourceList = + new StringBuilder(compileList.size() == 1 ? "File" : "Files") + .append(" to be compiled:").append(lSep) + .append(compileList.stream() + .peek(arg -> cmd.createArgument().setValue(arg)) + .map(arg -> " " + arg) + .collect(Collectors.joining(lSep))); jspc.log(niceSourceList.toString(), Project.MSG_VERBOSE); } @@ -83,6 +74,7 @@ public abstract class DefaultJspCompilerAdapter * set the owner * @param owner the owner JspC compiler */ + @Override public void setJspc(JspC owner) { this.owner = owner; } @@ -94,7 +86,6 @@ public abstract class DefaultJspCompilerAdapter return owner; } - /** * add an argument oneple to the argument list, if the value aint null * @param cmd the command line @@ -138,6 +129,7 @@ public abstract class DefaultJspCompilerAdapter * @return true if the compiler wants to do its own * depends */ + @Override public boolean implementsOwnDependencyChecking() { return false; } @@ -150,4 +142,3 @@ public abstract class DefaultJspCompilerAdapter return getJspc().getProject(); } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JasperC.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JasperC.java index 80ed6012d..46644ddb0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JasperC.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JasperC.java @@ -59,6 +59,7 @@ public class JasperC extends DefaultJspCompilerAdapter { * @return true if successful * @throws BuildException on error */ + @Override public boolean execute() throws BuildException { getJspc().log("Using jasper compiler", Project.MSG_VERBOSE); @@ -80,9 +81,8 @@ public class JasperC extends DefaultJspCompilerAdapter { java.setDir(getProject().getBaseDir()); java.setClassname("org.apache.jasper.JspC"); //this is really irritating; we need a way to set stuff - String []args = cmd.getJavaCommand().getArguments(); - for (int i = 0; i < args.length; i++) { - java.createArg().setValue(args[i]); + for (String arg : cmd.getJavaCommand().getArguments()) { + java.createArg().setValue(arg); } java.setFailonerror(getJspc().getFailonerror()); //we are forking here to be sure that if JspC calls @@ -94,17 +94,14 @@ public class JasperC extends DefaultJspCompilerAdapter { } catch (Exception ex) { if (ex instanceof BuildException) { throw (BuildException) ex; - } else { - throw new BuildException("Error running jsp compiler: ", - ex, getJspc().getLocation()); } + throw new BuildException("Error running jsp compiler: ", + ex, getJspc().getLocation()); } finally { getJspc().deleteEmptyJavaFiles(); } } - - /** * build up a command line * @return a command line for jasper @@ -144,7 +141,7 @@ public class JasperC extends DefaultJspCompilerAdapter { /** * @return an instance of the mangler this compiler uses */ - + @Override public JspMangler createMangler() { return mangler; } @@ -157,9 +154,8 @@ public class JasperC extends DefaultJspCompilerAdapter { if (p == null) { p = new Path(getProject()); return p.concatSystemClasspath("only"); - } else { - return p.concatSystemClasspath("ignore"); } + return p.concatSystemClasspath("ignore"); } /** diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JspCompilerAdapterFactory.java b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JspCompilerAdapterFactory.java index 2876ba0c3..a1723402c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JspCompilerAdapterFactory.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JspCompilerAdapterFactory.java @@ -80,11 +80,11 @@ public final class JspCompilerAdapterFactory { AntClassLoader loader) throws BuildException { - if (compilerType.equalsIgnoreCase("jasper")) { + if ("jasper".equalsIgnoreCase(compilerType)) { //tomcat4.0 gets the old mangler return new JasperC(new JspNameMangler()); } - if (compilerType.equalsIgnoreCase("jasper41")) { + if ("jasper41".equalsIgnoreCase(compilerType)) { //tomcat4.1 gets the new one return new JasperC(new Jasper41Mangler()); } @@ -104,9 +104,8 @@ public final class JspCompilerAdapterFactory { AntClassLoader classloader) throws BuildException { try { - Class c = classloader.findClass(className); - Object o = c.newInstance(); - return (JspCompilerAdapter) o; + Class<? extends JspCompilerAdapter> c = classloader.findClass(className).asSubclass(JspCompilerAdapter.class); + return c.newInstance(); } catch (ClassNotFoundException cnfe) { throw new BuildException(className + " can\'t be found.", cnfe); } catch (ClassCastException cce) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java index 026412fe6..b229d56b5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java @@ -23,10 +23,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.TransformerFactory; @@ -75,12 +71,27 @@ public class AggregateTransformer { * list authorized values. * @return authorized values. */ + @Override public String[] getValues() { return new String[]{FRAMES, NOFRAMES}; } } + private static final String JDK_INTERNAL_FACTORY = + "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; + // CheckStyle:VisibilityModifier OFF - bc + /** XML Parser factory */ + private static DocumentBuilderFactory privateDBFactory; + + /** XML Parser factory accessible to subclasses */ + protected static DocumentBuilderFactory dbfactory; + + static { + privateDBFactory = DocumentBuilderFactory.newInstance(); + dbfactory = privateDBFactory; + } + /** Task */ protected Task task; @@ -120,16 +131,6 @@ public class AggregateTransformer { /** the format to use for the report. Must be <tt>FRAMES</tt> or <tt>NOFRAMES</tt> */ protected String format = FRAMES; - /** XML Parser factory */ - private static DocumentBuilderFactory privateDBFactory; - - /** XML Parser factory accessible to subclasses */ - protected static DocumentBuilderFactory dbfactory; - - static { - privateDBFactory = DocumentBuilderFactory.newInstance(); - dbfactory = privateDBFactory; - } // CheckStyle:VisibilityModifier ON /** @@ -257,8 +258,8 @@ public class AggregateTransformer { // acrobatic cast. xsltTask.setIn(((XMLResultAggregator) task).getDestinationFile()); - File outputFile = null; - if (format.equals(FRAMES)) { + File outputFile; + if (FRAMES.equals(format)) { String tempFileProperty = getClass().getName() + String.valueOf(counter++); //NOSONAR File tmp = FILE_UTILS.resolveFile(project.getBaseDir(), project .getProperty("java.io.tmpdir")); @@ -352,8 +353,6 @@ public class AggregateTransformer { return JAXPUtils.getSystemId(file); } - private static final String JDK_INTERNAL_FACTORY = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; - /** * If we end up using the JDK's own TraX factory on Java 9+, then * set the features and attributes necessary to allow redirect @@ -372,8 +371,9 @@ public class AggregateTransformer { } if (JDK_INTERNAL_FACTORY.equals(factoryName) && JavaEnvUtils.isAtLeastJavaVersion(JavaEnvUtils.JAVA_9)) { - factory.addFeature(new XSLTProcess.Factory.Feature("http://www.oracle.com/xml/jaxp/properties/enableExtensionFunctions", - true)); + factory.addFeature(new XSLTProcess.Factory.Feature( + "http://www.oracle.com/xml/jaxp/properties/enableExtensionFunctions", + true)); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BaseTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BaseTest.java index 55e7a5d5c..046296980 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BaseTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BaseTest.java @@ -33,7 +33,7 @@ public abstract class BaseTest { protected boolean fork = false; protected String ifProperty = null; protected String unlessProperty = null; - protected Vector formatters = new Vector(); + protected Vector<FormatterElement> formatters = new Vector<>(); /** destination directory */ protected File destDir = null; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java index f41b96f13..fb5d44b5e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java @@ -22,6 +22,7 @@ package org.apache.tools.ant.taskdefs.optional.junit; import java.io.File; import java.util.Enumeration; import java.util.Vector; +import java.util.stream.Stream; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; @@ -79,7 +80,6 @@ public final class BatchTest extends BaseTest { } } - /** * Add a new ResourceCollection instance to this * batchtest. Whatever the collection is, only names that are @@ -98,7 +98,7 @@ public final class BatchTest extends BaseTest { * @return an enumeration of all elements of this batchtest that are * a <tt>JUnitTest</tt> instance. */ - public Enumeration elements() { + public Enumeration<JUnitTest> elements() { JUnitTest[] tests = createAllJUnitTest(); return Enumerations.fromArray(tests); } @@ -109,7 +109,7 @@ public final class BatchTest extends BaseTest { * @param v the vector to which should be added all individual tests of this * batch test. */ - void addTestsTo(Vector v) { + void addTestsTo(Vector<? super JUnitTest> v) { JUnitTest[] tests = createAllJUnitTest(); v.ensureCapacity(v.size() + tests.length); for (int i = 0; i < tests.length; i++) { @@ -123,13 +123,8 @@ public final class BatchTest extends BaseTest { * @return the array of all <tt>JUnitTest</tt>s that belongs to this batch. */ private JUnitTest[] createAllJUnitTest() { - String[] filenames = getFilenames(); - JUnitTest[] tests = new JUnitTest[filenames.length]; - for (int i = 0; i < tests.length; i++) { - String classname = javaToClass(filenames[i]); - tests[i] = createJUnitTest(classname); - } - return tests; + return Stream.of(getFilenames()).map(BatchTest::javaToClass) + .map(this::createJUnitTest).toArray(JUnitTest[]::new); } /** @@ -143,21 +138,11 @@ public final class BatchTest extends BaseTest { * For the class <tt>org/apache/Whatever.class</tt> it will return <tt>org/apache/Whatever</tt>. */ private String[] getFilenames() { - Vector v = new Vector(); - for (Resource r : resources) { - if (r.isExists()) { - String pathname = r.getName(); - if (pathname.endsWith(".java")) { - v.addElement(pathname.substring(0, pathname.length() - ".java".length())); - } else if (pathname.endsWith(".class")) { - v.addElement(pathname.substring(0, pathname.length() - ".class".length())); - } - } - } - - String[] files = new String[v.size()]; - v.copyInto(files); - return files; + return resources.stream().filter(Resource::isExists) + .map(Resource::getName) + .filter(name -> name.endsWith(".java") || name.endsWith(".class")) + .map(name -> name.substring(0, name.lastIndexOf('.'))) + .toArray(String[]::new); } /** @@ -192,10 +177,7 @@ public final class BatchTest extends BaseTest { test.setFailureProperty(failureProperty); test.setErrorProperty(errorProperty); test.setSkipNonTests(isSkipNonTests()); - Enumeration list = this.formatters.elements(); - while (list.hasMoreElements()) { - test.addFormatter((FormatterElement) list.nextElement()); - } + this.formatters.forEach(test::addFormatter); return test; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BriefJUnitResultFormatter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BriefJUnitResultFormatter.java index 46d6c6161..975de6894 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/BriefJUnitResultFormatter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/BriefJUnitResultFormatter.java @@ -89,6 +89,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * Sets the stream the formatter is supposed to write its results to. * @param out the output stream to write to */ + @Override public void setOutput(OutputStream out) { this.out = out; output = new BufferedWriter(new java.io.OutputStreamWriter(out)); @@ -98,6 +99,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @see JUnitResultFormatter#setSystemOutput(String) */ /** {@inheritDoc}. */ + @Override public void setSystemOutput(String out) { systemOutput = out; } @@ -106,6 +108,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @see JUnitResultFormatter#setSystemError(String) */ /** {@inheritDoc}. */ + @Override public void setSystemError(String err) { systemError = err; } @@ -115,15 +118,15 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * The whole testsuite started. * @param suite the test suite */ + @Override public void startTestSuite(JUnitTest suite) { if (output == null) { return; // Quick return - no output do nothing. } - StringBuffer sb = new StringBuffer("Testsuite: "); - sb.append(suite.getName()); - sb.append(StringUtils.LINE_SEP); try { - output.write(sb.toString()); + output + .write(new StringBuilder("Testsuite: ").append(suite.getName()) + .append(StringUtils.LINE_SEP).toString()); output.flush(); } catch (IOException ex) { throw new BuildException(ex); @@ -134,8 +137,9 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * The whole testsuite ended. * @param suite the test suite */ + @Override public void endTestSuite(JUnitTest suite) { - StringBuffer sb = new StringBuffer("Tests run: "); + StringBuilder sb = new StringBuilder("Tests run: "); sb.append(suite.runCount()); sb.append(", Failures: "); sb.append(suite.failureCount()); @@ -190,6 +194,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * A test started. * @param test a test */ + @Override public void startTest(Test test) { } @@ -197,6 +202,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * A test ended. * @param test a test */ + @Override public void endTest(Test test) { } @@ -218,6 +224,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param test a test * @param t the assertion failed by the test */ + @Override public void addFailure(Test test, AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -227,6 +234,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param test a test * @param error the error thrown by the test */ + @Override public void addError(Test test, Throwable error) { formatError("\tCaused an ERROR", test, error); } @@ -239,9 +247,8 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT protected String formatTest(Test test) { if (test == null) { return "Null Test: "; - } else { - return "Testcase: " + test.toString() + ":"; } + return "Testcase: " + test.toString() + ":"; } /** @@ -271,6 +278,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT } + @Override public void testIgnored(Test test) { formatSkip(test, JUnitVersionHelper.getIgnoreMessage(test)); } @@ -294,6 +302,7 @@ public class BriefJUnitResultFormatter implements JUnitResultFormatter, IgnoredT } + @Override public void testAssumptionFailure(Test test, Throwable cause) { formatSkip(test, cause.getMessage()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/CustomJUnit4TestAdapterCache.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/CustomJUnit4TestAdapterCache.java index 8ad40dd61..5b04c3724 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/CustomJUnit4TestAdapterCache.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/CustomJUnit4TestAdapterCache.java @@ -34,7 +34,7 @@ import org.junit.runner.notification.RunNotifier; * */ public class CustomJUnit4TestAdapterCache extends JUnit4TestAdapterCache { - + private static final long serialVersionUID = 1L; private static final CustomJUnit4TestAdapterCache INSTANCE = new CustomJUnit4TestAdapterCache(); public static CustomJUnit4TestAdapterCache getInstance() { @@ -45,6 +45,7 @@ public class CustomJUnit4TestAdapterCache extends JUnit4TestAdapterCache { super(); } + @Override public RunNotifier getNotifier(final TestResult result, final JUnit4TestAdapter adapter) { return getNotifier(result); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java index 325f44cfb..39d0ab3c9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java @@ -86,13 +86,14 @@ public final class DOMUtil { } /** custom implementation of a nodelist */ - public static class NodeListImpl extends Vector implements NodeList { + public static class NodeListImpl extends Vector<Node> implements NodeList { private static final long serialVersionUID = 3175749150080946423L; /** * Get the number of nodes in the list. * @return the length of the list. */ + @Override public int getLength() { return size(); } @@ -101,9 +102,10 @@ public final class DOMUtil { * @param i the index of the node to get. * @return the node if the index is in bounds, null otherwise. */ + @Override public Node item(int i) { try { - return (Node) elementAt(i); + return elementAt(i); } catch (ArrayIndexOutOfBoundsException e) { return null; // conforming to NodeList interface } @@ -164,9 +166,9 @@ public final class DOMUtil { * @return the cloned node that is appended to <tt>parent</tt> */ public static Node importNode(Node parent, Node child) { - Node copy = null; final Document doc = parent.getOwnerDocument(); + Node copy; switch (child.getNodeType()) { case Node.CDATA_SECTION_NODE: copy = doc.createCDATASection(((CDATASection) child).getData()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/Enumerations.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/Enumerations.java index 327547efc..1ca4a0c0b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/Enumerations.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/Enumerations.java @@ -17,6 +17,8 @@ */ package org.apache.tools.ant.taskdefs.optional.junit; +import java.util.Arrays; +import java.util.Collections; import java.util.Enumeration; import java.util.NoSuchElementException; @@ -28,78 +30,33 @@ import java.util.NoSuchElementException; */ public final class Enumerations { - private Enumerations() { - } + private Enumerations() { + } - /** - * creates an enumeration from an array of objects. - * @param array the array of object to enumerate. - * @return the enumeration over the array of objects. - */ - public static Enumeration fromArray(Object[] array) { - return new ArrayEnumeration(array); - } + /** + * creates an enumeration from an array of objects. + * @param array the array of object to enumerate. + * @return the enumeration over the array of objects. + */ + @SafeVarargs + public static <T> Enumeration<T> fromArray(T... array) { + return Collections.enumeration(Arrays.asList(array)); + } - /** - * creates an enumeration from an array of enumeration. The created enumeration - * will sequentially enumerate over all elements of each enumeration and skip - * <tt>null</tt> enumeration elements in the array. - * @param enums the array of enumerations. - * @return the enumeration over the array of enumerations. - */ - public static Enumeration fromCompound(Enumeration[] enums) { - return new CompoundEnumeration(enums); - } + /** + * creates an enumeration from an array of enumeration. The created enumeration + * will sequentially enumerate over all elements of each enumeration and skip + * <tt>null</tt> enumeration elements in the array. + * @param enums the array of enumerations. + * @return the enumeration over the array of enumerations. + */ + @SafeVarargs + public static <T> Enumeration<T> fromCompound(Enumeration<? extends T>... enums) { + return new CompoundEnumeration<>(enums); + } } - -/** - * Convenient enumeration over an array of objects. - */ -class ArrayEnumeration implements Enumeration { - - /** object array */ - private Object[] array; - - /** current index */ - private int pos; - - /** - * Initialize a new enumeration that wraps an array. - * @param array the array of object to enumerate. - */ - public ArrayEnumeration(Object[] array) { - this.array = array; - this.pos = 0; - } - /** - * Tests if this enumeration contains more elements. - * - * @return <code>true</code> if and only if this enumeration object - * contains at least one more element to provide; - * <code>false</code> otherwise. - */ - public boolean hasMoreElements() { - return (pos < array.length); - } - - /** - * Returns the next element of this enumeration if this enumeration - * object has at least one more element to provide. - * - * @return the next element of this enumeration. - * @throws NoSuchElementException if no more elements exist. - */ - public Object nextElement() throws NoSuchElementException { - if (hasMoreElements()) { - Object o = array[pos]; - pos++; - return o; - } - throw new NoSuchElementException(); - } -} /** * Convenient enumeration over an array of enumeration. For example: * <pre> @@ -130,48 +87,49 @@ class ArrayEnumeration implements Enumeration { * } * </pre> */ - class CompoundEnumeration implements Enumeration { + class CompoundEnumeration<T> implements Enumeration<T> { - /** enumeration array */ - private Enumeration[] enumArray; + /** enumeration array */ + private Enumeration<? extends T>[] enumArray; - /** index in the enums array */ - private int index = 0; + /** index in the enums array */ + private int index = 0; - public CompoundEnumeration(Enumeration[] enumarray) { - this.enumArray = enumarray; + @SafeVarargs + public CompoundEnumeration(Enumeration<? extends T>... enumarray) { + this.enumArray = enumarray; } - /** - * Tests if this enumeration contains more elements. - * - * @return <code>true</code> if and only if this enumeration object - * contains at least one more element to provide; - * <code>false</code> otherwise. - */ + /** + * Tests if this enumeration contains more elements. + * + * @return <code>true</code> if and only if this enumeration object + * contains at least one more element to provide; + * <code>false</code> otherwise. + */ + @Override public boolean hasMoreElements() { - while (index < enumArray.length) { - if (enumArray[index] != null && enumArray[index].hasMoreElements()) { - return true; - } - index++; - } - return false; + while (index < enumArray.length) { + if (enumArray[index] != null && enumArray[index].hasMoreElements()) { + return true; + } + index++; + } + return false; } - /** - * Returns the next element of this enumeration if this enumeration - * object has at least one more element to provide. - * - * @return the next element of this enumeration. - * @throws NoSuchElementException if no more elements exist. - */ - public Object nextElement() throws NoSuchElementException { - if (hasMoreElements()) { - return enumArray[index].nextElement(); - } - throw new NoSuchElementException(); + /** + * Returns the next element of this enumeration if this enumeration + * object has at least one more element to provide. + * + * @return the next element of this enumeration. + * @throws NoSuchElementException if no more elements exist. + */ + @Override + public T nextElement() throws NoSuchElementException { + if (hasMoreElements()) { + return enumArray[index].nextElement(); + } + throw new NoSuchElementException(); } } - - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java index bfcbfedb2..26ef42463 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java @@ -23,12 +23,11 @@ import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; +import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Vector; - import junit.framework.AssertionFailedError; import junit.framework.Test; @@ -89,7 +88,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm private static final String LOG_PREFIX = " [junit]"; /** Class names of failed tests without duplicates. */ - private static SortedSet/*<TestInfos>*/ failedTests = new TreeSet(); + private static SortedSet<TestInfos> failedTests = new TreeSet<>(); /** A writer for writing the generated source to. */ private BufferedWriter writer; @@ -146,20 +145,13 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param project * project reference */ + @Override public void setProject(Project project) { // store project reference for logging super.setProject(project); // check if already registered - boolean alreadyRegistered = false; - Vector allListeners = project.getBuildListeners(); - final int size = allListeners.size(); - for (int i = 0; i < size; i++) { - Object listener = allListeners.get(i); - if (listener instanceof FailureRecorder) { - alreadyRegistered = true; - break; - } - } + boolean alreadyRegistered = project.getBuildListeners().stream() + .anyMatch(FailureRecorder.class::isInstance); // register if needed if (!alreadyRegistered) { verbose("Register FailureRecorder (@" + this.hashCode() + ") as BuildListener"); @@ -173,6 +165,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void endTestSuite(JUnitTest suite) throws BuildException { } @@ -182,6 +175,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param throwable the reason it errored. * @see junit.framework.TestListener#addError(junit.framework.Test, java.lang.Throwable) */ + @Override public void addError(Test test, Throwable throwable) { failedTests.add(new TestInfos(test)); } @@ -194,6 +188,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see junit.framework.TestListener#addFailure(junit.framework.Test, junit.framework.AssertionFailedError) */ // CheckStyle:LineLengthCheck ON + @Override public void addFailure(Test test, AssertionFailedError error) { failedTests.add(new TestInfos(test)); } @@ -202,6 +197,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setOutput(OutputStream out) { // unused, close output file so it can be deleted before the VM exits if (out != System.out) { @@ -213,6 +209,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setSystemError(String err) { } @@ -220,6 +217,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setSystemOutput(String out) { } @@ -227,6 +225,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void startTestSuite(JUnitTest suite) throws BuildException { } @@ -234,6 +233,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void endTest(Test test) { } @@ -241,6 +241,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void startTest(Test test) { } @@ -248,7 +249,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm private void writeJavaClass() { try { - File sourceFile = new File((getLocationName() + ".java")); + File sourceFile = new File(getLocationName() + ".java"); verbose("Write collector class to '" + sourceFile.getAbsolutePath() + "'"); if (sourceFile.exists() && !sourceFile.delete()) { @@ -299,8 +300,8 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm writer.newLine(); writer.write(" TestSuite suite = new TestSuite();"); writer.newLine(); - for (Iterator iter = failedTests.iterator(); iter.hasNext();) { - TestInfos testInfos = (TestInfos) iter.next(); + for (Iterator<TestInfos> iter = failedTests.iterator(); iter.hasNext();) { + TestInfos testInfos = iter.next(); writer.write(" suite.addTest("); writer.write(String.valueOf(testInfos)); writer.write(");"); @@ -323,6 +324,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Logging facade in INFO-mode. * @param message Log-message */ + @Override public void log(String message) { getProject().log(LOG_PREFIX + " " + message, Project.MSG_INFO); } @@ -338,7 +340,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm /** * TestInfos holds information about a given test for later use. */ - public static class TestInfos implements Comparable { + public static class TestInfos implements Comparable<TestInfos> { /** The class name of the test. */ private final String className; @@ -363,6 +365,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see java.lang.Object#toString() * @see FailureRecorder#createSuiteMethod() */ + @Override public String toString() { return "new " + className + "(\"" + methodName + "\")"; } @@ -374,17 +377,18 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see java.lang.Comparable#compareTo * @see SortedSet#comparator() */ - public int compareTo(Object other) { - if (other instanceof TestInfos) { - TestInfos otherInfos = (TestInfos) other; - return toString().compareTo(otherInfos.toString()); - } else { - return -1; - } + @Override + public int compareTo(TestInfos other) { + return Comparator.comparing(Object::toString).compare(this, other); } + + @Override public boolean equals(Object obj) { - return obj instanceof TestInfos && toString().equals(obj.toString()); + return obj == this || obj instanceof TestInfos + && toString().equals(obj.toString()); } + + @Override public int hashCode() { return toString().hashCode(); } @@ -396,6 +400,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void buildFinished(BuildEvent event) { } @@ -403,6 +408,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void buildStarted(BuildEvent event) { } @@ -410,6 +416,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void messageLogged(BuildEvent event) { } @@ -417,6 +424,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void targetFinished(BuildEvent event) { } @@ -424,6 +432,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void targetStarted(BuildEvent event) { } @@ -433,6 +442,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param event not used * @see org.apache.tools.ant.BuildListener#taskFinished(org.apache.tools.ant.BuildEvent) */ + @Override public void taskFinished(BuildEvent event) { if (!failedTests.isEmpty()) { writeJavaClass(); @@ -443,6 +453,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void taskStarted(BuildEvent event) { } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java index 6587b1d1d..81841a01b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java @@ -31,6 +31,7 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.PropertyHelper; import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.optional.junit.JUnitTaskMirror.JUnitResultFormatterMirror; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.util.KeepAliveOutputStream; @@ -58,6 +59,18 @@ import org.apache.tools.ant.util.KeepAliveOutputStream; * @see JUnitResultFormatter */ public class FormatterElement { + /** xml formatter class */ + public static final String XML_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter"; + /** brief formatter class */ + public static final String BRIEF_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"; + /** plain formatter class */ + public static final String PLAIN_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter"; + /** failure recorder class */ + public static final String FAILURE_RECORDER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.FailureRecorder"; private String classname; private String extension; @@ -73,19 +86,6 @@ public class FormatterElement { */ private Project project; - /** xml formatter class */ - public static final String XML_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter"; - /** brief formatter class */ - public static final String BRIEF_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"; - /** plain formatter class */ - public static final String PLAIN_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter"; - /** failure recorder class */ - public static final String FAILURE_RECORDER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.FailureRecorder"; - /** * <p> Quick way to use a standard formatter. * @@ -102,18 +102,19 @@ public class FormatterElement { * @param type the enumerated value to use. */ public void setType(TypeAttribute type) { - if ("xml".equals(type.getValue())) { + switch (type.getValue()) { + case "xml": setClassname(XML_FORMATTER_CLASS_NAME); - } else { - if ("brief".equals(type.getValue())) { - setClassname(BRIEF_FORMATTER_CLASS_NAME); - } else { - if ("failure".equals(type.getValue())) { - setClassname(FAILURE_RECORDER_CLASS_NAME); - } else { // must be plain, ensured by TypeAttribute - setClassname(PLAIN_FORMATTER_CLASS_NAME); - } - } + break; + case "brief": + setClassname(BRIEF_FORMATTER_CLASS_NAME); + break; + case "failure": + setClassname(FAILURE_RECORDER_CLASS_NAME); + break; + default: + setClassname(PLAIN_FORMATTER_CLASS_NAME); + break; } } @@ -125,12 +126,18 @@ public class FormatterElement { */ public void setClassname(String classname) { this.classname = classname; - if (XML_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".xml"); - } else if (PLAIN_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".txt"); - } else if (BRIEF_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".txt"); + if (classname != null) { + switch (classname) { + case XML_FORMATTER_CLASS_NAME: + setExtension(".xml"); + break; + case PLAIN_FORMATTER_CLASS_NAME: + setExtension(".txt"); + break; + case BRIEF_FORMATTER_CLASS_NAME: + setExtension(".txt"); + break; + } } } @@ -266,7 +273,6 @@ public class FormatterElement { this.project = project; } - /** * @since Ant 1.6 */ @@ -279,7 +285,7 @@ public class FormatterElement { //although this code appears to duplicate that of ClasspathUtils.newInstance, //we cannot use that because this formatter may run in a forked process, //without that class. - Class f = null; + Class<?> f; try { if (loader == null) { f = Class.forName(classname); @@ -296,26 +302,21 @@ public class FormatterElement { + ": " + e, e); } - Object o = null; + JUnitResultFormatterMirror r; try { - o = f.newInstance(); - } catch (InstantiationException e) { - throw new BuildException(e); - } catch (IllegalAccessException e) { + r = f.asSubclass(JUnitResultFormatterMirror.class).newInstance(); + } catch (ClassCastException e) { + throw new BuildException("%s is not a JUnitResultFormatter", + classname); + } catch (InstantiationException | IllegalAccessException e) { throw new BuildException(e); } - if (!(o instanceof JUnitTaskMirror.JUnitResultFormatterMirror)) { - throw new BuildException(classname + " is not a JUnitResultFormatter"); - } - JUnitTaskMirror.JUnitResultFormatterMirror r = - (JUnitTaskMirror.JUnitResultFormatterMirror) o; if (useFile && outFile != null) { out = new DelayedFileOutputStream(outFile); } r.setOutput(out); - boolean needToSetProjectReference = true; try { Field field = r.getClass().getField("project"); @@ -333,8 +334,8 @@ public class FormatterElement { if (needToSetProjectReference) { Method setter; try { - setter = r.getClass().getMethod("setProject", new Class[] {Project.class}); - setter.invoke(r, new Object[] {project}); + setter = r.getClass().getMethod("setProject", Project.class); + setter.invoke(r, project); } catch (NoSuchMethodException e) { // no setProject to invoke; just ignore } catch (IllegalAccessException e) { @@ -354,8 +355,9 @@ public class FormatterElement { */ public static class TypeAttribute extends EnumeratedAttribute { /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[] {"plain", "xml", "brief", "failure"}; + return new String[] { "plain", "xml", "brief", "failure" }; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java index c3bb18da3..ef51fffb7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java @@ -33,15 +33,15 @@ import junit.framework.TestResult; public class IgnoredTestResult extends TestResult { - private List<IgnoredTestListener> listeners = new ArrayList<IgnoredTestListener>(); - private List<TestIgnored> ignored = new ArrayList<TestIgnored>(); - private List<TestIgnored> skipped = new ArrayList<TestIgnored>(); + private List<IgnoredTestListener> listeners = new ArrayList<>(); + private List<TestIgnored> ignored = new ArrayList<>(); + private List<TestIgnored> skipped = new ArrayList<>(); public IgnoredTestResult() { super(); } - + @Override public synchronized void addListener(TestListener listener) { if (listener instanceof IgnoredTestListener) { listeners.add((IgnoredTestListener)listener); @@ -49,6 +49,7 @@ public class IgnoredTestResult extends TestResult { super.addListener(listener); } + @Override public synchronized void removeListener(TestListener listener) { if (listener instanceof IgnoredTestListener) { listeners.remove(listener); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java index f03a409b4..c797a87eb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java @@ -18,8 +18,8 @@ package org.apache.tools.ant.taskdefs.optional.junit; -import java.util.Iterator; import java.util.List; +import java.util.function.Predicate; import junit.framework.Test; import junit.framework.TestResult; @@ -41,7 +41,7 @@ import org.junit.runner.manipulation.Filter; */ public class JUnit4TestMethodAdapter implements Test { - private final Class testClass; + private final Class<?> testClass; private final String[] methodNames; private final Runner runner; private final CustomJUnit4TestAdapterCache cache; @@ -55,7 +55,7 @@ public class JUnit4TestMethodAdapter implements Test { * if any of the arguments is {@code null} * or if any of the given method names is {@code null} or empty */ - public JUnit4TestMethodAdapter(final Class testClass, + public JUnit4TestMethodAdapter(final Class<?> testClass, final String[] methodNames) { if (testClass == null) { throw new IllegalArgumentException("testClass is <null>"); @@ -87,6 +87,7 @@ public class JUnit4TestMethodAdapter implements Test { runner = request.getRunner(); } + @Override public int countTestCases() { return runner.testCount(); } @@ -95,14 +96,15 @@ public class JUnit4TestMethodAdapter implements Test { return runner.getDescription(); } - public List/*<Test>*/ getTests() { + public List<Test> getTests() { return cache.asTestList(getDescription()); } - public Class getTestClass() { + public Class<?> getTestClass() { return testClass; } + @Override public void run(final TestResult result) { runner.run(cache.getNotifier(result)); } @@ -126,10 +128,10 @@ public class JUnit4TestMethodAdapter implements Test { private static final class MultipleMethodsFilter extends Filter { private final Description methodsListDescription; - private final Class testClass; + private final Class<?> testClass; private final String[] methodNames; - private MultipleMethodsFilter(Class testClass, String[] methodNames) { + private MultipleMethodsFilter(Class<?> testClass, String[] methodNames) { if (testClass == null) { throw new IllegalArgumentException("testClass is <null>"); } @@ -151,23 +153,10 @@ public class JUnit4TestMethodAdapter implements Test { return false; } if (description.isTest()) { - Iterator/*<Description>*/ it = methodsListDescription.getChildren().iterator(); - while (it.hasNext()) { - Description methodDescription = (Description) it.next(); - if (methodDescription.equals(description)) { - return true; - } - } - } else { - Iterator/*<Description>*/ it = description.getChildren().iterator(); - while (it.hasNext()) { - Description each = (Description) it.next(); - if (shouldRun(each)) { - return true; - } - } + return methodsListDescription.getChildren().stream() + .anyMatch(Predicate.isEqual(description)); } - return false; + return description.getChildren().stream().anyMatch(this::shouldRun); } @Override @@ -189,5 +178,4 @@ public class JUnit4TestMethodAdapter implements Test { } - } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java index dcb2a98d4..e32403c4b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java @@ -33,6 +33,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; @@ -135,10 +136,26 @@ public class JUnitTask extends Task { private static final String LINE_SEP = System.getProperty("line.separator"); private static final String CLASSPATH = "CLASSPATH"; + + private static final int STRING_BUFFER_SIZE = 128; + /** + * @since Ant 1.7 + */ + public static final String TESTLISTENER_PREFIX = + "junit.framework.TestListener: "; + + /** + * Name of magic property that enables test listener events. + */ + public static final String ENABLE_TESTLISTENER_EVENTS = + "ant.junit.enabletestlistenerevents"; + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private CommandlineJava commandline; - private final Vector<JUnitTest> tests = new Vector<JUnitTest>(); - private final Vector<BatchTest> batchTests = new Vector<BatchTest>(); - private final Vector<FormatterElement> formatters = new Vector<FormatterElement>(); + private final List<JUnitTest> tests = new Vector<>(); + private final List<BatchTest> batchTests = new Vector<>(); + private final Vector<FormatterElement> formatters = new Vector<>(); private File dir = null; private Integer timeout = null; @@ -186,21 +203,6 @@ public class JUnitTask extends Task { private String failureProperty; private String errorProperty; - private static final int STRING_BUFFER_SIZE = 128; - /** - * @since Ant 1.7 - */ - public static final String TESTLISTENER_PREFIX = - "junit.framework.TestListener: "; - - /** - * Name of magic property that enables test listener events. - */ - public static final String ENABLE_TESTLISTENER_EVENTS = - "ant.junit.enabletestlistenerevents"; - - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - /** * If true, force ant to re-classload all classes for each JUnit TestCase * @@ -368,8 +370,8 @@ public class JUnitTask extends Task { */ @Override public String[] getValues() { - return new String[] {"true", "yes", "false", "no", - "on", "off", "withOutAndErr"}; + return new String[] { "true", "yes", "false", "no", "on", "off", + "withOutAndErr" }; } /** @@ -584,7 +586,7 @@ public class JUnitTask extends Task { * @since Ant 1.2 */ public void addTest(final JUnitTest test) { - tests.addElement(test); + tests.add(test); preConfigure(test); } @@ -598,7 +600,7 @@ public class JUnitTask extends Task { */ public BatchTest createBatchTest() { final BatchTest test = new BatchTest(getProject()); - batchTests.addElement(test); + batchTests.add(test); preConfigure(test); return test; } @@ -610,7 +612,7 @@ public class JUnitTask extends Task { * @since Ant 1.2 */ public void addFormatter(final FormatterElement fe) { - formatters.addElement(fe); + formatters.add(fe); } /** @@ -714,11 +716,9 @@ public class JUnitTask extends Task { * @since Ant 1.6 */ public void setTempdir(final File tmpDir) { - if (tmpDir != null) { - if (!tmpDir.exists() || !tmpDir.isDirectory()) { - throw new BuildException(tmpDir.toString() - + " is not a valid temp directory"); - } + if (tmpDir != null && (!tmpDir.exists() || !tmpDir.isDirectory())) { + throw new BuildException("%s is not a valid temp directory", + tmpDir); } this.tmpDir = tmpDir; } @@ -776,12 +776,12 @@ public class JUnitTask extends Task { e, task.getLocation()); } try { - final Class c = loader.loadClass(JUnitTaskMirror.class.getName() + "Impl"); + final Class<? extends JUnitTaskMirror> c = loader.loadClass(JUnitTaskMirror.class.getName() + "Impl").asSubclass(JUnitTaskMirror.class); if (c.getClassLoader() != loader) { throw new BuildException("Overdelegating loader", task.getLocation()); } - final Constructor cons = c.getConstructor(new Class[] {JUnitTask.class}); - return (JUnitTaskMirror) cons.newInstance(new Object[] {task}); + final Constructor<? extends JUnitTaskMirror> cons = c.getConstructor(JUnitTask.class); + return cons.newInstance(task); } catch (final Exception e) { throw new BuildException(e, task.getLocation()); } @@ -807,28 +807,19 @@ public class JUnitTask extends Task { if (extra != null && !hasJunit(path)) { path.add(expandModulePath(extra)); } - mirrorLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return new SplitClassLoader(myLoader, path, getProject(), - new String[] { - "BriefJUnitResultFormatter", - "JUnit4TestMethodAdapter", - "JUnitResultFormatter", - "JUnitTaskMirrorImpl", - "JUnitTestRunner", - "JUnitVersionHelper", - "OutErrSummaryJUnitResultFormatter", - "PlainJUnitResultFormatter", - "SummaryJUnitResultFormatter", - "TearDownOnVmCrash", - "XMLJUnitResultFormatter", - "IgnoredTestListener", - "IgnoredTestResult", - "CustomJUnit4TestAdapterCache", - "TestListenerWrapper" - }); - } - }); + mirrorLoader = AccessController.doPrivileged( + (PrivilegedAction<ClassLoader>) () -> new SplitClassLoader( + myLoader, path, getProject(), + new String[] { "BriefJUnitResultFormatter", + "JUnit4TestMethodAdapter", "JUnitResultFormatter", + "JUnitTaskMirrorImpl", "JUnitTestRunner", + "JUnitVersionHelper", + "OutErrSummaryJUnitResultFormatter", + "PlainJUnitResultFormatter", + "SummaryJUnitResultFormatter", "TearDownOnVmCrash", + "XMLJUnitResultFormatter", "IgnoredTestListener", + "IgnoredTestResult", "CustomJUnit4TestAdapterCache", + "TestListenerWrapper" })); } else { mirrorLoader = myLoader; } @@ -847,25 +838,22 @@ public class JUnitTask extends Task { checkModules(); setupJUnitDelegate(); - final List<List> testLists = new ArrayList<List>(); + final List<List<JUnitTest>> testLists = new ArrayList<>(); /* parallel test execution is only supported for multi-process execution */ final int threads = ((!fork) || (forkMode.getValue().equals(ForkMode.ONCE)) ? 1 : this.threads); - final boolean forkPerTest = forkMode.getValue().equals(ForkMode.PER_TEST); - if (forkPerTest || forkMode.getValue().equals(ForkMode.ONCE)) { + final boolean forkPerTest = ForkMode.PER_TEST.equals(forkMode.getValue()); + if (forkPerTest || ForkMode.ONCE.equals(forkMode.getValue())) { testLists.addAll(executeOrQueue(getIndividualTests(), forkPerTest)); } else { /* forkMode.getValue().equals(ForkMode.PER_BATCH) */ - final int count = batchTests.size(); - for (int i = 0; i < count; i++) { - final BatchTest batchtest = batchTests.elementAt(i); - testLists.addAll(executeOrQueue(batchtest.elements(), false)); - } - testLists.addAll(executeOrQueue(tests.elements(), forkPerTest)); + batchTests.stream().map(b -> executeOrQueue(b.elements(), false)) + .forEach(testLists::addAll); + testLists.addAll( + executeOrQueue(Collections.enumeration(tests), forkPerTest)); } - try { /* prior to parallel the code in 'oneJunitThread' used to be here. */ runTestsInThreads(testLists, threads); @@ -890,12 +878,13 @@ public class JUnitTask extends Task { */ private class JunitTestThread implements Runnable { - JunitTestThread(final JUnitTask master, final Iterator<List> iterator, final int id) { + JunitTestThread(final JUnitTask master, final Iterator<List<JUnitTest>> iterator, final int id) { this.masterTask = master; this.iterator = iterator; this.id = id; } + @Override public void run() { try { masterTask.oneJunitThread(iterator, id); @@ -906,7 +895,7 @@ public class JUnitTask extends Task { } private final JUnitTask masterTask; - private final Iterator<List> iterator; + private final Iterator<List<JUnitTest>> iterator; private final int id; } @@ -917,8 +906,8 @@ public class JUnitTask extends Task { * threads get the same test, or two threads simultaneously pop the list so that a test * gets skipped! */ - private List getNextTest(final Iterator<List> iter) { - synchronized(iter) { + private List<JUnitTest> getNextTest(final Iterator<List<JUnitTest>> iter) { + synchronized (iter) { if (iter.hasNext()) { return iter.next(); } @@ -937,14 +926,14 @@ public class JUnitTask extends Task { * fatal reason, no new tests/batches will be started but the running threads will be * permitted to complete. Additional tests may start in already-running batch-test threads. */ - private void oneJunitThread(final Iterator<List> iter, final int threadId) { + private void oneJunitThread(final Iterator<List<JUnitTest>> iter, final int threadId) { - List l; + List<JUnitTest> l; log("Starting test thread " + threadId, Project.MSG_VERBOSE); while ((caughtBuildException == null) && ((l = getNextTest(iter)) != null)) { log("Running test " + l.get(0).toString() + "(" + l.size() + ") in thread " + threadId, Project.MSG_VERBOSE); if (l.size() == 1) { - execute((JUnitTest) l.get(0), threadId); + execute(l.get(0), threadId); } else { execute(l, threadId); } @@ -953,9 +942,9 @@ public class JUnitTask extends Task { } - private void runTestsInThreads(final List<List> testList, final int numThreads) { + private void runTestsInThreads(final List<List<JUnitTest>> testList, final int numThreads) { - Iterator<List> iter = testList.iterator(); + Iterator<List<JUnitTest>> iter = testList.iterator(); if (numThreads == 1) { /* with just one thread just run the test - don't create any threads */ @@ -968,24 +957,25 @@ public class JUnitTask extends Task { /* Need to split apart tests, which are still grouped in batches */ /* is there a simpler Java mechanism to do this? */ /* I assume we don't want to do this with "per batch" forking. */ - List<List> newlist = new ArrayList<List>(); + List<List<JUnitTest>> newlist = new ArrayList<>(); if (forkMode.getValue().equals(ForkMode.PER_TEST)) { - final Iterator<List> i1 = testList.iterator(); + final Iterator<List<JUnitTest>> i1 = testList.iterator(); while (i1.hasNext()) { - final List l = i1.next(); + final List<JUnitTest> l = i1.next(); if (l.size() == 1) { - newlist.add(l); + newlist.add(l); } else { - final Iterator i2 = l.iterator(); - while (i2.hasNext()) { - final List tmpSingleton = new ArrayList(); - tmpSingleton.add(i2.next()); - newlist.add(tmpSingleton); - } + final Iterator<JUnitTest> i2 = l.iterator(); + while (i2.hasNext()) { + final List<JUnitTest> tmpSingleton = + new ArrayList<>(); + tmpSingleton.add(i2.next()); + newlist.add(tmpSingleton); + } } } } else { - newlist = testList; + newlist = testList; } iter = newlist.iterator(); @@ -1028,7 +1018,7 @@ public class JUnitTask extends Task { protected void execute(final JUnitTest arg, final int thread) throws BuildException { validateTestName(arg.getName()); - final JUnitTest test = (JUnitTest) arg.clone(); + final JUnitTest test = arg.clone(); test.setThread(thread); // set the default values if not specified @@ -1042,13 +1032,13 @@ public class JUnitTask extends Task { } // execute the test and get the return code - TestResultHolder result = null; - if (!test.getFork()) { - result = executeInVM(test); - } else { + TestResultHolder result; + if (test.getFork()) { final ExecuteWatchdog watchdog = createWatchdog(); result = executeAsForked(test, watchdog, null); // null watchdog means no timeout, you'd better not check with null + } else { + result = executeInVM(test); } actOnTestResult(result, test, "Test " + test.getName()); } @@ -1070,8 +1060,8 @@ public class JUnitTask extends Task { * @throws BuildException if <code>testName</code> is not a valid test name */ private void validateTestName(final String testName) throws BuildException { - if (testName == null || testName.length() == 0 - || testName.equals("null")) { + if (testName == null || testName.isEmpty() + || "null".equals(testName)) { throw new BuildException("test name must be specified"); } } @@ -1082,23 +1072,21 @@ public class JUnitTask extends Task { * @param thread Identifies which thread is test running in (0 for single-threaded runs) * @throws BuildException on error. */ - protected void execute(final List testList, final int thread) throws BuildException { - JUnitTest test = null; + protected void execute(final List<JUnitTest> testList, final int thread) throws BuildException { // Create a temporary file to pass the test cases to run to // the runner (one test case per line) final File casesFile = createTempPropertiesFile("junittestcases"); - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(casesFile)); + try (BufferedWriter writer = + new BufferedWriter(new FileWriter(casesFile))) { log("Creating casesfile '" + casesFile.getAbsolutePath() + "' with content: ", Project.MSG_VERBOSE); final PrintStream logWriter = new PrintStream(new LogOutputStream(this, Project.MSG_VERBOSE)); - final Iterator iter = testList.iterator(); - while (iter.hasNext()) { - test = (JUnitTest) iter.next(); + JUnitTest test = null; + for (JUnitTest t : testList) { + test = t; test.setThread(thread); printDual(writer, logWriter, test.getName()); if (test.getMethods() != null) { @@ -1119,8 +1107,6 @@ public class JUnitTask extends Task { } } writer.flush(); - writer.close(); - writer = null; // execute the test and get the return code final ExecuteWatchdog watchdog = createWatchdog(); @@ -1131,8 +1117,6 @@ public class JUnitTask extends Task { log(e.toString(), Project.MSG_ERR); throw new BuildException(e); } finally { - FileUtils.close(writer); - try { FILE_UTILS.tryHardToDelete(casesFile); } catch (final Exception e) { @@ -1146,7 +1130,7 @@ public class JUnitTask extends Task { * @param testList the list of tests to execute. * @throws BuildException on error. */ - protected void execute(final List testList) throws BuildException { + protected void execute(final List<JUnitTest> testList) throws BuildException { execute(testList, 0); } @@ -1177,7 +1161,7 @@ public class JUnitTask extends Task { CommandlineJava cmd; try { - cmd = (CommandlineJava) (getCommandline().clone()); + cmd = getCommandline().clone(); } catch (final CloneNotSupportedException e) { throw new BuildException("This shouldn't happen", e, getLocation()); } @@ -1213,7 +1197,7 @@ public class JUnitTask extends Task { cmd.createArgument().setValue(Constants.LOGTESTLISTENEREVENTS + String.valueOf(getEnableTestListenerEvents())); - StringBuffer formatterArg = new StringBuffer(STRING_BUFFER_SIZE); + StringBuilder formatterArg = new StringBuilder(STRING_BUFFER_SIZE); final FormatterElement[] feArray = mergeFormatters(test); for (int i = 0; i < feArray.length; i++) { final FormatterElement fe = feArray[i]; @@ -1226,7 +1210,7 @@ public class JUnitTask extends Task { formatterArg.append(outFile); } cmd.createArgument().setValue(formatterArg.toString()); - formatterArg = new StringBuffer(); + formatterArg = new StringBuilder(); } } @@ -1236,17 +1220,14 @@ public class JUnitTask extends Task { final File propsFile = createTempPropertiesFile("junit"); cmd.createArgument().setValue(Constants.PROPSFILE + propsFile.getAbsolutePath()); - final Hashtable p = getProject().getProperties(); + final Hashtable<String, Object> p = getProject().getProperties(); final Properties props = new Properties(); - for (final Enumeration e = p.keys(); e.hasMoreElements();) { - final Object key = e.nextElement(); - props.put(key, p.get(key)); - } + p.forEach(props::put); try { final OutputStream outstream = Files.newOutputStream(propsFile.toPath()); props.store(outstream, "Ant JUnitTask generated properties file"); outstream.close(); - } catch (final java.io.IOException e) { + } catch (final IOException e) { FILE_UTILS.tryHardToDelete(propsFile); throw new BuildException("Error creating temporary properties " + "file.", e, getLocation()); @@ -1328,9 +1309,9 @@ public class JUnitTask extends Task { + propsFile.getAbsolutePath() + "'."; if (success) { throw new BuildException(msg); //NOSONAR - } else { // don't hide inner exception - log(msg, Project.MSG_ERR); } + // don't hide inner exception + log(msg, Project.MSG_ERR); } } @@ -1343,8 +1324,8 @@ public class JUnitTask extends Task { */ private void checkIncludeAntRuntime(final CommandlineJava cmd) { if (includeAntRuntime) { - final Map/*<String, String>*/ env = Execute.getEnvironmentVariables(); - final String cp = (String) env.get(CLASSPATH); + final Map<String, String> env = Execute.getEnvironmentVariables(); + final String cp = env.get(CLASSPATH); if (cp != null) { cmd.createClasspath(getProject()).createPath() .append(new Path(getProject(), cp)); @@ -1356,7 +1337,6 @@ public class JUnitTask extends Task { } } - /** * check for the parameter being "withoutanderr" in a locale-independent way. * @param summaryOption the summary option -can be null @@ -1400,9 +1380,9 @@ public class JUnitTask extends Task { LoaderUtils.classNameToResource(Project.class.getName()); URL previous = null; try { - for (final Enumeration e = loader.getResources(projectResourceName); + for (final Enumeration<URL> e = loader.getResources(projectResourceName); e.hasMoreElements();) { - final URL current = (URL) e.nextElement(); + final URL current = e.nextElement(); if (previous != null && !urlEquals(current, previous)) { log("WARNING: multiple versions of ant detected " + "in path for junit " @@ -1501,9 +1481,8 @@ public class JUnitTask extends Task { throws IOException { if (runner != null) { return runner.handleInput(buffer, offset, length); - } else { - return super.handleInput(buffer, offset, length); } + return super.handleInput(buffer, offset, length); } @@ -1580,7 +1559,7 @@ public class JUnitTask extends Task { setupJUnitDelegate(); } - final JUnitTest test = (JUnitTest) arg.clone(); + final JUnitTest test = arg.clone(); test.setProperties(getProject().getProperties()); if (dir != null) { log("dir attribute ignored if running in the same VM", @@ -1691,12 +1670,14 @@ public class JUnitTask extends Task { */ protected Enumeration<JUnitTest> getIndividualTests() { final int count = batchTests.size(); - final Enumeration[] enums = new Enumeration[ count + 1]; + @SuppressWarnings("unchecked") + final Enumeration<JUnitTest>[] enums = new Enumeration[ count + 1]; + for (int i = 0; i < count; i++) { - final BatchTest batchtest = batchTests.elementAt(i); + final BatchTest batchtest = batchTests.get(i); enums[i] = batchtest.elements(); } - enums[enums.length - 1] = tests.elements(); + enums[enums.length - 1] = Collections.enumeration(tests); return Enumerations.fromCompound(enums); } @@ -1713,10 +1694,7 @@ public class JUnitTask extends Task { if (tests.isEmpty()) { return; } - - final Enumeration<JUnitTest> testsEnum = tests.elements(); - while (testsEnum.hasMoreElements()) { - final JUnitTest test = testsEnum.nextElement(); + for (JUnitTest test : tests) { if (test.hasMethodsSpecified() && test.shouldRun(getProject())) { test.resolveMethods(); } @@ -1730,15 +1708,10 @@ public class JUnitTask extends Task { private void checkModules() { if (hasPath(getCommandline().getModulepath()) || hasPath(getCommandline().getUpgrademodulepath())) { - for (int i = 0, count = batchTests.size(); i < count; i++) { - if(!batchTests.elementAt(i).getFork()) { - throw new BuildException("The module path requires fork attribute to be set to true."); - } - } - for (int i = 0, count = tests.size(); i < count; i++) { - if (!tests.elementAt(i).getFork()) { - throw new BuildException("The module path requires fork attribute to be set to true."); - } + if (!(batchTests.stream().allMatch(BaseTest::getFork) + && tests.stream().allMatch(BaseTest::getFork))) { + throw new BuildException( + "The module path requires fork attribute to be set to true."); } } } @@ -1775,7 +1748,8 @@ public class JUnitTask extends Task { for (String path : modulePath.list()) { final File modulePathEntry = getProject().resolveFile(path); if (modulePathEntry.isDirectory() && !hasModuleInfo(modulePathEntry)) { - final File[] modules = modulePathEntry.listFiles((dir,name)->name.toLowerCase(Locale.ENGLISH).endsWith(".jar")); + final File[] modules = modulePathEntry.listFiles((dir, + name) -> name.toLowerCase(Locale.ENGLISH).endsWith(".jar")); if (modules != null) { for (File module : modules) { expanded.add(new Path(getProject(), String.format( @@ -1797,9 +1771,9 @@ public class JUnitTask extends Task { * @return enumeration * @since Ant 1.3 */ - protected Enumeration<JUnitTest> allTests() { - final Enumeration[] enums = {tests.elements(), batchTests.elements()}; - return Enumerations.fromCompound(enums); + protected Enumeration<BaseTest> allTests() { + return Enumerations.fromCompound(Collections.enumeration(tests), + Collections.enumeration(batchTests)); } /** @@ -1808,6 +1782,7 @@ public class JUnitTask extends Task { * @since Ant 1.3 */ private FormatterElement[] mergeFormatters(final JUnitTest test) { + @SuppressWarnings("unchecked") final Vector<FormatterElement> feVector = (Vector<FormatterElement>) formatters.clone(); test.addFormattersTo(feVector); final FormatterElement[] feArray = new FormatterElement[feVector.size()]; @@ -2181,7 +2156,7 @@ public class JUnitTask extends Task { /** {@inheritDoc}. */ @Override public String[] getValues() { - return new String[] {ONCE, PER_TEST, PER_BATCH}; + return new String[] { ONCE, PER_TEST, PER_BATCH }; } } @@ -2195,9 +2170,10 @@ public class JUnitTask extends Task { * @return a list of tasks to be executed. * @since 1.6.2 */ - protected Collection<List> executeOrQueue(final Enumeration<JUnitTest> testList, - final boolean runIndividual) { - final Map<ForkedTestConfiguration, List> testConfigurations = new HashMap<ForkedTestConfiguration, List>(); + protected Collection<List<JUnitTest>> executeOrQueue( + final Enumeration<JUnitTest> testList, final boolean runIndividual) { + final Map<ForkedTestConfiguration, List<JUnitTest>> testConfigurations = + new HashMap<>(); while (testList.hasMoreElements()) { final JUnitTest test = testList.nextElement(); if (test.shouldRun(getProject())) { @@ -2206,14 +2182,10 @@ public class JUnitTask extends Task { if ((runIndividual || !test.getFork()) && (threads == 1)) { execute(test, 0); } else { - final ForkedTestConfiguration c = - new ForkedTestConfiguration(test); - List<JUnitTest> l = testConfigurations.get(c); - if (l == null) { - l = new ArrayList<JUnitTest>(); - testConfigurations.put(c, l); - } - l.add(test); + testConfigurations + .computeIfAbsent(new ForkedTestConfiguration(test), + k -> new ArrayList<>()) + .add(test); } } } @@ -2361,7 +2333,7 @@ public class JUnitTask extends Task { * @see "https://issues.apache.org/bugzilla/show_bug.cgi?id=45227" */ private static JUnitTest createDummyTestForBatchTest(final JUnitTest test) { - final JUnitTest t = (JUnitTest) test.clone(); + final JUnitTest t = test.clone(); final int index = test.getName().lastIndexOf('.'); // make sure test looks as if it was in the same "package" as // the last test of the batch diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java index c7dae2589..894b6a070 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java @@ -35,6 +35,7 @@ import org.apache.tools.ant.AntClassLoader; */ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { + @SuppressWarnings("unused") private final JUnitTask task; /** @@ -46,6 +47,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public void addVmExit(JUnitTest test, JUnitTaskMirror.JUnitResultFormatterMirror aFormatter, OutputStream out, String message, String testCase) { JUnitResultFormatter formatter = (JUnitResultFormatter) aFormatter; @@ -61,6 +63,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public JUnitTaskMirror.JUnitTestRunnerMirror newJUnitTestRunner(JUnitTest test, String[] methods, boolean haltOnError, boolean filterTrace, boolean haltOnFailure, @@ -70,6 +73,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public JUnitTaskMirror.SummaryJUnitResultFormatterMirror newSummaryJUnitResultFormatter() { return new SummaryJUnitResultFormatter(); } @@ -86,14 +90,17 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { testCase = aTestCase; } + @Override public int countTestCases() { return 1; } + @Override public void run(TestResult r) { throw new AssertionFailedError(message); } + @Override public String getName() { return testCase; } @@ -102,6 +109,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { return test.getName(); } + @Override public String toString() { return test.getName() + ":" + testCase; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java index 835c013b6..2ec56535a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs.optional.junit; -import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; @@ -228,7 +227,7 @@ public class JUnitTest extends BaseTest implements Cloneable { } else if (methods.length == 1) { methodsList = methods[0]; } else { - StringBuffer buf = new StringBuffer(methods.length * 16); + StringBuilder buf = new StringBuilder(methods.length * 16); buf.append(methods[0]); for (int i = 1; i < methods.length; i++) { buf.append(',').append(methods[i]); @@ -482,12 +481,9 @@ public class JUnitTest extends BaseTest implements Cloneable { * @param p the properties. * This is a copy of the projects ant properties. */ - public void setProperties(Hashtable p) { + public void setProperties(Hashtable<?,?> p) { props = new Properties(); - for (Enumeration e = p.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); - props.put(key, p.get(key)); - } + p.forEach(props::put); } /** @@ -516,7 +512,7 @@ public class JUnitTest extends BaseTest implements Cloneable { /** * Convenient method to add formatters to a vector */ - void addFormattersTo(Vector v) { + void addFormattersTo(Vector<? super FormatterElement> v) { final int count = formatters.size(); for (int i = 0; i < count; i++) { v.addElement(formatters.elementAt(i)); @@ -527,12 +523,13 @@ public class JUnitTest extends BaseTest implements Cloneable { * @since Ant 1.5 * @return a clone of this test. */ + @SuppressWarnings("unchecked") @Override - public Object clone() { + public JUnitTest clone() { try { JUnitTest t = (JUnitTest) super.clone(); t.props = props == null ? null : (Properties) props.clone(); - t.formatters = (Vector) formatters.clone(); + t.formatters = (Vector<FormatterElement>) formatters.clone(); return t; } catch (CloneNotSupportedException e) { // plain impossible diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java index ea7524da8..400966654 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java @@ -29,12 +29,12 @@ import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.io.StringWriter; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Enumeration; -import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; @@ -73,21 +73,49 @@ import org.apache.tools.ant.util.TeeOutputStream; */ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestRunnerMirror { + private static final String JUNIT_4_TEST_ADAPTER + = "junit.framework.JUnit4TestAdapter"; + + private static final String[] DEFAULT_TRACE_FILTERS = new String[] { + "junit.framework.TestCase", + "junit.framework.TestResult", + "junit.framework.TestSuite", + "junit.framework.Assert.", // don't filter AssertionFailure + "junit.swingui.TestRunner", + "junit.awtui.TestRunner", + "junit.textui.TestRunner", + "java.lang.reflect.Method.invoke(", + "sun.reflect.", + "org.apache.tools.ant.", + // JUnit 4 support: + "org.junit.", + "junit.framework.JUnit4TestAdapter", + " more", + }; /** - * Holds the registered formatters. + * Do we filter junit.*.* stack frames out of failure and error exceptions. */ - private final Vector<JUnitTaskMirror.JUnitResultFormatterMirror> formatters = new Vector(); + private static boolean filtertrace = true; + + /** Running more than one test suite? */ + private static boolean multipleTests = false; /** - * Collects TestResults. + * The file used to indicate that the build crashed. + * File will be empty in case the build did not crash. */ - private IgnoredTestResult res; + private static String crashFile = null; /** - * Do we filter junit.*.* stack frames out of failure and error exceptions. + * Holds the registered formatters. */ - private static boolean filtertrace = true; + private final Vector<JUnitTaskMirror.JUnitResultFormatterMirror> formatters = new Vector<>(); + + /** + * Collects TestResults. + */ + private IgnoredTestResult res; /** * Do we send output to System.out/.err in addition to the formatters? @@ -101,27 +129,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR */ private Permissions perm = null; - private static final String JUNIT_4_TEST_ADAPTER - = "junit.framework.JUnit4TestAdapter"; - - private static final String[] DEFAULT_TRACE_FILTERS = new String[] { - "junit.framework.TestCase", - "junit.framework.TestResult", - "junit.framework.TestSuite", - "junit.framework.Assert.", // don't filter AssertionFailure - "junit.swingui.TestRunner", - "junit.awtui.TestRunner", - "junit.textui.TestRunner", - "java.lang.reflect.Method.invoke(", - "sun.reflect.", - "org.apache.tools.ant.", - // JUnit 4 support: - "org.junit.", - "junit.framework.JUnit4TestAdapter", - " more", - }; - - /** * Do we stop on errors. */ @@ -151,9 +158,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** is this runner running in forked mode? */ private boolean forked = false; - /** Running more than one test suite? */ - private static boolean multipleTests = false; - /** ClassLoader passed in in non-forked mode. */ private final ClassLoader loader; @@ -163,12 +167,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** Turned on if we are using JUnit 4 for this test suite. see #38811 */ private boolean junit4; - /** - * The file used to indicate that the build crashed. - * File will be empty in case the build did not crash. - */ - private static String crashFile = null; - /** Names of test methods to execute */ private String[] methods = null; @@ -357,6 +355,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * Run the test. */ + @Override public void run() { res = new IgnoredTestResult(); res.addListener(wrapListener(this)); @@ -377,7 +376,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR try { try { - Class testClass = null; + Class<?> testClass; if (loader == null) { testClass = Class.forName(junitTest.getName()); } else { @@ -391,24 +390,24 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // JUnit 4 Method suiteMethod = null; if (!testMethodsSpecified) { - try { - // check if there is a suite method - suiteMethod = testClass.getMethod("suite", new Class[0]); - } catch (final NoSuchMethodException e) { - // no appropriate suite method found. We don't report any - // error here since it might be perfectly normal. - } + try { + // check if there is a suite method + suiteMethod = testClass.getMethod("suite"); + } catch (final NoSuchMethodException e) { + // no appropriate suite method found. We don't report any + // error here since it might be perfectly normal. + } } if (suiteMethod != null) { // if there is a suite method available, then try // to extract the suite from it. If there is an error // here it will be caught below and reported. - suite = (Test) suiteMethod.invoke(null, new Object[0]); + suite = (Test) suiteMethod.invoke(null); } else { - Class junit4TestAdapterClass = null; - Class junit4TestAdapterCacheClass = null; + Class<?> junit4TestAdapterClass = null; + Class<?> junit4TestAdapterCacheClass = null; boolean useSingleMethodAdapter = false; if (junit.framework.TestCase.class.isAssignableFrom(testClass)) { @@ -434,64 +433,69 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // In that case first C.fN will fail with CNFE and we // will avoid UnsupportedClassVersionError. - try { - Class.forName("java.lang.annotation.Annotation"); - junit4TestAdapterCacheClass = Class.forName("org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache"); - if (loader == null) { - junit4TestAdapterClass = - Class.forName(JUNIT_4_TEST_ADAPTER); - if (testMethodsSpecified) { - /* - * We cannot try to load the JUnit4TestAdapter - * before trying to load JUnit4TestMethodAdapter - * because it might fail with - * NoClassDefFoundException, instead of plain - * ClassNotFoundException. - */ - junit4TestAdapterClass = Class.forName( - "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter"); - useSingleMethodAdapter = true; - } - } else { - junit4TestAdapterClass = - Class.forName(JUNIT_4_TEST_ADAPTER, - true, loader); - if (testMethodsSpecified) { + try { + Class.forName("java.lang.annotation.Annotation"); + junit4TestAdapterCacheClass = Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache"); + if (loader == null) { junit4TestAdapterClass = - Class.forName( - "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter", - true, loader); - useSingleMethodAdapter = true; + Class.forName(JUNIT_4_TEST_ADAPTER); + if (testMethodsSpecified) { + /* + * We cannot try to load the JUnit4TestAdapter + * before trying to load JUnit4TestMethodAdapter + * because it might fail with + * NoClassDefFoundException, instead of plain + * ClassNotFoundException. + */ + junit4TestAdapterClass = Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter"); + useSingleMethodAdapter = true; + } + } else { + junit4TestAdapterClass = + Class.forName(JUNIT_4_TEST_ADAPTER, + true, loader); + if (testMethodsSpecified) { + junit4TestAdapterClass = + Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter", + true, loader); + useSingleMethodAdapter = true; + } } + } catch (final ClassNotFoundException e) { + // OK, fall back to JUnit 3. } - } catch (final ClassNotFoundException e) { - // OK, fall back to JUnit 3. - } } junit4 = junit4TestAdapterClass != null; - if (junitTest.isSkipNonTests()) { - if (!containsTests(testClass, junit4)) { - return; - } + if (junitTest.isSkipNonTests() + && !containsTests(testClass, junit4)) { + return; } - if (junit4) { // Let's use it! - Class[] formalParams; + Class<?>[] formalParams; Object[] actualParams; if (useSingleMethodAdapter) { - formalParams = new Class[] {Class.class, String[].class}; - actualParams = new Object[] {testClass, methods}; + formalParams = + new Class[] { Class.class, String[].class }; + actualParams = new Object[] { testClass, methods }; } else { - formalParams = new Class[] {Class.class, Class.forName("junit.framework.JUnit4TestAdapterCache")}; - actualParams = new Object[] {testClass, junit4TestAdapterCacheClass.getMethod("getInstance").invoke(null)}; + formalParams = + new Class[] { Class.class, Class.forName( + "junit.framework.JUnit4TestAdapterCache") }; + actualParams = + new Object[] { testClass, + junit4TestAdapterCacheClass + .getMethod("getInstance") + .invoke(null) }; } - suite = - (Test) junit4TestAdapterClass - .getConstructor(formalParams). - newInstance(actualParams); + suite = junit4TestAdapterClass.asSubclass(Test.class) + .getConstructor(formalParams) + .newInstance(actualParams); } else { // Use JUnit 3. @@ -511,9 +515,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR suite = testSuite; } } - } - } catch (final Throwable e) { retCode = ERRORS; exception = e; @@ -588,12 +590,13 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } private static boolean containsTests(final Class<?> testClass, final boolean isJUnit4) { - Class testAnnotation = null; - Class suiteAnnotation = null; - Class runWithAnnotation = null; + Class<? extends Annotation> testAnnotation = null; + Class<? extends Annotation> suiteAnnotation = null; + Class<? extends Annotation> runWithAnnotation = null; try { - testAnnotation = Class.forName("org.junit.Test"); + testAnnotation = + Class.forName("org.junit.Test").asSubclass(Annotation.class); } catch (final ClassNotFoundException e) { if (isJUnit4) { // odd - we think we're JUnit4 but don't support the test annotation. We therefore can't have any tests! @@ -603,17 +606,18 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } try { - suiteAnnotation = Class.forName("org.junit.Suite.SuiteClasses"); + suiteAnnotation = Class.forName("org.junit.Suite.SuiteClasses") + .asSubclass(Annotation.class); } catch(final ClassNotFoundException ex) { // ignore - we don't have this annotation so make sure we don't check for it } try { - runWithAnnotation = Class.forName("org.junit.runner.RunWith"); + runWithAnnotation = Class.forName("org.junit.runner.RunWith") + .asSubclass(Annotation.class); } catch(final ClassNotFoundException ex) { // also ignore as this annotation doesn't exist so tests can't use it } - if (!isJUnit4 && !TestCase.class.isAssignableFrom(testClass)) { //a test we think is JUnit3 but does not extend TestCase. Can't really be a test. return false; @@ -621,22 +625,26 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // check if we have any inner classes that contain suitable test methods for (final Class<?> innerClass : testClass.getDeclaredClasses()) { - if (containsTests(innerClass, isJUnit4) || containsTests(innerClass, !isJUnit4)) { + if (containsTests(innerClass, isJUnit4) + || containsTests(innerClass, !isJUnit4)) { return true; } } - if (Modifier.isAbstract(testClass.getModifiers()) || Modifier.isInterface(testClass.getModifiers())) { + if (Modifier.isAbstract(testClass.getModifiers()) + || Modifier.isInterface(testClass.getModifiers())) { // can't instantiate class and no inner classes are tests either return false; } if (isJUnit4) { - if (suiteAnnotation != null && testClass.getAnnotation(suiteAnnotation) != null) { + if (suiteAnnotation != null + && testClass.getAnnotation(suiteAnnotation) != null) { // class is marked as a suite. Let JUnit try and work its magic on it. return true; - } - if (runWithAnnotation != null && testClass.getAnnotation(runWithAnnotation) != null) { + } + if (runWithAnnotation != null + && testClass.getAnnotation(runWithAnnotation) != null) { /* Class is marked with @RunWith. If this class is badly written (no test methods, multiple * constructors, private constructor etc) then the class is automatically run and fails in the * IDEs I've tried... so I'm happy handing the class to JUnit to try and run, and let JUnit @@ -656,16 +664,19 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } else { // check if JUnit3 class have public or protected no-args methods starting with names starting with test - if (m.getName().startsWith("test") && m.getParameterTypes().length == 0 - && (Modifier.isProtected(m.getModifiers()) || Modifier.isPublic(m.getModifiers()))) { + if (m.getName().startsWith("test") + && m.getParameterTypes().length == 0 + && (Modifier.isProtected(m.getModifiers()) + || Modifier.isPublic(m.getModifiers()))) { return true; } } // check if JUnit3 or JUnit4 test have a public or protected, static, // no-args 'suite' method - if (m.getName().equals("suite") && m.getParameterTypes().length == 0 - && (Modifier.isProtected(m.getModifiers()) || Modifier.isPublic(m.getModifiers())) - && Modifier.isStatic(m.getModifiers())) { + if ("suite".equals(m.getName()) && m.getParameterTypes().length == 0 + && (Modifier.isProtected(m.getModifiers()) + || Modifier.isPublic(m.getModifiers())) + && Modifier.isStatic(m.getModifiers())) { return true; } } @@ -679,6 +690,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @return 2 if errors occurred, 1 if tests failed else 0. */ + @Override public int getRetCode() { return retCode; } @@ -689,6 +701,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * <p>A new Test is started. * @param t the test. */ + @Override public void startTest(final Test t) { final String testName = JUnitVersionHelper.getTestCaseName(t); logTestListenerEvent("startTest(" + testName + ")"); @@ -700,6 +713,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * <p>A Test is finished. * @param test the test. */ + @Override public void endTest(final Test test) { final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("endTest(" + testName + ")"); @@ -709,10 +723,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR if (logTestListenerEvents) { final PrintStream out = savedOut != null ? savedOut : System.out; out.flush(); - if (msg == null) { - msg = "null"; - } - final StringTokenizer msgLines = new StringTokenizer(msg, "\r\n", false); + final StringTokenizer msgLines = + new StringTokenizer(String.valueOf(msg), "\r\n", false); while (msgLines.hasMoreTokens()) { out.println(JUnitTask.TESTLISTENER_PREFIX + msgLines.nextToken()); @@ -743,6 +755,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the assertion thrown by the test. */ + @Override public void addFailure(final Test test, final AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -754,6 +767,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the error thrown by the test. */ + @Override public void addError(final Test test, final Throwable t) { final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("addError(" + testName + ", " + t.getMessage() + ")"); @@ -767,6 +781,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @since Ant 1.6 * @param permissions the permissions to use. */ + @Override public void setPermissions(final Permissions permissions) { perm = permissions; } @@ -775,6 +790,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * Handle a string destined for standard output. * @param output the string to output */ + @Override public void handleOutput(final String output) { if (!logTestListenerEvents && output.startsWith(JUnitTask.TESTLISTENER_PREFIX)) { // ignore @@ -794,12 +810,14 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @since Ant 1.6 */ + @Override public int handleInput(final byte[] buffer, final int offset, final int length) throws IOException { return -1; } /** {@inheritDoc}. */ + @Override public void handleErrorOutput(final String output) { if (systemError != null) { systemError.print(output); @@ -807,6 +825,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void handleFlush(final String output) { if (systemOut != null) { systemOut.print(output); @@ -814,6 +833,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void handleErrorFlush(final String output) { if (systemError != null) { systemError.print(output); @@ -824,7 +844,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR final int size = formatters.size(); for (int i = 0; i < size; i++) { final JUnitResultFormatter formatter = - ((JUnitResultFormatter) formatters.elementAt(i)); + (JUnitResultFormatter) formatters.get(i); formatter.setSystemOutput(out); formatter.setSystemError(err); @@ -856,6 +876,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void addFormatter(final JUnitTaskMirror.JUnitResultFormatterMirror f) { formatters.addElement(f); } @@ -966,19 +987,13 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } // Add/overlay system properties on the properties from the Ant project - final Hashtable p = System.getProperties(); - for (final Enumeration e = p.keys(); e.hasMoreElements();) { - final Object key = e.nextElement(); - props.put(key, p.get(key)); - } + System.getProperties().forEach(props::put); int returnCode = SUCCESS; if (multipleTests) { - try { - final java.io.BufferedReader reader = - new java.io.BufferedReader(new java.io.FileReader(args[0])); - String testCaseName; - String[] testMethodNames; + try ( + final BufferedReader reader = + new BufferedReader(new java.io.FileReader(args[0]))){ int code = 0; boolean errorOccurred = false; boolean failureOccurred = false; @@ -987,6 +1002,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR final StringTokenizer st = new StringTokenizer(line, ","); final String testListSpec = st.nextToken(); final int colonIndex = testListSpec.indexOf(':'); + String testCaseName; + String[] testMethodNames; if (colonIndex == -1) { testCaseName = testListSpec; testMethodNames = null; @@ -1041,43 +1058,52 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR System.exit(returnCode); } - private static Vector fromCmdLine = new Vector(); + private static Vector<FormatterElement> fromCmdLine = new Vector<>(); private static void transferFormatters(final JUnitTestRunner runner, final JUnitTest test) { runner.addFormatter(new JUnitResultFormatter() { + @Override public void startTestSuite(final JUnitTest suite) throws BuildException { } + @Override public void endTestSuite(final JUnitTest suite) throws BuildException { } + @Override public void setOutput(final OutputStream out) { } + @Override public void setSystemOutput(final String out) { } + @Override public void setSystemError(final String err) { } + @Override public void addError(final Test arg0, final Throwable arg1) { } + @Override public void addFailure(final Test arg0, final AssertionFailedError arg1) { } + @Override public void endTest(final Test arg0) { } + @Override public void startTest(final Test arg0) { registerTestCase(JUnitVersionHelper.getTestCaseName(arg0)); } }); final int size = fromCmdLine.size(); for (int i = 0; i < size; i++) { - final FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i); + final FormatterElement fe = fromCmdLine.elementAt(i); if (multipleTests && fe.getUseFile()) { final File destFile = new File(test.getTodir(), @@ -1279,14 +1305,19 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private int[] findJUnit4FailureErrorCount(final TestResult result) { int failures = 0; int errors = 0; - Enumeration e = result.failures(); - while (e.hasMoreElements()) { - e.nextElement(); - failures++; + { + @SuppressWarnings("unchecked") + Enumeration<TestFailure> e = result.failures(); + while (e.hasMoreElements()) { + e.nextElement(); + failures++; + } } - e = result.errors(); + @SuppressWarnings("unchecked") + Enumeration<TestFailure> e = result.errors(); while (e.hasMoreElements()) { - final Throwable t = ((TestFailure) e.nextElement()).thrownException(); + final Throwable t = + e.nextElement().thrownException(); if (t instanceof AssertionFailedError || t instanceof AssertionError) { failures++; @@ -1294,7 +1325,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR errors++; } } - return new int[] {failures, errors}; + return new int[] { failures, errors }; } } // JUnitTestRunner diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelper.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelper.java index 9a21caeec..5ac988ecf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelper.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelper.java @@ -82,9 +82,8 @@ public class JUnitVersionHelper { if (name.endsWith(")")) { int paren = name.lastIndexOf('('); return name.substring(0, paren); - } else { - return name; } + return name; } if (t instanceof TestCase && testCaseName != null) { try { @@ -94,17 +93,16 @@ public class JUnitVersionHelper { } } else { try { - Method getNameMethod = null; + Method getNameMethod; try { getNameMethod = - t.getClass().getMethod("getName", new Class [0]); + t.getClass().getMethod("getName"); } catch (NoSuchMethodException e) { - getNameMethod = t.getClass().getMethod("name", - new Class [0]); + getNameMethod = t.getClass().getMethod("name"); } if (getNameMethod != null && getNameMethod.getReturnType() == String.class) { - return (String) getNameMethod.invoke(t, new Object[0]); + return (String) getNameMethod.invoke(t); } } catch (Throwable ignored) { // ignore @@ -125,8 +123,7 @@ public class JUnitVersionHelper { String className = test.getClass().getName(); if (test instanceof JUnitTaskMirrorImpl.VmExitErrorTest) { className = ((JUnitTaskMirrorImpl.VmExitErrorTest) test).getClassName(); - } else - if (className.equals(JUNIT_FRAMEWORK_JUNIT4_TEST_CASE_FACADE)) { + } else if (className.equals(JUNIT_FRAMEWORK_JUNIT4_TEST_CASE_FACADE)) { // JUnit 4 wraps solo tests this way. We can extract // the original test name with a little hack. String name = test.toString(); @@ -152,28 +149,22 @@ public class JUnitVersionHelper { Class<?> testClass = Class.forName(JUnitVersionHelper.getTestCaseClassName(test)); Method testMethod = testClass.getMethod(JUnitVersionHelper.getTestCaseName(test)); - Class ignoreAnnotation = Class.forName("org.junit.Ignore"); + Class<? extends Annotation> ignoreAnnotation = Class + .forName("org.junit.Ignore").asSubclass(Annotation.class); Annotation annotation = testMethod.getAnnotation(ignoreAnnotation); if (annotation != null) { - Method valueMethod = annotation.getClass().getMethod("value"); + Method valueMethod = annotation.annotationType().getMethod("value"); String value = (String) valueMethod.invoke(annotation); if (value != null && value.length() > 0) { message = value; } } - } - } catch (NoSuchMethodException e) { - // silently ignore - we'll report a skip with no message - } catch (ClassNotFoundException e) { - // silently ignore - we'll report a skip with no message - } catch (InvocationTargetException e) { - // silently ignore - we'll report a skip with no message - } catch (IllegalAccessException e) { + } catch (NoSuchMethodException | ClassNotFoundException + | InvocationTargetException | IllegalAccessException e) { // silently ignore - we'll report a skip with no message } return message; - } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/PlainJUnitResultFormatter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/PlainJUnitResultFormatter.java index 07264b711..85cfb0c79 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/PlainJUnitResultFormatter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/PlainJUnitResultFormatter.java @@ -24,6 +24,7 @@ import java.io.OutputStream; import java.io.StringWriter; import java.text.NumberFormat; import java.util.Hashtable; +import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.Test; @@ -37,7 +38,6 @@ import org.apache.tools.ant.util.StringUtils; * Prints plain text output of the test to a specified Writer. * */ - public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredTestListener { private static final double ONE_SECOND = 1000.0; @@ -49,7 +49,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT /** * Timing helper. */ - private Hashtable testStarts = new Hashtable(); + private Map<Test, Long> testStarts = new Hashtable<>(); /** * Where to write the log to. */ @@ -65,7 +65,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT /** * Suppress endTest if testcase failed. */ - private Hashtable failed = new Hashtable(); + private Map<Test, Boolean> failed = new Hashtable<>(); private String systemOutput = null; private String systemError = null; @@ -77,16 +77,19 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT } /** {@inheritDoc}. */ + @Override public void setOutput(OutputStream out) { this.out = out; } /** {@inheritDoc}. */ + @Override public void setSystemOutput(String out) { systemOutput = out; } /** {@inheritDoc}. */ + @Override public void setSystemError(String err) { systemError = err; } @@ -96,15 +99,14 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param suite the test suite * @throws BuildException if unable to write the output */ + @Override public void startTestSuite(JUnitTest suite) throws BuildException { if (out == null) { return; // Quick return - no output do nothing. } - StringBuffer sb = new StringBuffer("Testsuite: "); - sb.append(suite.getName()); - sb.append(StringUtils.LINE_SEP); try { - out.write(sb.toString().getBytes()); + out.write(new StringBuilder("Testsuite: ").append(suite.getName()) + .append(StringUtils.LINE_SEP).toString().getBytes()); out.flush(); } catch (IOException ex) { throw new BuildException("Unable to write output", ex); @@ -116,10 +118,11 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param suite the test suite * @throws BuildException if unable to write the output */ + @Override public void endTestSuite(JUnitTest suite) throws BuildException { boolean success = false; try { - StringBuffer sb = new StringBuffer("Tests run: "); + StringBuilder sb = new StringBuilder("Tests run: "); sb.append(suite.runCount()); sb.append(", Failures: "); sb.append(suite.failureCount()); @@ -185,6 +188,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * <p>A new Test is started. * @param t the test. */ + @Override public void startTest(Test t) { testStarts.put(t, new Long(System.currentTimeMillis())); failed.put(t, Boolean.FALSE); @@ -196,6 +200,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * <p>A Test is finished. * @param test the test. */ + @Override public void endTest(Test test) { if (Boolean.TRUE.equals(failed.get(test))) { return; @@ -204,7 +209,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT try { wri.write("Testcase: " + JUnitVersionHelper.getTestCaseName(test)); - Long l = (Long) testStarts.get(test); + Long l = testStarts.get(test); double seconds = 0; // can be null if an error occurred in setUp if (l != null) { @@ -238,6 +243,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param test the test. * @param t the assertion that failed. */ + @Override public void addFailure(Test test, AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -249,6 +255,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT * @param test the test. * @param t the exception. */ + @Override public void addError(Test test, Throwable t) { formatError("\tCaused an ERROR", test, t); } @@ -274,6 +281,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT } } + @Override public void testIgnored(Test test) { formatSkip(test, JUnitVersionHelper.getIgnoreMessage(test)); } @@ -297,6 +305,7 @@ public class PlainJUnitResultFormatter implements JUnitResultFormatter, IgnoredT } + @Override public void testAssumptionFailure(Test test, Throwable throwable) { formatSkip(test, throwable.getMessage()); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/SummaryJUnitResultFormatter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/SummaryJUnitResultFormatter.java index 4eb30fbe6..27239d6fb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/SummaryJUnitResultFormatter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/SummaryJUnitResultFormatter.java @@ -52,12 +52,6 @@ public class SummaryJUnitResultFormatter private String systemError = null; /** - * Empty - */ - public SummaryJUnitResultFormatter() { - } - - /** * Insures that a line of log output is written and flushed as a single * operation, to prevent lines from being spliced into other lines. * (Hopefully this solves the issue of run on lines - @@ -81,9 +75,10 @@ public class SummaryJUnitResultFormatter * The testsuite started. * @param suite the testsuite. */ + @Override public void startTestSuite(JUnitTest suite) { String newLine = System.getProperty("line.separator"); - StringBuffer sb = new StringBuffer("Running "); + StringBuilder sb = new StringBuilder("Running "); int antThreadID = suite.getThread(); sb.append(suite.getName()); @@ -99,12 +94,14 @@ public class SummaryJUnitResultFormatter * Empty * @param t not used. */ + @Override public void startTest(Test t) { } /** * Empty * @param test not used. */ + @Override public void endTest(Test test) { } /** @@ -121,6 +118,7 @@ public class SummaryJUnitResultFormatter * @param test not used. * @param t not used. */ + @Override public void addFailure(Test test, AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -129,20 +127,24 @@ public class SummaryJUnitResultFormatter * @param test not used. * @param t not used. */ + @Override public void addError(Test test, Throwable t) { } /** {@inheritDoc}. */ + @Override public void setOutput(OutputStream out) { this.out = out; } /** {@inheritDoc}. */ + @Override public void setSystemOutput(String out) { systemOutput = out; } /** {@inheritDoc}. */ + @Override public void setSystemError(String err) { systemError = err; } @@ -152,6 +154,7 @@ public class SummaryJUnitResultFormatter * the summary. * @param value if true write System.out and System.err to the summary. */ + @Override public void setWithOutAndErr(boolean value) { withOutAndErr = value; } @@ -161,9 +164,10 @@ public class SummaryJUnitResultFormatter * @param suite the testsuite. * @throws BuildException if there is an error. */ + @Override public void endTestSuite(JUnitTest suite) throws BuildException { String newLine = System.getProperty("line.separator"); - StringBuffer sb = new StringBuffer("Tests run: "); + StringBuilder sb = new StringBuilder("Tests run: "); sb.append(suite.runCount()); sb.append(", Failures: "); sb.append(suite.failureCount()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java index e381a70c3..a50083951 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrash.java @@ -19,7 +19,6 @@ package org.apache.tools.ant.taskdefs.optional.junit; import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import junit.framework.AssertionFailedError; @@ -43,6 +42,7 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { * Records the suite's name to later determine the class to invoke * tearDown on. */ + @Override public void startTestSuite(final JUnitTest suite) { suiteName = suite.getName(); if (suiteName != null && @@ -57,6 +57,7 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { * test we get when a Batch fails and the error is an actual * error generated by Ant. */ + @Override public void addError(final Test fakeTest, final Throwable t) { if (suiteName != null && fakeTest instanceof JUnitTaskMirrorImpl.VmExitErrorTest) { @@ -67,25 +68,32 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { // no need to implement the rest public void addFailure(Test test, Throwable t) {} + @Override public void addFailure(Test test, AssertionFailedError t) {} + @Override public void startTest(Test test) {} + @Override public void endTest(Test test) {} + @Override public void endTestSuite(JUnitTest suite) {} + @Override public void setOutput(OutputStream out) {} + @Override public void setSystemOutput(String out) {} + @Override public void setSystemError(String err) {} private void tearDown() { try { // first try to load the class and let's hope it is on our // classpath - Class testClass = null; + Class<?> testClass = null; if (Thread.currentThread().getContextClassLoader() != null) { try { testClass = Thread.currentThread().getContextClassLoader() @@ -111,7 +119,7 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { // which test of the executed suite timed out, ignore it try { // check if there is a suite method - testClass.getMethod("suite", new Class[0]); + testClass.getMethod("suite"); return; } catch (NoSuchMethodException e) { // no suite method @@ -122,9 +130,9 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { // doesn't have any tearDown method. try { - Method td = testClass.getMethod("tearDown", new Class[0]); + Method td = testClass.getMethod("tearDown"); if (td.getReturnType() == Void.TYPE) { - td.invoke(testClass.newInstance(), new Object[0]); + td.invoke(testClass.newInstance()); } } catch (NoSuchMethodException nsme) { // no tearDown, fine @@ -133,9 +141,6 @@ public class TearDownOnVmCrash implements JUnitResultFormatter { } catch (ClassNotFoundException cnfe) { // class probably is not in our classpath, there is // nothing we can do - } catch (InvocationTargetException ite) { - System.err.println("Caught an exception while trying to invoke" - + " tearDown: " + ite.getMessage()); } catch (Throwable t) { System.err.println("Caught an exception while trying to invoke" + " tearDown: " + t.getMessage()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TestListenerWrapper.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TestListenerWrapper.java index 692e4fc98..d65b7f227 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/TestListenerWrapper.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/TestListenerWrapper.java @@ -32,31 +32,38 @@ public class TestListenerWrapper implements TestListener, IgnoredTestListener { wrapped = listener; } + @Override public void addError(Test test, Throwable throwable) { wrapped.addError(test, throwable); } + @Override public void addFailure(Test test, AssertionFailedError assertionFailedError) { wrapped.addFailure(test, assertionFailedError); } + @Override public void endTest(Test test) { wrapped.endTest(test); } + @Override public void startTest(Test test) { wrapped.startTest(test); } + @Override public void testIgnored(Test test) { if (wrapped instanceof IgnoredTestListener) { - ((IgnoredTestListener)wrapped).testIgnored(test); + ((IgnoredTestListener) wrapped).testIgnored(test); } } + @Override public void testAssumptionFailure(Test test, Throwable throwable) { if (wrapped instanceof IgnoredTestListener) { - ((IgnoredTestListener)wrapped).testAssumptionFailure(test, throwable); + ((IgnoredTestListener) wrapped).testAssumptionFailure(test, + throwable); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java index 416c10d43..d62a847d4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLJUnitResultFormatter.java @@ -26,8 +26,8 @@ import java.io.Writer; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; -import java.util.Enumeration; import java.util.Hashtable; +import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; @@ -50,7 +50,6 @@ import org.w3c.dom.Text; * * @see FormatterElement */ - public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstants, IgnoredTestListener { private static final double ONE_SECOND = 1000.0; @@ -84,45 +83,44 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * so we can't easily match Test objects without manually iterating over all keys and checking * individual fields. */ - private final Hashtable<String, Element> testElements = new Hashtable<String, Element>(); + private final Hashtable<String, Element> testElements = new Hashtable<>(); /** * tests that failed. */ - private final Hashtable failedTests = new Hashtable(); + private final Map<Test, Test> failedTests = new Hashtable<>(); /** * Tests that were skipped. */ - private final Hashtable<String, Test> skippedTests = new Hashtable<String, Test>(); + private final Map<String, Test> skippedTests = new Hashtable<>(); /** * Tests that were ignored. See the note above about the key being a bit of a hack. */ - private final Hashtable<String, Test> ignoredTests = new Hashtable<String, Test>(); + private final Map<String, Test> ignoredTests = new Hashtable<>(); /** * Timing helper. */ - private final Hashtable<String, Long> testStarts = new Hashtable<String, Long>(); + private final Map<String, Long> testStarts = new Hashtable<>(); /** * Where to write the log to. */ private OutputStream out; - /** No arg constructor. */ - public XMLJUnitResultFormatter() { - } - /** {@inheritDoc}. */ + @Override public void setOutput(final OutputStream out) { this.out = out; } /** {@inheritDoc}. */ + @Override public void setSystemOutput(final String out) { formatOutput(SYSTEM_OUT, out); } /** {@inheritDoc}. */ + @Override public void setSystemError(final String out) { formatOutput(SYSTEM_ERR, out); } @@ -131,6 +129,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * The whole testsuite started. * @param suite the testsuite. */ + @Override public void startTestSuite(final JUnitTest suite) { doc = getDocumentBuilder().newDocument(); rootElement = doc.createElement(TESTSUITE); @@ -149,9 +148,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan rootElement.appendChild(propsElement); final Properties props = suite.getProperties(); if (props != null) { - final Enumeration e = props.propertyNames(); - while (e.hasMoreElements()) { - final String name = (String) e.nextElement(); + for (String name : props.stringPropertyNames()) { final Element propElement = doc.createElement(PROPERTY); propElement.setAttribute(ATTR_NAME, name); propElement.setAttribute(ATTR_VALUE, props.getProperty(name)); @@ -182,19 +179,20 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param suite the testsuite. * @throws BuildException on error. */ + @Override public void endTestSuite(final JUnitTest suite) throws BuildException { - rootElement.setAttribute(ATTR_TESTS, "" + suite.runCount()); - rootElement.setAttribute(ATTR_FAILURES, "" + suite.failureCount()); - rootElement.setAttribute(ATTR_ERRORS, "" + suite.errorCount()); - rootElement.setAttribute(ATTR_SKIPPED, "" + suite.skipCount()); + rootElement.setAttribute(ATTR_TESTS, Long.toString(suite.runCount())); + rootElement.setAttribute(ATTR_FAILURES, Long.toString(suite.failureCount())); + rootElement.setAttribute(ATTR_ERRORS, Long.toString(suite.errorCount())); + rootElement.setAttribute(ATTR_SKIPPED, Long.toString(suite.skipCount())); rootElement.setAttribute( - ATTR_TIME, "" + (suite.getRunTime() / ONE_SECOND)); + ATTR_TIME, Double.toString(suite.getRunTime() / ONE_SECOND)); if (out != null) { Writer wri = null; try { wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8")); wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); - (new DOMElementWriter()).write(rootElement, wri, 0, " "); + new DOMElementWriter().write(rootElement, wri, 0, " "); } catch (final IOException exc) { throw new BuildException("Unable to write log file", exc); } finally { @@ -218,12 +216,14 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * <p>A new Test is started. * @param t the test. */ + @Override public void startTest(final Test t) { testStarts.put(createDescription(t), System.currentTimeMillis()); } private static String createDescription(final Test test) throws BuildException { - return JUnitVersionHelper.getTestCaseName(test) + "(" + JUnitVersionHelper.getTestCaseClassName(test) + ")"; + return JUnitVersionHelper.getTestCaseName(test) + "(" + + JUnitVersionHelper.getTestCaseClassName(test) + ")"; } /** @@ -232,6 +232,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * <p>A Test is finished. * @param test the test. */ + @Override public void endTest(final Test test) { final String testDescription = createDescription(test); @@ -242,7 +243,9 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan startTest(test); } Element currentTest; - if (!failedTests.containsKey(test) && !skippedTests.containsKey(testDescription) && !ignoredTests.containsKey(testDescription)) { + if (!failedTests.containsKey(test) + && !skippedTests.containsKey(testDescription) + && !ignoredTests.containsKey(testDescription)) { currentTest = doc.createElement(TESTCASE); final String n = JUnitVersionHelper.getTestCaseName(test); currentTest.setAttribute(ATTR_NAME, @@ -259,7 +262,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan final Long l = testStarts.get(createDescription(test)); currentTest.setAttribute(ATTR_TIME, - "" + ((System.currentTimeMillis() - l) / ONE_SECOND)); + Double.toString((System.currentTimeMillis() - l) / ONE_SECOND)); } /** @@ -280,6 +283,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param test the test. * @param t the assertion. */ + @Override public void addFailure(final Test test, final AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -291,6 +295,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan * @param test the test. * @param t the error. */ + @Override public void addError(final Test test, final Throwable t) { formatError(ERROR, test, t); } @@ -302,12 +307,8 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan } final Element nested = doc.createElement(type); - Element currentTest; - if (test != null) { - currentTest = testElements.get(createDescription(test)); - } else { - currentTest = rootElement; - } + Element currentTest = test == null ? rootElement + : testElements.get(createDescription(test)); currentTest.appendChild(nested); @@ -328,6 +329,7 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan nested.appendChild(doc.createCDATASection(output)); } + @Override public void testIgnored(final Test test) { formatSkip(test, JUnitVersionHelper.getIgnoreMessage(test)); if (test != null) { @@ -335,7 +337,6 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan } } - public void formatSkip(final Test test, final String message) { if (test != null) { endTest(test); @@ -347,17 +348,14 @@ public class XMLJUnitResultFormatter implements JUnitResultFormatter, XMLConstan nested.setAttribute("message", message); } - Element currentTest; - if (test != null) { - currentTest = testElements.get(createDescription(test)); - } else { - currentTest = rootElement; - } + Element currentTest = test == null ? rootElement + : testElements.get(createDescription(test)); currentTest.appendChild(nested); } + @Override public void testAssumptionFailure(final Test test, final Throwable failure) { formatSkip(test, failure.getMessage()); skippedTests.put(createDescription(test), test); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java index 92e3553b8..b877c0bb8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregator.java @@ -24,8 +24,8 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.file.Files; -import java.util.Enumeration; import java.util.Vector; +import java.util.stream.Stream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -61,7 +61,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { // CheckStyle:VisibilityModifier OFF - bc /** the list of all filesets, that should contains the xml to aggregate */ - protected Vector filesets = new Vector(); + protected Vector<FileSet> filesets = new Vector<>(); /** the name of the result file */ protected String toFile; @@ -69,7 +69,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { /** the directory to write the file to */ protected File toDir; - protected Vector transformers = new Vector(); + protected Vector<AggregateTransformer> transformers = new Vector<>(); /** The default directory: <tt>.</tt>. It is resolved from the project directory */ public static final String DEFAULT_DIR = "."; @@ -103,7 +103,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { */ public AggregateTransformer createReport() { AggregateTransformer transformer = new AggregateTransformer(this); - transformers.addElement(transformer); + transformers.add(transformer); return transformer; } @@ -133,7 +133,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { * @param fs the new fileset of xml results. */ public void addFileSet(FileSet fs) { - filesets.addElement(fs); + filesets.add(fs); } /** @@ -142,6 +142,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { * @throws BuildException thrown if there is a serious error while writing * the document. */ + @Override public void execute() throws BuildException { Element rootElement = createDocument(); File destFile = getDestinationFile(); @@ -152,10 +153,7 @@ public class XMLResultAggregator extends Task implements XMLConstants { throw new BuildException("Unable to write test aggregate to '" + destFile + "'", e); } // apply transformation - Enumeration e = transformers.elements(); - while (e.hasMoreElements()) { - AggregateTransformer transformer = - (AggregateTransformer) e.nextElement(); + for (AggregateTransformer transformer : transformers) { transformer.setXmlDocument(rootElement.getOwnerDocument()); transformer.transform(); } @@ -182,26 +180,16 @@ public class XMLResultAggregator extends Task implements XMLConstants { * @return all files in the fileset that end with a '.xml'. */ protected File[] getFiles() { - Vector v = new Vector(); - final int size = filesets.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) filesets.elementAt(i); - DirectoryScanner ds = fs.getDirectoryScanner(getProject()); + Project p = getProject(); + return filesets.stream().flatMap(fs -> { + DirectoryScanner ds = fs.getDirectoryScanner(p); ds.scan(); - String[] f = ds.getIncludedFiles(); - for (int j = 0; j < f.length; j++) { - String pathname = f[j]; - if (pathname.endsWith(".xml")) { - File file = new File(ds.getBasedir(), pathname); - file = getProject().resolveFile(file.getPath()); - v.addElement(file); - } - } - } - - File[] files = new File[v.size()]; - v.copyInto(files); - return files; + return Stream.of(ds.getIncludedFiles()) + .filter(pathname -> pathname.endsWith(".xml")).map(pathname -> { + return p.resolveFile( + new File(ds.getBasedir(), pathname).getPath()); + }); + }).toArray(File[]::new); } //----- from now, the methods are all related to DOM tree manipulation @@ -216,7 +204,8 @@ public class XMLResultAggregator extends Task implements XMLConstants { try (OutputStream os = Files.newOutputStream(file.toPath()); PrintWriter wri = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(os), "UTF8"))) { wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); - (new DOMElementWriter()).write(doc.getDocumentElement(), wri, 0, " "); + new DOMElementWriter().write(doc.getDocumentElement(), wri, 0, + " "); wri.flush(); // writers do not throw exceptions, so check for them. if (wri.checkError()) { @@ -247,9 +236,8 @@ public class XMLResultAggregator extends Task implements XMLConstants { try { log("Parsing file: '" + file + "'", Project.MSG_VERBOSE); if (file.length() > 0) { - Document testsuiteDoc - = builder.parse( - FileUtils.getFileUtils().toURI(files[i].getAbsolutePath())); + Document testsuiteDoc = builder.parse(FileUtils + .getFileUtils().toURI(files[i].getAbsolutePath())); Element elem = testsuiteDoc.getDocumentElement(); // make sure that this is REALLY a testsuite. if (TESTSUITE.equals(elem.getNodeName())) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/BuiltinNative2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/BuiltinNative2Ascii.java index 244b8c140..f8059fe55 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/BuiltinNative2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/BuiltinNative2Ascii.java @@ -25,13 +25,14 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; +import java.io.PrintWriter; import java.io.Writer; +import java.util.function.UnaryOperator; import java.nio.file.Files; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.optional.Native2Ascii; import org.apache.tools.ant.util.Native2AsciiUtils; -import org.apache.tools.ant.util.StringUtils; /** * Encapsulates the built-in Native2Ascii implementation. @@ -48,8 +49,10 @@ public class BuiltinNative2Ascii implements Native2AsciiAdapter { boolean reverse = args.getReverse(); String encoding = args.getEncoding(); try (BufferedReader input = getReader(srcFile, encoding, reverse); - Writer output = getWriter(destFile, encoding, reverse)) { - translate(input, output, reverse); + Writer output = getWriter(destFile, encoding, reverse)) { + + translate(input, output, reverse ? Native2AsciiUtils::ascii2native + : Native2AsciiUtils::native2ascii); return true; } catch (IOException ex) { throw new BuildException("Exception trying to translate data", ex); @@ -79,15 +82,12 @@ public class BuiltinNative2Ascii implements Native2AsciiAdapter { } private void translate(BufferedReader input, Writer output, - boolean reverse) throws IOException { - String line = null; - while ((line = input.readLine()) != null) { - if (!reverse) { - output.write(Native2AsciiUtils.native2ascii(line)); - } else { - output.write(Native2AsciiUtils.ascii2native(line)); - } - output.write(StringUtils.LINE_SEP); + UnaryOperator<String> translation) throws IOException { + PrintWriter pw = new PrintWriter(output); + + for (String line : (Iterable<String>) () -> input.lines() + .map(translation).iterator()) { + pw.println(line); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/DefaultNative2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/DefaultNative2Ascii.java index 3cd52afe5..438bfe9e7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/DefaultNative2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/DefaultNative2Ascii.java @@ -47,6 +47,7 @@ public abstract class DefaultNative2Ascii implements Native2AsciiAdapter { * (delegated to {@link #addFiles addFiles}) and running the tool * (delegated to {@link #run run}). */ + @Override public final boolean convert(Native2Ascii args, File srcFile, File destFile) throws BuildException { Commandline cmd = new Commandline(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java index da4836fde..e29634a39 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/KaffeNative2Ascii.java @@ -43,6 +43,7 @@ public final class KaffeNative2Ascii extends DefaultNative2Ascii { public static final String IMPLEMENTATION_NAME = "kaffe"; /** {@inheritDoc} */ + @Override protected void setup(Commandline cmd, Native2Ascii args) throws BuildException { if (args.getReverse()) { @@ -52,13 +53,14 @@ public final class KaffeNative2Ascii extends DefaultNative2Ascii { } /** {@inheritDoc} */ + @Override protected boolean run(Commandline cmd, ProjectComponent log) throws BuildException { ExecuteJava ej = new ExecuteJava(); - Class c = getN2aClass(); + Class<?> c = getN2aClass(); if (c == null) { - throw new BuildException("Couldn't load Kaffe's Native2Ascii" - + " class"); + throw new BuildException( + "Couldn't load Kaffe's Native2Ascii class"); } cmd.setExecutable(c.getName()); @@ -74,7 +76,7 @@ public final class KaffeNative2Ascii extends DefaultNative2Ascii { * * @return null if neither class can get loaded. */ - private static Class getN2aClass() { + private static Class<?> getN2aClass() { for (int i = 0; i < N2A_CLASSNAMES.length; i++) { try { return Class.forName(N2A_CLASSNAMES[i]); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/SunNative2Ascii.java b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/SunNative2Ascii.java index fac94b18c..fdcce7d1d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/SunNative2Ascii.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/native2ascii/SunNative2Ascii.java @@ -36,7 +36,10 @@ public final class SunNative2Ascii extends DefaultNative2Ascii { */ public static final String IMPLEMENTATION_NAME = "sun"; + private static final String SUN_TOOLS_NATIVE2ASCII_MAIN = "sun.tools.native2ascii.Main"; + /** {@inheritDoc} */ + @Override protected void setup(Commandline cmd, Native2Ascii args) throws BuildException { if (args.getReverse()) { @@ -46,23 +49,20 @@ public final class SunNative2Ascii extends DefaultNative2Ascii { } /** {@inheritDoc} */ + @Override protected boolean run(Commandline cmd, ProjectComponent log) throws BuildException { try { - Class n2aMain = Class.forName("sun.tools.native2ascii.Main"); - Class[] param = new Class[] {String[].class}; - Method convert = n2aMain.getMethod("convert", param); - if (convert == null) { - throw new BuildException("Could not find convert() method in " - + "sun.tools.native2ascii.Main"); - } - Object o = n2aMain.newInstance(); - return ((Boolean) convert.invoke(o, - new Object[] {cmd.getArguments()}) - ).booleanValue(); + Class<?> n2aMain = Class.forName(SUN_TOOLS_NATIVE2ASCII_MAIN); + Method convert = n2aMain.getMethod("convert", String[].class); + return Boolean.TRUE.equals(convert.invoke(n2aMain.newInstance(), + (Object) cmd.getArguments())); } catch (BuildException ex) { //rethrow throw ex; + } catch (NoSuchMethodException ex) { + throw new BuildException("Could not find convert() method in %s", + SUN_TOOLS_NATIVE2ASCII_MAIN); } catch (Exception ex) { //wrap throw new BuildException("Error starting Sun's native2ascii: ", ex); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java index a9d079c2e..2a5239022 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTP.java @@ -29,16 +29,16 @@ import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; @@ -119,8 +119,8 @@ public class FTP extends Task implements FTPTaskConfig { private long granularityMillis = 0L; private boolean timeDiffAuto = false; private int action = SEND_FILES; - private Vector filesets = new Vector(); - private Set dirCache = new HashSet(); + private Vector<FileSet> filesets = new Vector<>(); + private Set<File> dirCache = new HashSet<>(); private int transferred = 0; private String remoteFileSep = "/"; private int port = DEFAULT_FTP_PORT; @@ -182,6 +182,7 @@ public class FTP extends Task implements FTPTaskConfig { * */ protected static class FTPFileProxy extends File { + private static final long serialVersionUID = 1L; private final FTPFile file; private final String[] parts; @@ -213,6 +214,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#exists() */ + @Override public boolean exists() { return true; } @@ -221,6 +223,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#getAbsolutePath() */ + @Override public String getAbsolutePath() { return name; } @@ -229,6 +232,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#getName() */ + @Override public String getName() { return parts.length > 0 ? parts[parts.length - 1] : name; } @@ -237,6 +241,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#getParent() */ + @Override public String getParent() { String result = ""; for(int i = 0; i < parts.length - 1; i++){ @@ -249,6 +254,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#getPath() */ + @Override public String getPath() { return name; } @@ -258,6 +264,7 @@ public class FTP extends Task implements FTPTaskConfig { * FTP files are stored as absolute paths * @return true */ + @Override public boolean isAbsolute() { return true; } @@ -266,6 +273,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#isDirectory() */ + @Override public boolean isDirectory() { return file == null; } @@ -274,6 +282,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#isFile() */ + @Override public boolean isFile() { return file != null; } @@ -284,6 +293,7 @@ public class FTP extends Task implements FTPTaskConfig { * * @return false */ + @Override public boolean isHidden() { return false; } @@ -292,6 +302,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#lastModified() */ + @Override public long lastModified() { if (file != null) { return file.getTimestamp().getTimeInMillis(); @@ -303,6 +314,7 @@ public class FTP extends Task implements FTPTaskConfig { /* (non-Javadoc) * @see java.io.File#length() */ + @Override public long length() { if (file != null) { return file.getSize(); @@ -348,6 +360,7 @@ public class FTP extends Task implements FTPTaskConfig { * scans the remote directory, * storing internally the included files, directories, ... */ + @Override public void scan() { if (includes == null) { // No includes supplied, so set it to 'matches all' @@ -358,12 +371,12 @@ public class FTP extends Task implements FTPTaskConfig { excludes = new String[0]; } - filesIncluded = new VectorSet(); - filesNotIncluded = new Vector(); - filesExcluded = new VectorSet(); - dirsIncluded = new VectorSet(); - dirsNotIncluded = new Vector(); - dirsExcluded = new VectorSet(); + filesIncluded = new VectorSet<>(); + filesNotIncluded = new Vector<>(); + filesExcluded = new VectorSet<>(); + dirsIncluded = new VectorSet<>(); + dirsNotIncluded = new Vector<>(); + dirsExcluded = new VectorSet<>(); try { String cwd = ftp.printWorkingDirectory(); @@ -386,7 +399,7 @@ public class FTP extends Task implements FTPTaskConfig { */ private void checkIncludePatterns() { - Hashtable newroots = new Hashtable(); + Map<String, String> newroots = new HashMap<>(); // put in the newroots vector the include patterns without // wildcard tokens for (int icounter = 0; icounter < includes.length; icounter++) { @@ -411,75 +424,70 @@ public class FTP extends Task implements FTPTaskConfig { } else { // only scan directories that can include matched files or // directories - Enumeration enum2 = newroots.keys(); - - while (enum2.hasMoreElements()) { - String currentelement = (String) enum2.nextElement(); - String originalpattern = (String) newroots.get(currentelement); - AntFTPFile myfile = new AntFTPFile(baseFTPFile, currentelement); - boolean isOK = true; - boolean traversesSymlinks = false; - String path = null; - - if (myfile.exists()) { - forceRemoteSensitivityCheck(); - if (remoteSensitivityChecked - && remoteSystemCaseSensitive && isFollowSymlinks()) { - // cool case, - //we do not need to scan all the subdirs in the relative path - path = myfile.getFastRelativePath(); - } else { - // may be on a case insensitive file system. We want - // the results to show what's really on the disk, so - // we need to double check. - try { - path = myfile.getRelativePath(); - traversesSymlinks = myfile.isTraverseSymlinks(); - } catch (IOException be) { - throw new BuildException(be, getLocation()); - } catch (BuildException be) { - isOK = false; - } - } - } else { + newroots.forEach((k,v) -> scanRoots(baseFTPFile, k, v)); + } + } + + private void scanRoots(AntFTPFile baseFTPFile, String currentelement, String originalpattern) { + AntFTPFile myfile = new AntFTPFile(baseFTPFile, currentelement); + boolean isOK = true; + boolean traversesSymlinks = false; + String path = null; + + if (myfile.exists()) { + forceRemoteSensitivityCheck(); + if (remoteSensitivityChecked + && remoteSystemCaseSensitive && isFollowSymlinks()) { + // cool case, + //we do not need to scan all the subdirs in the relative path + path = myfile.getFastRelativePath(); + } else { + // may be on a case insensitive file system. We want + // the results to show what's really on the disk, so + // we need to double check. + try { + path = myfile.getRelativePath(); + traversesSymlinks = myfile.isTraverseSymlinks(); + } catch (IOException be) { + throw new BuildException(be, getLocation()); + } catch (BuildException be) { isOK = false; } - if (isOK) { - currentelement = path.replace(remoteFileSep.charAt(0), File.separatorChar); - if (!isFollowSymlinks() - && traversesSymlinks) { - continue; - } + } + } else { + isOK = false; + } + if (isOK) { + currentelement = path.replace(remoteFileSep.charAt(0), File.separatorChar); + if (!isFollowSymlinks() && traversesSymlinks) { + return; + } - if (myfile.isDirectory()) { - if (isIncluded(currentelement) - && currentelement.length() > 0) { - accountForIncludedDir(currentelement, myfile, true); - } else { - if (currentelement.length() > 0) { - if (currentelement.charAt(currentelement - .length() - 1) - != File.separatorChar) { - currentelement = - currentelement + File.separatorChar; - } - } - scandir(myfile.getAbsolutePath(), currentelement, true); - } - } else { - if (isCaseSensitive - && originalpattern.equals(currentelement)) { - accountForIncludedFile(currentelement); - } else if (!isCaseSensitive - && originalpattern - .equalsIgnoreCase(currentelement)) { - accountForIncludedFile(currentelement); + if (myfile.isDirectory()) { + if (isIncluded(currentelement) + && currentelement.length() > 0) { + accountForIncludedDir(currentelement, myfile, true); + } else { + if (currentelement.length() > 0) { + if (currentelement.charAt(currentelement + .length() - 1) + != File.separatorChar) { + currentelement = + currentelement + File.separatorChar; } } + scandir(myfile.getAbsolutePath(), currentelement, true); } + } else if (isCaseSensitive + && originalpattern.equals(currentelement)) { + accountForIncludedFile(currentelement); + } else if (!isCaseSensitive && originalpattern + .equalsIgnoreCase(currentelement)) { + accountForIncludedFile(currentelement); } } } + /** * scans a particular directory. populates the scannedDirs cache. * @@ -561,7 +569,7 @@ public class FTP extends Task implements FTPTaskConfig { if (isIncluded(name)) { if (!isExcluded(name) - && isSelected(name, (File) scannedDirs.get(name))) { + && isSelected(name, scannedDirs.get(name))) { filesIncluded.addElement(name); } else { filesExcluded.addElement(name); @@ -623,14 +631,14 @@ public class FTP extends Task implements FTPTaskConfig { * * @since Ant 1.6 */ - private Map fileListMap = new HashMap(); + private Map<String, FTPFile[]> fileListMap = new HashMap<>(); /** * List of all scanned directories. * * @since Ant 1.6 */ - private Map scannedDirs = new HashMap(); + private Map<String, FTPFileProxy> scannedDirs = new HashMap<>(); /** * Has the directory with the given path relative to the base @@ -658,12 +666,10 @@ public class FTP extends Task implements FTPTaskConfig { * @return array of FTPFile */ public FTPFile[] listFiles(String directory, boolean changedir) { - //getProject().log("listing files in directory " + directory, Project.MSG_DEBUG); String currentPath = directory; if (changedir) { try { - boolean result = ftp.changeWorkingDirectory(directory); - if (!result) { + if (!ftp.changeWorkingDirectory(directory)) { return null; } currentPath = ftp.printWorkingDirectory(); @@ -673,9 +679,9 @@ public class FTP extends Task implements FTPTaskConfig { } if (fileListMap.containsKey(currentPath)) { getProject().log("filelist map used in listing files", Project.MSG_DEBUG); - return ((FTPFile[]) fileListMap.get(currentPath)); + return fileListMap.get(currentPath); } - FTPFile[] result = null; + FTPFile[] result; try { result = ftp.listFiles(); } catch (IOException ioe) { @@ -706,6 +712,7 @@ public class FTP extends Task implements FTPTaskConfig { public FTPFile[] listFiles(String directory) { return listFiles(directory, true); } + private void checkRemoteSensitivity(FTPFile[] array, String directory) { if (array == null) { return; @@ -714,8 +721,8 @@ public class FTP extends Task implements FTPTaskConfig { String target = null; for (int icounter = 0; icounter < array.length; icounter++) { if (array[icounter] != null && array[icounter].isDirectory()) { - if (!array[icounter].getName().equals(".") - && !array[icounter].getName().equals("..")) { + if (!".".equals(array[icounter].getName()) + && !"..".equals(array[icounter].getName())) { candidateFound = true; target = fiddleName(array[icounter].getName()); getProject().log("will try to cd to " @@ -754,8 +761,9 @@ public class FTP extends Task implements FTPTaskConfig { remoteSensitivityChecked = true; } } + private String fiddleName(String origin) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int icounter = 0; icounter < origin.length(); icounter++) { if (Character.isLowerCase(origin.charAt(icounter))) { result.append(Character.toUpperCase(origin.charAt(icounter))); @@ -767,6 +775,7 @@ public class FTP extends Task implements FTPTaskConfig { } return result.toString(); } + /** * an AntFTPFile is a representation of a remote file * @since Ant 1.6 @@ -810,46 +819,47 @@ public class FTP extends Task implements FTPTaskConfig { public AntFTPFile(AntFTPFile parent, String path) { this.parent = parent; this.client = parent.client; - Vector pathElements = SelectorUtils.tokenizePath(path); + List<String> pathElements = SelectorUtils.tokenizePath(path); try { - boolean result = this.client.changeWorkingDirectory(parent.getAbsolutePath()); //this should not happen, except if parent has been deleted by another process - if (!result) { + if (!this.client.changeWorkingDirectory(parent.getAbsolutePath())) { return; } this.curpwd = parent.getAbsolutePath(); } catch (IOException ioe) { - throw new BuildException("could not change working dir to " - + parent.curpwd); + throw new BuildException( + "could not change working dir to %s", parent.curpwd); } final int size = pathElements.size(); for (int fcount = 0; fcount < size - 1; fcount++) { - String currentPathElement = (String) pathElements.elementAt(fcount); + String currentPathElement = pathElements.get(fcount); try { - boolean result = this.client.changeWorkingDirectory(currentPathElement); - if (!result && !isCaseSensitive() - && (remoteSystemCaseSensitive || !remoteSensitivityChecked)) { - currentPathElement = findPathElementCaseUnsensitive(this.curpwd, - currentPathElement); - if (currentPathElement == null) { - return; + if (!this.client + .changeWorkingDirectory(currentPathElement)) { + if (!isCaseSensitive() && (remoteSystemCaseSensitive + || !remoteSensitivityChecked)) { + currentPathElement = + findPathElementCaseUnsensitive(this.curpwd, + currentPathElement); + if (currentPathElement == null) { + return; + } } - } else if (!result) { return; } - this.curpwd = getCurpwdPlusFileSep() - + currentPathElement; + this.curpwd = + getCurpwdPlusFileSep() + currentPathElement; } catch (IOException ioe) { - throw new BuildException("could not change working dir to " - + (String) pathElements.elementAt(fcount) - + " from " + this.curpwd); + throw new BuildException( + "could not change working dir to %s from %s", + currentPathElement, curpwd); } - } - String lastpathelement = (String) pathElements.elementAt(size - 1); - FTPFile [] theFiles = listFiles(this.curpwd); + String lastpathelement = pathElements.get(pathElements.size() - 1); + FTPFile[] theFiles = listFiles(this.curpwd); this.ftpFile = getFile(theFiles, lastpathelement); } + /** * find a file in a directory in case unsensitive way * @param parentPath where we are @@ -864,14 +874,15 @@ public class FTP extends Task implements FTPTaskConfig { if (theFiles == null) { return null; } - for (int icounter = 0; icounter < theFiles.length; icounter++) { - if (theFiles[icounter] != null - && theFiles[icounter].getName().equalsIgnoreCase(soughtPathElement)) { - return theFiles[icounter].getName(); + for (FTPFile f : theFiles) { + if (f != null + && f.getName().equalsIgnoreCase(soughtPathElement)) { + return f.getName(); } } return null; } + /** * find out if the file exists * @return true if the file exists @@ -879,6 +890,7 @@ public class FTP extends Task implements FTPTaskConfig { public boolean exists() { return (ftpFile != null); } + /** * if the file is a symbolic link, find out to what it is pointing * @return the target of the symbolic link @@ -886,6 +898,7 @@ public class FTP extends Task implements FTPTaskConfig { public String getLink() { return ftpFile.getLink(); } + /** * get the name of the file * @return the name of the file @@ -893,6 +906,7 @@ public class FTP extends Task implements FTPTaskConfig { public String getName() { return ftpFile.getName(); } + /** * find out the absolute path of the file * @return absolute path as string @@ -900,6 +914,7 @@ public class FTP extends Task implements FTPTaskConfig { public String getAbsolutePath() { return getCurpwdPlusFileSep() + ftpFile.getName(); } + /** * find out the relative path assuming that the path used to construct * this AntFTPFile was spelled properly with regards to case. @@ -913,6 +928,7 @@ public class FTP extends Task implements FTPTaskConfig { } return null; } + /** * find out the relative path to the rootPath of the enclosing scanner. * this relative path is spelled exactly like on disk, @@ -939,6 +955,7 @@ public class FTP extends Task implements FTPTaskConfig { } return relativePath; } + /** * get the relative path of this file * @param currentPath base path @@ -946,18 +963,18 @@ public class FTP extends Task implements FTPTaskConfig { * @return relative path */ private String getRelativePath(String currentPath, String currentRelativePath) { - Vector pathElements = SelectorUtils.tokenizePath(getAbsolutePath(), remoteFileSep); - Vector pathElements2 = SelectorUtils.tokenizePath(currentPath, remoteFileSep); + List<String> pathElements = SelectorUtils.tokenizePath(getAbsolutePath(), remoteFileSep); + List<String> pathElements2 = SelectorUtils.tokenizePath(currentPath, remoteFileSep); String relPath = currentRelativePath; final int size = pathElements.size(); for (int pcount = pathElements2.size(); pcount < size; pcount++) { - String currentElement = (String) pathElements.elementAt(pcount); + String currentElement = pathElements.get(pcount); FTPFile[] theFiles = listFiles(currentPath); FTPFile theFile = null; if (theFiles != null) { theFile = getFile(theFiles, currentElement); } - if (!relPath.equals("")) { + if (!"".equals(relPath)) { relPath = relPath + remoteFileSep; } if (theFile == null) { @@ -975,6 +992,7 @@ public class FTP extends Task implements FTPTaskConfig { } return relPath; } + /** * find a file matching a string in an array of FTPFile. * This method will find "alpha" when requested for "ALPHA" @@ -988,19 +1006,13 @@ public class FTP extends Task implements FTPTaskConfig { if (theFiles == null) { return null; } - for (int fcount = 0; fcount < theFiles.length; fcount++) { - if (theFiles[fcount] != null) { - if (theFiles[fcount].getName().equals(lastpathelement)) { - return theFiles[fcount]; - } else if (!isCaseSensitive() - && theFiles[fcount].getName().equalsIgnoreCase( - lastpathelement)) { - return theFiles[fcount]; - } - } - } - return null; + Predicate<String> test = + isCaseSensitive() ? lastpathelement::equals + : lastpathelement::equalsIgnoreCase; + return Stream.of(theFiles).filter(f -> test.test(f.getName())) + .findFirst().orElse(null); } + /** * tell if a file is a directory. * note that it will return false for symbolic links pointing to directories. @@ -1009,6 +1021,7 @@ public class FTP extends Task implements FTPTaskConfig { public boolean isDirectory() { return ftpFile.isDirectory(); } + /** * tell if a file is a symbolic link * @return <code>true</code> for symbolic links @@ -1016,6 +1029,7 @@ public class FTP extends Task implements FTPTaskConfig { public boolean isSymbolicLink() { return ftpFile.isSymbolicLink(); } + /** * return the attached FTP client object. * Warning : this instance is really shared with the enclosing class. @@ -1032,6 +1046,7 @@ public class FTP extends Task implements FTPTaskConfig { protected void setCurpwd(String curpwd) { this.curpwd = curpwd; } + /** * returns the path of the directory containing the AntFTPFile. * of the full path of the file itself in case of AntFTPRootFile @@ -1040,6 +1055,7 @@ public class FTP extends Task implements FTPTaskConfig { public String getCurpwd() { return curpwd; } + /** * returns the path of the directory containing the AntFTPFile. * of the full path of the file itself in case of AntFTPRootFile @@ -1051,6 +1067,7 @@ public class FTP extends Task implements FTPTaskConfig { return curpwd.endsWith(remoteFileSep) ? curpwd : curpwd + remoteFileSep; } + /** * find out if a symbolic link is encountered in the relative path of this file * from rootPath. @@ -1071,16 +1088,19 @@ public class FTP extends Task implements FTPTaskConfig { * Get a string rep of this object. * @return a string containing the pwd and the file. */ + @Override public String toString() { return "AntFtpFile: " + curpwd + "%" + ftpFile; } } + /** * special class to represent the remote directory itself * @since Ant 1.6 */ protected class AntFTPRootFile extends AntFTPFile { private String remotedir; + /** * constructor * @param aclient FTP client @@ -1096,24 +1116,29 @@ public class FTP extends Task implements FTPTaskConfig { throw new BuildException(ioe, getLocation()); } } + /** * find the absolute path * @return absolute path */ + @Override public String getAbsolutePath() { return this.getCurpwd(); } + /** * find out the relative path to root * @return empty string * @throws BuildException actually never * @throws IOException actually never */ + @Override public String getRelativePath() throws BuildException, IOException { return ""; } } } + /** * check FTPFiles to check whether they function as directories too * the FTPFile API seem to make directory and symbolic links incompatible @@ -1124,13 +1149,13 @@ public class FTP extends Task implements FTPTaskConfig { * @since ant 1.6 */ private boolean isFunctioningAsDirectory(FTPClient ftp, String dir, FTPFile file) { - boolean result = false; - String currentWorkingDir = null; if (file.isDirectory()) { return true; - } else if (file.isFile()) { + } + if (file.isFile()) { return false; } + String currentWorkingDir = null; try { currentWorkingDir = ftp.printWorkingDirectory(); } catch (IOException ioe) { @@ -1138,6 +1163,7 @@ public class FTP extends Task implements FTPTaskConfig { + " while checking a symlink", Project.MSG_DEBUG); } + boolean result = false; if (currentWorkingDir != null) { try { result = ftp.changeWorkingDirectory(file.getLink()); @@ -1154,14 +1180,16 @@ public class FTP extends Task implements FTPTaskConfig { Project.MSG_ERR); } finally { if (!comeback) { - throw new BuildException("could not cd back to " + dir //NOSONAR - + " while checking a symlink"); + throw new BuildException( + "could not cd back to %s while checking a symlink", + dir); } } } } return result; } + /** * check FTPFiles to check whether they function as directories too * the FTPFile API seem to make directory and symbolic links incompatible @@ -1174,11 +1202,13 @@ public class FTP extends Task implements FTPTaskConfig { private boolean isFunctioningAsFile(FTPClient ftp, String dir, FTPFile file) { if (file.isDirectory()) { return false; - } else if (file.isFile()) { + } + if (file.isFile()) { return true; } return !isFunctioningAsDirectory(ftp, dir, file); } + /** * Sets the remote directory where files will be placed. This may be a * relative or absolute path, and must be in the path syntax expected by @@ -1190,7 +1220,6 @@ public class FTP extends Task implements FTPTaskConfig { this.remotedir = dir; } - /** * Sets the FTP server to send files to. * @@ -1397,9 +1426,9 @@ public class FTP extends Task implements FTPTaskConfig { * * @throws BuildException if the action is not a valid action. */ + @Deprecated public void setAction(String action) throws BuildException { - log("DEPRECATED - The setAction(String) method has been deprecated." - + " Use setAction(FTP.Action) instead."); + log("DEPRECATED - The setAction(String) method has been deprecated. Use setAction(FTP.Action) instead."); Action a = new Action(); @@ -1468,7 +1497,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setSystemTypeKey(FTPSystemType systemKey) { - if (systemKey != null && !systemKey.getValue().equals("")) { + if (systemKey != null && !"".equals(systemKey.getValue())) { this.systemTypeKey = systemKey; configurationHasBeenSet(); } @@ -1481,7 +1510,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setDefaultDateFormatConfig(String defaultDateFormat) { - if (defaultDateFormat != null && !defaultDateFormat.equals("")) { + if (defaultDateFormat != null && !"".equals(defaultDateFormat)) { this.defaultDateFormatConfig = defaultDateFormat; configurationHasBeenSet(); } @@ -1494,7 +1523,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setRecentDateFormatConfig(String recentDateFormat) { - if (recentDateFormat != null && !recentDateFormat.equals("")) { + if (recentDateFormat != null && !"".equals(recentDateFormat)) { this.recentDateFormatConfig = recentDateFormat; configurationHasBeenSet(); } @@ -1507,7 +1536,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setServerLanguageCodeConfig(LanguageCode serverLanguageCode) { - if (serverLanguageCode != null && !"".equals(serverLanguageCode.getValue())) { + if (serverLanguageCode != null && !serverLanguageCode.getValue().equals("")) { this.serverLanguageCodeConfig = serverLanguageCode; configurationHasBeenSet(); } @@ -1520,7 +1549,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setServerTimeZoneConfig(String serverTimeZoneId) { - if (serverTimeZoneId != null && !serverTimeZoneId.equals("")) { + if (serverTimeZoneId != null && !"".equals(serverTimeZoneId)) { this.serverTimeZoneConfig = serverTimeZoneId; configurationHasBeenSet(); } @@ -1534,7 +1563,7 @@ public class FTP extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setShortMonthNamesConfig(String shortMonthNames) { - if (shortMonthNames != null && !shortMonthNames.equals("")) { + if (shortMonthNames != null && !"".equals(shortMonthNames)) { this.shortMonthNamesConfig = shortMonthNames; configurationHasBeenSet(); } @@ -1558,62 +1587,73 @@ public class FTP extends Task implements FTPTaskConfig { int retries = Integer.parseInt(retriesAllowed); if (retries < Retryable.RETRY_FOREVER) { throw new BuildException( - "Invalid value for retriesAllowed attribute: " - + retriesAllowed); - + "Invalid value for retriesAllowed attribute: %s", + retriesAllowed); } this.retriesAllowed = retries; } catch (NumberFormatException px) { throw new BuildException( - "Invalid value for retriesAllowed attribute: " - + retriesAllowed); - + "Invalid value for retriesAllowed attribute: %s", + retriesAllowed); } - } } + /** * @return Returns the systemTypeKey. */ + @Override public String getSystemTypeKey() { return systemTypeKey.getValue(); } + /** * @return Returns the defaultDateFormatConfig. */ + @Override public String getDefaultDateFormatConfig() { return defaultDateFormatConfig; } + /** * @return Returns the recentDateFormatConfig. */ + @Override public String getRecentDateFormatConfig() { return recentDateFormatConfig; } + /** * @return Returns the serverLanguageCodeConfig. */ + @Override public String getServerLanguageCodeConfig() { return serverLanguageCodeConfig.getValue(); } + /** * @return Returns the serverTimeZoneConfig. */ + @Override public String getServerTimeZoneConfig() { return serverTimeZoneConfig; } + /** * @return Returns the shortMonthNamesConfig. */ + @Override public String getShortMonthNamesConfig() { return shortMonthNamesConfig; } + /** * @return Returns the timestampGranularity. */ Granularity getTimestampGranularity() { return timestampGranularity; } + /** * Sets the timestampGranularity attribute * @param timestampGranularity The timestampGranularity to set. @@ -1624,6 +1664,7 @@ public class FTP extends Task implements FTPTaskConfig { } this.timestampGranularity = timestampGranularity; } + /** * Sets the siteCommand attribute. This attribute * names the command that will be executed if the action @@ -1633,6 +1674,7 @@ public class FTP extends Task implements FTPTaskConfig { public void setSiteCommand(String siteCommand) { this.siteCommand = siteCommand; } + /** * Sets the initialSiteCommand attribute. This attribute * names a site command that will be executed immediately @@ -1670,32 +1712,30 @@ public class FTP extends Task implements FTPTaskConfig { } if ((action == LIST_FILES) && (listing == null)) { - throw new BuildException("listing attribute must be set for list " - + "action!"); + throw new BuildException( + "listing attribute must be set for list action!"); } if (action == MK_DIR && remotedir == null) { - throw new BuildException("remotedir attribute must be set for " - + "mkdir action!"); + throw new BuildException( + "remotedir attribute must be set for mkdir action!"); } if (action == CHMOD && chmod == null) { - throw new BuildException("chmod attribute must be set for chmod " - + "action!"); + throw new BuildException( + "chmod attribute must be set for chmod action!"); } if (action == SITE_CMD && siteCommand == null) { - throw new BuildException("sitecommand attribute must be set for site " - + "action!"); + throw new BuildException( + "sitecommand attribute must be set for site action!"); } - if (this.isConfigurationSet) { try { Class.forName("org.apache.commons.net.ftp.FTPClientConfig"); } catch (ClassNotFoundException e) { throw new BuildException( - "commons-net.jar >= 1.4.0 is required for at least one" - + " of the attributes specified."); + "commons-net.jar >= 1.4.0 is required for at least one of the attributes specified."); } } } @@ -1738,7 +1778,7 @@ public class FTP extends Task implements FTPTaskConfig { ds.scan(); } - String[] dsfiles = null; + String[] dsfiles; if (action == RM_DIR) { dsfiles = ds.getIncludedDirectories(); } else { @@ -1748,12 +1788,11 @@ public class FTP extends Task implements FTPTaskConfig { if ((ds.getBasedir() == null) && ((action == SEND_FILES) || (action == GET_FILES))) { - throw new BuildException("the dir attribute must be set for send " - + "and get actions"); - } else { - if ((action == SEND_FILES) || (action == GET_FILES)) { - dir = ds.getBasedir().getAbsolutePath(); - } + throw new BuildException( + "the dir attribute must be set for send and get actions"); + } + if ((action == SEND_FILES) || (action == GET_FILES)) { + dir = ds.getBasedir().getAbsolutePath(); } // If we are doing a listing, we need the output stream created now. @@ -1774,11 +1813,7 @@ public class FTP extends Task implements FTPTaskConfig { // the trunk does not let itself be removed before the leaves for (int i = dsfiles.length - 1; i >= 0; i--) { final String dsfile = dsfiles[i]; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - rmDir(ftp, dsfile); - } - }, dsfile); + executeRetryable(h, () -> rmDir(ftp, dsfile), dsfile); } } else { final BufferedWriter fbw = bw; @@ -1789,31 +1824,29 @@ public class FTP extends Task implements FTPTaskConfig { } for (int i = 0; i < dsfiles.length; i++) { final String dsfile = dsfiles[i]; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - switch (action) { - case SEND_FILES: - sendFile(ftp, fdir, dsfile); - break; - case GET_FILES: - getFile(ftp, fdir, dsfile); - break; - case DEL_FILES: - delFile(ftp, dsfile); - break; - case LIST_FILES: - listFile(ftp, fbw, dsfile); - break; - case CHMOD: - doSiteCommand(ftp, "chmod " + chmod - + " " + resolveFile(dsfile)); - transferred++; - break; - default: - throw new BuildException("unknown ftp action " + action); - } - } - }, dsfile); + executeRetryable(h, () -> { + switch (action) { + case SEND_FILES: + sendFile(ftp, fdir, dsfile); + break; + case GET_FILES: + getFile(ftp, fdir, dsfile); + break; + case DEL_FILES: + delFile(ftp, dsfile); + break; + case LIST_FILES: + listFile(ftp, fbw, dsfile); + break; + case CHMOD: + doSiteCommand(ftp, "chmod " + chmod + + " " + resolveFile(dsfile)); + transferred++; + break; + default: + throw new BuildException("unknown ftp action " + action); + } + }, dsfile); } } } finally { @@ -1823,7 +1856,6 @@ public class FTP extends Task implements FTPTaskConfig { return dsfiles.length; } - /** * Sends all files specified by the configured filesets to the remote * server. @@ -1838,17 +1870,12 @@ public class FTP extends Task implements FTPTaskConfig { transferred = 0; skipped = 0; - if (filesets.size() == 0) { + if (filesets.isEmpty()) { throw new BuildException("at least one fileset must be specified."); - } else { - // get files from filesets - final int size = filesets.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) filesets.elementAt(i); - - if (fs != null) { - transferFiles(ftp, fs); - } + } + for (FileSet fs : filesets) { + if (fs != null) { + transferFiles(ftp, fs); } } @@ -1860,7 +1887,6 @@ public class FTP extends Task implements FTPTaskConfig { } } - /** * Correct a file path to correspond to the remote host requirements. This * implementation currently assumes that the remote end can handle @@ -1877,7 +1903,6 @@ public class FTP extends Task implements FTPTaskConfig { remoteFileSep.charAt(0)); } - /** * Creates all parent directories specified in a complete relative * pathname. Attempts to create existing directories will not cause @@ -1898,7 +1923,7 @@ public class FTP extends Task implements FTPTaskConfig { return; } - Vector parents = new Vector(); + List<File> parents = new Vector<>(); String dirname; while ((dirname = dir.getParent()) != null) { @@ -1907,7 +1932,7 @@ public class FTP extends Task implements FTPTaskConfig { break; } dir = checkDir; - parents.addElement(dir); + parents.add(dir); } // find first non cached dir @@ -1916,15 +1941,14 @@ public class FTP extends Task implements FTPTaskConfig { if (i >= 0) { String cwd = ftp.printWorkingDirectory(); String parent = dir.getParent(); - if (parent != null) { - if (!ftp.changeWorkingDirectory(resolveFile(parent))) { - throw new BuildException("could not change to " - + "directory: " + ftp.getReplyString()); - } + if (parent != null + && !ftp.changeWorkingDirectory(resolveFile(parent))) { + throw new BuildException("could not change to directory: %s", + ftp.getReplyString()); } while (i >= 0) { - dir = (File) parents.elementAt(i--); + dir = parents.get(i--); // check if dir exists by trying to change into it. if (!ftp.changeWorkingDirectory(dir.getName())) { // could not change to it - try to create it @@ -1934,8 +1958,9 @@ public class FTP extends Task implements FTPTaskConfig { handleMkDirFailure(ftp); } if (!ftp.changeWorkingDirectory(dir.getName())) { - throw new BuildException("could not change to " - + "directory: " + ftp.getReplyString()); + throw new BuildException( + "could not change to directory: %s", + ftp.getReplyString()); } } dirCache.add(dir); @@ -1979,11 +2004,12 @@ public class FTP extends Task implements FTPTaskConfig { } return returnValue; } + /** * find a suitable name for local and remote temporary file */ private File findFileName(FTPClient ftp) { - FTPFile [] theFiles = null; + FTPFile[] theFiles = null; final int maxIterations = 1000; for (int counter = 1; counter < maxIterations; counter++) { File localFile = FILE_UTILS.createTempFile( @@ -2041,10 +2067,9 @@ public class FTP extends Task implements FTPTaskConfig { log("Could not date test remote file: " + remoteFile + "assuming out of date.", Project.MSG_VERBOSE); return false; - } else { - throw new BuildException("could not date test remote file: " - + ftp.getReplyString()); } + throw new BuildException("could not date test remote file: %s", + ftp.getReplyString()); } long remoteTimestamp = files[0].getTimestamp().getTime().getTime(); @@ -2052,38 +2077,36 @@ public class FTP extends Task implements FTPTaskConfig { long adjustedRemoteTimestamp = remoteTimestamp + this.timeDiffMillis + this.granularityMillis; - StringBuffer msg; - synchronized(TIMESTAMP_LOGGING_SDF) { - msg = new StringBuffer(" [") + StringBuilder msg; + synchronized (TIMESTAMP_LOGGING_SDF) { + msg = new StringBuilder(" [") .append(TIMESTAMP_LOGGING_SDF.format(new Date(localTimestamp))) .append("] local"); } log(msg.toString(), Project.MSG_VERBOSE); - synchronized(TIMESTAMP_LOGGING_SDF) { - msg = new StringBuffer(" [") - .append(TIMESTAMP_LOGGING_SDF.format(new Date(adjustedRemoteTimestamp))) + synchronized (TIMESTAMP_LOGGING_SDF) { + msg = new StringBuilder(" [") + .append(TIMESTAMP_LOGGING_SDF + .format(new Date(adjustedRemoteTimestamp))) .append("] remote"); } if (remoteTimestamp != adjustedRemoteTimestamp) { - synchronized(TIMESTAMP_LOGGING_SDF) { + synchronized (TIMESTAMP_LOGGING_SDF) { msg.append(" - (raw: ") - .append(TIMESTAMP_LOGGING_SDF.format(new Date(remoteTimestamp))) + .append( + TIMESTAMP_LOGGING_SDF.format(new Date(remoteTimestamp))) .append(")"); } } log(msg.toString(), Project.MSG_VERBOSE); - - if (this.action == SEND_FILES) { return adjustedRemoteTimestamp >= localTimestamp; - } else { - return localTimestamp >= adjustedRemoteTimestamp; } + return localTimestamp >= adjustedRemoteTimestamp; } - /** * Sends a site command to the ftp server * @param ftp ftp client @@ -2093,28 +2116,20 @@ public class FTP extends Task implements FTPTaskConfig { */ protected void doSiteCommand(FTPClient ftp, String theCMD) throws IOException, BuildException { - boolean rc; - String[] myReply = null; log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE); - rc = ftp.sendSiteCommand(theCMD); - - if (!rc) { + if (!ftp.sendSiteCommand(theCMD)) { log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN); } else { - - myReply = ftp.getReplyStrings(); - - for (int x = 0; x < myReply.length; x++) { - if (myReply[x] != null && myReply[x].indexOf("200") == -1) { - log(myReply[x], Project.MSG_WARN); + for (String reply : ftp.getReplyStrings()) { + if (reply != null && reply.indexOf("200") == -1) { + log(reply, Project.MSG_WARN); } } } } - /** * Sends a single file to the remote host. <code>filename</code> may * contain a relative path specification. When this is the case, <code>sendFile</code> @@ -2179,7 +2194,6 @@ public class FTP extends Task implements FTPTaskConfig { } } - /** * Delete a file from the remote host. * @param ftp ftp client @@ -2259,10 +2273,9 @@ public class FTP extends Task implements FTPTaskConfig { */ protected void getFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException { + File file = getProject().resolveFile(new File(dir, filename).getPath()); OutputStream outstream = null; try { - File file = getProject().resolveFile(new File(dir, filename).getPath()); - if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) { return; } @@ -2310,7 +2323,6 @@ public class FTP extends Task implements FTPTaskConfig { } } - /** * List information about a single file from the remote host. <code>filename</code> * may contain a relative path specification. <p> @@ -2355,41 +2367,41 @@ public class FTP extends Task implements FTPTaskConfig { protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException { String workingDirectory = ftp.printWorkingDirectory(); + boolean absolute = dir.startsWith("/"); if (verbose) { - if (dir.startsWith("/") || workingDirectory == null) { + if (absolute || workingDirectory == null) { log("Creating directory: " + dir + " in /"); } else { log("Creating directory: " + dir + " in " + workingDirectory); } } - if (dir.startsWith("/")) { + if (absolute) { ftp.changeWorkingDirectory("/"); } - String subdir = ""; StringTokenizer st = new StringTokenizer(dir, "/"); while (st.hasMoreTokens()) { - subdir = st.nextToken(); + String subdir = st.nextToken(); log("Checking " + subdir, Project.MSG_DEBUG); if (!ftp.changeWorkingDirectory(subdir)) { - if (!ftp.makeDirectory(subdir)) { + if (ftp.makeDirectory(subdir)) { + if (verbose) { + log("Directory created OK"); + } + ftp.changeWorkingDirectory(subdir); + } else { // codes 521, 550 and 553 can be produced by FTP Servers // to indicate that an attempt to create a directory has // failed because the directory already exists. int rc = ftp.getReplyCode(); - if (!(ignoreNoncriticalErrors - && (rc == CODE_550 || rc == CODE_553 - || rc == CODE_521))) { - throw new BuildException("could not create directory: " - + ftp.getReplyString()); + if (!(ignoreNoncriticalErrors && (rc == CODE_550 + || rc == CODE_553 || rc == CODE_521))) { + throw new BuildException( + "could not create directory: %s", + ftp.getReplyString()); } if (verbose) { log("Directory already exists"); } - } else { - if (verbose) { - log("Directory created OK"); - } - ftp.changeWorkingDirectory(subdir); } } } @@ -2409,8 +2421,8 @@ public class FTP extends Task implements FTPTaskConfig { int rc = ftp.getReplyCode(); if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) { - throw new BuildException("could not create directory: " - + ftp.getReplyString()); + throw new BuildException("could not create directory: %s", + ftp.getReplyString()); } } @@ -2420,6 +2432,7 @@ public class FTP extends Task implements FTPTaskConfig { * @throws BuildException if the task fails or is not configured * correctly. */ + @Override public void execute() throws BuildException { checkAttributes(); @@ -2436,8 +2449,8 @@ public class FTP extends Task implements FTPTaskConfig { ftp.setRemoteVerificationEnabled(enableRemoteVerification); ftp.connect(server, port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("FTP connection failed: " - + ftp.getReplyString()); + throw new BuildException("FTP connection failed: %s", + ftp.getReplyString()); } log("connected", Project.MSG_VERBOSE); @@ -2453,14 +2466,14 @@ public class FTP extends Task implements FTPTaskConfig { if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not set transfer type: " - + ftp.getReplyString()); + throw new BuildException("could not set transfer type: %s", + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not set transfer type: " - + ftp.getReplyString()); + throw new BuildException("could not set transfer type: %s", + ftp.getReplyString()); } } @@ -2468,8 +2481,9 @@ public class FTP extends Task implements FTPTaskConfig { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not enter into passive " - + "mode: " + ftp.getReplyString()); + throw new BuildException( + "could not enter into passive mode: %s", + ftp.getReplyString()); } } @@ -2478,56 +2492,43 @@ public class FTP extends Task implements FTPTaskConfig { // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { - RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, FTP.this.initialSiteCommand); - } - }, "initial site command: " + this.initialSiteCommand); + executeRetryable(new RetryHandler(this.retriesAllowed, this), + () -> doSiteCommand(lftp, FTP.this.initialSiteCommand), + "initial site command: " + this.initialSiteCommand); } - // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { - RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, "umask " + umask); - } - }, "umask " + umask); + executeRetryable(new RetryHandler(this.retriesAllowed, this), + () -> doSiteCommand(lftp, "umask " + umask), + "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { - RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - makeRemoteDir(lftp, remotedir); - } - }, remotedir); + executeRetryable(new RetryHandler(this.retriesAllowed, this), + () -> makeRemoteDir(lftp, remotedir), remotedir); } else if (action == SITE_CMD) { - RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, FTP.this.siteCommand); - } - }, "Site Command: " + this.siteCommand); + executeRetryable(new RetryHandler(this.retriesAllowed, this), + () -> doSiteCommand(lftp, FTP.this.siteCommand), + "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not change remote " - + "directory: " + ftp.getReplyString()); + throw new BuildException( + "could not change remote directory: %s", + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { @@ -2554,7 +2555,6 @@ public class FTP extends Task implements FTPTaskConfig { } } - /** * an action to perform, one of * "send", "put", "recv", "get", "del", "delete", "list", "mkdir", "chmod", @@ -2567,44 +2567,47 @@ public class FTP extends Task implements FTPTaskConfig { "chmod", "rmdir", "site" }; - /** * Get the valid values * * @return an array of the valid FTP actions. */ + @Override public String[] getValues() { return VALID_ACTIONS; } - /** * Get the symbolic equivalent of the action value. * * @return the SYMBOL representing the given action. */ public int getAction() { - String actionL = getValue().toLowerCase(Locale.ENGLISH); - if (actionL.equals("send") || actionL.equals("put")) { + switch (getValue().toLowerCase(Locale.ENGLISH)) { + case "send": + case "put": return SEND_FILES; - } else if (actionL.equals("recv") || actionL.equals("get")) { + case "recv": + case "get": return GET_FILES; - } else if (actionL.equals("del") || actionL.equals("delete")) { + case "del": + case "delete": return DEL_FILES; - } else if (actionL.equals("list")) { + case "list": return LIST_FILES; - } else if (actionL.equals("chmod")) { + case "chmod": return CHMOD; - } else if (actionL.equals("mkdir")) { + case "mkdir": return MK_DIR; - } else if (actionL.equals("rmdir")) { + case "rmdir": return RM_DIR; - } else if (actionL.equals("site")) { + case "site": return SITE_CMD; } return SEND_FILES; } } + /** * represents one of the valid timestamp adjustment values * recognized by the <code>timestampGranularity</code> attribute.<p> @@ -2630,9 +2633,11 @@ public class FTP extends Task implements FTPTaskConfig { * Get the valid values. * @return the list of valid Granularity values */ + @Override public String[] getValues() { return VALID_GRANULARITIES; } + /** * returns the number of milliseconds associated with * the attribute, which can vary in some cases depending @@ -2652,13 +2657,14 @@ public class FTP extends Task implements FTPTaskConfig { } return 0L; } + static final Granularity getDefault() { Granularity g = new Granularity(); g.setValue(""); return g; } - } + /** * one of the valid system type keys recognized by the systemTypeKey * attribute. @@ -2675,6 +2681,7 @@ public class FTP extends Task implements FTPTaskConfig { * Get the valid values. * @return the list of valid system types. */ + @Override public String[] getValues() { return VALID_SYSTEM_TYPES; } @@ -2685,31 +2692,32 @@ public class FTP extends Task implements FTPTaskConfig { return ftpst; } } + /** * Enumerated class for languages. */ public static class LanguageCode extends EnumeratedAttribute { - private static final String[] VALID_LANGUAGE_CODES = getValidLanguageCodes(); private static String[] getValidLanguageCodes() { - Collection c = FTPClientConfig.getSupportedLanguageCodes(); + @SuppressWarnings("unchecked") + Collection<String> c = FTPClientConfig.getSupportedLanguageCodes(); String[] ret = new String[c.size() + 1]; int i = 0; ret[i++] = ""; - for (Iterator it = c.iterator(); it.hasNext(); i++) { - ret[i] = (String) it.next(); + for (String element : c) { + ret[i++] = element; } return ret; } - /** * Return the value values. * @return the list of valid language types. */ + @Override public String[] getValues() { return VALID_LANGUAGE_CODES; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTask.java index aa060ae2a..2e5228d9b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTask.java @@ -83,7 +83,7 @@ public class FTPTask extends Task implements FTPTaskConfig { private long granularityMillis = 0L; private boolean timeDiffAuto = false; private int action = SEND_FILES; - private Vector filesets = new Vector(); + private Vector<FileSet> filesets = new Vector<>(); private String remoteFileSep = "/"; private int port = DEFAULT_FTP_PORT; private boolean skipFailedTransfers = false; @@ -396,7 +396,7 @@ public class FTPTask extends Task implements FTPTaskConfig { filesets.addElement(set); } - public Vector getFilesets() { + public Vector<FileSet> getFilesets() { return filesets; } @@ -415,6 +415,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * * @throws BuildException if the action is not a valid action. */ + @Deprecated public void setAction(String action) throws BuildException { log("DEPRECATED - The setAction(String) method has been deprecated." + " Use setAction(FTP.Action) instead."); @@ -503,7 +504,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setSystemTypeKey(FTPSystemType systemKey) { - if (systemKey != null && !systemKey.getValue().equals("")) { + if (systemKey != null && !"".equals(systemKey.getValue())) { this.systemTypeKey = systemKey; configurationHasBeenSet(); } @@ -516,7 +517,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setDefaultDateFormatConfig(String defaultDateFormat) { - if (defaultDateFormat != null && !defaultDateFormat.equals("")) { + if (defaultDateFormat != null && !"".equals(defaultDateFormat)) { this.defaultDateFormatConfig = defaultDateFormat; configurationHasBeenSet(); } @@ -529,7 +530,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setRecentDateFormatConfig(String recentDateFormat) { - if (recentDateFormat != null && !recentDateFormat.equals("")) { + if (recentDateFormat != null && !"".equals(recentDateFormat)) { this.recentDateFormatConfig = recentDateFormat; configurationHasBeenSet(); } @@ -542,7 +543,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setServerLanguageCodeConfig(String serverLanguageCode) { - if (serverLanguageCode != null && !"".equals(serverLanguageCode)) { + if (serverLanguageCode != null && !serverLanguageCode.equals("")) { this.serverLanguageCodeConfig = serverLanguageCode; configurationHasBeenSet(); } @@ -555,7 +556,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setServerTimeZoneConfig(String serverTimeZoneId) { - if (serverTimeZoneId != null && !serverTimeZoneId.equals("")) { + if (serverTimeZoneId != null && !"".equals(serverTimeZoneId)) { this.serverTimeZoneConfig = serverTimeZoneId; configurationHasBeenSet(); } @@ -569,7 +570,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @see org.apache.commons.net.ftp.FTPClientConfig */ public void setShortMonthNamesConfig(String shortMonthNames) { - if (shortMonthNames != null && !shortMonthNames.equals("")) { + if (shortMonthNames != null && !"".equals(shortMonthNames)) { this.shortMonthNamesConfig = shortMonthNames; configurationHasBeenSet(); } @@ -593,16 +594,14 @@ public class FTPTask extends Task implements FTPTaskConfig { int retries = Integer.parseInt(retriesAllowed); if (retries < Retryable.RETRY_FOREVER) { throw new BuildException( - "Invalid value for retriesAllowed attribute: " - + retriesAllowed); - + "Invalid value for retriesAllowed attribute: %s", + retriesAllowed); } this.retriesAllowed = retries; } catch (NumberFormatException px) { throw new BuildException( - "Invalid value for retriesAllowed attribute: " - + retriesAllowed); - + "Invalid value for retriesAllowed attribute: %s", + retriesAllowed); } } @@ -615,45 +614,58 @@ public class FTPTask extends Task implements FTPTaskConfig { /** * @return Returns the systemTypeKey. */ + @Override public String getSystemTypeKey() { return systemTypeKey.getValue(); } + /** * @return Returns the defaultDateFormatConfig. */ + @Override public String getDefaultDateFormatConfig() { return defaultDateFormatConfig; } + /** * @return Returns the recentDateFormatConfig. */ + @Override public String getRecentDateFormatConfig() { return recentDateFormatConfig; } + /** * @return Returns the serverLanguageCodeConfig. */ + @Override public String getServerLanguageCodeConfig() { return serverLanguageCodeConfig; } + /** * @return Returns the serverTimeZoneConfig. */ + @Override public String getServerTimeZoneConfig() { return serverTimeZoneConfig; } + /** * @return Returns the shortMonthNamesConfig. */ + @Override public String getShortMonthNamesConfig() { return shortMonthNamesConfig; } + /** * @return Returns the timestampGranularity. */ public Granularity getTimestampGranularity() { return timestampGranularity; } + /** * Sets the timestampGranularity attribute * @param timestampGranularity The timestampGranularity to set. @@ -664,6 +676,7 @@ public class FTPTask extends Task implements FTPTaskConfig { } this.timestampGranularity = timestampGranularity; } + /** * Sets the siteCommand attribute. This attribute * names the command that will be executed if the action @@ -731,32 +744,30 @@ public class FTPTask extends Task implements FTPTaskConfig { } if ((action == LIST_FILES) && (listing == null)) { - throw new BuildException("listing attribute must be set for list " - + "action!"); + throw new BuildException( + "listing attribute must be set for list action!"); } if (action == MK_DIR && remotedir == null) { - throw new BuildException("remotedir attribute must be set for " - + "mkdir action!"); + throw new BuildException( + "remotedir attribute must be set for mkdir action!"); } if (action == CHMOD && chmod == null) { - throw new BuildException("chmod attribute must be set for chmod " - + "action!"); + throw new BuildException( + "chmod attribute must be set for chmod action!"); } if (action == SITE_CMD && siteCommand == null) { - throw new BuildException("sitecommand attribute must be set for site " - + "action!"); + throw new BuildException( + "sitecommand attribute must be set for site action!"); } - if (this.isConfigurationSet) { try { Class.forName("org.apache.commons.net.ftp.FTPClientConfig"); } catch (ClassNotFoundException e) { throw new BuildException( - "commons-net.jar >= 1.4.0 is required for at least one" - + " of the attributes specified."); + "commons-net.jar >= 1.4.0 is required for at least one of the attributes specified."); } } } @@ -767,6 +778,7 @@ public class FTPTask extends Task implements FTPTaskConfig { * @throws BuildException if the task fails or is not configured * correctly. */ + @Override public void execute() throws BuildException { checkAttributes(); try { @@ -814,18 +826,21 @@ public class FTPTask extends Task implements FTPTaskConfig { try { loader.loadClass("org.apache.commons.net.ftp.FTP"); // sanity check } catch (ClassNotFoundException e) { - throw new BuildException("The <classpath> for <ftp> must include" - + " commons-net.jar if not in Ant's own " - + " classpath", e, task.getLocation()); + throw new BuildException( + "The <classpath> for <ftp> must include commons-net.jar if not in Ant's own classpath", + e, task.getLocation()); } try { - Class c = loader.loadClass(FTPTaskMirror.class.getName() + "Impl"); + Class<? extends FTPTaskMirror> c = + loader.loadClass(FTPTaskMirror.class.getName() + "Impl") + .asSubclass(FTPTaskMirror.class); if (c.getClassLoader() != loader) { throw new BuildException("Overdelegating loader", - task.getLocation()); + task.getLocation()); } - Constructor cons = c.getConstructor(new Class[] {FTPTask.class}); - return (FTPTaskMirror) cons.newInstance(new Object[] {task}); + Constructor<? extends FTPTaskMirror> cons = + c.getConstructor(FTPTask.class); + return cons.newInstance(task); } catch (Exception e) { throw new BuildException(e, task.getLocation()); } @@ -843,17 +858,16 @@ public class FTPTask extends Task implements FTPTaskConfig { "chmod", "rmdir", "site" }; - /** * Get the valid values * * @return an array of the valid FTP actions. */ + @Override public String[] getValues() { return VALID_ACTIONS; } - /** * Get the symbolic equivalent of the action value. * @@ -861,26 +875,31 @@ public class FTPTask extends Task implements FTPTaskConfig { */ public int getAction() { String actionL = getValue().toLowerCase(Locale.ENGLISH); - if (actionL.equals("send") || actionL.equals("put")) { + switch (actionL) { + case "send": + case "put": return SEND_FILES; - } else if (actionL.equals("recv") || actionL.equals("get")) { + case "recv": + case "get": return GET_FILES; - } else if (actionL.equals("del") || actionL.equals("delete")) { + case "del": + case "delete": return DEL_FILES; - } else if (actionL.equals("list")) { + case "list": return LIST_FILES; - } else if (actionL.equals("chmod")) { + case "chmod": return CHMOD; - } else if (actionL.equals("mkdir")) { + case "mkdir": return MK_DIR; - } else if (actionL.equals("rmdir")) { + case "rmdir": return RM_DIR; - } else if (actionL.equals("site")) { + case "site": return SITE_CMD; } return SEND_FILES; } } + /** * represents one of the valid timestamp adjustment values * recognized by the <code>timestampGranularity</code> attribute.<p> @@ -906,9 +925,11 @@ public class FTPTask extends Task implements FTPTaskConfig { * Get the valid values. * @return the list of valid Granularity values */ + @Override public String[] getValues() { return VALID_GRANULARITIES; } + /** * returns the number of milliseconds associated with * the attribute, which can vary in some cases depending @@ -928,13 +949,14 @@ public class FTPTask extends Task implements FTPTaskConfig { } return 0L; } + static final Granularity getDefault() { Granularity g = new Granularity(); g.setValue(""); return g; } - } + /** * one of the valid system type keys recognized by the systemTypeKey * attribute. @@ -946,11 +968,11 @@ public class FTPTask extends Task implements FTPTaskConfig { "MVS" }; - /** * Get the valid values. * @return the list of valid system types. */ + @Override public String[] getValues() { return VALID_SYSTEM_TYPES; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java index 35f01b355..f546b230b 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/FTPTaskMirrorImpl.java @@ -28,14 +28,16 @@ import java.io.OutputStream; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; @@ -65,7 +67,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); private final FTPTask task; - private Set dirCache = new HashSet(); + private Set<File> dirCache = new HashSet<>(); private int transferred = 0; private int skipped = 0; @@ -83,6 +85,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * */ protected static class FTPFileProxy extends File { + private static final long serialVersionUID = 1L; private final FTPFile file; private final String[] parts; @@ -110,34 +113,34 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { parts = FileUtils.getPathStack(completePath); } - /* (non-Javadoc) * @see java.io.File#exists() */ + @Override public boolean exists() { return true; } - /* (non-Javadoc) * @see java.io.File#getAbsolutePath() */ + @Override public String getAbsolutePath() { return name; } - /* (non-Javadoc) * @see java.io.File#getName() */ + @Override public String getName() { return parts.length > 0 ? parts[parts.length - 1] : name; } - /* (non-Javadoc) * @see java.io.File#getParent() */ + @Override public String getParent() { String result = ""; for(int i = 0; i < parts.length - 1; i++){ @@ -146,53 +149,53 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { return result; } - /* (non-Javadoc) * @see java.io.File#getPath() */ + @Override public String getPath() { return name; } - /** * FTP files are stored as absolute paths * @return true */ + @Override public boolean isAbsolute() { return true; } - /* (non-Javadoc) * @see java.io.File#isDirectory() */ + @Override public boolean isDirectory() { return file == null; } - /* (non-Javadoc) * @see java.io.File#isFile() */ + @Override public boolean isFile() { return file != null; } - /** * FTP files cannot be hidden * * @return false */ + @Override public boolean isHidden() { return false; } - /* (non-Javadoc) * @see java.io.File#lastModified() */ + @Override public long lastModified() { if (file != null) { return file.getTimestamp().getTimeInMillis(); @@ -200,10 +203,10 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { return 0; } - /* (non-Javadoc) * @see java.io.File#length() */ + @Override public long length() { if (file != null) { return file.getSize(); @@ -244,11 +247,11 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { this.setFollowSymlinks(false); } - /** * scans the remote directory, * storing internally the included files, directories, ... */ + @Override public void scan() { if (includes == null) { // No includes supplied, so set it to 'matches all' @@ -259,12 +262,12 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { excludes = new String[0]; } - filesIncluded = new VectorSet(); - filesNotIncluded = new Vector(); - filesExcluded = new VectorSet(); - dirsIncluded = new VectorSet(); - dirsNotIncluded = new Vector(); - dirsExcluded = new VectorSet(); + filesIncluded = new VectorSet<>(); + filesNotIncluded = new Vector<>(); + filesExcluded = new VectorSet<>(); + dirsIncluded = new VectorSet<>(); + dirsNotIncluded = new Vector<>(); + dirsExcluded = new VectorSet<>(); try { String cwd = ftp.printWorkingDirectory(); @@ -279,7 +282,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } - /** * this routine is actually checking all the include patterns in * order to avoid scanning everything under base dir @@ -287,7 +289,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { */ private void checkIncludePatterns() { - Hashtable newroots = new Hashtable(); + Map<String, String> newroots = new Hashtable<>(); // put in the newroots vector the include patterns without // wildcard tokens for (int icounter = 0; icounter < includes.length; icounter++) { @@ -312,75 +314,73 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } else { // only scan directories that can include matched files or // directories - Enumeration enum2 = newroots.keys(); - - while (enum2.hasMoreElements()) { - String currentelement = (String) enum2.nextElement(); - String originalpattern = (String) newroots.get(currentelement); - AntFTPFile myfile = new AntFTPFile(baseFTPFile, currentelement); - boolean isOK = true; - boolean traversesSymlinks = false; - String path = null; - - if (myfile.exists()) { - forceRemoteSensitivityCheck(); - if (remoteSensitivityChecked - && remoteSystemCaseSensitive && isFollowSymlinks()) { - // cool case, - //we do not need to scan all the subdirs in the relative path - path = myfile.getFastRelativePath(); - } else { - // may be on a case insensitive file system. We want - // the results to show what's really on the disk, so - // we need to double check. - try { - path = myfile.getRelativePath(); - traversesSymlinks = myfile.isTraverseSymlinks(); - } catch (IOException be) { - throw new BuildException(be, task.getLocation()); - } catch (BuildException be) { - isOK = false; - } - } - } else { + newroots.forEach( + (k, v) -> scanRoot(new AntFTPFile(baseFTPFile, k), v)); + } + } + + private void scanRoot(AntFTPFile myfile, String originalpattern) { + String currentelement; + boolean isOK = true; + boolean traversesSymlinks = false; + String path = null; + + if (myfile.exists()) { + forceRemoteSensitivityCheck(); + if (remoteSensitivityChecked + && remoteSystemCaseSensitive && isFollowSymlinks()) { + // cool case, + //we do not need to scan all the subdirs in the relative path + path = myfile.getFastRelativePath(); + } else { + // may be on a case insensitive file system. We want + // the results to show what's really on the disk, so + // we need to double check. + try { + path = myfile.getRelativePath(); + traversesSymlinks = myfile.isTraverseSymlinks(); + } catch (IOException be) { + throw new BuildException(be, task.getLocation()); + } catch (BuildException be) { isOK = false; } - if (isOK) { - currentelement = path.replace(task.getSeparator().charAt(0), File.separatorChar); - if (!isFollowSymlinks() - && traversesSymlinks) { - continue; - } + } + } else { + isOK = false; + } + if (isOK) { + currentelement = path.replace(task.getSeparator().charAt(0), File.separatorChar); + if (!isFollowSymlinks() + && traversesSymlinks) { + return; + } - if (myfile.isDirectory()) { - if (isIncluded(currentelement) - && currentelement.length() > 0) { - accountForIncludedDir(currentelement, myfile, true); - } else { - if (currentelement.length() > 0) { - if (currentelement.charAt(currentelement - .length() - 1) - != File.separatorChar) { - currentelement = - currentelement + File.separatorChar; - } - } - scandir(myfile.getAbsolutePath(), currentelement, true); - } - } else { - if (isCaseSensitive - && originalpattern.equals(currentelement)) { - accountForIncludedFile(currentelement); - } else if (!isCaseSensitive - && originalpattern - .equalsIgnoreCase(currentelement)) { - accountForIncludedFile(currentelement); + if (myfile.isDirectory()) { + if (isIncluded(currentelement) + && currentelement.length() > 0) { + accountForIncludedDir(currentelement, myfile, true); + } else { + if (currentelement.length() > 0) { + if (currentelement.charAt(currentelement + .length() - 1) + != File.separatorChar) { + currentelement = + currentelement + File.separatorChar; } } + scandir(myfile.getAbsolutePath(), currentelement, true); } + } else if (isCaseSensitive + && originalpattern.equals(currentelement)) { + accountForIncludedFile(currentelement); + } else if (!isCaseSensitive + && originalpattern + .equalsIgnoreCase(currentelement)) { + accountForIncludedFile(currentelement); } } } + /** * scans a particular directory. populates the scannedDirs cache. * @@ -398,8 +398,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (!ftp.changeWorkingDirectory(dir)) { return; } - String completePath = null; - if (!vpath.equals("")) { + String completePath; + if (!"".equals(vpath)) { completePath = rootPath + task.getSeparator() + vpath.replace(File.separatorChar, task.getSeparator().charAt(0)); } else { @@ -414,8 +414,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { for (int i = 0; i < newfiles.length; i++) { FTPFile file = newfiles[i]; if (file != null - && !file.getName().equals(".") - && !file.getName().equals("..")) { + && !".".equals(file.getName()) + && !"..".equals(file.getName())) { String name = vpath + file.getName(); scannedDirs.put(name, new FTPFileProxy(file)); if (isFunctioningAsDirectory(ftp, dir, file)) { @@ -462,7 +462,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (isIncluded(name)) { if (!isExcluded(name) - && isSelected(name, (File) scannedDirs.get(name))) { + && isSelected(name, scannedDirs.get(name))) { filesIncluded.addElement(name); } else { filesExcluded.addElement(name); @@ -519,19 +519,21 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } } + /** * temporary table to speed up the various scanning methods below * * @since Ant 1.6 */ - private Map fileListMap = new HashMap(); + private Map<String, FTPFile[]> fileListMap = new HashMap<>(); + /** * List of all scanned directories. * * @since Ant 1.6 */ - private Map scannedDirs = new HashMap(); + private Map<String, FTPFileProxy> scannedDirs = new HashMap<>(); /** * Has the directory with the given path relative to the base @@ -552,6 +554,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { fileListMap.clear(); scannedDirs.clear(); } + /** * list the files present in one directory. * @param directory full path on the remote side @@ -563,8 +566,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String currentPath = directory; if (changedir) { try { - boolean result = ftp.changeWorkingDirectory(directory); - if (!result) { + if (!ftp.changeWorkingDirectory(directory)) { return null; } currentPath = ftp.printWorkingDirectory(); @@ -574,9 +576,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } if (fileListMap.containsKey(currentPath)) { task.log("filelist map used in listing files", Project.MSG_DEBUG); - return ((FTPFile[]) fileListMap.get(currentPath)); + return fileListMap.get(currentPath); } - FTPFile[] result = null; + FTPFile[] result; try { result = ftp.listFiles(); } catch (IOException ioe) { @@ -598,6 +600,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } } + /** * cd into one directory and * list the files present in one directory. @@ -607,6 +610,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public FTPFile[] listFiles(String directory) { return listFiles(directory, true); } + private void checkRemoteSensitivity(FTPFile[] array, String directory) { if (array == null) { return; @@ -615,8 +619,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String target = null; for (int icounter = 0; icounter < array.length; icounter++) { if (array[icounter] != null && array[icounter].isDirectory()) { - if (!array[icounter].getName().equals(".") - && !array[icounter].getName().equals("..")) { + if (!".".equals(array[icounter].getName()) + && !"..".equals(array[icounter].getName())) { candidateFound = true; target = fiddleName(array[icounter].getName()); task.log("will try to cd to " @@ -656,8 +660,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { remoteSensitivityChecked = true; } } + private String fiddleName(String origin) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int icounter = 0; icounter < origin.length(); icounter++) { if (Character.isLowerCase(origin.charAt(icounter))) { result.append(Character.toUpperCase(origin.charAt(icounter))); @@ -669,6 +674,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } return result.toString(); } + /** * an AntFTPFile is a representation of a remote file * @since Ant 1.6 @@ -693,6 +699,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { private boolean relativePathCalculated = false; private boolean traversesSymlinks = false; private String relativePath = ""; + /** * constructor * @param client ftp client variable @@ -704,6 +711,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { this.ftpFile = ftpFile; this.curpwd = curpwd; } + /** * other constructor * @param parent the parent file @@ -712,7 +720,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public AntFTPFile(AntFTPFile parent, String path) { this.parent = parent; this.client = parent.client; - Vector pathElements = SelectorUtils.tokenizePath(path); + List<String> pathElements = SelectorUtils.tokenizePath(path); try { boolean result = this.client.changeWorkingDirectory(parent.getAbsolutePath()); //this should not happen, except if parent has been deleted by another process @@ -721,35 +729,35 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } this.curpwd = parent.getAbsolutePath(); } catch (IOException ioe) { - throw new BuildException("could not change working dir to " - + parent.curpwd); + throw new BuildException( + "could not change working dir to %s", parent.curpwd); } final int size = pathElements.size(); for (int fcount = 0; fcount < size - 1; fcount++) { - String currentPathElement = (String) pathElements.elementAt(fcount); + String currentPathElement = pathElements.get(fcount); try { - boolean result = this.client.changeWorkingDirectory(currentPathElement); - if (!result && !isCaseSensitive() - && (remoteSystemCaseSensitive || !remoteSensitivityChecked)) { - currentPathElement = findPathElementCaseUnsensitive(this.curpwd, - currentPathElement); - if (currentPathElement == null) { - return; + if (!this.client.changeWorkingDirectory(currentPathElement)) { + if (!isCaseSensitive() && (remoteSystemCaseSensitive + || !remoteSensitivityChecked)) { + currentPathElement = + findPathElementCaseUnsensitive(this.curpwd, + currentPathElement); + if (currentPathElement == null) { + return; + } } - } else if (!result) { return; } - this.curpwd = getCurpwdPlusFileSep() - + currentPathElement; + this.curpwd = + getCurpwdPlusFileSep() + currentPathElement; } catch (IOException ioe) { - throw new BuildException("could not change working dir to " - + (String) pathElements.elementAt(fcount) - + " from " + this.curpwd); + throw new BuildException( + "could not change working dir to %s from %s", + currentPathElement, this.curpwd); } - } - String lastpathelement = (String) pathElements.elementAt(size - 1); - FTPFile [] theFiles = listFiles(this.curpwd); + String lastpathelement = pathElements.get(size - 1); + FTPFile[] theFiles = listFiles(this.curpwd); this.ftpFile = getFile(theFiles, lastpathelement); } /** @@ -766,10 +774,10 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (theFiles == null) { return null; } - for (int icounter = 0; icounter < theFiles.length; icounter++) { - if (theFiles[icounter] != null - && theFiles[icounter].getName().equalsIgnoreCase(soughtPathElement)) { - return theFiles[icounter].getName(); + for (FTPFile f : theFiles) { + if (f != null + && f.getName().equalsIgnoreCase(soughtPathElement)) { + return f.getName(); } } return null; @@ -779,8 +787,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * @return true if the file exists */ public boolean exists() { - return (ftpFile != null); + return ftpFile != null; } + /** * if the file is a symbolic link, find out to what it is pointing * @return the target of the symbolic link @@ -788,6 +797,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public String getLink() { return ftpFile.getLink(); } + /** * get the name of the file * @return the name of the file @@ -795,6 +805,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public String getName() { return ftpFile.getName(); } + /** * find out the absolute path of the file * @return absolute path as string @@ -802,6 +813,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public String getAbsolutePath() { return getCurpwdPlusFileSep() + ftpFile.getName(); } + /** * find out the relative path assuming that the path used to construct * this AntFTPFile was spelled properly with regards to case. @@ -816,6 +828,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } return null; } + /** * find out the relative path to the rootPath of the enclosing scanner. * this relative path is spelled exactly like on disk, @@ -842,6 +855,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } return relativePath; } + /** * get the relative path of this file * @param currentPath base path @@ -849,19 +863,20 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * @return relative path */ private String getRelativePath(String currentPath, String currentRelativePath) { - Vector pathElements = SelectorUtils.tokenizePath(getAbsolutePath(), task.getSeparator()); - Vector pathElements2 = SelectorUtils.tokenizePath(currentPath, - task.getSeparator()); + List<String> pathElements = SelectorUtils + .tokenizePath(getAbsolutePath(), task.getSeparator()); + List<String> pathElements2 = SelectorUtils + .tokenizePath(currentPath, task.getSeparator()); String relPath = currentRelativePath; final int size = pathElements.size(); for (int pcount = pathElements2.size(); pcount < size; pcount++) { - String currentElement = (String) pathElements.elementAt(pcount); + String currentElement = pathElements.get(pcount); FTPFile[] theFiles = listFiles(currentPath); FTPFile theFile = null; if (theFiles != null) { theFile = getFile(theFiles, currentElement); } - if (!relPath.equals("")) { + if (!"".equals(relPath)) { relPath = relPath + task.getSeparator(); } if (theFile == null) { @@ -881,6 +896,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } return relPath; } + /** * find a file matching a string in an array of FTPFile. * This method will find "alpha" when requested for "ALPHA" @@ -894,19 +910,13 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (theFiles == null) { return null; } - for (int fcount = 0; fcount < theFiles.length; fcount++) { - if (theFiles[fcount] != null) { - if (theFiles[fcount].getName().equals(lastpathelement)) { - return theFiles[fcount]; - } else if (!isCaseSensitive() - && theFiles[fcount].getName().equalsIgnoreCase( - lastpathelement)) { - return theFiles[fcount]; - } - } - } - return null; + Predicate<String> test = + isCaseSensitive() ? lastpathelement::equals + : lastpathelement::equalsIgnoreCase; + return Stream.of(theFiles).filter(f -> test.test(f.getName())) + .findFirst().orElse(null); } + /** * tell if a file is a directory. * note that it will return false for symbolic links pointing to directories. @@ -915,6 +925,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public boolean isDirectory() { return ftpFile.isDirectory(); } + /** * tell if a file is a symbolic link * @return <code>true</code> for symbolic links @@ -922,6 +933,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public boolean isSymbolicLink() { return ftpFile.isSymbolicLink(); } + /** * return the attached FTP client object. * Warning : this instance is really shared with the enclosing class. @@ -938,6 +950,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { protected void setCurpwd(String curpwd) { this.curpwd = curpwd; } + /** * returns the path of the directory containing the AntFTPFile. * of the full path of the file itself in case of AntFTPRootFile @@ -946,6 +959,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { public String getCurpwd() { return curpwd; } + /** * returns the path of the directory containing the AntFTPFile. * of the full path of the file itself in case of AntFTPRootFile @@ -957,6 +971,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String sep = task.getSeparator(); return curpwd.endsWith(sep) ? curpwd : curpwd + sep; } + /** * find out if a symbolic link is encountered in the relative path of this file * from rootPath. @@ -977,16 +992,19 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { * Get a string rep of this object. * @return a string containing the pwd and the file. */ + @Override public String toString() { return "AntFtpFile: " + curpwd + "%" + ftpFile; } } + /** * special class to represent the remote directory itself * @since Ant 1.6 */ protected class AntFTPRootFile extends AntFTPFile { private String remotedir; + /** * constructor * @param aclient FTP client @@ -1002,24 +1020,29 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { throw new BuildException(ioe, task.getLocation()); } } + /** * find the absolute path * @return absolute path */ + @Override public String getAbsolutePath() { return this.getCurpwd(); } + /** * find out the relative path to root * @return empty string * @throws BuildException actually never * @throws IOException actually never */ + @Override public String getRelativePath() throws BuildException, IOException { return ""; } } } + /** * check FTPFiles to check whether they function as directories too * the FTPFile API seem to make directory and symbolic links incompatible @@ -1034,7 +1057,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String currentWorkingDir = null; if (file.isDirectory()) { return true; - } else if (file.isFile()) { + } + if (file.isFile()) { return false; } try { @@ -1060,14 +1084,16 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { Project.MSG_ERR); } finally { if (!comeback) { - throw new BuildException("could not cd back to " + dir //NOSONAR - + " while checking a symlink"); + throw new BuildException( + "could not cd back to %s while checking a symlink", + dir); } } } } return result; } + /** * check FTPFiles to check whether they function as directories too * the FTPFile API seem to make directory and symbolic links incompatible @@ -1080,7 +1106,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { private boolean isFunctioningAsFile(FTPClient ftp, String dir, FTPFile file) { if (file.isDirectory()) { return false; - } else if (file.isFile()) { + } + if (file.isFile()) { return true; } return !isFunctioningAsDirectory(ftp, dir, file); @@ -1099,7 +1126,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { h.execute(r, descr); } - /** * For each file in the fileset, do the appropriate action: send, get, * delete, or list. @@ -1130,16 +1156,17 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } else { dsfiles = ds.getIncludedFiles(); } - String dir = null; if ((ds.getBasedir() == null) - && ((task.getAction() == FTPTask.SEND_FILES) || (task.getAction() == FTPTask.GET_FILES))) { - throw new BuildException("the dir attribute must be set for send " - + "and get actions"); - } else { - if ((task.getAction() == FTPTask.SEND_FILES) || (task.getAction() == FTPTask.GET_FILES)) { - dir = ds.getBasedir().getAbsolutePath(); - } + && ((task.getAction() == FTPTask.SEND_FILES) + || (task.getAction() == FTPTask.GET_FILES))) { + throw new BuildException( + "the dir attribute must be set for send and get actions"); + } + String dir = null; + if ((task.getAction() == FTPTask.SEND_FILES) + || (task.getAction() == FTPTask.GET_FILES)) { + dir = ds.getBasedir().getAbsolutePath(); } // If we are doing a listing, we need the output stream created now. @@ -1160,11 +1187,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { // the trunk does not let itself be removed before the leaves for (int i = dsfiles.length - 1; i >= 0; i--) { final String dsfile = dsfiles[i]; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - rmDir(ftp, dsfile); - } - }, dsfile); + executeRetryable(h, () -> rmDir(ftp, dsfile), dsfile); } } else { final BufferedWriter fbw = bw; @@ -1175,32 +1198,30 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } for (int i = 0; i < dsfiles.length; i++) { final String dsfile = dsfiles[i]; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - switch (task.getAction()) { - case FTPTask.SEND_FILES: - sendFile(ftp, fdir, dsfile); - break; - case FTPTask.GET_FILES: - getFile(ftp, fdir, dsfile); - break; - case FTPTask.DEL_FILES: - delFile(ftp, dsfile); - break; - case FTPTask.LIST_FILES: - listFile(ftp, fbw, dsfile); - break; - case FTPTask.CHMOD: - doSiteCommand(ftp, "chmod " + task.getChmod() + " " - + resolveFile(dsfile)); - transferred++; - break; - default: - throw new BuildException("unknown ftp action " - + task.getAction()); - } - } - }, dsfile); + executeRetryable(h, () -> { + switch (task.getAction()) { + case FTPTask.SEND_FILES: + sendFile(ftp, fdir, dsfile); + break; + case FTPTask.GET_FILES: + getFile(ftp, fdir, dsfile); + break; + case FTPTask.DEL_FILES: + delFile(ftp, dsfile); + break; + case FTPTask.LIST_FILES: + listFile(ftp, fbw, dsfile); + break; + case FTPTask.CHMOD: + doSiteCommand(ftp, "chmod " + task.getChmod() + " " + + resolveFile(dsfile)); + transferred++; + break; + default: + throw new BuildException("unknown ftp action %s", + task.getAction()); + } + }, dsfile); } } } finally { @@ -1227,29 +1248,26 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { transferred = 0; skipped = 0; - if (task.getFilesets().size() == 0) { + if (task.getFilesets().isEmpty()) { throw new BuildException("at least one fileset must be specified."); - } else { - // get files from filesets - final int size = task.getFilesets().size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) task.getFilesets().elementAt(i); - - if (fs != null) { - transferFiles(ftp, fs); - } + } + // get files from filesets + for (FileSet fs : task.getFilesets()) { + if (fs != null) { + transferFiles(ftp, fs); } } - - task.log(transferred + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()] + " " - + FTPTask.COMPLETED_ACTION_STRS[task.getAction()]); + task.log( + transferred + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()] + + " " + FTPTask.COMPLETED_ACTION_STRS[task.getAction()]); if (skipped != 0) { - task.log(skipped + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()] - + " were not successfully " + FTPTask.COMPLETED_ACTION_STRS[task.getAction()]); + task.log( + skipped + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()] + + " were not successfully " + + FTPTask.COMPLETED_ACTION_STRS[task.getAction()]); } } - /** * Correct a file path to correspond to the remote host requirements. This * implementation currently assumes that the remote end can handle @@ -1266,7 +1284,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { task.getSeparator().charAt(0)); } - /** * Creates all parent directories specified in a complete relative * pathname. Attempts to create existing directories will not cause @@ -1287,7 +1304,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { return; } - Vector parents = new Vector(); + Vector<File> parents = new Vector<>(); String dirname; while ((dirname = dir.getParent()) != null) { @@ -1307,13 +1324,14 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { String parent = dir.getParent(); if (parent != null) { if (!ftp.changeWorkingDirectory(resolveFile(parent))) { - throw new BuildException("could not change to " - + "directory: " + ftp.getReplyString()); + throw new BuildException( + "could not change to directory: %s", + ftp.getReplyString()); } } while (i >= 0) { - dir = (File) parents.elementAt(i--); + dir = parents.elementAt(i--); // check if dir exists by trying to change into it. if (!ftp.changeWorkingDirectory(dir.getName())) { // could not change to it - try to create it @@ -1323,8 +1341,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { handleMkDirFailure(ftp); } if (!ftp.changeWorkingDirectory(dir.getName())) { - throw new BuildException("could not change to " - + "directory: " + ftp.getReplyString()); + throw new BuildException( + "could not change to directory: %s", + ftp.getReplyString()); } } dirCache.add(dir); @@ -1332,6 +1351,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { ftp.changeWorkingDirectory(cwd); } } + /** * auto find the time difference between local and remote * @param ftp handle to ftp client @@ -1348,8 +1368,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { BufferedInputStream instream = new BufferedInputStream(Files.newInputStream(tempFile.toPath())); ftp.storeFile(tempFile.getName(), instream); instream.close(); - boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); - if (success) { + if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { FTPFile [] ftpFiles = ftp.listFiles(tempFile.getName()); if (ftpFiles.length == 1) { long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime(); @@ -1368,11 +1387,12 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } return returnValue; } + /** * find a suitable name for local and remote temporary file */ private File findFileName(FTPClient ftp) { - FTPFile [] theFiles = null; + FTPFile[] theFiles = null; final int maxIterations = 1000; for (int counter = 1; counter < maxIterations; counter++) { File localFile = FILE_UTILS.createTempFile( @@ -1430,10 +1450,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { task.log("Could not date test remote file: " + remoteFile + "assuming out of date.", Project.MSG_VERBOSE); return false; - } else { - throw new BuildException("could not date test remote file: " - + ftp.getReplyString()); } + throw new BuildException("could not date test remote file: %s", + ftp.getReplyString()); } long remoteTimestamp = files[0].getTimestamp().getTime().getTime(); @@ -1441,16 +1460,16 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { long adjustedRemoteTimestamp = remoteTimestamp + task.getTimeDiffMillis() + task.getGranularityMillis(); - StringBuffer msg; + StringBuilder msg; synchronized(TIMESTAMP_LOGGING_SDF) { - msg = new StringBuffer(" [") + msg = new StringBuilder(" [") .append(TIMESTAMP_LOGGING_SDF.format(new Date(localTimestamp))) .append("] local"); } task.log(msg.toString(), Project.MSG_VERBOSE); synchronized(TIMESTAMP_LOGGING_SDF) { - msg = new StringBuffer(" [") + msg = new StringBuilder(" [") .append(TIMESTAMP_LOGGING_SDF.format(new Date(adjustedRemoteTimestamp))) .append("] remote"); } @@ -1465,9 +1484,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (task.getAction() == FTPTask.SEND_FILES) { return adjustedRemoteTimestamp >= localTimestamp; - } else { - return localTimestamp >= adjustedRemoteTimestamp; } + return localTimestamp >= adjustedRemoteTimestamp; } @@ -1480,28 +1498,21 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { */ protected void doSiteCommand(FTPClient ftp, String theCMD) throws IOException, BuildException { - boolean rc; - String[] myReply = null; task.log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE); - rc = ftp.sendSiteCommand(theCMD); - - if (!rc) { - task.log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN); + if (!ftp.sendSiteCommand(theCMD)) { + task.log("Failed to issue Site Command: " + theCMD, + Project.MSG_WARN); } else { - - myReply = ftp.getReplyStrings(); - - for (int x = 0; x < myReply.length; x++) { - if (myReply[x].indexOf("200") == -1) { - task.log(myReply[x], Project.MSG_WARN); + for (String reply : ftp.getReplyStrings()) { + if (reply.indexOf("200") == -1) { + task.log(reply, Project.MSG_WARN); } } } } - /** * Sends a single file to the remote host. <code>filename</code> may * contain a relative path specification. When this is the case, <code>sendFile</code> @@ -1540,9 +1551,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { ftp.storeFile(resolveFile(filename), instream); - boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); - - if (!success) { + if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { String s = "could not put file: " + ftp.getReplyString(); if (task.isSkipFailedTransfers()) { @@ -1567,7 +1576,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } - /** * Delete a file from the remote host. * @param ftp ftp client @@ -1628,7 +1636,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } - /** * Retrieve a single file from the remote host. <code>filename</code> may * contain a relative path specification. <p> @@ -1699,7 +1706,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } - /** * List information about a single file from the remote host. <code>filename</code> * may contain a relative path specification. <p> @@ -1728,7 +1734,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } - /** * Create the specified directory on the remote host. * @@ -1754,10 +1759,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (dir.startsWith("/")) { ftp.changeWorkingDirectory("/"); } - String subdir = ""; StringTokenizer st = new StringTokenizer(dir, "/"); while (st.hasMoreTokens()) { - subdir = st.nextToken(); + String subdir = st.nextToken(); task.log("Checking " + subdir, Project.MSG_DEBUG); if (!ftp.changeWorkingDirectory(subdir)) { if (!ftp.makeDirectory(subdir)) { @@ -1804,6 +1808,7 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } + @Override public void doFTP() throws BuildException { FTPClient ftp = null; @@ -1818,8 +1823,8 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification()); ftp.connect(task.getServer(), task.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("FTP connection failed: " - + ftp.getReplyString()); + throw new BuildException("FTP connection failed: %s", + ftp.getReplyString()); } task.log("connected", Project.MSG_VERBOSE); @@ -1835,14 +1840,14 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { if (task.isBinary()) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not set transfer type: " - + ftp.getReplyString()); + throw new BuildException("could not set transfer type: %s", + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not set transfer type: " - + ftp.getReplyString()); + throw new BuildException("could not set transfer type: %s", + ftp.getReplyString()); } } @@ -1850,8 +1855,9 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { task.log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not enter into passive " - + "mode: " + ftp.getReplyString()); + throw new BuildException( + "could not enter into passive mode: %s", + ftp.getReplyString()); } } @@ -1860,55 +1866,46 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { // E.G. switching between a UNIX file system mode and // a legacy file system. if (task.getInitialSiteCommand() != null) { - RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, task.getInitialSiteCommand()); - } - }, "initial site command: " + task.getInitialSiteCommand()); + executeRetryable(new RetryHandler(task.getRetriesAllowed(), task), + () -> doSiteCommand(lftp, task.getInitialSiteCommand()), + "initial site command: " + task.getInitialSiteCommand()); } - // For a unix ftp server you can set the default mask for all files // created. if (task.getUmask() != null) { - RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, "umask " + task.getUmask()); - } - }, "umask " + task.getUmask()); + executeRetryable( + new RetryHandler(task.getRetriesAllowed(), task), + () -> doSiteCommand(lftp, "umask " + task.getUmask()), + "umask " + task.getUmask()); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (task.getAction() == FTPTask.MK_DIR) { - RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - makeRemoteDir(lftp, task.getRemotedir()); - } - }, task.getRemotedir()); + executeRetryable( + new RetryHandler(task.getRetriesAllowed(), task), + () -> makeRemoteDir(lftp, task.getRemotedir()), + task.getRemotedir()); } else if (task.getAction() == FTPTask.SITE_CMD) { - RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; - executeRetryable(h, new Retryable() { - public void execute() throws IOException { - doSiteCommand(lftp, task.getSiteCommand()); - } - }, "Site Command: " + task.getSiteCommand()); + executeRetryable( + new RetryHandler(task.getRetriesAllowed(), task), + () -> doSiteCommand(lftp, task.getSiteCommand()), + "Site Command: " + task.getSiteCommand()); } else { if (task.getRemotedir() != null) { task.log("changing the remote directory", Project.MSG_VERBOSE); ftp.changeWorkingDirectory(task.getRemotedir()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { - throw new BuildException("could not change remote " - + "directory: " + ftp.getReplyString()); + throw new BuildException( + "could not change remote directory: %s", + ftp.getReplyString()); } } if (task.isNewer() && task.isTimeDiffAuto()) { @@ -1919,7 +1916,6 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { task.log(FTPTask.ACTION_STRS[task.getAction()] + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()]); transferFiles(ftp); } - } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { @@ -1935,4 +1931,3 @@ public class FTPTaskMirrorImpl implements FTPTaskMirror { } } } - diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/MimeMail.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/MimeMail.java index fca4215e0..01db77a93 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/MimeMail.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/MimeMail.java @@ -28,12 +28,14 @@ import org.apache.tools.ant.taskdefs.email.EmailTask; * * @since Ant1.4 */ +@Deprecated public class MimeMail extends EmailTask { /** * Executes this build task. * * @exception BuildException On error. */ + @Override public void execute() throws BuildException { log("DEPRECATED - The " + getTaskName() + " task is deprecated. " diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/RExecTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/RExecTask.java index d88874f25..ff24bebfd 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/RExecTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/RExecTask.java @@ -22,7 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; -import java.util.Enumeration; +import java.util.List; import java.util.Vector; import org.apache.commons.net.bsd.RExecClient; @@ -68,7 +68,7 @@ public class RExecTask extends Task { /** * The list of read/write commands for this session */ - private Vector rexecTasks = new Vector(); + private List<RExecSubTask> rexecTasks = new Vector<>(); /** * If true, adds a CR to beginning of login script @@ -97,7 +97,7 @@ public class RExecTask extends Task { */ public void execute(AntRExecClient rexec) throws BuildException { - throw new BuildException("Shouldn't be able instantiate a SubTask directly"); + throw new BuildException("Shouldn't be able to instantiate a SubTask directly"); } /** @@ -127,6 +127,7 @@ public class RExecTask extends Task { * @param rexec the task to use * @throws BuildException on error */ + @Override public void execute(AntRExecClient rexec) throws BuildException { rexec.sendString(taskString, echoString); @@ -153,6 +154,7 @@ public class RExecTask extends Task { * @param rexec the task to use * @throws BuildException on error */ + @Override public void execute(AntRExecClient rexec) throws BuildException { rexec.waitForString(taskString, timeout); @@ -202,7 +204,7 @@ public class RExecTask extends Task { public void waitForString(String s, Integer timeout) { InputStream is = this.getInputStream(); try { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int windowStart = -s.length(); if (timeout == null || timeout.intValue() == 0) { while (windowStart < 0 @@ -253,6 +255,7 @@ public class RExecTask extends Task { throw new BuildException(e, getLocation()); } } + /** * Read from the rexec session until the EOF is found or * the timeout has been reached @@ -261,15 +264,15 @@ public class RExecTask extends Task { public void waitForEOF(Integer timeout) { InputStream is = this.getInputStream(); try { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (timeout == null || timeout.intValue() == 0) { int read; while ((read = is.read()) != -1) { char c = (char) read; sb.append(c); if (c == '\n') { - log(sb.toString(), Project.MSG_INFO); - sb.delete(0, sb.length()); + log(sb.toString(), Project.MSG_INFO); + sb.delete(0, sb.length()); } } } else { @@ -281,24 +284,24 @@ public class RExecTask extends Task { Thread.sleep(PAUSE_TIME); } if (is.available() == 0) { - log(sb.toString(), Project.MSG_INFO); - throw new BuildException( - "Response timed-out waiting for EOF", - getLocation()); + log(sb.toString(), Project.MSG_INFO); + throw new BuildException( + "Response timed-out waiting for EOF", + getLocation()); } read = is.read(); if (read != -1) { - char c = (char) read; - sb.append(c); - if (c == '\n') { + char c = (char) read; + sb.append(c); + if (c == '\n') { log(sb.toString(), Project.MSG_INFO); sb.delete(0, sb.length()); - } + } } } } if (sb.length() > 0) { - log(sb.toString(), Project.MSG_INFO); + log(sb.toString(), Project.MSG_INFO); } } catch (BuildException be) { throw be; @@ -306,8 +309,8 @@ public class RExecTask extends Task { throw new BuildException(e, getLocation()); } } - } + /** * A string to wait for from the server. * A subTask <read> tag was found. Create the object, @@ -316,10 +319,11 @@ public class RExecTask extends Task { */ public RExecSubTask createRead() { - RExecSubTask task = (RExecSubTask) new RExecRead(); - rexecTasks.addElement(task); + RExecSubTask task = new RExecRead(); + rexecTasks.add(task); return task; } + /** * Add text to send to the server * A subTask <write> tag was found. Create the object, @@ -327,16 +331,18 @@ public class RExecTask extends Task { * @return a write sub task */ public RExecSubTask createWrite() { - RExecSubTask task = (RExecSubTask) new RExecWrite(); - rexecTasks.addElement(task); + RExecSubTask task = new RExecWrite(); + rexecTasks.add(task); return task; } + /** * Verify that all parameters are included. * Connect and possibly login. * Iterate through the list of Reads and writes. * @throws BuildException on error */ + @Override public void execute() throws BuildException { /** A server name is required to continue */ if (server == null) { @@ -363,7 +369,7 @@ public class RExecTask extends Task { throw new BuildException("Can't connect to " + server); } if (userid != null && password != null && command != null //NOSONAR - && rexecTasks.size() == 0) { + && rexecTasks.isEmpty()) { // simple one-shot execution rexec.rexec(userid, password, command); } else { @@ -384,13 +390,14 @@ public class RExecTask extends Task { String msg = "Error disconnecting from " + server; if (success) { throw new BuildException(msg); //NOSONAR - } else { // don't hide inner exception - log(msg, Project.MSG_ERR); } + // don't hide inner exception + log(msg, Project.MSG_ERR); } } } } + /** * Process a 'typical' login. If it differs, use the read * and write tasks explicitly @@ -404,6 +411,7 @@ public class RExecTask extends Task { rexec.waitForString("assword:"); rexec.sendString(password, false); } + /** * Set the the command to execute on the server; * @param c a <code>String</code> value @@ -419,6 +427,7 @@ public class RExecTask extends Task { public void setInitialCR(boolean b) { this.addCarriageReturn = b; } + /** * Set the the login password to use * required if <tt>userid</tt> is set. @@ -452,6 +461,7 @@ public class RExecTask extends Task { public void setTimeout(Integer i) { this.defaultTimeout = i; } + /** * Set the the login id to use on the server; * required if <tt>password</tt> is set. @@ -473,9 +483,7 @@ public class RExecTask extends Task { login(rexec); } /** Process each sub command */ - Enumeration tasksToRun = rexecTasks.elements(); - while (tasksToRun != null && tasksToRun.hasMoreElements()) { - RExecSubTask task = (RExecSubTask) tasksToRun.nextElement(); + for (RExecSubTask task : rexecTasks) { if (task instanceof RExecRead && defaultTimeout != null) { ((RExecRead) task).setDefaultTimeout(defaultTimeout); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/SetProxy.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/SetProxy.java index 1e1f65910..748afcf97 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/SetProxy.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/SetProxy.java @@ -175,7 +175,6 @@ public class SetProxy extends Task { * apply to all network connections * Relevant docs: buglist #4183340 */ - public void applyWebProxySettings() { boolean settingsChanged = false; boolean enablingProxy = false; @@ -261,6 +260,7 @@ public class SetProxy extends Task { * * @exception BuildException thrown in unrecoverable error. */ + @Override public void execute() throws BuildException { applyWebProxySettings(); } @@ -275,6 +275,7 @@ public class SetProxy extends Task { auth = new PasswordAuthentication(user, pass.toCharArray()); } + @Override protected PasswordAuthentication getPasswordAuthentication() { return auth; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/net/TelnetTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/net/TelnetTask.java index a89e7a9c8..412ef93a9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/net/TelnetTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/net/TelnetTask.java @@ -22,7 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; -import java.util.Enumeration; +import java.util.List; import java.util.Vector; import org.apache.commons.net.telnet.TelnetClient; @@ -34,7 +34,6 @@ import org.apache.tools.ant.Task; * Automates the telnet protocol. * */ - public class TelnetTask extends Task { private static final int WAIT_INTERVAL = 250; private static final int TELNET_PORT = 23; @@ -62,7 +61,7 @@ public class TelnetTask extends Task { /** * The list of read/write commands for this session */ - private Vector telnetTasks = new Vector(); + private List<TelnetSubTask> telnetTasks = new Vector<>(); /** * If true, adds a CR to beginning of login script @@ -81,6 +80,7 @@ public class TelnetTask extends Task { * Iterate through the list of Reads and writes * @throws BuildException on error */ + @Override public void execute() throws BuildException { /** A server name is required to continue */ if (server == null) { @@ -111,9 +111,7 @@ public class TelnetTask extends Task { login(telnet); } /** Process each sub command */ - Enumeration tasksToRun = telnetTasks.elements(); - while (tasksToRun != null && tasksToRun.hasMoreElements()) { - TelnetSubTask task = (TelnetSubTask) tasksToRun.nextElement(); + for (TelnetSubTask task : telnetTasks) { if (task instanceof TelnetRead && defaultTimeout != null) { ((TelnetRead) task).setDefaultTimeout(defaultTimeout); } @@ -209,8 +207,8 @@ public class TelnetTask extends Task { */ public TelnetSubTask createRead() { - TelnetSubTask task = (TelnetSubTask) new TelnetRead(); - telnetTasks.addElement(task); + TelnetSubTask task = new TelnetRead(); + telnetTasks.add(task); return task; } @@ -221,8 +219,8 @@ public class TelnetTask extends Task { * @return a write telnet sub task */ public TelnetSubTask createWrite() { - TelnetSubTask task = (TelnetSubTask) new TelnetWrite(); - telnetTasks.addElement(task); + TelnetSubTask task = new TelnetWrite(); + telnetTasks.add(task); return task; } @@ -271,6 +269,7 @@ public class TelnetTask extends Task { * @param telnet the task to use * @throws BuildException on error */ + @Override public void execute(AntTelnetClient telnet) throws BuildException { telnet.sendString(taskString, echoString); @@ -297,6 +296,7 @@ public class TelnetTask extends Task { * @param telnet the task to use * @throws BuildException on error */ + @Override public void execute(AntTelnetClient telnet) throws BuildException { telnet.waitForString(taskString, timeout); @@ -346,7 +346,7 @@ public class TelnetTask extends Task { public void waitForString(String s, Integer timeout) { InputStream is = this.getInputStream(); try { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int windowStart = -s.length(); if (timeout == null || timeout.intValue() == 0) { while (windowStart < 0 diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/Pvcs.java b/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/Pvcs.java index 7bcfef93b..9d844a157 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/Pvcs.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/Pvcs.java @@ -28,7 +28,6 @@ import java.io.OutputStream; import java.nio.file.Files; import java.text.MessageFormat; import java.text.ParseException; -import java.util.Enumeration; import java.util.Random; import java.util.Vector; @@ -79,10 +78,20 @@ public class Pvcs extends org.apache.tools.ant.Task { private static final int POS_2 = 2; private static final int POS_3 = 3; + /** + * Constant for the thing to execute + */ + private static final String PCLI_EXE = "pcli"; + + /** + * Constant for the thing to execute + */ + private static final String GET_EXE = "get"; + private String pvcsbin; private String repository; private String pvcsProject; - private Vector pvcsProjects; + private Vector<PvcsProject> pvcsProjects; private String workspace; private String force; private String promotiongroup; @@ -94,21 +103,25 @@ public class Pvcs extends org.apache.tools.ant.Task { private String lineStart; private String userId; private String config; - /** - * Constant for the thing to execute - */ - private static final String PCLI_EXE = "pcli"; - - /* - * Constant for the PCLI listversionedfiles recursive i a format "get" understands - */ - // private static final String PCLI_LVF_ARGS = "lvf -z -aw"; /** - * Constant for the thing to execute + * Creates a Pvcs object */ - private static final String GET_EXE = "get"; - + public Pvcs() { + super(); + pvcsProject = null; + pvcsProjects = new Vector<>(); + workspace = null; + repository = null; + pvcsbin = null; + force = null; + promotiongroup = null; + label = null; + ignorerc = false; + updateOnly = false; + lineStart = "\"P:"; + filenameFormat = "{0}-arc({1})"; + } /** * Run the command. @@ -124,7 +137,7 @@ public class Pvcs extends org.apache.tools.ant.Task { exe.setWorkingDirectory(aProj.getBaseDir()); exe.setCommandline(cmd.getCommandline()); return exe.execute(); - } catch (java.io.IOException e) { + } catch (IOException e) { String msg = "Failed executing: " + cmd.toString() + ". Exception: " + e.getMessage(); throw new BuildException(msg, getLocation()); @@ -132,7 +145,7 @@ public class Pvcs extends org.apache.tools.ant.Task { } private String getExecutable(String exe) { - StringBuffer correctedExe = new StringBuffer(); + StringBuilder correctedExe = new StringBuilder(); if (getPvcsbin() != null) { if (pvcsbin.endsWith(File.separator)) { correctedExe.append(pvcsbin); @@ -146,10 +159,11 @@ public class Pvcs extends org.apache.tools.ant.Task { /** * @exception org.apache.tools.ant.BuildException Something is stopping the build... */ - public void execute() throws org.apache.tools.ant.BuildException { + @Override + public void execute() throws BuildException { int result = 0; - if (repository == null || repository.trim().equals("")) { + if (repository == null || repository.trim().isEmpty()) { throw new BuildException("Required argument repository not specified"); } @@ -183,12 +197,11 @@ public class Pvcs extends org.apache.tools.ant.Task { commandLine.createArgument().setValue(getPvcsproject()); } if (!getPvcsprojects().isEmpty()) { - Enumeration e = getPvcsprojects().elements(); - while (e.hasMoreElements()) { - String projectName = ((PvcsProject) e.nextElement()).getName(); - if (projectName == null || (projectName.trim()).equals("")) { - throw new BuildException("name is a required attribute " - + "of pvcsproject"); + for (PvcsProject pvcsProject : getPvcsprojects()) { + String projectName = pvcsProject.getName(); + if (projectName == null || projectName.trim().isEmpty()) { + throw new BuildException( + "name is a required attribute of pvcsproject"); } commandLine.createArgument().setValue(projectName); } @@ -298,9 +311,7 @@ public class Pvcs extends org.apache.tools.ant.Task { * Parses the file and creates the folders specified in the output section */ private void createFolders(File file) throws IOException, ParseException { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); + try (BufferedReader in = new BufferedReader(new FileReader(file))) { MessageFormat mf = new MessageFormat(getFilenameFormat()); String line = in.readLine(); while (line != null) { @@ -318,7 +329,10 @@ public class Pvcs extends org.apache.tools.ant.Task { int index = f.lastIndexOf(File.separator); if (index > -1) { File dir = new File(f.substring(0, index)); - if (!dir.exists()) { + if (dir.exists()) { + log(dir.getAbsolutePath() + " exists. Skipping", + Project.MSG_VERBOSE); + } else { log("Creating " + dir.getAbsolutePath(), Project.MSG_VERBOSE); if (dir.mkdirs() || dir.isDirectory()) { @@ -329,9 +343,6 @@ public class Pvcs extends org.apache.tools.ant.Task { + dir.getAbsolutePath(), Project.MSG_INFO); } - } else { - log(dir.getAbsolutePath() + " exists. Skipping", - Project.MSG_VERBOSE); } } else { log("File separator problem with " + line, @@ -342,8 +353,6 @@ public class Pvcs extends org.apache.tools.ant.Task { } line = in.readLine(); } - } finally { - FileUtils.close(in); } } @@ -355,20 +364,14 @@ public class Pvcs extends org.apache.tools.ant.Task { */ private void massagePCLI(File in, File out) throws IOException { - BufferedReader inReader = null; - BufferedWriter outWriter = null; - try { - inReader = new BufferedReader(new FileReader(in)); - outWriter = new BufferedWriter(new FileWriter(out)); - String s = null; - while ((s = inReader.readLine()) != null) { - String sNormal = s.replace('\\', '/'); - outWriter.write(sNormal); + try (BufferedReader inReader = new BufferedReader(new FileReader(in)); + BufferedWriter outWriter = + new BufferedWriter(new FileWriter(out))) { + for (String line : (Iterable<String>) () -> inReader.lines() + .map(s -> s.replace('\\', '/')).iterator()) { + outWriter.write(line); outWriter.newLine(); } - } finally { - FileUtils.close(inReader); - FileUtils.close(outWriter); } } @@ -458,7 +461,7 @@ public class Pvcs extends org.apache.tools.ant.Task { * Get name of the project in the PVCS repository * @return Vector */ - public Vector getPvcsprojects() { + public Vector<PvcsProject> getPvcsprojects() { return pvcsProjects; } @@ -523,11 +526,7 @@ public class Pvcs extends org.apache.tools.ant.Task { * @param f String (yes/no) */ public void setForce(String f) { - if (f != null && f.equalsIgnoreCase("yes")) { - force = "yes"; - } else { - force = "no"; - } + force = "yes".equalsIgnoreCase(f) ? "yes" : "no"; } /** @@ -654,23 +653,5 @@ public class Pvcs extends org.apache.tools.ant.Task { userId = u; } - /** - * Creates a Pvcs object - */ - public Pvcs() { - super(); - pvcsProject = null; - pvcsProjects = new Vector(); - workspace = null; - repository = null; - pvcsbin = null; - force = null; - promotiongroup = null; - label = null; - ignorerc = false; - updateOnly = false; - lineStart = "\"P:"; - filenameFormat = "{0}-arc({1})"; - } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/PvcsProject.java b/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/PvcsProject.java index a8c6a2a14..8f0aed799 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/PvcsProject.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/pvcs/PvcsProject.java @@ -26,11 +26,6 @@ package org.apache.tools.ant.taskdefs.optional.pvcs; public class PvcsProject { private String name; - /** no arg constructor */ - public PvcsProject() { - super(); - } - /** * Set the name of the project * @param name the value to use. diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDef.java b/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDef.java index 7e62549ee..35d873cc8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDef.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDef.java @@ -21,7 +21,6 @@ import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -54,21 +53,22 @@ public class ScriptDef extends DefBase { private String name; /** Attributes definitions of this script */ - private List attributes = new ArrayList(); + private List<Attribute> attributes = new ArrayList<>(); /** Nested Element definitions of this script */ - private List nestedElements = new ArrayList(); + private List<NestedElement> nestedElements = new ArrayList<>(); /** The attribute names as a set */ - private Set attributeSet; + private Set<String> attributeSet; /** The nested element definitions indexed by their names */ - private Map nestedElementMap; + private Map<String, NestedElement> nestedElementMap; /** * Set the project. * @param project the project that this definition belongs to. */ + @Override public void setProject(Project project) { super.setProject(project); helper.setProjectComponent(this); @@ -181,20 +181,21 @@ public class ScriptDef extends DefBase { /** * Defines the script. */ + @Override public void execute() { if (name == null) { - throw new BuildException("scriptdef requires a name attribute to " - + "name the script"); + throw new BuildException( + "scriptdef requires a name attribute to name the script"); } if (helper.getLanguage() == null) { - throw new BuildException("scriptdef requires a language attribute " - + "to specify the script language"); + throw new BuildException( + "scriptdef requires a language attribute to specify the script language"); } if (helper.getSrc() == null && helper.getEncoding() != null) { - throw new BuildException("scriptdef requires a src attribute " - + "if the encoding is set"); + throw new BuildException( + "scriptdef requires a src attribute if the encoding is set"); } // Check if need to set the loader @@ -202,51 +203,47 @@ public class ScriptDef extends DefBase { helper.setClassLoader(createLoader()); } - attributeSet = new HashSet(); - for (Iterator i = attributes.iterator(); i.hasNext();) { - Attribute attribute = (Attribute) i.next(); + attributeSet = new HashSet<>(); + for (Attribute attribute : attributes) { if (attribute.name == null) { - throw new BuildException("scriptdef <attribute> elements " - + "must specify an attribute name"); + throw new BuildException( + "scriptdef <attribute> elements must specify an attribute name"); } - if (attributeSet.contains(attribute.name)) { - throw new BuildException("scriptdef <" + name + "> declares " - + "the " + attribute.name + " attribute more than once"); + throw new BuildException( + "scriptdef <%s> declares the %s attribute more than once", + name, attribute.name); } attributeSet.add(attribute.name); } - nestedElementMap = new HashMap(); - for (Iterator i = nestedElements.iterator(); i.hasNext();) { - NestedElement nestedElement = (NestedElement) i.next(); + nestedElementMap = new HashMap<>(); + for (NestedElement nestedElement : nestedElements) { if (nestedElement.name == null) { - throw new BuildException("scriptdef <element> elements " - + "must specify an element name"); + throw new BuildException( + "scriptdef <element> elements must specify an element name"); } if (nestedElementMap.containsKey(nestedElement.name)) { - throw new BuildException("scriptdef <" + name + "> declares " - + "the " + nestedElement.name + " nested element more " - + "than once"); + throw new BuildException( + "scriptdef <%s> declares the %s nested element more than once", + name, nestedElement.name); } if (nestedElement.className == null && nestedElement.type == null) { - throw new BuildException("scriptdef <element> elements " - + "must specify either a classname or type attribute"); + throw new BuildException( + "scriptdef <element> elements must specify either a classname or type attribute"); } if (nestedElement.className != null && nestedElement.type != null) { - throw new BuildException("scriptdef <element> elements " - + "must specify only one of the classname and type " - + "attributes"); + throw new BuildException( + "scriptdef <element> elements must specify only one of the classname and type attributes"); } - nestedElementMap.put(nestedElement.name, nestedElement); } // find the script repository - it is stored in the project - Map scriptRepository = lookupScriptRepository(); + Map<String, ScriptDef> scriptRepository = lookupScriptRepository(); name = ProjectHelper.genComponentName(getURI(), name); scriptRepository.put(name, this); AntTypeDefinition def = new AntTypeDefinition(); @@ -261,14 +258,14 @@ public class ScriptDef extends DefBase { * This method is synchronized on the project under {@link MagicNames#SCRIPT_REPOSITORY} * @return the current script repository registered as a reference. */ - private Map lookupScriptRepository() { - Map scriptRepository = null; + private Map<String, ScriptDef> lookupScriptRepository() { + Map<String, ScriptDef> scriptRepository; Project p = getProject(); synchronized (p) { scriptRepository = - (Map) p.getReference(MagicNames.SCRIPT_REPOSITORY); + p.getReference(MagicNames.SCRIPT_REPOSITORY); if (scriptRepository == null) { - scriptRepository = new HashMap(); + scriptRepository = new HashMap<>(); p.addReference(MagicNames.SCRIPT_REPOSITORY, scriptRepository); } @@ -283,14 +280,14 @@ public class ScriptDef extends DefBase { * @return object representing the element name. */ public Object createNestedElement(String elementName) { - NestedElement definition - = (NestedElement) nestedElementMap.get(elementName); + NestedElement definition = nestedElementMap.get(elementName); if (definition == null) { - throw new BuildException("<" + name + "> does not support " - + "the <" + elementName + "> nested element"); + throw new BuildException( + "<%s> does not support the <%s> nested element", name, + elementName); } - Object instance = null; + Object instance; String classname = definition.className; if (classname == null) { instance = getProject().createTask(definition.type); @@ -298,11 +295,6 @@ public class ScriptDef extends DefBase { instance = getProject().createDataType(definition.type); } } else { - /* - // try the context classloader - ClassLoader loader - = Thread.currentThread().getContextClassLoader(); - */ ClassLoader loader = createLoader(); try { @@ -310,13 +302,13 @@ public class ScriptDef extends DefBase { } catch (BuildException e) { instance = ClasspathUtils.newInstance(classname, ScriptDef.class.getClassLoader()); } - getProject().setProjectReference(instance); } if (instance == null) { - throw new BuildException("<" + name + "> is unable to create " - + "the <" + elementName + "> nested element"); + throw new BuildException( + "<%s> is unable to create the <%s> nested element", name, + elementName); } return instance; } @@ -329,7 +321,9 @@ public class ScriptDef extends DefBase { * @deprecated since 1.7. * Use executeScript(attribute, elements, instance) instead. */ - public void executeScript(Map attributes, Map elements) { + @Deprecated + public void executeScript(Map<String, String> attributes, + Map<String, List<Object>> elements) { executeScript(attributes, elements, null); } @@ -342,7 +336,8 @@ public class ScriptDef extends DefBase { * @param elements a list of nested element values. * @param instance the script instance; can be null */ - public void executeScript(Map attributes, Map elements, ScriptDefBase instance) { + public void executeScript(Map<String, String> attributes, + Map<String, List<Object>> elements, ScriptDefBase instance) { ScriptRunnerBase runner = helper.getScriptRunner(); runner.addBean("attributes", attributes); runner.addBean("elements", elements); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDefBase.java b/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDefBase.java index 95d15aa6b..a4a0bd610 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDefBase.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/script/ScriptDefBase.java @@ -36,10 +36,10 @@ import org.apache.tools.ant.Task; public class ScriptDefBase extends Task implements DynamicConfigurator { /** Nested elements */ - private Map nestedElementMap = new HashMap(); + private Map<String, List<Object>> nestedElementMap = new HashMap<>(); /** Attributes */ - private Map attributes = new HashMap(); + private Map<String, String> attributes = new HashMap<>(); private String text; @@ -47,19 +47,20 @@ public class ScriptDefBase extends Task implements DynamicConfigurator { * Locate the script defining task and execute the script by passing * control to it */ + @Override public void execute() { getScript().executeScript(attributes, nestedElementMap, this); } private ScriptDef getScript() { String name = getTaskType(); - Map scriptRepository - = (Map) getProject().getReference(MagicNames.SCRIPT_REPOSITORY); + Map<String, ScriptDef> scriptRepository = + getProject().getReference(MagicNames.SCRIPT_REPOSITORY); if (scriptRepository == null) { throw new BuildException("Script repository not found for " + name); } - ScriptDef definition = (ScriptDef) scriptRepository.get(getTaskType()); + ScriptDef definition = scriptRepository.get(getTaskType()); if (definition == null) { throw new BuildException("Script definition not found for " + name); } @@ -72,12 +73,10 @@ public class ScriptDefBase extends Task implements DynamicConfigurator { * @param name the nested element name * @return the element to be configured */ + @Override public Object createDynamicElement(String name) { - List nestedElementList = (List) nestedElementMap.get(name); - if (nestedElementList == null) { - nestedElementList = new ArrayList(); - nestedElementMap.put(name, nestedElementList); - } + List<Object> nestedElementList = + nestedElementMap.computeIfAbsent(name, k -> new ArrayList<>()); Object element = getScript().createNestedElement(name); nestedElementList.add(element); return element; @@ -89,13 +88,14 @@ public class ScriptDefBase extends Task implements DynamicConfigurator { * @param name the attribute name. * @param value the attribute's string value */ + @Override public void setDynamicAttribute(String name, String value) { ScriptDef definition = getScript(); if (!definition.isAttributeSupported(name)) { - throw new BuildException("<" + getTaskType() - + "> does not support the \"" + name + "\" attribute"); + throw new BuildException( + "<%s> does not support the \"%s\" attribute", getTaskType(), + name); } - attributes.put(name, value); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOS.java b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOS.java index c6614cbdd..66e0eb2a5 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOS.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOS.java @@ -388,6 +388,7 @@ public abstract class SOS extends Task implements SOSCmd { * * @throws BuildException on error. */ + @Override public void execute() throws BuildException { int result = 0; diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckin.java b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckin.java index 9095f075c..3a82ea4f9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckin.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckin.java @@ -69,6 +69,7 @@ public class SOSCheckin extends SOS { * * @return Commandline the generated command to be executed */ + @Override protected Commandline buildCmdLine() { commandLine = new Commandline(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckout.java b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckout.java index fab6fb9f2..a7b23c5bb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckout.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSCheckout.java @@ -58,6 +58,7 @@ public class SOSCheckout extends SOS { * * @return Commandline the generated command to be executed */ + @Override protected Commandline buildCmdLine() { commandLine = new Commandline(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSGet.java b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSGet.java index cdbf92bc9..b17e0c16f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSGet.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSGet.java @@ -78,6 +78,7 @@ public class SOSGet extends SOS { * * @return Commandline the generated command to be executed */ + @Override protected Commandline buildCmdLine() { commandLine = new Commandline(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSLabel.java b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSLabel.java index dd6b13a2a..0b4110548 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSLabel.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sos/SOSLabel.java @@ -63,6 +63,7 @@ public class SOSLabel extends SOS { * * @return Commandline the generated command to be executed */ + @Override protected Commandline buildCmdLine() { commandLine = new Commandline(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/sound/AntSoundPlayer.java b/src/main/org/apache/tools/ant/taskdefs/optional/sound/AntSoundPlayer.java index 92dd348b7..84b4317bb 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/sound/AntSoundPlayer.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/sound/AntSoundPlayer.java @@ -60,10 +60,6 @@ public class AntSoundPlayer implements LineListener, BuildListener { private int loopsFail = 0; private Long durationFail = null; - /** Constructor for AntSoundPlayer. */ - public AntSoundPlayer() { - } - /** * @param file the location of the audio file to be played when the * build is successful @@ -102,7 +98,6 @@ public class AntSoundPlayer implements LineListener, BuildListener { AudioInputStream audioInputStream = null; - try { audioInputStream = AudioSystem.getAudioInputStream(file); } catch (UnsupportedAudioFileException uafe) { @@ -180,6 +175,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * clip if required. * @param event the line event to follow */ + @Override public void update(LineEvent event) { if (event.getType().equals(LineEvent.Type.STOP)) { Line line = event.getLine(); @@ -192,6 +188,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * Fired before any targets are started. * @param event ignored */ + @Override public void buildStarted(BuildEvent event) { } @@ -201,6 +198,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @param event the build finished event. * @see BuildEvent#getException() */ + @Override public void buildFinished(BuildEvent event) { if (event.getException() == null && fileSuccess != null) { // build successful! @@ -215,6 +213,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @param event ignored. * @see BuildEvent#getTarget() */ + @Override public void targetStarted(BuildEvent event) { } @@ -224,6 +223,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @param event ignored. * @see BuildEvent#getException() */ + @Override public void targetFinished(BuildEvent event) { } @@ -232,6 +232,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @param event ignored. * @see BuildEvent#getTask() */ + @Override public void taskStarted(BuildEvent event) { } @@ -241,6 +242,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @param event ignored. * @see BuildEvent#getException() */ + @Override public void taskFinished(BuildEvent event) { } @@ -250,6 +252,7 @@ public class AntSoundPlayer implements LineListener, BuildListener { * @see BuildEvent#getMessage() * @see BuildEvent#getPriority() */ + @Override public void messageLogged(BuildEvent event) { } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashScreen.java b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashScreen.java index 5de84cca9..e7d1c31c3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashScreen.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashScreen.java @@ -37,8 +37,10 @@ import javax.swing.JWindow; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildListener; +import org.apache.tools.ant.Project; class SplashScreen extends JWindow implements ActionListener, BuildListener { + private static final long serialVersionUID = 1L; private static final int FONT_SIZE = 12; private JLabel text; private JProgressBar pb; @@ -118,6 +120,7 @@ class SplashScreen extends JWindow implements ActionListener, BuildListener { text.setText(txt); } + @Override public void actionPerformed(ActionEvent a) { if (!hasProgressPattern()) { if (total < MAX) { @@ -129,31 +132,38 @@ class SplashScreen extends JWindow implements ActionListener, BuildListener { } } + @Override public void buildStarted(BuildEvent event) { actionPerformed(null); } + @Override public void buildFinished(BuildEvent event) { pb.setValue(MAX); setVisible(false); dispose(); } + @Override public void targetStarted(BuildEvent event) { actionPerformed(null); } + @Override public void targetFinished(BuildEvent event) { actionPerformed(null); } + @Override public void taskStarted(BuildEvent event) { actionPerformed(null); } + @Override public void taskFinished(BuildEvent event) { actionPerformed(null); } + @Override public void messageLogged(BuildEvent event) { actionPerformed(null); if (hasProgressPattern()) { @@ -162,12 +172,11 @@ class SplashScreen extends JWindow implements ActionListener, BuildListener { if (matcher != null && matcher.matches()) { String gr = matcher.group(1); try { - int i = Math.min(new Integer(gr).intValue() * 2, MAX); - pb.setValue(i); + pb.setValue(Math.min(Integer.parseInt(gr) * 2, MAX)); } catch (NumberFormatException e) { - //TODO: how to reach logger?!? - //log("Number parsing error in progressRegExp", Project.MSG_VERBOSE); - + event.getProject().log( + "Number parsing error in progressRegExp", + Project.MSG_VERBOSE); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java index 9d995bce6..a3235f901 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/splash/SplashTask.java @@ -20,7 +20,6 @@ package org.apache.tools.ant.taskdefs.optional.splash; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; -import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; @@ -237,9 +236,9 @@ public class SplashTask extends Task { boolean success = false; if (in != null) { - DataInputStream din = new DataInputStream(in); - try { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try ( + DataInputStream din = new DataInputStream(in); + ByteArrayOutputStream bout = new ByteArrayOutputStream()){ int data; while ((data = din.read()) != -1) { bout.write((byte) data); @@ -257,15 +256,6 @@ public class SplashTask extends Task { } catch (Exception e) { throw new BuildException(e); } finally { - try { - din.close(); - } catch (IOException ioe) { - // swallow if there was an error before so that - // original error will be passed up - if (success) { - throw new BuildException(ioe); //NOSONAR - } - } } } else { try { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/AbstractSshMessage.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/AbstractSshMessage.java index c0236e1f6..1a26fa433 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/AbstractSshMessage.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/AbstractSshMessage.java @@ -41,10 +41,8 @@ public abstract class AbstractSshMessage { private final Session session; private final boolean verbose; private final boolean compressed; - private LogListener listener = new LogListener() { - public void log(final String message) { - // do nothing; - } + private LogListener listener = message -> { + // do nothing; }; /** @@ -97,9 +95,7 @@ public abstract class AbstractSshMessage { * @throws JSchException on error */ protected ChannelSftp openSftpChannel() throws JSchException { - final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); - - return channel; + return (ChannelSftp) session.openChannel("sftp"); } /** @@ -132,8 +128,9 @@ public abstract class AbstractSshMessage { if (b == -1) { // didn't receive any response throw new BuildException("No response from server"); - } else if (b != 0) { - final StringBuffer sb = new StringBuffer(); + } + if (b != 0) { + final StringBuilder sb = new StringBuilder(); int c = in.read(); while (c > 0 && c != '\n') { @@ -270,12 +267,12 @@ public abstract class AbstractSshMessage { private long totalLength = 0; private int percentTransmitted = 0; + @Override public void init(final int op, final String src, final String dest, final long max) { initFileSize = max; - totalLength = 0; - percentTransmitted = 0; } + @Override public boolean count(final long len) { totalLength += len; percentTransmitted = trackProgress(initFileSize, @@ -284,6 +281,7 @@ public abstract class AbstractSshMessage { return true; } + @Override public void end() { } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java index b5088a7d5..89230beac 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Directory.java @@ -22,6 +22,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; import java.util.StringTokenizer; @@ -31,8 +32,8 @@ import java.util.StringTokenizer; public class Directory { private File directory; - private Set childDirectories; - private ArrayList files; + private Set<Directory> childDirectories; + private List<File> files; private Directory parent; /** @@ -50,8 +51,8 @@ public class Directory { */ public Directory(File directory , Directory parent) { this.parent = parent; - this.childDirectories = new LinkedHashSet(); - this.files = new ArrayList(); + this.childDirectories = new LinkedHashSet<>(); + this.files = new ArrayList<>(); this.directory = directory; } @@ -77,7 +78,7 @@ public class Directory { * Get an iterator over the child Directories. * @return an iterator */ - public Iterator directoryIterator() { + public Iterator<Directory> directoryIterator() { return childDirectories.iterator(); } @@ -85,7 +86,7 @@ public class Directory { * Get an iterator over the files. * @return an iterator */ - public Iterator filesIterator() { + public Iterator<File> filesIterator() { return files.iterator(); } @@ -119,8 +120,7 @@ public class Directory { * @return the child directory, or null if not found */ public Directory getChild(File dir) { - for (Iterator i = childDirectories.iterator(); i.hasNext();) { - Directory current = (Directory) i.next(); + for (Directory current : childDirectories) { if (current.getDirectory().equals(dir)) { return current; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHBase.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHBase.java index d6abb95d5..2e426ee15 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHBase.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHBase.java @@ -226,6 +226,7 @@ public abstract class SSHBase extends Task implements LogListener { * This initializizs the known hosts and sets the default port. * @throws BuildException on error */ + @Override public void init() throws BuildException { super.init(); this.knownHosts = System.getProperty("user.home") + "/.ssh/known_hosts"; @@ -241,14 +242,17 @@ public abstract class SSHBase extends Task implements LogListener { final JSch jsch = new JSch(); final SSHBase base = this; if (verbose) { - JSch.setLogger(new com.jcraft.jsch.Logger(){ - public boolean isEnabled(final int level){ - return true; - } - public void log(final int level, final String message){ - base.log(message, Project.MSG_INFO); - } - }); + JSch.setLogger(new com.jcraft.jsch.Logger() { + @Override + public boolean isEnabled(final int level) { + return true; + } + + @Override + public void log(final int level, final String message) { + base.log(message, Project.MSG_INFO); + } + }); } if (null != userInfo.getKeyfile()) { jsch.addIdentity(userInfo.getKeyfile()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java index 394200335..1206d7979 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHExec.java @@ -295,18 +295,16 @@ public class SSHExec extends SSHBase { + (inputProperty != null ? 1 : 0) + (inputString != null ? 1 : 0); if (numberOfInputs > 1) { - throw new BuildException("You can't specify more than one of" - + " inputFile, inputProperty and" - + " inputString."); + throw new BuildException( + "You can't specify more than one of inputFile, inputProperty and inputString."); } if (inputFile != null && !inputFile.exists()) { - throw new BuildException("The input file " - + inputFile.getAbsolutePath() - + " does not exist."); + throw new BuildException("The input file %s does not exist.", + inputFile.getAbsolutePath()); } Session session = null; - final StringBuffer output = new StringBuffer(); + final StringBuilder output = new StringBuilder(); try { session = openSession(); /* called once */ @@ -314,32 +312,27 @@ public class SSHExec extends SSHBase { log("cmd : " + command, Project.MSG_INFO); executeCommand(session, command, output); } else { // read command resource and execute for each command - try { - final BufferedReader br = new BufferedReader( - new InputStreamReader(commandResource.getInputStream())); - String cmd; - while ((cmd = br.readLine()) != null) { + try (final BufferedReader br = new BufferedReader( + new InputStreamReader(commandResource.getInputStream()))) { + final Session s = session; + br.lines().forEach(cmd -> { log("cmd : " + cmd, Project.MSG_INFO); output.append(cmd).append(" : "); - executeCommand(session, cmd, output); + executeCommand(s, cmd, output); output.append("\n"); - } - FileUtils.close(br); + }); } catch (final IOException e) { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), - Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } } catch (final JSchException e) { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } finally { if (outputProperty != null) { getProject().setNewProperty(outputProperty, output.toString()); @@ -350,7 +343,7 @@ public class SSHExec extends SSHBase { } } - private void executeCommand(final Session session, final String cmd, final StringBuffer sb) + private void executeCommand(final Session session, final String cmd, final StringBuilder sb) throws BuildException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream errout = new ByteArrayOutputStream(); @@ -423,9 +416,8 @@ public class SSHExec extends SSHBase { thread = null; if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE); - } else { - log(TIMEOUT_MESSAGE, Project.MSG_ERR); } + log(TIMEOUT_MESSAGE, Project.MSG_ERR); } else { // stdout to outputFile if (outputFile != null) { @@ -450,9 +442,8 @@ public class SSHExec extends SSHBase { final String msg = "Remote command failed with exit status " + ec; if (getFailonerror()) { throw new BuildException(msg); - } else { - log(msg, Project.MSG_ERR); } + log(msg, Project.MSG_ERR); } } } catch (final BuildException e) { @@ -461,23 +452,19 @@ public class SSHExec extends SSHBase { if (e.getMessage().indexOf("session is down") >= 0) { if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE, e); - } else { - log(TIMEOUT_MESSAGE, Project.MSG_ERR); } + log(TIMEOUT_MESSAGE, Project.MSG_ERR); } else { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), - Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } catch (final Exception e) { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } finally { sb.append(out.toString()); FileUtils.close(istream); @@ -498,9 +485,8 @@ public class SSHExec extends SSHBase { try (FileWriter out = new FileWriter(to.getAbsolutePath(), append)) { final StringReader in = new StringReader(from); final char[] buffer = new char[BUFFER_SIZE]; - int bytesRead; while (true) { - bytesRead = in.read(buffer); + int bytesRead = in.read(buffer); if (bytesRead == -1) { break; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java index e9f267574..3fec9114e 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.java @@ -19,7 +19,6 @@ package org.apache.tools.ant.taskdefs.optional.ssh; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -29,7 +28,6 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.TaskContainer; - import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; @@ -45,10 +43,10 @@ public class SSHSession extends SSHBase { /** units are milliseconds, default is 0=infinite */ private long maxwait = 0; - private final Vector localTunnels = new Vector(); - private final Set localPortsUsed = new TreeSet(); - private final Vector remoteTunnels = new Vector(); - private final Set remotePortsUsed = new TreeSet(); + private final List<LocalTunnel> localTunnels = new Vector<>(); + private final Set<Integer> localPortsUsed = new TreeSet<>(); + private final List<RemoteTunnel> remoteTunnels = new Vector<>(); + private final Set<Integer> remotePortsUsed = new TreeSet<>(); private NestedSequential nestedSequential = null; private static final String TIMEOUT_MESSAGE = @@ -56,7 +54,7 @@ public class SSHSession extends SSHBase { /** Optional Vector holding the nested tasks */ - private final Vector nestedTasks = new Vector(); + private final List<Task> nestedTasks = new Vector<>(); /** * Add a nested task to Sequential. @@ -65,7 +63,7 @@ public class SSHSession extends SSHBase { * <p> */ public void addTask(final Task nestedTask) { - nestedTasks.addElement(nestedTask); + nestedTasks.add(nestedTask); } /** @@ -148,48 +146,38 @@ public class SSHSession extends SSHBase { throw new BuildException("Missing sequential element."); } - Session session = null; try { // establish the session session = openSession(); session.setTimeout((int) maxwait); - for (final Iterator i = localTunnels.iterator(); i.hasNext();) { - final LocalTunnel tunnel = (LocalTunnel) i.next(); + for (LocalTunnel tunnel : localTunnels) { session.setPortForwardingL(tunnel.getLPort(), tunnel.getRHost(), tunnel.getRPort()); } - for (final Iterator i = remoteTunnels.iterator(); i.hasNext();) { - final RemoteTunnel tunnel = (RemoteTunnel) i.next(); + for (RemoteTunnel tunnel : remoteTunnels) { session.setPortForwardingR(tunnel.getRPort(), tunnel.getLHost(), tunnel.getLPort()); } - for (final Iterator i = nestedSequential.getNested().iterator(); - i.hasNext();) { - final Task nestedTask = (Task) i.next(); - nestedTask.perform(); - } + nestedSequential.getNested().forEach(Task::perform); // completed successfully } catch (final JSchException e) { if (e.getMessage().indexOf("session is down") >= 0) { if (getFailonerror()) { throw new BuildException(TIMEOUT_MESSAGE, e); - } else { - log(TIMEOUT_MESSAGE, Project.MSG_ERR); } + log(TIMEOUT_MESSAGE, Project.MSG_ERR); } else { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), - Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } catch (final BuildException e) { // avoid wrapping it into yet another BuildException further down @@ -197,9 +185,8 @@ public class SSHSession extends SSHBase { } catch (final Exception e) { if (getFailonerror()) { throw new BuildException(e); - } else { - log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } finally { if (session != null && session.isConnected()) { session.disconnect(); @@ -220,34 +207,44 @@ public class SSHSession extends SSHBase { } public class LocalTunnel { - public LocalTunnel() {} int lport = 0; String rhost = null; int rport = 0; + public void setLPort(final int lport) { - final Integer portKey = new Integer(lport); + final Integer portKey = Integer.valueOf(lport); if (localPortsUsed.contains(portKey)) { - throw new BuildException("Multiple local tunnels defined to" - + " use same local port " + lport); + throw new BuildException( + "Multiple local tunnels defined to use same local port %d", + lport); } localPortsUsed.add(portKey); this.lport = lport; } - public void setRHost(final String rhost) { this.rhost = rhost; } - public void setRPort(final int rport) { this.rport = rport; } + + public void setRHost(final String rhost) { + this.rhost = rhost; + } + + public void setRPort(final int rport) { + this.rport = rport; + } + public int getLPort() { if (lport == 0) { throw new BuildException("lport is required for LocalTunnel."); } return lport; } + public String getRHost() { if (rhost == null) { throw new BuildException("rhost is required for LocalTunnel."); } return rhost; } + public int getRPort() { if (rport == 0) { throw new BuildException("rport is required for LocalTunnel."); @@ -257,34 +254,44 @@ public class SSHSession extends SSHBase { } public class RemoteTunnel { - public RemoteTunnel() {} int lport = 0; String lhost = null; int rport = 0; - public void setLPort(final int lport) { this.lport = lport; } - public void setLHost(final String lhost) { this.lhost = lhost; } + + public void setLPort(final int lport) { + this.lport = lport; + } + + public void setLHost(final String lhost) { + this.lhost = lhost; + } + public void setRPort(final int rport) { - final Integer portKey = new Integer(rport); + final Integer portKey = Integer.valueOf(rport); if (remotePortsUsed.contains(portKey)) { - throw new BuildException("Multiple remote tunnels defined to" - + " use same remote port " + rport); + throw new BuildException( + "Multiple remote tunnels defined to use same remote port %d", + rport); } remotePortsUsed.add(portKey); this.rport = rport; } + public int getLPort() { if (lport == 0) { throw new BuildException("lport is required for RemoteTunnel."); } return lport; } + public String getLHost() { if (lhost == null) { throw new BuildException("lhost is required for RemoteTunnel."); } return lhost; } + public int getRPort() { if (rport == 0) { throw new BuildException("rport is required for RemoteTunnel."); @@ -311,13 +318,14 @@ public class SSHSession extends SSHBase { * This is a simple task container. */ public static class NestedSequential implements TaskContainer { - private final List<Task> nested = new ArrayList<Task>(); + private final List<Task> nested = new ArrayList<>(); /** * Add a task or type to the container. * * @param task an unknown element. */ + @Override public void addTask(final Task task) { nested.add(task); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHUserInfo.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHUserInfo.java index 54e702932..455d12b37 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHUserInfo.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/SSHUserInfo.java @@ -35,8 +35,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { /** Constructor for SSHUserInfo. */ public SSHUserInfo() { - super(); - this.trustAllCertificates = false; + this(null, false); } /** @@ -71,6 +70,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * Gets the user's password. * @return the user's password */ + @Override public String getPassword() { return password; } @@ -135,6 +135,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * Returns the passphrase. * @return String */ + @Override public String getPassphrase() { return passphrase; } @@ -160,6 +161,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * @param message ignored * @return true always */ + @Override public boolean promptPassphrase(String message) { return true; } @@ -169,6 +171,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * @param passwordPrompt ignored * @return true the first time this is called, false otherwise */ + @Override public boolean promptPassword(String passwordPrompt) { return true; } @@ -178,6 +181,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * @param message ignored * @return the value of trustAllCertificates */ + @Override public boolean promptYesNo(String message) { return trustAllCertificates; } @@ -187,6 +191,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * Implement the UserInfo interface (noop). * @param message ignored */ + @Override public void showMessage(String message) { //log(message, Project.MSG_DEBUG); } @@ -201,6 +206,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { * @return the password in an size one array if there is a password * and if the prompt and echo checks pass. */ + @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, @@ -209,9 +215,7 @@ public class SSHUserInfo implements UserInfo, UIKeyboardInteractive { if (prompt.length != 1 || echo[0] || this.password == null) { return null; } - String[] response = new String[1]; - response[0] = this.password; - return response; + return new String[] { this.password }; } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java index 087a4022b..e68f38d0f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/Scp.java @@ -21,9 +21,10 @@ package org.apache.tools.ant.taskdefs.optional.ssh; import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; @@ -156,11 +157,9 @@ public class Scp extends SSHBase { private static void validateRemoteUri(final String type, final String aToUri) { if (!isRemoteUri(aToUri)) { - throw new BuildException(type + " '" + aToUri + "' is invalid. " - + "The 'remoteToDir' attribute must " - + "have syntax like the " - + "following: user:password@host:/path" - + " - the :password part is optional"); + throw new BuildException( + "%s '%s' is invalid. The 'remoteToDir' attribute must have syntax like the following: user:password@host:/path - the :password part is optional", + type, aToUri); } } @@ -229,7 +228,7 @@ public class Scp extends SSHBase { */ public void add(ResourceCollection res) { if (rcs == null) { - rcs = new LinkedList<ResourceCollection>(); + rcs = new LinkedList<>(); } rcs.add(res); } @@ -271,24 +270,21 @@ public class Scp extends SSHBase { throw new BuildException( "Copying from a remote server to a remote server is not supported."); } else { - throw new BuildException("'todir' and 'file' attributes " - + "must have syntax like the following: " - + "user:password@host:/path"); + throw new BuildException( + "'todir' and 'file' attributes must have syntax like the following: user:password@host:/path"); } } catch (final Exception e) { if (getFailonerror()) { - if(e instanceof BuildException) { + if (e instanceof BuildException) { final BuildException be = (BuildException) e; - if(be.getLocation() == null) { + if (be.getLocation() == null) { be.setLocation(getLocation()); } throw be; - } else { - throw new BuildException(e); } - } else { - log("Caught exception: " + e.getMessage(), Project.MSG_ERR); + throw new BuildException(e); } + log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } @@ -330,9 +326,8 @@ public class Scp extends SSHBase { Session session = null; try { - final List<Directory> list = new ArrayList<Directory>(rcs.size()); - for (final Iterator<ResourceCollection> i = rcs.iterator(); i.hasNext();) { - final ResourceCollection rc = (ResourceCollection) i.next(); + final List<Directory> list = new ArrayList<>(rcs.size()); + for (ResourceCollection rc : rcs) { if (rc instanceof FileSet && rc.isFilesystemOnly()) { FileSet fs = (FileSet) rc; final Directory d = createDirectory(fs); @@ -340,15 +335,15 @@ public class Scp extends SSHBase { list.add(d); } } else { - List<Directory> ds = createDirectoryCollection(rc); - if (ds !=null) { - list.addAll(ds); - } + List<Directory> ds = createDirectoryCollection(rc); + if (ds != null) { + list.addAll(ds); + } } } if (!list.isEmpty()) { session = openSession(); - ScpToMessage message = null; + ScpToMessage message; if (!isSftp) { message = new ScpToMessage(getVerbose(), compressed, session, list, file, preserveLastModified); @@ -433,19 +428,19 @@ public class Scp extends SSHBase { if (getUserInfo().getPassword() == null && getUserInfo().getKeyfile() == null) { - throw new BuildException("neither password nor keyfile for user " - + getUserInfo().getName() + " has been " - + "given. Can't authenticate."); + throw new BuildException( + "neither password nor keyfile for user %s has been given. Can't authenticate.", + getUserInfo().getName()); } final int indexOfPath = uri.indexOf(':', indexOfAt + 1); if (indexOfPath == -1) { - throw new BuildException("no remote path in " + uri); + throw new BuildException("no remote path in %s", uri); } setHost(uri.substring(indexOfAt + 1, indexOfPath)); String remotePath = uri.substring(indexOfPath + 1); - if (remotePath.equals("")) { + if (remotePath.isEmpty()) { remotePath = "."; } return remotePath; @@ -462,28 +457,26 @@ public class Scp extends SSHBase { private Directory createDirectory(final FileSet set) { final DirectoryScanner scanner = set.getDirectoryScanner(getProject()); - Directory root = new Directory(scanner.getBasedir()); final String[] files = scanner.getIncludedFiles(); - if (files.length != 0) { - for (int j = 0; j < files.length; j++) { - final String[] path = Directory.getPath(files[j]); - Directory current = root; - File currentParent = scanner.getBasedir(); - for (int i = 0; i < path.length; i++) { - final File file = new File(currentParent, path[i]); - if (file.isDirectory()) { - current.addDirectory(new Directory(file)); - current = current.getChild(file); - currentParent = current.getDirectory(); - } else if (file.isFile()) { - current.addFile(file); - } - } - } - } else { + if (files.length == 0) { // skip - root = null; + return null; } + Directory root = new Directory(scanner.getBasedir()); + Stream.of(files).map(Directory::getPath).forEach(path -> { + Directory current = root; + File currentParent = scanner.getBasedir(); + for (String element : path) { + final File file = new File(currentParent, element); + if (file.isDirectory()) { + current.addDirectory(new Directory(file)); + current = current.getChild(file); + currentParent = current.getDirectory(); + } else if (file.isFile()) { + current.addFile(file); + } + } + }); return root; } @@ -493,21 +486,24 @@ public class Scp extends SSHBase { throw new BuildException("Only FileSystem resources are supported."); } - List<Directory> ds = new ArrayList<Directory>(); + List<Directory> ds = new ArrayList<>(); for (Resource r : rc) { if (!r.isExists()) { - throw new BuildException("Could not find resource " + r.toLongString() + " to scp."); + throw new BuildException("Could not find resource %s to scp.", + r.toLongString()); } FileProvider fp = r.as(FileProvider.class); if (fp == null) { - throw new BuildException("Resource " + r.toLongString() + " is not a file."); + throw new BuildException("Resource %s is not a file.", + r.toLongString()); } FileResource fr = ResourceUtils.asFileResource(fp); File baseDir = fr.getBaseDir(); if (baseDir == null) { - throw new BuildException("basedir for resource " + r.toLongString() + " is undefined."); + throw new BuildException( + "basedir for resource %s is undefined.", r.toLongString()); } // if the basedir is set, the name will be relative to that @@ -515,9 +511,8 @@ public class Scp extends SSHBase { Directory root = new Directory(baseDir); Directory current = root; File currentParent = baseDir; - final String[] path = Directory.getPath(name); - for (int i = 0; i < path.length; i++) { - final File file = new File(currentParent, path[i]); + for (String element : Directory.getPath(name)) { + final File file = new File(currentParent, element); if (file.isDirectory()) { current.addDirectory(new Directory(file)); current = current.getChild(file); @@ -527,7 +522,7 @@ public class Scp extends SSHBase { } } ds.add(root); - } + } return ds; } @@ -550,15 +545,8 @@ public class Scp extends SSHBase { } private BuildException exactlyOne(final String[] attrs, final String alt) { - final StringBuffer buf = new StringBuffer("Exactly one of ").append( - '[').append(attrs[0]); - for (int i = 1; i < attrs.length; i++) { - buf.append('|').append(attrs[i]); - } - buf.append(']'); - if (alt != null) { - buf.append(" or ").append(alt); - } - return new BuildException(buf.append(" is required.").toString()); + return new BuildException("Exactly one of [%s]%s is required", + Stream.of(attrs).collect(Collectors.joining("|")), + alt == null ? "" : " or " + alt); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessage.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessage.java index 8775c1190..1ffb5bd88 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessage.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessage.java @@ -149,6 +149,7 @@ public class ScpFromMessage extends AbstractSshMessage { * @throws IOException on i/o errors * @throws JSchException on errors detected by scp */ + @Override public void execute() throws IOException, JSchException { String command = "scp -f "; if (isRecursive) { @@ -220,9 +221,9 @@ public class ScpFromMessage extends AbstractSshMessage { private File parseAndCreateDirectory(final String serverResponse, final File localFile) { - int start = serverResponse.indexOf(" "); + int start = serverResponse.indexOf(' '); // appears that the next token is not used and it's zero. - start = serverResponse.indexOf(" ", start + 1); + start = serverResponse.indexOf(' ', start + 1); final String directoryName = serverResponse.substring(start + 1); if (localFile.isDirectory()) { final File dir = new File(localFile, directoryName); @@ -239,13 +240,13 @@ public class ScpFromMessage extends AbstractSshMessage { final InputStream in) throws IOException, JSchException { int start = 0; - int end = serverResponse.indexOf(" ", start + 1); + int end = serverResponse.indexOf(' ', start + 1); start = end + 1; - end = serverResponse.indexOf(" ", start + 1); + end = serverResponse.indexOf(' ', start + 1); final long filesize = Long.parseLong(serverResponse.substring(start, end)); final String filename = serverResponse.substring(end + 1); log("Receiving: " + filename + " : " + filesize); - final File transferFile = (localFile.isDirectory()) + final File transferFile = localFile.isDirectory() ? new File(localFile, filename) : localFile; fetchFile(transferFile, filesize, out, in); @@ -277,7 +278,7 @@ public class ScpFromMessage extends AbstractSshMessage { try { while (true) { length = in.read(buf, 0, - (BUFFER_SIZE < filesize) ? BUFFER_SIZE + BUFFER_SIZE < filesize ? BUFFER_SIZE : (int) filesize); if (length < 0) { throw new EOFException("Unexpected end of stream."); @@ -327,10 +328,10 @@ public class ScpFromMessage extends AbstractSshMessage { * returns the directory part of the remote file, if any. */ private static String remoteDir(final String remoteFile) { - int index = remoteFile.lastIndexOf("/"); + int index = remoteFile.lastIndexOf('/'); if (index < 0) { - index = remoteFile.lastIndexOf("\\"); + index = remoteFile.lastIndexOf('\\'); } - return index > -1 ? remoteFile.substring(0, index + 1) : ""; + return index < 0 ? "" : remoteFile.substring(0, index + 1); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessageBySftp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessageBySftp.java index 04f72d235..886d06da7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessageBySftp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessageBySftp.java @@ -20,7 +20,7 @@ package org.apache.tools.ant.taskdefs.optional.ssh; import java.io.File; import java.io.IOException; - +import java.util.List; import org.apache.tools.ant.util.FileUtils; import com.jcraft.jsch.ChannelSftp; @@ -103,6 +103,7 @@ public class ScpFromMessageBySftp extends ScpFromMessage { * @throws IOException on i/o errors * @throws JSchException on errors detected by scp */ + @Override public void execute() throws IOException, JSchException { final ChannelSftp channel = openSftpChannel(); try { @@ -117,9 +118,9 @@ public class ScpFromMessageBySftp extends ScpFromMessage { } getDir(channel, remoteFile, localFile); } catch (final SftpException e) { - final JSchException schException = new JSchException("Could not get '"+ remoteFile - +"' to '"+localFile+"' - " - +e.toString()); + final JSchException schException = + new JSchException("Could not get '" + remoteFile + "' to '" + + localFile + "' - " + e.toString()); schException.initCause(e); throw schException; } finally { @@ -143,13 +144,12 @@ public class ScpFromMessageBySftp extends ScpFromMessage { if (!localFile.exists()) { localFile.mkdirs(); } - final java.util.Vector files = channel.ls(remoteFile); - final int size = files.size(); - for (int i = 0; i < size; i++) { - final ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) files.elementAt(i); + @SuppressWarnings("unchecked") + final List<ChannelSftp.LsEntry> files = channel.ls(remoteFile); + for (ChannelSftp.LsEntry le : files) { final String name = le.getFilename(); if (le.getAttrs().isDir()) { - if (name.equals(".") || name.equals("..")) { + if (".".equals(name) || "..".equals(name)) { continue; } getDir(channel, diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessage.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessage.java index 214dd4ea1..67424f412 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessage.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessage.java @@ -42,7 +42,7 @@ public class ScpToMessage extends AbstractSshMessage { private File localFile; private String remotePath; - private List directoryList; + private List<Directory> directoryList; private Integer fileMode, dirMode; private boolean preserveLastModified; @@ -124,7 +124,7 @@ public class ScpToMessage extends AbstractSshMessage { */ public ScpToMessage(final boolean verbose, final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath, final boolean preserveLastModified) { this(verbose, false, session, aDirectoryList, aRemotePath, preserveLastModified); @@ -143,7 +143,7 @@ public class ScpToMessage extends AbstractSshMessage { public ScpToMessage(final boolean verbose, final boolean compressed, final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath, final boolean preserveLastModified) { this(verbose, compressed, session, aRemotePath); @@ -176,7 +176,7 @@ public class ScpToMessage extends AbstractSshMessage { */ public ScpToMessage(final boolean verbose, final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath) { this(verbose, session, aDirectoryList, aRemotePath, false); } @@ -184,19 +184,6 @@ public class ScpToMessage extends AbstractSshMessage { /** * Constructor for ScpToMessage. * @param verbose if true do verbose logging - * @param session the scp session to use - * @param aRemotePath the remote path - * @since Ant 1.6.2 - */ - private ScpToMessage(final boolean verbose, - final Session session, - final String aRemotePath) { - this(verbose, false, session, aRemotePath); - } - - /** - * Constructor for ScpToMessage. - * @param verbose if true do verbose logging * @param compressed if true use compression * @param session the scp session to use * @param aRemotePath the remote path @@ -229,7 +216,7 @@ public class ScpToMessage extends AbstractSshMessage { * @param aRemotePath the remote path */ public ScpToMessage(final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath) { this(false, session, aDirectoryList, aRemotePath); } @@ -262,7 +249,6 @@ public class ScpToMessage extends AbstractSshMessage { final String cmd = sb.toString(); final Channel channel = openExecChannel(cmd); try { - final OutputStream out = channel.getOutputStream(); final InputStream in = channel.getInputStream(); @@ -294,8 +280,7 @@ public class ScpToMessage extends AbstractSshMessage { channel.connect(); waitForAck(in); - for (final Iterator i = directoryList.iterator(); i.hasNext();) { - final Directory current = (Directory) i.next(); + for (Directory current : directoryList) { sendDirectory(current, in, out); } } finally { @@ -308,12 +293,11 @@ public class ScpToMessage extends AbstractSshMessage { private void sendDirectory(final Directory current, final InputStream in, final OutputStream out) throws IOException { - for (final Iterator fileIt = current.filesIterator(); fileIt.hasNext();) { - sendFileToRemote((File) fileIt.next(), in, out); + for (final Iterator<File> fileIt = current.filesIterator(); fileIt.hasNext();) { + sendFileToRemote(fileIt.next(), in, out); } - for (final Iterator dirIt = current.directoryIterator(); dirIt.hasNext();) { - final Directory dir = (Directory) dirIt.next(); - sendDirectoryToRemote(dir, in, out); + for (final Iterator<Directory> dirIt = current.directoryIterator(); dirIt.hasNext();) { + sendDirectoryToRemote(dirIt.next(), in, out); } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessageBySftp.java b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessageBySftp.java index 2b32907d7..dc8f2f15d 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessageBySftp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpToMessageBySftp.java @@ -38,7 +38,7 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { private File localFile; private final String remotePath; - private List directoryList; + private List<Directory> directoryList; /** * Constructor for a local file to remote. @@ -67,7 +67,7 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { */ public ScpToMessageBySftp(final boolean verbose, final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath) { this(verbose, session, aRemotePath); @@ -107,7 +107,7 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { * @param aRemotePath the remote path */ public ScpToMessageBySftp(final Session session, - final List aDirectoryList, + final List<Directory> aDirectoryList, final String aRemotePath) { this(false, session, aDirectoryList, aRemotePath); } @@ -171,21 +171,19 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { throw new JSchException("Could not CD to '" + remotePath + "' - " + e.toString(), e); } - Directory current = null; - try { - for (final Iterator i = directoryList.iterator(); i.hasNext();) { - current = (Directory) i.next(); + for (Directory current : directoryList) { + try { if (getVerbose()) { log("Sending directory " + current); } sendDirectory(channel, current); + } catch (final SftpException e) { + String msg = "Error sending directory"; + if (current != null && current.getDirectory() != null) { + msg += " '" + current.getDirectory().getName() + "'"; + } + throw new JSchException(msg, e); } - } catch (final SftpException e) { - String msg = "Error sending directory"; - if (current != null && current.getDirectory() != null) { - msg += " '" + current.getDirectory().getName() + "'"; - } - throw new JSchException(msg, e); } } finally { if (channel != null) { @@ -197,12 +195,11 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { private void sendDirectory(final ChannelSftp channel, final Directory current) throws IOException, SftpException { - for (final Iterator fileIt = current.filesIterator(); fileIt.hasNext();) { - sendFileToRemote(channel, (File) fileIt.next(), null); + for (final Iterator<File> fileIt = current.filesIterator(); fileIt.hasNext();) { + sendFileToRemote(channel, fileIt.next(), null); } - for (final Iterator dirIt = current.directoryIterator(); dirIt.hasNext();) { - final Directory dir = (Directory) dirIt.next(); - sendDirectoryToRemote(channel, dir); + for (final Iterator<Directory> dirIt = current.directoryIterator(); dirIt.hasNext();) { + sendDirectoryToRemote(channel, dirIt.next()); } } @@ -263,6 +260,7 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { * Get the local file. * @return the local file. */ + @Override public File getLocalFile() { return localFile; } @@ -271,6 +269,7 @@ public class ScpToMessageBySftp extends ScpToMessage/*AbstractSshMessage*/ { * Get the remote path. * @return the remote path. */ + @Override public String getRemotePath() { return remotePath; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/testing/BlockFor.java b/src/main/org/apache/tools/ant/taskdefs/optional/testing/BlockFor.java index 4b2978ab6..9d8338eaf 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/testing/BlockFor.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/testing/BlockFor.java @@ -54,6 +54,7 @@ public class BlockFor extends WaitFor { * @throws BuildTimeoutException on timeout, using the text in {@link #text} * */ + @Override protected void processTimeout() throws BuildTimeoutException { super.processTimeout(); throw new BuildTimeoutException(text, getLocation()); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/testing/Funtest.java b/src/main/org/apache/tools/ant/taskdefs/optional/testing/Funtest.java index 2eb357a39..a7eb85fb8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/testing/Funtest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/testing/Funtest.java @@ -58,6 +58,19 @@ import org.apache.tools.ant.util.WorkerAnt; */ public class Funtest extends Task { + /** {@value} */ + public static final String WARN_OVERRIDING = "Overriding previous definition of "; + /** {@value} */ + public static final String APPLICATION_FORCIBLY_SHUT_DOWN = "Application forcibly shut down"; + /** {@value} */ + public static final String SHUTDOWN_INTERRUPTED = "Shutdown interrupted"; + /** {@value} */ + public static final String SKIPPING_TESTS + = "Condition failed -skipping tests"; + /** Application exception : {@value} */ + public static final String APPLICATION_EXCEPTION = "Application Exception"; + /** Teardown exception : {@value} */ + public static final String TEARDOWN_EXCEPTION = "Teardown Exception"; /** * A condition that must be true before the tests are run. This makes it @@ -158,20 +171,6 @@ public class Funtest extends Task { */ private BuildException taskException; - /** {@value} */ - public static final String WARN_OVERRIDING = "Overriding previous definition of "; - /** {@value} */ - public static final String APPLICATION_FORCIBLY_SHUT_DOWN = "Application forcibly shut down"; - /** {@value} */ - public static final String SHUTDOWN_INTERRUPTED = "Shutdown interrupted"; - /** {@value} */ - public static final String SKIPPING_TESTS - = "Condition failed -skipping tests"; - /** Application exception : {@value} */ - public static final String APPLICATION_EXCEPTION = "Application Exception"; - /** Teardown exception : {@value} */ - public static final String TEARDOWN_EXCEPTION = "Teardown Exception"; - /** * Log if the definition is overriding something * @@ -378,8 +377,9 @@ public class Funtest extends Task { * @param role role of the task */ private void validateTask(Task task, String role) { - if (task!=null && task.getProject() == null) { - throw new BuildException(role + " task is not bound to the project" + task); + if (task != null && task.getProject() == null) { + throw new BuildException("%s task is not bound to the project %s", + role, task); } } @@ -392,6 +392,7 @@ public class Funtest extends Task { * test failing that is more important. * @throws BuildException if something was caught during the run or teardown. */ + @Override public void execute() throws BuildException { //validation @@ -566,12 +567,13 @@ public class Funtest extends Task { } private static class NestedCondition extends ConditionBase implements Condition { + @Override public boolean eval() { if (countConditions() != 1) { throw new BuildException( "A single nested condition is required."); } - return ((Condition) (getConditions().nextElement())).eval(); + return getConditions().nextElement().eval(); } } } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/unix/AbstractAccessTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/unix/AbstractAccessTask.java index d3385e6cc..baced9e50 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/unix/AbstractAccessTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/unix/AbstractAccessTask.java @@ -69,6 +69,7 @@ public abstract class AbstractAccessTask * @ant.attribute ignore="true" * @param cmdl A user supplied command line that we won't accept. */ + @Override public void setCommand(Commandline cmdl) { throw new BuildException(getTaskType() + " doesn\'t support the command attribute", @@ -81,6 +82,7 @@ public abstract class AbstractAccessTask * @ant.attribute ignore="true" * @param skip A user supplied boolean we won't accept. */ + @Override public void setSkipEmptyFilesets(boolean skip) { throw new BuildException(getTaskType() + " doesn\'t support the " + "skipemptyfileset attribute", @@ -93,6 +95,7 @@ public abstract class AbstractAccessTask * @ant.attribute ignore="true" * @param b A user supplied boolean we won't accept. */ + @Override public void setAddsourcefile(boolean b) { throw new BuildException(getTaskType() + " doesn\'t support the addsourcefile attribute", getLocation()); @@ -103,6 +106,7 @@ public abstract class AbstractAccessTask * @return true if a valid OS, for unix this is always true, otherwise * use the superclasses' test (user set). */ + @Override protected boolean isValidOs() { return getOs() == null && getOsFamily() == null ? Os.isFamily(Os.FAMILY_UNIX) : super.isValidOs(); diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chgrp.java b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chgrp.java index 1279a2c82..ecf819b92 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chgrp.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chgrp.java @@ -63,6 +63,7 @@ public class Chgrp extends AbstractAccessTask { * Ensure that all the required arguments and other conditions have * been set. */ + @Override protected void checkConfiguration() { if (!haveGroup) { throw new BuildException("Required attribute group not set in " @@ -76,6 +77,7 @@ public class Chgrp extends AbstractAccessTask { * * @param e User supplied executable that we won't accept. */ + @Override public void setExecutable(String e) { throw new BuildException(getTaskType() + " doesn\'t support the executable" diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chown.java b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chown.java index 53f72536b..cd827e616 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chown.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Chown.java @@ -63,6 +63,7 @@ public class Chown extends AbstractAccessTask { * Ensure that all the required arguments and other conditions have * been set. */ + @Override protected void checkConfiguration() { if (!haveOwner) { throw new BuildException("Required attribute owner not set in" @@ -76,6 +77,7 @@ public class Chown extends AbstractAccessTask { * * @param e User supplied executable that we won't accept. */ + @Override public void setExecutable(String e) { throw new BuildException(getTaskType() + " doesn\'t support the executable" diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java index a45b74ffb..606a2b3c4 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/unix/Symlink.java @@ -35,14 +35,16 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.io.PrintStream; +import java.util.ArrayList; +import java.util.HashMap; import java.nio.file.Files; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.Properties; -import java.util.Vector; +import java.util.Set; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; @@ -119,7 +121,7 @@ public class Symlink extends DispatchTask { private String resource; private String link; - private Vector fileSets = new Vector(); + private List<FileSet> fileSets = new ArrayList<>(); private String linkFileName; private boolean overwrite; private boolean failonerror; @@ -189,8 +191,6 @@ public class Symlink extends DispatchTask { SYMLINK_UTILS.deleteSymbolicLink(FILE_UTILS .resolveFile(new File("."), link), this); - } catch (FileNotFoundException fnfe) { - handleError(fnfe.toString()); } catch (IOException ioe) { handleError(ioe.toString()); } finally { @@ -206,14 +206,13 @@ public class Symlink extends DispatchTask { public void recreate() throws BuildException { try { if (fileSets.isEmpty()) { - handleError("File set identifying link file(s) " - + "required for action recreate"); + handleError( + "File set identifying link file(s) required for action recreate"); return; } Properties links = loadLinks(fileSets); - for (Iterator kitr = links.keySet().iterator(); kitr.hasNext();) { - String lnk = (String) kitr.next(); + for (String lnk : links.stringPropertyNames()) { String res = links.getProperty(lnk); // handle the case where lnk points to a directory (bug 25181) try { @@ -249,30 +248,20 @@ public class Symlink extends DispatchTask { handleError("Name of file to record links in required"); return; } - // create a hashtable to group them by parent directory: - Hashtable byDir = new Hashtable(); + // create a map to group them by parent directory: + Map<File, List<File>> byDir = new HashMap<>(); // get an Iterator of file objects representing links (canonical): - for (Iterator litr = findLinks(fileSets).iterator(); - litr.hasNext();) { - File thisLink = (File) litr.next(); - File parent = thisLink.getParentFile(); - Vector v = (Vector) byDir.get(parent); - if (v == null) { - v = new Vector(); - byDir.put(parent, v); - } - v.addElement(thisLink); - } + findLinks(fileSets).forEach(lnk -> byDir + .computeIfAbsent(lnk.getParentFile(), k -> new ArrayList<>()) + .add(lnk)); + // write a Properties file in each directory: - for (Iterator dirs = byDir.keySet().iterator(); dirs.hasNext();) { - File dir = (File) dirs.next(); - Vector linksInDir = (Vector) byDir.get(dir); + byDir.forEach((dir, linksInDir) -> { Properties linksToStore = new Properties(); // fill up a Properties object with link and resource names: - for (Iterator dlnk = linksInDir.iterator(); dlnk.hasNext();) { - File lnk = (File) dlnk.next(); + for (File lnk : linksInDir) { try { linksToStore.put(lnk.getName(), lnk.getCanonicalPath()); } catch (IOException ioe) { @@ -280,7 +269,7 @@ public class Symlink extends DispatchTask { } } writePropertyFile(linksToStore, dir); - } + }); } finally { setDefaults(); } @@ -367,7 +356,7 @@ public class Symlink extends DispatchTask { * @param set The fileset to add. */ public void addFileset(FileSet set) { - fileSets.addElement(set); + fileSets.add(set); } /** @@ -434,15 +423,11 @@ public class Symlink extends DispatchTask { */ private void writePropertyFile(Properties properties, File dir) throws BuildException { - BufferedOutputStream bos = null; - try { - bos = new BufferedOutputStream( - Files.newOutputStream(new File(dir, linkFileName).toPath())); + try (BufferedOutputStream bos = new BufferedOutputStream( + Files.newOutputStream(new File(dir, linkFileName).toPath()))) { properties.store(bos, "Symlinks from " + dir); } catch (IOException ioe) { throw new BuildException(ioe, getLocation()); - } finally { - FileUtils.close(bos); } } @@ -485,16 +470,14 @@ public class Symlink extends DispatchTask { } } } - String[] cmd = new String[] {"ln", options, res, lnk}; try { - Execute.runCommand(this, cmd); + Execute.runCommand(this, "ln", options, res, lnk); } catch (BuildException failedToExecute) { if (failonerror) { throw failedToExecute; - } else { - //log at the info level, and keep going. - log(failedToExecute.getMessage(), failedToExecute, Project.MSG_INFO); } + //log at the info level, and keep going. + log(failedToExecute.getMessage(), failedToExecute, Project.MSG_INFO); } } @@ -505,33 +488,30 @@ public class Symlink extends DispatchTask { * "record". This means that filesets are interpreted * as the directories in which links may be found. * - * @param v The filesets specified by the user. + * @param fileSets The filesets specified by the user. * @return A HashSet of <code>File</code> objects containing the * links (with canonical parent directories). */ - private HashSet findLinks(Vector v) { - HashSet result = new HashSet(); - final int size = v.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) v.get(i); + private Set<File> findLinks(List<FileSet> fileSets) { + Set<File> result = new HashSet<>(); + for (FileSet fs : fileSets) { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); - String[][] fnd = new String[][] - {ds.getIncludedFiles(), ds.getIncludedDirectories()}; + File dir = fs.getDir(getProject()); - for (int j = 0; j < fnd.length; j++) { - for (int k = 0; k < fnd[j].length; k++) { + + Stream.of(ds.getIncludedFiles(), ds.getIncludedDirectories()) + .flatMap(Stream::of).forEach(path -> { try { - File f = new File(dir, fnd[j][k]); + File f = new File(dir, path); File pf = f.getParentFile(); String name = f.getName(); if (SYMLINK_UTILS.isSymbolicLink(pf, name)) { result.add(new File(pf.getCanonicalFile(), name)); } } catch (IOException e) { - handleError("IOException: " + fnd[j][k] + " omitted"); + handleError("IOException: " + path + " omitted"); } - } - } + }); } return result; } @@ -544,41 +524,35 @@ public class Symlink extends DispatchTask { * names of the property files with the link information and the * subdirectories in which to look for them. * - * @param v The <code>FileSet</code>s for this task. + * @param fileSets The <code>FileSet</code>s for this task. * @return The links to be made. */ - private Properties loadLinks(Vector v) { + private Properties loadLinks(List<FileSet> fileSets) { Properties finalList = new Properties(); // loop through the supplied file sets: - final int size = v.size(); - for (int i = 0; i < size; i++) { - FileSet fs = (FileSet) v.elementAt(i); + for (FileSet fs : fileSets) { DirectoryScanner ds = new DirectoryScanner(); fs.setupDirectoryScanner(ds, getProject()); ds.setFollowSymlinks(false); ds.scan(); - String[] incs = ds.getIncludedFiles(); File dir = fs.getDir(getProject()); // load included files as properties files: - for (int j = 0; j < incs.length; j++) { - File inc = new File(dir, incs[j]); + for (String name : ds.getIncludedFiles()) { + File inc = new File(dir, name); File pf = inc.getParentFile(); Properties lnks = new Properties(); - InputStream is = null; - try { - is = new BufferedInputStream(Files.newInputStream(inc.toPath())); + try (InputStream is = new BufferedInputStream( + Files.newInputStream(inc.toPath()))) { lnks.load(is); pf = pf.getCanonicalFile(); } catch (FileNotFoundException fnfe) { - handleError("Unable to find " + incs[j] + "; skipping it."); + handleError("Unable to find " + name + "; skipping it."); continue; } catch (IOException ioe) { - handleError("Unable to open " + incs[j] - + " or its parent dir; skipping it."); + handleError("Unable to open " + name + + " or its parent dir; skipping it."); continue; - } finally { - FileUtils.close(is); } lnks.list(new PrintStream( new LogOutputStream(this, Project.MSG_INFO))); @@ -586,8 +560,7 @@ public class Symlink extends DispatchTask { // This method assumes that all links are defined in // terms of absolute paths, or paths relative to the // working directory: - for (Iterator kitr = lnks.keySet().iterator(); kitr.hasNext();) { - String key = (String) kitr.next(); + for (String key : lnks.stringPropertyNames()) { finalList.put(new File(pf, key).getAbsolutePath(), lnks.getProperty(key)); } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/windows/Attrib.java b/src/main/org/apache/tools/ant/taskdefs/optional/windows/Attrib.java index e02919141..7fe1351a7 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/windows/Attrib.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/windows/Attrib.java @@ -93,6 +93,7 @@ public class Attrib extends ExecuteOn { /** * Check the attributes. */ + @Override protected void checkConfiguration() { if (!haveAttr()) { throw new BuildException("Missing attribute parameter", @@ -107,6 +108,7 @@ public class Attrib extends ExecuteOn { * @param e ignored * @ant.attribute ignore="true" */ + @Override public void setExecutable(String e) { throw new BuildException(getTaskType() + " doesn\'t support the executable attribute", getLocation()); @@ -129,6 +131,7 @@ public class Attrib extends ExecuteOn { * @param b ignored * @ant.attribute ignore="true" */ + @Override public void setAddsourcefile(boolean b) { throw new BuildException(getTaskType() + " doesn\'t support the addsourcefile attribute", getLocation()); @@ -140,6 +143,7 @@ public class Attrib extends ExecuteOn { * @param skip ignored * @ant.attribute ignore="true" */ + @Override public void setSkipEmptyFilesets(boolean skip) { throw new BuildException(getTaskType() + " doesn\'t support the " + "skipemptyfileset attribute", @@ -152,6 +156,7 @@ public class Attrib extends ExecuteOn { * @param parallel ignored * @ant.attribute ignore="true" */ + @Override public void setParallel(boolean parallel) { throw new BuildException(getTaskType() + " doesn\'t support the parallel attribute", @@ -164,6 +169,7 @@ public class Attrib extends ExecuteOn { * @param max ignored * @ant.attribute ignore="true" */ + @Override public void setMaxParallel(int max) { throw new BuildException(getTaskType() + " doesn\'t support the maxparallel attribute", @@ -175,13 +181,14 @@ public class Attrib extends ExecuteOn { * Default is to allow windows * @return true if the os is valid. */ + @Override protected boolean isValidOs() { return getOs() == null && getOsFamily() == null ? Os.isFamily(Os.FAMILY_WINDOWS) : super.isValidOs(); } private static String getSignString(boolean attr) { - return (attr ? SET : UNSET); + return attr ? SET : UNSET; } private void addArg(boolean sign, String attribute) { diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/xz/Unxz.java b/src/main/org/apache/tools/ant/taskdefs/optional/xz/Unxz.java index f55fb7c3b..4502d070a 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/xz/Unxz.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/xz/Unxz.java @@ -19,13 +19,11 @@ package org.apache.tools.ant.taskdefs.optional.xz; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Unpack; -import org.apache.tools.ant.util.FileUtils; import org.tukaani.xz.XZInputStream; /** @@ -46,6 +44,7 @@ public class Unxz extends Unpack { * Get the default extension. * @return the value ".xz" */ + @Override protected String getDefaultExtension() { return DEFAULT_EXTENSION; } @@ -53,18 +52,15 @@ public class Unxz extends Unpack { /** * Implement the gunzipping. */ + @Override protected void extract() { if (srcResource.getLastModified() > dest.lastModified()) { log("Expanding " + srcResource.getName() + " to " + dest.getAbsolutePath()); - OutputStream out = null; - XZInputStream zIn = null; - InputStream fis = null; - try { - out = Files.newOutputStream(dest.toPath()); - fis = srcResource.getInputStream(); - zIn = new XZInputStream(fis); + try (XZInputStream zIn = + new XZInputStream(srcResource.getInputStream()); + OutputStream out = Files.newOutputStream(dest.toPath())) { byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; do { @@ -74,10 +70,6 @@ public class Unxz extends Unpack { } catch (IOException ioe) { String msg = "Problem expanding xz " + ioe.getMessage(); throw new BuildException(msg, ioe, getLocation()); - } finally { - FileUtils.close(fis); - FileUtils.close(out); - FileUtils.close(zIn); } } } @@ -88,6 +80,7 @@ public class Unxz extends Unpack { * <p>This implementation returns true only.</p> * @return true */ + @Override protected boolean supportsNonFileResources() { return true; } diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/xz/Xz.java b/src/main/org/apache/tools/ant/taskdefs/optional/xz/Xz.java index 76031921c..58cff61c9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/xz/Xz.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/xz/Xz.java @@ -18,12 +18,10 @@ package org.apache.tools.ant.taskdefs.optional.xz; -import java.io.BufferedOutputStream; import java.io.IOException; import java.nio.file.Files; import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.taskdefs.Pack; import org.tukaani.xz.LZMA2Options; import org.tukaani.xz.XZOutputStream; @@ -41,17 +39,14 @@ public class Xz extends Pack { /** * Compress the zipFile. */ + @Override protected void pack() { - XZOutputStream zOut = null; - try { - zOut = new XZOutputStream(Files.newOutputStream(zipFile.toPath()), - new LZMA2Options()); + try (XZOutputStream zOut = new XZOutputStream( + Files.newOutputStream(zipFile.toPath()), new LZMA2Options())) { zipResource(getSrcResource(), zOut); } catch (IOException ioe) { String msg = "Problem creating xz " + ioe.getMessage(); throw new BuildException(msg, ioe, getLocation()); - } finally { - FileUtils.close(zOut); } } @@ -61,6 +56,7 @@ public class Xz extends Pack { * <p>This implementation always returns true only.</p> * @return true */ + @Override protected boolean supportsNonFileResources() { return true; } |