http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTask.java ---------------------------------------------------------------------- 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 c608583..abc52e3 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; + } + }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jlink/ClassNameReader.java ---------------------------------------------------------------------- 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 20e9fc5..7609c2f 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; } - } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jlink/JlinkTask.java ---------------------------------------------------------------------- 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 f5767e6..4e4b0aa 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; - } - - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jlink/jlink.java ---------------------------------------------------------------------- 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 4f3cff9..0d4895c 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(); } - } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/Jasper41Mangler.java ---------------------------------------------------------------------- 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 609938c..d863715 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; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspC.java ---------------------------------------------------------------------- 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 9832e3e..4af9f3d 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 } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/JspNameMangler.java ---------------------------------------------------------------------- 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 850c6bc..4cde079 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; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/WLJspc.java ---------------------------------------------------------------------- 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 45a427a..779b01b 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); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/DefaultJspCompilerAdapter.java ---------------------------------------------------------------------- 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 5c4d0e3..303ef6f 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(); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JasperC.java ---------------------------------------------------------------------- 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 80ed601..46644dd 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"); } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/jsp/compilers/JspCompilerAdapterFactory.java ---------------------------------------------------------------------- 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 2876ba0..a172340 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) { http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/AggregateTransformer.java ---------------------------------------------------------------------- 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 026412f..b229d56 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)); } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/BaseTest.java ---------------------------------------------------------------------- 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 55e7a5d..0462969 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; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/BatchTest.java ---------------------------------------------------------------------- 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 f41b96f..fb5d44b 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; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/BriefJUnitResultFormatter.java ---------------------------------------------------------------------- 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 46d6c61..975de68 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()); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/CustomJUnit4TestAdapterCache.java ---------------------------------------------------------------------- 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 8ad40dd..5b04c37 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); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java ---------------------------------------------------------------------- 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 325f44c..39d0ab3 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()); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/Enumerations.java ---------------------------------------------------------------------- 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 327547e..1ca4a0c 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(); } } - -
