| @@ -178,7 +178,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo | |||||
| * The components of the classpath that the classloader searches | * The components of the classpath that the classloader searches | ||||
| * for classes. | * for classes. | ||||
| */ | */ | ||||
| private final Vector<File> pathComponents = new VectorSet<File>(); | |||||
| private final Vector<File> pathComponents = new VectorSet<>(); | |||||
| /** | /** | ||||
| * The project to which this class loader belongs. | * The project to which this class loader belongs. | ||||
| @@ -196,14 +196,14 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo | |||||
| * loader regardless of whether the parent class loader is being searched | * loader regardless of whether the parent class loader is being searched | ||||
| * first or not. | * first or not. | ||||
| */ | */ | ||||
| private final Vector<String> systemPackages = new Vector<String>(); | |||||
| private final Vector<String> systemPackages = new Vector<>(); | |||||
| /** | /** | ||||
| * These are the package roots that are to be loaded by this class loader | * These are the package roots that are to be loaded by this class loader | ||||
| * regardless of whether the parent class loader is being searched first | * regardless of whether the parent class loader is being searched first | ||||
| * or not. | * or not. | ||||
| */ | */ | ||||
| private final Vector<String> loaderPackages = new Vector<String>(); | |||||
| private final Vector<String> loaderPackages = new Vector<>(); | |||||
| /** | /** | ||||
| * Whether or not this classloader will ignore the base | * Whether or not this classloader will ignore the base | ||||
| @@ -221,7 +221,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo | |||||
| /** | /** | ||||
| * A hashtable of zip files opened by the classloader (File to JarFile). | * A hashtable of zip files opened by the classloader (File to JarFile). | ||||
| */ | */ | ||||
| private Hashtable<File, JarFile> jarFiles = new Hashtable<File, JarFile>(); | |||||
| private Hashtable<File, JarFile> jarFiles = new Hashtable<>(); | |||||
| /** Static map of jar file/time to manifest class-path entries */ | /** Static map of jar file/time to manifest class-path entries */ | ||||
| private static Map<String, String> pathMap = | private static Map<String, String> pathMap = | ||||
| @@ -293,8 +293,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo | |||||
| * classloader should be consulted before trying to | * classloader should be consulted before trying to | ||||
| * load the a class through this loader. | * load the a class through this loader. | ||||
| */ | */ | ||||
| public AntClassLoader( | |||||
| final ClassLoader parent, final Project project, final Path classpath, final boolean parentFirst) { | |||||
| public AntClassLoader(final ClassLoader parent, final Project project, | |||||
| final Path classpath, final boolean parentFirst) { | |||||
| this(project, classpath); | this(project, classpath); | ||||
| if (parent != null) { | if (parent != null) { | ||||
| setParent(parent); | setParent(parent); | ||||
| @@ -315,7 +315,8 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener, Clo | |||||
| * classloader should be consulted before trying to | * classloader should be consulted before trying to | ||||
| * load the a class through this loader. | * load the a class through this loader. | ||||
| */ | */ | ||||
| public AntClassLoader(final Project project, final Path classpath, final boolean parentFirst) { | |||||
| public AntClassLoader(final Project project, final Path classpath, | |||||
| final boolean parentFirst) { | |||||
| this(null, project, classpath, parentFirst); | this(null, project, classpath, parentFirst); | ||||
| } | } | ||||
| @@ -21,6 +21,7 @@ import java.io.BufferedReader; | |||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.InputStream; | import java.io.InputStream; | ||||
| import java.io.InputStreamReader; | import java.io.InputStreamReader; | ||||
| import java.io.UnsupportedEncodingException; | |||||
| import java.net.URL; | import java.net.URL; | ||||
| import java.net.URLConnection; | import java.net.URLConnection; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| @@ -151,7 +152,7 @@ public class ArgumentProcessorRegistry { | |||||
| try { | try { | ||||
| try { | try { | ||||
| isr = new InputStreamReader(is, "UTF-8"); | isr = new InputStreamReader(is, "UTF-8"); | ||||
| } catch (java.io.UnsupportedEncodingException e) { | |||||
| } catch (UnsupportedEncodingException e) { | |||||
| isr = new InputStreamReader(is); | isr = new InputStreamReader(is); | ||||
| } | } | ||||
| BufferedReader rd = new BufferedReader(isr); | BufferedReader rd = new BufferedReader(isr); | ||||
| @@ -38,12 +38,25 @@ public class BuildException extends RuntimeException { | |||||
| * Constructs an exception with the given descriptive message. | * Constructs an exception with the given descriptive message. | ||||
| * | * | ||||
| * @param message A description of or information about the exception. | * @param message A description of or information about the exception. | ||||
| * Should not be <code>null</code>. | |||||
| * Should not be {@code null}. | |||||
| */ | */ | ||||
| public BuildException(String message) { | public BuildException(String message) { | ||||
| super(message); | super(message); | ||||
| } | } | ||||
| /** | |||||
| * Constructs an exception with the given format pattern and arguments. | |||||
| * | |||||
| * @param pattern A description of or information about the exception. | |||||
| * Should not be {@code null}. | |||||
| * @param formatArguments | |||||
| * @see String#format(String, Object...) | |||||
| * @since Ant 1.11 | |||||
| */ | |||||
| public BuildException(String pattern, Object... formatArguments) { | |||||
| super(String.format(pattern, formatArguments)); | |||||
| } | |||||
| /** | /** | ||||
| * Constructs an exception with the given message and exception as | * Constructs an exception with the given message and exception as | ||||
| * a root cause. | * a root cause. | ||||
| @@ -59,31 +59,31 @@ import org.apache.tools.ant.util.FileUtils; | |||||
| */ | */ | ||||
| public class ComponentHelper { | public class ComponentHelper { | ||||
| /** Map of component name to lists of restricted definitions */ | /** Map of component name to lists of restricted definitions */ | ||||
| private Map<String, List<AntTypeDefinition>> restrictedDefinitions = new HashMap<String, List<AntTypeDefinition>>(); | |||||
| private Map<String, List<AntTypeDefinition>> restrictedDefinitions = new HashMap<>(); | |||||
| /** Map from component name to anttypedefinition */ | /** Map from component name to anttypedefinition */ | ||||
| private final Hashtable<String, AntTypeDefinition> antTypeTable = new Hashtable<String, AntTypeDefinition>(); | |||||
| private final Hashtable<String, AntTypeDefinition> antTypeTable = new Hashtable<>(); | |||||
| /** Map of tasks generated from antTypeTable */ | /** Map of tasks generated from antTypeTable */ | ||||
| private final Hashtable<String, Class<?>> taskClassDefinitions = new Hashtable<String, Class<?>>(); | |||||
| private final Hashtable<String, Class<?>> taskClassDefinitions = new Hashtable<>(); | |||||
| /** flag to rebuild taskClassDefinitions */ | /** flag to rebuild taskClassDefinitions */ | ||||
| private boolean rebuildTaskClassDefinitions = true; | private boolean rebuildTaskClassDefinitions = true; | ||||
| /** Map of types generated from antTypeTable */ | /** Map of types generated from antTypeTable */ | ||||
| private final Hashtable<String, Class<?>> typeClassDefinitions = new Hashtable<String, Class<?>>(); | |||||
| private final Hashtable<String, Class<?>> typeClassDefinitions = new Hashtable<>(); | |||||
| /** flag to rebuild typeClassDefinitions */ | /** flag to rebuild typeClassDefinitions */ | ||||
| private boolean rebuildTypeClassDefinitions = true; | private boolean rebuildTypeClassDefinitions = true; | ||||
| /** Set of namespaces that have been checked for antlibs */ | /** Set of namespaces that have been checked for antlibs */ | ||||
| private final HashSet<String> checkedNamespaces = new HashSet<String>(); | |||||
| private final HashSet<String> checkedNamespaces = new HashSet<>(); | |||||
| /** | /** | ||||
| * Stack of antlib contexts used to resolve definitions while | * Stack of antlib contexts used to resolve definitions while | ||||
| * processing antlib | * processing antlib | ||||
| */ | */ | ||||
| private Stack<String> antLibStack = new Stack<String>(); | |||||
| private Stack<String> antLibStack = new Stack<>(); | |||||
| /** current antlib uri */ | /** current antlib uri */ | ||||
| private String antLibCurrentUri = null; | private String antLibCurrentUri = null; | ||||
| @@ -189,7 +189,6 @@ public class ComponentHelper { | |||||
| */ | */ | ||||
| public void setProject(Project project) { | public void setProject(Project project) { | ||||
| this.project = project; | this.project = project; | ||||
| // antTypeTable = new Hashtable<String, AntTypeDefinition>(project); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -205,13 +204,13 @@ public class ComponentHelper { | |||||
| * @return A deep copy of the restrictredDefinition | * @return A deep copy of the restrictredDefinition | ||||
| */ | */ | ||||
| private Map<String, List<AntTypeDefinition>> getRestrictedDefinition() { | private Map<String, List<AntTypeDefinition>> getRestrictedDefinition() { | ||||
| final Map<String, List<AntTypeDefinition>> result = new HashMap<String, List<AntTypeDefinition>>(); | |||||
| final Map<String, List<AntTypeDefinition>> result = new HashMap<>(); | |||||
| synchronized (restrictedDefinitions) { | synchronized (restrictedDefinitions) { | ||||
| for (Map.Entry<String, List<AntTypeDefinition>> entry : restrictedDefinitions.entrySet()) { | for (Map.Entry<String, List<AntTypeDefinition>> entry : restrictedDefinitions.entrySet()) { | ||||
| List<AntTypeDefinition> entryVal = entry.getValue(); | List<AntTypeDefinition> entryVal = entry.getValue(); | ||||
| synchronized (entryVal) { | synchronized (entryVal) { | ||||
| //copy the entryVal | //copy the entryVal | ||||
| entryVal = new ArrayList<AntTypeDefinition> (entryVal); | |||||
| entryVal = new ArrayList<>(entryVal); | |||||
| } | } | ||||
| result.put(entry.getKey(), entryVal); | result.put(entry.getKey(), entryVal); | ||||
| } | } | ||||
| @@ -750,7 +749,7 @@ public class ComponentHelper { | |||||
| */ | */ | ||||
| public void exitAntLib() { | public void exitAntLib() { | ||||
| antLibStack.pop(); | antLibStack.pop(); | ||||
| antLibCurrentUri = (antLibStack.size() == 0) ? null : (String) antLibStack.peek(); | |||||
| antLibCurrentUri = (antLibStack.isEmpty()) ? null : (String) antLibStack.peek(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -759,9 +758,7 @@ public class ComponentHelper { | |||||
| private void initTasks() { | private void initTasks() { | ||||
| ClassLoader classLoader = getClassLoader(null); | ClassLoader classLoader = getClassLoader(null); | ||||
| Properties props = getDefaultDefinitions(false); | Properties props = getDefaultDefinitions(false); | ||||
| Enumeration<?> e = props.propertyNames(); | |||||
| while (e.hasMoreElements()) { | |||||
| String name = (String) e.nextElement(); | |||||
| for (String name : props.stringPropertyNames()) { | |||||
| String className = props.getProperty(name); | String className = props.getProperty(name); | ||||
| AntTypeDefinition def = new AntTypeDefinition(); | AntTypeDefinition def = new AntTypeDefinition(); | ||||
| def.setName(name); | def.setName(name); | ||||
| @@ -902,7 +899,7 @@ public class ComponentHelper { | |||||
| probablyIDE = true; | probablyIDE = true; | ||||
| antHomeLib = "ANT_HOME" + File.separatorChar + "lib"; | antHomeLib = "ANT_HOME" + File.separatorChar + "lib"; | ||||
| } | } | ||||
| StringBuffer dirListingText = new StringBuffer(); | |||||
| StringBuilder dirListingText = new StringBuilder(); | |||||
| final String tab = " -"; | final String tab = " -"; | ||||
| dirListingText.append(tab); | dirListingText.append(tab); | ||||
| dirListingText.append(antHomeLib); | dirListingText.append(antHomeLib); | ||||
| @@ -1026,14 +1023,7 @@ public class ComponentHelper { | |||||
| + " declarations have taken place."); | + " declarations have taken place."); | ||||
| if (uri.length() > 0) { | if (uri.length() > 0) { | ||||
| final List<AntTypeDefinition> matches = findTypeMatches(uri); | final List<AntTypeDefinition> matches = findTypeMatches(uri); | ||||
| if (matches.size() > 0) { | |||||
| out.println(); | |||||
| out.println("The definitions in the namespace " + uri + " are:"); | |||||
| for (AntTypeDefinition def : matches) { | |||||
| String local = ProjectHelper.extractNameFromComponentName(def.getName()); | |||||
| out.println(" " + local); | |||||
| } | |||||
| } else { | |||||
| if (matches.isEmpty()) { | |||||
| out.println("No types or tasks have been defined in this namespace yet"); | out.println("No types or tasks have been defined in this namespace yet"); | ||||
| if (isAntlib) { | if (isAntlib) { | ||||
| out.println(); | out.println(); | ||||
| @@ -1041,6 +1031,13 @@ public class ComponentHelper { | |||||
| out.println("Action: Check that the implementing library exists in one of:"); | out.println("Action: Check that the implementing library exists in one of:"); | ||||
| out.println(dirListing); | out.println(dirListing); | ||||
| } | } | ||||
| } else { | |||||
| out.println(); | |||||
| out.println("The definitions in the namespace " + uri + " are:"); | |||||
| for (AntTypeDefinition def : matches) { | |||||
| String local = ProjectHelper.extractNameFromComponentName(def.getName()); | |||||
| out.println(" " + local); | |||||
| } | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -66,7 +66,6 @@ public final class DefaultDefinitions { | |||||
| private void componentDef(String ns, String name, String classname) { | private void componentDef(String ns, String name, String classname) { | ||||
| AntTypeDefinition def = new AntTypeDefinition(); | AntTypeDefinition def = new AntTypeDefinition(); | ||||
| String n = ProjectHelper.genComponentName(ns, name); | |||||
| def.setName(ProjectHelper.genComponentName(ns, name)); | def.setName(ProjectHelper.genComponentName(ns, name)); | ||||
| def.setClassName(classname); | def.setClassName(classname); | ||||
| def.setClassLoader(getClass().getClassLoader()); | def.setClassLoader(getClass().getClassLoader()); | ||||
| @@ -24,9 +24,10 @@ import java.io.PrintStream; | |||||
| import java.io.StringReader; | import java.io.StringReader; | ||||
| import java.text.DateFormat; | import java.text.DateFormat; | ||||
| import java.util.Date; | import java.util.Date; | ||||
| import java.util.stream.Collectors; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.util.DateUtils; | import org.apache.tools.ant.util.DateUtils; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| import org.apache.tools.ant.util.StringUtils; | import org.apache.tools.ant.util.StringUtils; | ||||
| /** | /** | ||||
| @@ -257,48 +258,30 @@ public class DefaultLogger implements BuildLogger { | |||||
| // Filter out messages based on priority | // Filter out messages based on priority | ||||
| if (priority <= msgOutputLevel) { | if (priority <= msgOutputLevel) { | ||||
| StringBuffer message = new StringBuffer(); | |||||
| if (event.getTask() != null && !emacsMode) { | |||||
| StringBuilder message = new StringBuilder(); | |||||
| if (event.getTask() == null || emacsMode) { | |||||
| //emacs mode or there is no task | |||||
| message.append(event.getMessage()); | |||||
| } else { | |||||
| // Print out the name of the task if we're in one | // Print out the name of the task if we're in one | ||||
| String name = event.getTask().getTaskName(); | String name = event.getTask().getTaskName(); | ||||
| String label = "[" + name + "] "; | String label = "[" + name + "] "; | ||||
| int size = LEFT_COLUMN_SIZE - label.length(); | int size = LEFT_COLUMN_SIZE - label.length(); | ||||
| StringBuffer tmp = new StringBuffer(); | |||||
| for (int i = 0; i < size; i++) { | |||||
| tmp.append(" "); | |||||
| } | |||||
| tmp.append(label); | |||||
| label = tmp.toString(); | |||||
| BufferedReader r = null; | |||||
| try { | |||||
| r = new BufferedReader( | |||||
| new StringReader(event.getMessage())); | |||||
| String line = r.readLine(); | |||||
| boolean first = true; | |||||
| do { | |||||
| if (first) { | |||||
| if (line == null) { | |||||
| message.append(label); | |||||
| break; | |||||
| } | |||||
| } else { | |||||
| message.append(StringUtils.LINE_SEP); | |||||
| } | |||||
| first = false; | |||||
| message.append(label).append(line); | |||||
| line = r.readLine(); | |||||
| } while (line != null); | |||||
| final String prefix = size > 0 ? Stream.generate(() -> " ") | |||||
| .limit(size).collect(Collectors.joining()) + label : label; | |||||
| try (BufferedReader r = | |||||
| new BufferedReader(new StringReader(event.getMessage()))) { | |||||
| message.append(r.lines().map(line -> prefix + line) | |||||
| .collect(Collectors.joining(StringUtils.LINE_SEP))); | |||||
| if (message.length() == 0) { | |||||
| message.append(prefix); | |||||
| } | |||||
| } catch (IOException e) { | } catch (IOException e) { | ||||
| // shouldn't be possible | // shouldn't be possible | ||||
| message.append(label).append(event.getMessage()); | message.append(label).append(event.getMessage()); | ||||
| } finally { | |||||
| FileUtils.close(r); | |||||
| } | } | ||||
| } else { | |||||
| //emacs mode or there is no task | |||||
| message.append(event.getMessage()); | |||||
| } | } | ||||
| Throwable ex = event.getException(); | Throwable ex = event.getException(); | ||||
| if (Project.MSG_DEBUG <= msgOutputLevel && ex != null) { | if (Project.MSG_DEBUG <= msgOutputLevel && ex != null) { | ||||
| @@ -361,8 +344,7 @@ public class DefaultLogger implements BuildLogger { | |||||
| protected String getTimestamp() { | protected String getTimestamp() { | ||||
| Date date = new Date(System.currentTimeMillis()); | Date date = new Date(System.currentTimeMillis()); | ||||
| DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); | DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); | ||||
| String finishTime = formatter.format(date); | |||||
| return finishTime; | |||||
| return formatter.format(date); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -50,6 +50,7 @@ public class DemuxInputStream extends InputStream { | |||||
| * @return the next byte | * @return the next byte | ||||
| * @throws IOException on error | * @throws IOException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public int read() throws IOException { | public int read() throws IOException { | ||||
| byte[] buffer = new byte[1]; | byte[] buffer = new byte[1]; | ||||
| if (project.demuxInput(buffer, 0, 1) == -1) { | if (project.demuxInput(buffer, 0, 1) == -1) { | ||||
| @@ -67,6 +68,7 @@ public class DemuxInputStream extends InputStream { | |||||
| * @return the number of bytes read | * @return the number of bytes read | ||||
| * @throws IOException on error | * @throws IOException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public int read(byte[] buffer, int offset, int length) throws IOException { | public int read(byte[] buffer, int offset, int length) throws IOException { | ||||
| return project.demuxInput(buffer, offset, length); | return project.demuxInput(buffer, offset, length); | ||||
| } | } | ||||
| @@ -64,7 +64,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| private static final int LF = 0x0a; | private static final int LF = 0x0a; | ||||
| /** Mapping from thread to buffer (Thread to BufferInfo). */ | /** Mapping from thread to buffer (Thread to BufferInfo). */ | ||||
| private WeakHashMap<Thread, BufferInfo> buffers = new WeakHashMap<Thread, BufferInfo>(); | |||||
| private WeakHashMap<Thread, BufferInfo> buffers = new WeakHashMap<>(); | |||||
| /** | /** | ||||
| * The project to send output to. | * The project to send output to. | ||||
| @@ -98,14 +98,12 @@ public class DemuxOutputStream extends OutputStream { | |||||
| */ | */ | ||||
| private BufferInfo getBufferInfo() { | private BufferInfo getBufferInfo() { | ||||
| Thread current = Thread.currentThread(); | Thread current = Thread.currentThread(); | ||||
| BufferInfo bufferInfo = (BufferInfo) buffers.get(current); | |||||
| if (bufferInfo == null) { | |||||
| bufferInfo = new BufferInfo(); | |||||
| return buffers.computeIfAbsent(current, x -> { | |||||
| BufferInfo bufferInfo = new BufferInfo(); | |||||
| bufferInfo.buffer = new ByteArrayOutputStream(INITIAL_SIZE); | bufferInfo.buffer = new ByteArrayOutputStream(INITIAL_SIZE); | ||||
| bufferInfo.crSeen = false; | bufferInfo.crSeen = false; | ||||
| buffers.put(current, bufferInfo); | |||||
| } | |||||
| return bufferInfo; | |||||
| return bufferInfo; | |||||
| }); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -113,7 +111,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| */ | */ | ||||
| private void resetBufferInfo() { | private void resetBufferInfo() { | ||||
| Thread current = Thread.currentThread(); | Thread current = Thread.currentThread(); | ||||
| BufferInfo bufferInfo = (BufferInfo) buffers.get(current); | |||||
| BufferInfo bufferInfo = buffers.get(current); | |||||
| FileUtils.close(bufferInfo.buffer); | FileUtils.close(bufferInfo.buffer); | ||||
| bufferInfo.buffer = new ByteArrayOutputStream(); | bufferInfo.buffer = new ByteArrayOutputStream(); | ||||
| bufferInfo.crSeen = false; | bufferInfo.crSeen = false; | ||||
| @@ -134,6 +132,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| * @param cc data to log (byte). | * @param cc data to log (byte). | ||||
| * @exception IOException if the data cannot be written to the stream | * @exception IOException if the data cannot be written to the stream | ||||
| */ | */ | ||||
| @Override | |||||
| public void write(int cc) throws IOException { | public void write(int cc) throws IOException { | ||||
| final byte c = (byte) cc; | final byte c = (byte) cc; | ||||
| @@ -192,6 +191,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| * | * | ||||
| * @see #flush | * @see #flush | ||||
| */ | */ | ||||
| @Override | |||||
| public void close() throws IOException { | public void close() throws IOException { | ||||
| flush(); | flush(); | ||||
| removeBuffer(); | removeBuffer(); | ||||
| @@ -203,6 +203,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| * | * | ||||
| * @exception IOException if there is a problem flushing the stream. | * @exception IOException if there is a problem flushing the stream. | ||||
| */ | */ | ||||
| @Override | |||||
| public void flush() throws IOException { | public void flush() throws IOException { | ||||
| BufferInfo bufferInfo = getBufferInfo(); | BufferInfo bufferInfo = getBufferInfo(); | ||||
| if (bufferInfo.buffer.size() > 0) { | if (bufferInfo.buffer.size() > 0) { | ||||
| @@ -219,6 +220,7 @@ public class DemuxOutputStream extends OutputStream { | |||||
| * | * | ||||
| * @throws IOException if the data cannot be written into the stream. | * @throws IOException if the data cannot be written into the stream. | ||||
| */ | */ | ||||
| @Override | |||||
| public void write(byte[] b, int off, int len) throws IOException { | public void write(byte[] b, int off, int len) throws IOException { | ||||
| // find the line breaks and pass other chars through in blocks | // find the line breaks and pass other chars through in blocks | ||||
| int offset = off; | int offset = off; | ||||
| @@ -54,9 +54,6 @@ import org.xml.sax.XMLReader; | |||||
| */ | */ | ||||
| public final class Diagnostics { | public final class Diagnostics { | ||||
| /** the version number for java 1.5 returned from JavaEnvUtils */ | |||||
| private static final int JAVA_1_5_NUMBER = 15; | |||||
| /** | /** | ||||
| * value for which a difference between clock and temp file time triggers | * value for which a difference between clock and temp file time triggers | ||||
| * a warning. | * a warning. | ||||
| @@ -113,8 +110,7 @@ public final class Diagnostics { | |||||
| if (home == null) { | if (home == null) { | ||||
| return null; | return null; | ||||
| } | } | ||||
| File libDir = new File(home, "lib"); | |||||
| return listJarFiles(libDir); | |||||
| return listJarFiles(new File(home, "lib")); | |||||
| } | } | ||||
| @@ -124,13 +120,8 @@ public final class Diagnostics { | |||||
| * @return array of files (or null for no such directory) | * @return array of files (or null for no such directory) | ||||
| */ | */ | ||||
| private static File[] listJarFiles(File libDir) { | private static File[] listJarFiles(File libDir) { | ||||
| FilenameFilter filter = new FilenameFilter() { | |||||
| public boolean accept(File dir, String name) { | |||||
| return name.endsWith(".jar"); | |||||
| } | |||||
| }; | |||||
| File[] files = libDir.listFiles(filter); | |||||
| return files; | |||||
| return libDir | |||||
| .listFiles((FilenameFilter) (dir, name) -> name.endsWith(".jar")); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -173,8 +164,7 @@ public final class Diagnostics { | |||||
| return "Could not create an XML Parser"; | return "Could not create an XML Parser"; | ||||
| } | } | ||||
| // check to what is in the classname | // check to what is in the classname | ||||
| String saxParserName = saxParser.getClass().getName(); | |||||
| return saxParserName; | |||||
| return saxParser.getClass().getName(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -187,8 +177,7 @@ public final class Diagnostics { | |||||
| return "Could not create an XSLT Processor"; | return "Could not create an XSLT Processor"; | ||||
| } | } | ||||
| // check to what is in the classname | // check to what is in the classname | ||||
| String processorName = transformer.getClass().getName(); | |||||
| return processorName; | |||||
| return transformer.getClass().getName(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -216,17 +205,15 @@ public final class Diagnostics { | |||||
| */ | */ | ||||
| private static Transformer getXSLTProcessor() { | private static Transformer getXSLTProcessor() { | ||||
| TransformerFactory transformerFactory = TransformerFactory.newInstance(); | TransformerFactory transformerFactory = TransformerFactory.newInstance(); | ||||
| if (transformerFactory == null) { | |||||
| return null; | |||||
| } | |||||
| Transformer transformer = null; | |||||
| try { | |||||
| transformer = transformerFactory.newTransformer(); | |||||
| } catch (Exception e) { | |||||
| // ignore | |||||
| ignoreThrowable(e); | |||||
| if (transformerFactory != null) { | |||||
| try { | |||||
| return transformerFactory.newTransformer(); | |||||
| } catch (Exception e) { | |||||
| // ignore | |||||
| ignoreThrowable(e); | |||||
| } | |||||
| } | } | ||||
| return transformer; | |||||
| return null; | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -22,13 +22,17 @@ import java.io.File; | |||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Arrays; | import java.util.Arrays; | ||||
| import java.util.Collections; | |||||
| import java.util.Deque; | |||||
| import java.util.HashMap; | import java.util.HashMap; | ||||
| import java.util.HashSet; | import java.util.HashSet; | ||||
| import java.util.Iterator; | |||||
| import java.util.LinkedList; | import java.util.LinkedList; | ||||
| import java.util.List; | |||||
| import java.util.Map; | import java.util.Map; | ||||
| import java.util.Set; | import java.util.Set; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import java.util.function.Predicate; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.taskdefs.condition.Os; | import org.apache.tools.ant.taskdefs.condition.Os; | ||||
| import org.apache.tools.ant.types.Resource; | import org.apache.tools.ant.types.Resource; | ||||
| @@ -39,7 +43,6 @@ import org.apache.tools.ant.types.selectors.SelectorScanner; | |||||
| import org.apache.tools.ant.types.selectors.SelectorUtils; | import org.apache.tools.ant.types.selectors.SelectorUtils; | ||||
| import org.apache.tools.ant.types.selectors.TokenizedPath; | import org.apache.tools.ant.types.selectors.TokenizedPath; | ||||
| import org.apache.tools.ant.types.selectors.TokenizedPattern; | import org.apache.tools.ant.types.selectors.TokenizedPattern; | ||||
| import org.apache.tools.ant.util.CollectionUtils; | |||||
| import org.apache.tools.ant.util.FileUtils; | import org.apache.tools.ant.util.FileUtils; | ||||
| import org.apache.tools.ant.util.SymbolicLinkUtils; | import org.apache.tools.ant.util.SymbolicLinkUtils; | ||||
| import org.apache.tools.ant.util.VectorSet; | import org.apache.tools.ant.util.VectorSet; | ||||
| @@ -217,7 +220,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #addDefaultExcludes() | * @see #addDefaultExcludes() | ||||
| */ | */ | ||||
| private static final Set<String> defaultExcludes = new HashSet<String>(); | |||||
| private static final Set<String> defaultExcludes = new HashSet<>(); | |||||
| static { | static { | ||||
| resetDefaultExcludes(); | resetDefaultExcludes(); | ||||
| } | } | ||||
| @@ -310,7 +313,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| private final Set<String> scannedDirs = new HashSet<String>(); | |||||
| private final Set<String> scannedDirs = new HashSet<>(); | |||||
| /** | /** | ||||
| * Map of all include patterns that are full file names and don't | * Map of all include patterns that are full file names and don't | ||||
| @@ -327,7 +330,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private final Map<String, TokenizedPath> includeNonPatterns = new HashMap<String, TokenizedPath>(); | |||||
| private final Map<String, TokenizedPath> includeNonPatterns = new HashMap<>(); | |||||
| /** | /** | ||||
| * Map of all exclude patterns that are full file names and don't | * Map of all exclude patterns that are full file names and don't | ||||
| @@ -344,7 +347,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private final Map<String, TokenizedPath> excludeNonPatterns = new HashMap<String, TokenizedPath>(); | |||||
| private final Map<String, TokenizedPath> excludeNonPatterns = new HashMap<>(); | |||||
| /** | /** | ||||
| * Array of all include patterns that contain wildcards. | * Array of all include patterns that contain wildcards. | ||||
| @@ -423,13 +426,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private final Set<String> notFollowedSymlinks = new HashSet<String>(); | |||||
| /** | |||||
| * Sole constructor. | |||||
| */ | |||||
| public DirectoryScanner() { | |||||
| } | |||||
| private final Set<String> notFollowedSymlinks = new HashSet<>(); | |||||
| /** | /** | ||||
| * Test whether or not a given path matches the start of a given | * Test whether or not a given path matches the start of a given | ||||
| @@ -605,8 +602,8 @@ public class DirectoryScanner | |||||
| public static void resetDefaultExcludes() { | public static void resetDefaultExcludes() { | ||||
| synchronized (defaultExcludes) { | synchronized (defaultExcludes) { | ||||
| defaultExcludes.clear(); | defaultExcludes.clear(); | ||||
| for (int i = 0; i < DEFAULTEXCLUDES.length; i++) { | |||||
| defaultExcludes.add(DEFAULTEXCLUDES[i]); | |||||
| for (String element : DEFAULTEXCLUDES) { | |||||
| defaultExcludes.add(element); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -619,8 +616,9 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @param basedir The base directory to scan. | * @param basedir The base directory to scan. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setBasedir(final String basedir) { | public void setBasedir(final String basedir) { | ||||
| setBasedir(basedir == null ? (File) null | |||||
| setBasedir(basedir == null ? null | |||||
| : new File(basedir.replace('/', File.separatorChar).replace( | : new File(basedir.replace('/', File.separatorChar).replace( | ||||
| '\\', File.separatorChar))); | '\\', File.separatorChar))); | ||||
| } | } | ||||
| @@ -631,6 +629,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @param basedir The base directory for scanning. | * @param basedir The base directory for scanning. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void setBasedir(final File basedir) { | public synchronized void setBasedir(final File basedir) { | ||||
| this.basedir = basedir; | this.basedir = basedir; | ||||
| } | } | ||||
| @@ -641,6 +640,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @return the base directory to be scanned. | * @return the base directory to be scanned. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized File getBasedir() { | public synchronized File getBasedir() { | ||||
| return basedir; | return basedir; | ||||
| } | } | ||||
| @@ -662,6 +662,7 @@ public class DirectoryScanner | |||||
| * @param isCaseSensitive whether or not the file system should be | * @param isCaseSensitive whether or not the file system should be | ||||
| * regarded as a case sensitive one. | * regarded as a case sensitive one. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void setCaseSensitive(final boolean isCaseSensitive) { | public synchronized void setCaseSensitive(final boolean isCaseSensitive) { | ||||
| this.isCaseSensitive = isCaseSensitive; | this.isCaseSensitive = isCaseSensitive; | ||||
| } | } | ||||
| @@ -720,14 +721,13 @@ public class DirectoryScanner | |||||
| * list is given, all elements must be | * list is given, all elements must be | ||||
| * non-<code>null</code>. | * non-<code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void setIncludes(final String[] includes) { | public synchronized void setIncludes(final String[] includes) { | ||||
| if (includes == null) { | if (includes == null) { | ||||
| this.includes = null; | this.includes = null; | ||||
| } else { | } else { | ||||
| this.includes = new String[includes.length]; | |||||
| for (int i = 0; i < includes.length; i++) { | |||||
| this.includes[i] = normalizePattern(includes[i]); | |||||
| } | |||||
| this.includes = Stream.of(includes) | |||||
| .map(DirectoryScanner::normalizePattern).toArray(String[]::new); | |||||
| } | } | ||||
| } | } | ||||
| @@ -743,14 +743,13 @@ public class DirectoryScanner | |||||
| * should be excluded. If a non-<code>null</code> list is | * should be excluded. If a non-<code>null</code> list is | ||||
| * given, all elements must be non-<code>null</code>. | * given, all elements must be non-<code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void setExcludes(final String[] excludes) { | public synchronized void setExcludes(final String[] excludes) { | ||||
| if (excludes == null) { | if (excludes == null) { | ||||
| this.excludes = null; | this.excludes = null; | ||||
| } else { | } else { | ||||
| this.excludes = new String[excludes.length]; | |||||
| for (int i = 0; i < excludes.length; i++) { | |||||
| this.excludes[i] = normalizePattern(excludes[i]); | |||||
| } | |||||
| this.excludes = Stream.of(excludes) | |||||
| .map(DirectoryScanner::normalizePattern).toArray(String[]::new); | |||||
| } | } | ||||
| } | } | ||||
| @@ -769,18 +768,14 @@ public class DirectoryScanner | |||||
| */ | */ | ||||
| public synchronized void addExcludes(final String[] excludes) { | public synchronized void addExcludes(final String[] excludes) { | ||||
| if (excludes != null && excludes.length > 0) { | if (excludes != null && excludes.length > 0) { | ||||
| if (this.excludes != null && this.excludes.length > 0) { | |||||
| final String[] tmp = new String[excludes.length | |||||
| + this.excludes.length]; | |||||
| System.arraycopy(this.excludes, 0, tmp, 0, | |||||
| this.excludes.length); | |||||
| for (int i = 0; i < excludes.length; i++) { | |||||
| tmp[this.excludes.length + i] = | |||||
| normalizePattern(excludes[i]); | |||||
| } | |||||
| this.excludes = tmp; | |||||
| } else { | |||||
| if (this.excludes == null || this.excludes.length == 0) { | |||||
| setExcludes(excludes); | setExcludes(excludes); | ||||
| } else { | |||||
| this.excludes = Stream | |||||
| .concat(Stream.of(this.excludes), | |||||
| Stream.of(excludes) | |||||
| .map(DirectoryScanner::normalizePattern)) | |||||
| .toArray(String[]::new); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -808,6 +803,7 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @param selectors specifies the selectors to be invoked on a scan. | * @param selectors specifies the selectors to be invoked on a scan. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void setSelectors(final FileSelector[] selectors) { | public synchronized void setSelectors(final FileSelector[] selectors) { | ||||
| this.selectors = selectors; | this.selectors = selectors; | ||||
| } | } | ||||
| @@ -833,6 +829,7 @@ public class DirectoryScanner | |||||
| * @exception IllegalStateException if the base directory was set | * @exception IllegalStateException if the base directory was set | ||||
| * incorrectly (i.e. if it doesn't exist or isn't a directory). | * incorrectly (i.e. if it doesn't exist or isn't a directory). | ||||
| */ | */ | ||||
| @Override | |||||
| public void scan() throws IllegalStateException { | public void scan() throws IllegalStateException { | ||||
| synchronized (scanLock) { | synchronized (scanLock) { | ||||
| if (scanning) { | if (scanning) { | ||||
| @@ -857,10 +854,10 @@ public class DirectoryScanner | |||||
| clearResults(); | clearResults(); | ||||
| // set in/excludes to reasonable defaults if needed: | // set in/excludes to reasonable defaults if needed: | ||||
| final boolean nullIncludes = (includes == null); | |||||
| final boolean nullIncludes = includes == null; | |||||
| includes = nullIncludes | includes = nullIncludes | ||||
| ? new String[] {SelectorUtils.DEEP_TREE_MATCH} : includes; | |||||
| final boolean nullExcludes = (excludes == null); | |||||
| ? new String[] { SelectorUtils.DEEP_TREE_MATCH } : includes; | |||||
| final boolean nullExcludes = excludes == null; | |||||
| excludes = nullExcludes ? new String[0] : excludes; | excludes = nullExcludes ? new String[0] : excludes; | ||||
| if (basedir != null && !followSymlinks | if (basedir != null && !followSymlinks | ||||
| @@ -887,22 +884,19 @@ public class DirectoryScanner | |||||
| } else if (!basedir.isDirectory()) { | } else if (!basedir.isDirectory()) { | ||||
| illegal = new IllegalStateException("basedir " | illegal = new IllegalStateException("basedir " | ||||
| + basedir | + basedir | ||||
| + " is not a" | |||||
| + " directory."); | |||||
| + " is not a directory."); | |||||
| } | } | ||||
| if (illegal != null) { | if (illegal != null) { | ||||
| throw illegal; | throw illegal; | ||||
| } | } | ||||
| } | } | ||||
| if (isIncluded(TokenizedPath.EMPTY_PATH)) { | if (isIncluded(TokenizedPath.EMPTY_PATH)) { | ||||
| if (!isExcluded(TokenizedPath.EMPTY_PATH)) { | |||||
| if (isSelected("", basedir)) { | |||||
| dirsIncluded.addElement(""); | |||||
| } else { | |||||
| dirsDeselected.addElement(""); | |||||
| } | |||||
| } else { | |||||
| if (isExcluded(TokenizedPath.EMPTY_PATH)) { | |||||
| dirsExcluded.addElement(""); | dirsExcluded.addElement(""); | ||||
| } else if (isSelected("", basedir)) { | |||||
| dirsIncluded.addElement(""); | |||||
| } else { | |||||
| dirsDeselected.addElement(""); | |||||
| } | } | ||||
| } else { | } else { | ||||
| dirsNotIncluded.addElement(""); | dirsNotIncluded.addElement(""); | ||||
| @@ -930,18 +924,19 @@ public class DirectoryScanner | |||||
| */ | */ | ||||
| private void checkIncludePatterns() { | private void checkIncludePatterns() { | ||||
| ensureNonPatternSetsReady(); | ensureNonPatternSetsReady(); | ||||
| final Map<TokenizedPath, String> newroots = new HashMap<TokenizedPath, String>(); | |||||
| final Map<TokenizedPath, String> newroots = new HashMap<>(); | |||||
| // put in the newroots map the include patterns without | // put in the newroots map the include patterns without | ||||
| // wildcard tokens | // wildcard tokens | ||||
| for (int i = 0; i < includePatterns.length; i++) { | |||||
| final String pattern = includePatterns[i].toString(); | |||||
| for (TokenizedPattern includePattern : includePatterns) { | |||||
| final String pattern = includePattern.toString(); | |||||
| if (!shouldSkipPattern(pattern)) { | if (!shouldSkipPattern(pattern)) { | ||||
| newroots.put(includePatterns[i].rtrimWildcardTokens(), | |||||
| newroots.put(includePattern.rtrimWildcardTokens(), | |||||
| pattern); | pattern); | ||||
| } | } | ||||
| } | } | ||||
| for (final Map.Entry<String, TokenizedPath> entry : includeNonPatterns.entrySet()) { | |||||
| for (final Map.Entry<String, TokenizedPath> entry : includeNonPatterns | |||||
| .entrySet()) { | |||||
| final String pattern = entry.getKey(); | final String pattern = entry.getKey(); | ||||
| if (!shouldSkipPattern(pattern)) { | if (!shouldSkipPattern(pattern)) { | ||||
| newroots.put(entry.getValue(), pattern); | newroots.put(entry.getValue(), pattern); | ||||
| @@ -1046,10 +1041,9 @@ public class DirectoryScanner | |||||
| private boolean shouldSkipPattern(final String pattern) { | private boolean shouldSkipPattern(final String pattern) { | ||||
| if (FileUtils.isAbsolutePath(pattern)) { | if (FileUtils.isAbsolutePath(pattern)) { | ||||
| //skip abs. paths not under basedir, if set: | //skip abs. paths not under basedir, if set: | ||||
| if (basedir != null | |||||
| && !SelectorUtils.matchPatternStart(pattern, | |||||
| basedir.getAbsolutePath(), | |||||
| isCaseSensitive())) { | |||||
| if (!(basedir == null || SelectorUtils.matchPatternStart(pattern, | |||||
| basedir.getAbsolutePath(), | |||||
| isCaseSensitive()))) { | |||||
| return true; | return true; | ||||
| } | } | ||||
| } else if (basedir == null) { | } else if (basedir == null) { | ||||
| @@ -1063,14 +1057,14 @@ public class DirectoryScanner | |||||
| * Clear the result caches for a scan. | * Clear the result caches for a scan. | ||||
| */ | */ | ||||
| protected synchronized void clearResults() { | protected synchronized void clearResults() { | ||||
| filesIncluded = new VectorSet<String>(); | |||||
| filesNotIncluded = new VectorSet<String>(); | |||||
| filesExcluded = new VectorSet<String>(); | |||||
| filesDeselected = new VectorSet<String>(); | |||||
| dirsIncluded = new VectorSet<String>(); | |||||
| dirsNotIncluded = new VectorSet<String>(); | |||||
| dirsExcluded = new VectorSet<String>(); | |||||
| dirsDeselected = new VectorSet<String>(); | |||||
| filesIncluded = new VectorSet<>(); | |||||
| filesNotIncluded = new VectorSet<>(); | |||||
| filesExcluded = new VectorSet<>(); | |||||
| filesDeselected = new VectorSet<>(); | |||||
| dirsIncluded = new VectorSet<>(); | |||||
| dirsNotIncluded = new VectorSet<>(); | |||||
| dirsExcluded = new VectorSet<>(); | |||||
| dirsDeselected = new VectorSet<>(); | |||||
| everythingIncluded = (basedir != null); | everythingIncluded = (basedir != null); | ||||
| scannedDirs.clear(); | scannedDirs.clear(); | ||||
| notFollowedSymlinks.clear(); | notFollowedSymlinks.clear(); | ||||
| @@ -1135,10 +1129,10 @@ public class DirectoryScanner | |||||
| } | } | ||||
| private void processSlowScan(final String[] arr) { | private void processSlowScan(final String[] arr) { | ||||
| for (int i = 0; i < arr.length; i++) { | |||||
| final TokenizedPath path = new TokenizedPath(arr[i]); | |||||
| for (String element : arr) { | |||||
| final TokenizedPath path = new TokenizedPath(element); | |||||
| if (!couldHoldIncluded(path) || contentsExcluded(path)) { | if (!couldHoldIncluded(path) || contentsExcluded(path)) { | ||||
| scandir(new File(basedir, arr[i]), path, false); | |||||
| scandir(new File(basedir, element), path, false); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -1196,17 +1190,17 @@ public class DirectoryScanner | |||||
| if (!dir.exists()) { | if (!dir.exists()) { | ||||
| throw new BuildException(dir + DOES_NOT_EXIST_POSTFIX); | throw new BuildException(dir + DOES_NOT_EXIST_POSTFIX); | ||||
| } else if (!dir.isDirectory()) { | } else if (!dir.isDirectory()) { | ||||
| throw new BuildException(dir + " is not a directory."); | |||||
| throw new BuildException("%s is not a directory.", dir); | |||||
| } else { | } else { | ||||
| throw new BuildException("IO error scanning directory '" | |||||
| + dir.getAbsolutePath() + "'"); | |||||
| throw new BuildException("IO error scanning directory '%s'", | |||||
| dir.getAbsolutePath()); | |||||
| } | } | ||||
| } | } | ||||
| scandir(dir, path, fast, newfiles, new LinkedList<String>()); | scandir(dir, path, fast, newfiles, new LinkedList<String>()); | ||||
| } | } | ||||
| private void scandir(final File dir, final TokenizedPath path, final boolean fast, | private void scandir(final File dir, final TokenizedPath path, final boolean fast, | ||||
| String[] newfiles, final LinkedList<String> directoryNamesFollowed) { | |||||
| String[] newfiles, final Deque<String> directoryNamesFollowed) { | |||||
| String vpath = path.toString(); | String vpath = path.toString(); | ||||
| if (vpath.length() > 0 && !vpath.endsWith(File.separator)) { | if (vpath.length() > 0 && !vpath.endsWith(File.separator)) { | ||||
| vpath += File.separator; | vpath += File.separator; | ||||
| @@ -1217,12 +1211,12 @@ public class DirectoryScanner | |||||
| return; | return; | ||||
| } | } | ||||
| if (!followSymlinks) { | if (!followSymlinks) { | ||||
| final ArrayList<String> noLinks = new ArrayList<String>(); | |||||
| for (int i = 0; i < newfiles.length; i++) { | |||||
| final ArrayList<String> noLinks = new ArrayList<>(); | |||||
| for (String newfile : newfiles) { | |||||
| try { | try { | ||||
| if (SYMLINK_UTILS.isSymbolicLink(dir, newfiles[i])) { | |||||
| final String name = vpath + newfiles[i]; | |||||
| final File file = new File(dir, newfiles[i]); | |||||
| if (SYMLINK_UTILS.isSymbolicLink(dir, newfile)) { | |||||
| final String name = vpath + newfile; | |||||
| final File file = new File(dir, newfile); | |||||
| if (file.isDirectory()) { | if (file.isDirectory()) { | ||||
| dirsExcluded.addElement(name); | dirsExcluded.addElement(name); | ||||
| } else if (file.isFile()) { | } else if (file.isFile()) { | ||||
| @@ -1230,17 +1224,17 @@ public class DirectoryScanner | |||||
| } | } | ||||
| accountForNotFollowedSymlink(name, file); | accountForNotFollowedSymlink(name, file); | ||||
| } else { | } else { | ||||
| noLinks.add(newfiles[i]); | |||||
| noLinks.add(newfile); | |||||
| } | } | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| final String msg = "IOException caught while checking " | final String msg = "IOException caught while checking " | ||||
| + "for links, couldn't get canonical path!"; | + "for links, couldn't get canonical path!"; | ||||
| // will be caught and redirected to Ant's logging system | // will be caught and redirected to Ant's logging system | ||||
| System.err.println(msg); | System.err.println(msg); | ||||
| noLinks.add(newfiles[i]); | |||||
| noLinks.add(newfile); | |||||
| } | } | ||||
| } | } | ||||
| newfiles = (noLinks.toArray(new String[noLinks.size()])); | |||||
| newfiles = noLinks.toArray(new String[noLinks.size()]); | |||||
| } else { | } else { | ||||
| directoryNamesFollowed.addFirst(dir.getName()); | directoryNamesFollowed.addFirst(dir.getName()); | ||||
| } | } | ||||
| @@ -1322,7 +1316,7 @@ public class DirectoryScanner | |||||
| private void accountForIncludedDir(final TokenizedPath name, | private void accountForIncludedDir(final TokenizedPath name, | ||||
| final File file, final boolean fast, | final File file, final boolean fast, | ||||
| final String[] children, | final String[] children, | ||||
| final LinkedList<String> directoryNamesFollowed) { | |||||
| final Deque<String> directoryNamesFollowed) { | |||||
| processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected); | processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected); | ||||
| if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) { | if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) { | ||||
| scandir(file, name, fast, children, directoryNamesFollowed); | scandir(file, name, fast, children, directoryNamesFollowed); | ||||
| @@ -1343,13 +1337,12 @@ public class DirectoryScanner | |||||
| } | } | ||||
| private void processIncluded(final TokenizedPath path, | private void processIncluded(final TokenizedPath path, | ||||
| final File file, final Vector<String> inc, final Vector<String> exc, | |||||
| final Vector<String> des) { | |||||
| final File file, final List<String> inc, final List<String> exc, | |||||
| final List<String> des) { | |||||
| final String name = path.toString(); | final String name = path.toString(); | ||||
| if (inc.contains(name) || exc.contains(name) || des.contains(name)) { | if (inc.contains(name) || exc.contains(name) || des.contains(name)) { | ||||
| return; | return; | ||||
| } | } | ||||
| boolean included = false; | boolean included = false; | ||||
| if (isExcluded(path)) { | if (isExcluded(path)) { | ||||
| exc.add(name); | exc.add(name); | ||||
| @@ -1385,17 +1378,13 @@ public class DirectoryScanner | |||||
| private boolean isIncluded(final TokenizedPath path) { | private boolean isIncluded(final TokenizedPath path) { | ||||
| ensureNonPatternSetsReady(); | ensureNonPatternSetsReady(); | ||||
| if (isCaseSensitive() | |||||
| ? includeNonPatterns.containsKey(path.toString()) | |||||
| : includeNonPatterns.containsKey(path.toString().toUpperCase())) { | |||||
| return true; | |||||
| } | |||||
| for (int i = 0; i < includePatterns.length; i++) { | |||||
| if (includePatterns[i].matchPath(path, isCaseSensitive())) { | |||||
| return true; | |||||
| } | |||||
| String toMatch = path.toString(); | |||||
| if (!isCaseSensitive()) { | |||||
| toMatch = toMatch.toUpperCase(); | |||||
| } | } | ||||
| return false; | |||||
| return includeNonPatterns.containsKey(toMatch) | |||||
| || Stream.of(includePatterns) | |||||
| .anyMatch(p -> p.matchPath(path, isCaseSensitive())); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1419,19 +1408,11 @@ public class DirectoryScanner | |||||
| * least one include pattern, or <code>false</code> otherwise. | * least one include pattern, or <code>false</code> otherwise. | ||||
| */ | */ | ||||
| private boolean couldHoldIncluded(final TokenizedPath tokenizedName) { | private boolean couldHoldIncluded(final TokenizedPath tokenizedName) { | ||||
| for (int i = 0; i < includePatterns.length; i++) { | |||||
| if (couldHoldIncluded(tokenizedName, includePatterns[i])) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| for (final Iterator<TokenizedPath> iter = includeNonPatterns.values().iterator(); | |||||
| iter.hasNext();) { | |||||
| if (couldHoldIncluded(tokenizedName, | |||||
| iter.next().toPattern())) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| return false; | |||||
| return Stream | |||||
| .concat(Stream.of(includePatterns), | |||||
| includeNonPatterns.values().stream() | |||||
| .map(TokenizedPath::toPattern)) | |||||
| .anyMatch(pat -> couldHoldIncluded(tokenizedName, pat)); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1481,12 +1462,8 @@ public class DirectoryScanner | |||||
| private boolean isMorePowerfulThanExcludes(final String name) { | private boolean isMorePowerfulThanExcludes(final String name) { | ||||
| final String soughtexclude = | final String soughtexclude = | ||||
| name + File.separatorChar + SelectorUtils.DEEP_TREE_MATCH; | name + File.separatorChar + SelectorUtils.DEEP_TREE_MATCH; | ||||
| for (int counter = 0; counter < excludePatterns.length; counter++) { | |||||
| if (excludePatterns[counter].toString().equals(soughtexclude)) { | |||||
| return false; | |||||
| } | |||||
| } | |||||
| return true; | |||||
| return Stream.of(excludePatterns).map(Object::toString) | |||||
| .noneMatch(Predicate.isEqual(soughtexclude)); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1495,14 +1472,10 @@ public class DirectoryScanner | |||||
| * @return whether all the specified directory's contents are excluded. | * @return whether all the specified directory's contents are excluded. | ||||
| */ | */ | ||||
| /* package */ boolean contentsExcluded(final TokenizedPath path) { | /* package */ boolean contentsExcluded(final TokenizedPath path) { | ||||
| for (int i = 0; i < excludePatterns.length; i++) { | |||||
| if (excludePatterns[i].endsWith(SelectorUtils.DEEP_TREE_MATCH) | |||||
| && excludePatterns[i].withoutLastToken() | |||||
| .matchPath(path, isCaseSensitive())) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| return false; | |||||
| return Stream.of(excludePatterns) | |||||
| .filter(p -> p.endsWith(SelectorUtils.DEEP_TREE_MATCH)) | |||||
| .map(TokenizedPattern::withoutLastToken) | |||||
| .anyMatch(wlt -> wlt.matchPath(path, isCaseSensitive())); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1528,17 +1501,13 @@ public class DirectoryScanner | |||||
| private boolean isExcluded(final TokenizedPath name) { | private boolean isExcluded(final TokenizedPath name) { | ||||
| ensureNonPatternSetsReady(); | ensureNonPatternSetsReady(); | ||||
| if (isCaseSensitive() | |||||
| ? excludeNonPatterns.containsKey(name.toString()) | |||||
| : excludeNonPatterns.containsKey(name.toString().toUpperCase())) { | |||||
| return true; | |||||
| } | |||||
| for (int i = 0; i < excludePatterns.length; i++) { | |||||
| if (excludePatterns[i].matchPath(name, isCaseSensitive())) { | |||||
| return true; | |||||
| } | |||||
| String toMatch = name.toString(); | |||||
| if (!isCaseSensitive()) { | |||||
| toMatch = toMatch.toUpperCase(); | |||||
| } | } | ||||
| return false; | |||||
| return excludeNonPatterns.containsKey(toMatch) | |||||
| || Stream.of(excludePatterns) | |||||
| .anyMatch(p -> p.matchPath(name, isCaseSensitive())); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1550,14 +1519,8 @@ public class DirectoryScanner | |||||
| * should not be selected, <code>true</code> otherwise. | * should not be selected, <code>true</code> otherwise. | ||||
| */ | */ | ||||
| protected boolean isSelected(final String name, final File file) { | protected boolean isSelected(final String name, final File file) { | ||||
| if (selectors != null) { | |||||
| for (int i = 0; i < selectors.length; i++) { | |||||
| if (!selectors[i].isSelected(basedir, name, file)) { | |||||
| return false; | |||||
| } | |||||
| } | |||||
| } | |||||
| return true; | |||||
| return selectors == null || Stream.of(selectors) | |||||
| .allMatch(sel -> sel.isSelected(basedir, name, file)); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1568,14 +1531,14 @@ public class DirectoryScanner | |||||
| * @return the names of the files which matched at least one of the | * @return the names of the files which matched at least one of the | ||||
| * include patterns and none of the exclude patterns. | * include patterns and none of the exclude patterns. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getIncludedFiles() { | public String[] getIncludedFiles() { | ||||
| String[] files; | String[] files; | ||||
| synchronized (this) { | synchronized (this) { | ||||
| if (filesIncluded == null) { | if (filesIncluded == null) { | ||||
| throw new IllegalStateException("Must call scan() first"); | throw new IllegalStateException("Must call scan() first"); | ||||
| } | } | ||||
| files = new String[filesIncluded.size()]; | |||||
| filesIncluded.copyInto(files); | |||||
| files = filesIncluded.toArray(new String[filesIncluded.size()]); | |||||
| } | } | ||||
| Arrays.sort(files); | Arrays.sort(files); | ||||
| return files; | return files; | ||||
| @@ -1603,11 +1566,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getNotIncludedFiles() { | public synchronized String[] getNotIncludedFiles() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] files = new String[filesNotIncluded.size()]; | |||||
| filesNotIncluded.copyInto(files); | |||||
| return files; | |||||
| return filesNotIncluded.toArray(new String[filesNotIncluded.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1621,11 +1583,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getExcludedFiles() { | public synchronized String[] getExcludedFiles() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] files = new String[filesExcluded.size()]; | |||||
| filesExcluded.copyInto(files); | |||||
| return files; | |||||
| return filesExcluded.toArray(new String[filesExcluded.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1639,11 +1600,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getDeselectedFiles() { | public synchronized String[] getDeselectedFiles() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] files = new String[filesDeselected.size()]; | |||||
| filesDeselected.copyInto(files); | |||||
| return files; | |||||
| return filesDeselected.toArray(new String[filesDeselected.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1654,14 +1614,14 @@ public class DirectoryScanner | |||||
| * @return the names of the directories which matched at least one of the | * @return the names of the directories which matched at least one of the | ||||
| * include patterns and none of the exclude patterns. | * include patterns and none of the exclude patterns. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getIncludedDirectories() { | public String[] getIncludedDirectories() { | ||||
| String[] directories; | String[] directories; | ||||
| synchronized (this) { | synchronized (this) { | ||||
| if (dirsIncluded == null) { | if (dirsIncluded == null) { | ||||
| throw new IllegalStateException("Must call scan() first"); | throw new IllegalStateException("Must call scan() first"); | ||||
| } | } | ||||
| directories = new String[dirsIncluded.size()]; | |||||
| dirsIncluded.copyInto(directories); | |||||
| directories = dirsIncluded.toArray(new String[dirsIncluded.size()]); | |||||
| } | } | ||||
| Arrays.sort(directories); | Arrays.sort(directories); | ||||
| return directories; | return directories; | ||||
| @@ -1689,11 +1649,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getNotIncludedDirectories() { | public synchronized String[] getNotIncludedDirectories() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] directories = new String[dirsNotIncluded.size()]; | |||||
| dirsNotIncluded.copyInto(directories); | |||||
| return directories; | |||||
| return dirsNotIncluded.toArray(new String[dirsNotIncluded.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1707,11 +1666,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getExcludedDirectories() { | public synchronized String[] getExcludedDirectories() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] directories = new String[dirsExcluded.size()]; | |||||
| dirsExcluded.copyInto(directories); | |||||
| return directories; | |||||
| return dirsExcluded.toArray(new String[dirsExcluded.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1725,11 +1683,10 @@ public class DirectoryScanner | |||||
| * | * | ||||
| * @see #slowScan | * @see #slowScan | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized String[] getDeselectedDirectories() { | public synchronized String[] getDeselectedDirectories() { | ||||
| slowScan(); | slowScan(); | ||||
| final String[] directories = new String[dirsDeselected.size()]; | |||||
| dirsDeselected.copyInto(directories); | |||||
| return directories; | |||||
| return dirsDeselected.toArray(new String[dirsDeselected.size()]); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1754,20 +1711,15 @@ public class DirectoryScanner | |||||
| /** | /** | ||||
| * Add default exclusions to the current exclusions set. | * Add default exclusions to the current exclusions set. | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void addDefaultExcludes() { | public synchronized void addDefaultExcludes() { | ||||
| final int excludesLength = excludes == null ? 0 : excludes.length; | |||||
| String[] newExcludes; | |||||
| final String[] defaultExcludesTemp = getDefaultExcludes(); | |||||
| newExcludes = new String[excludesLength + defaultExcludesTemp.length]; | |||||
| if (excludesLength > 0) { | |||||
| System.arraycopy(excludes, 0, newExcludes, 0, excludesLength); | |||||
| } | |||||
| for (int i = 0; i < defaultExcludesTemp.length; i++) { | |||||
| newExcludes[i + excludesLength] = | |||||
| defaultExcludesTemp[i].replace('/', File.separatorChar) | |||||
| .replace('\\', File.separatorChar); | |||||
| Stream<String> s = Stream.of(getDefaultExcludes()) | |||||
| .map(p -> p.replace('/', File.separatorChar).replace('\\', | |||||
| File.separatorChar)); | |||||
| if (excludes != null) { | |||||
| s = Stream.concat(Stream.of(excludes), s); | |||||
| } | } | ||||
| excludes = newExcludes; | |||||
| excludes = s.toArray(String[]::new); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1777,6 +1729,7 @@ public class DirectoryScanner | |||||
| * @return the resource with the given name. | * @return the resource with the given name. | ||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized Resource getResource(final String name) { | public synchronized Resource getResource(final String name) { | ||||
| return new FileResource(basedir, name); | return new FileResource(basedir, name); | ||||
| } | } | ||||
| @@ -1838,14 +1791,14 @@ public class DirectoryScanner | |||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private TokenizedPattern[] fillNonPatternSet(final Map<String, TokenizedPath> map, final String[] patterns) { | private TokenizedPattern[] fillNonPatternSet(final Map<String, TokenizedPath> map, final String[] patterns) { | ||||
| final ArrayList<TokenizedPattern> al = new ArrayList<TokenizedPattern>(patterns.length); | |||||
| for (int i = 0; i < patterns.length; i++) { | |||||
| if (!SelectorUtils.hasWildcards(patterns[i])) { | |||||
| final List<TokenizedPattern> al = new ArrayList<>(patterns.length); | |||||
| for (String pattern : patterns) { | |||||
| if (SelectorUtils.hasWildcards(pattern)) { | |||||
| al.add(new TokenizedPattern(pattern)); | |||||
| } else { | |||||
| final String s = isCaseSensitive() | final String s = isCaseSensitive() | ||||
| ? patterns[i] : patterns[i].toUpperCase(); | |||||
| ? pattern : pattern.toUpperCase(); | |||||
| map.put(s, new TokenizedPath(s)); | map.put(s, new TokenizedPath(s)); | ||||
| } else { | |||||
| al.add(new TokenizedPattern(patterns[i])); | |||||
| } | } | ||||
| } | } | ||||
| return al.toArray(new TokenizedPattern[al.size()]); | return al.toArray(new TokenizedPattern[al.size()]); | ||||
| @@ -1863,14 +1816,14 @@ public class DirectoryScanner | |||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private boolean causesIllegalSymlinkLoop(final String dirName, final File parent, | private boolean causesIllegalSymlinkLoop(final String dirName, final File parent, | ||||
| final LinkedList<String> directoryNamesFollowed) { | |||||
| final Deque<String> directoryNamesFollowed) { | |||||
| try { | try { | ||||
| if (directoryNamesFollowed.size() >= maxLevelsOfSymlinks | if (directoryNamesFollowed.size() >= maxLevelsOfSymlinks | ||||
| && CollectionUtils.frequency(directoryNamesFollowed, dirName) | |||||
| && Collections.frequency(directoryNamesFollowed, dirName) | |||||
| >= maxLevelsOfSymlinks | >= maxLevelsOfSymlinks | ||||
| && SYMLINK_UTILS.isSymbolicLink(parent, dirName)) { | && SYMLINK_UTILS.isSymbolicLink(parent, dirName)) { | ||||
| final ArrayList<String> files = new ArrayList<String>(); | |||||
| final List<String> files = new ArrayList<>(); | |||||
| File f = FILE_UTILS.resolveFile(parent, dirName); | File f = FILE_UTILS.resolveFile(parent, dirName); | ||||
| final String target = f.getCanonicalPath(); | final String target = f.getCanonicalPath(); | ||||
| files.add(target); | files.add(target); | ||||
| @@ -1882,18 +1835,17 @@ public class DirectoryScanner | |||||
| f = FILE_UTILS.resolveFile(parent, relPath + dir); | f = FILE_UTILS.resolveFile(parent, relPath + dir); | ||||
| files.add(f.getCanonicalPath()); | files.add(f.getCanonicalPath()); | ||||
| if (files.size() > maxLevelsOfSymlinks | if (files.size() > maxLevelsOfSymlinks | ||||
| && CollectionUtils.frequency(files, target) | |||||
| && Collections.frequency(files, target) | |||||
| > maxLevelsOfSymlinks) { | > maxLevelsOfSymlinks) { | ||||
| return true; | return true; | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| return false; | return false; | ||||
| } catch (final IOException ex) { | } catch (final IOException ex) { | ||||
| throw new BuildException("Caught error while checking for" | |||||
| + " symbolic links", ex); | |||||
| throw new BuildException( | |||||
| "Caught error while checking for symbolic links", ex); | |||||
| } | } | ||||
| } | } | ||||
| @@ -26,4 +26,3 @@ package org.apache.tools.ant; | |||||
| public interface DynamicConfigurator | public interface DynamicConfigurator | ||||
| extends DynamicAttribute, DynamicElement { | extends DynamicAttribute, DynamicElement { | ||||
| } | } | ||||
| @@ -17,13 +17,19 @@ | |||||
| */ | */ | ||||
| package org.apache.tools.ant; | package org.apache.tools.ant; | ||||
| import java.util.function.Supplier; | |||||
| /** | /** | ||||
| * Kind of task attribute that can be evaluated before being assigned | * Kind of task attribute that can be evaluated before being assigned | ||||
| * @param <T> as {@link Supplier} | |||||
| * | * | ||||
| * @see RuntimeConfigurable | * @see RuntimeConfigurable | ||||
| */ | */ | ||||
| public interface Evaluable { | |||||
| public interface Evaluable<T> extends Supplier<T> { | |||||
| Object eval(); | |||||
| T eval(); | |||||
| default T get() { | |||||
| return eval(); | |||||
| } | |||||
| } | } | ||||
| @@ -63,7 +63,7 @@ public final class IntrospectionHelper { | |||||
| /** | /** | ||||
| * Helper instances we've already created (Class.getName() to IntrospectionHelper). | * Helper instances we've already created (Class.getName() to IntrospectionHelper). | ||||
| */ | */ | ||||
| private static final Map<String, IntrospectionHelper> HELPERS = new Hashtable<String, IntrospectionHelper>(); | |||||
| private static final Map<String, IntrospectionHelper> HELPERS = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map from primitive types to wrapper classes for use in | * Map from primitive types to wrapper classes for use in | ||||
| @@ -71,7 +71,7 @@ public final class IntrospectionHelper { | |||||
| * and boolean are in here even though they get special treatment | * and boolean are in here even though they get special treatment | ||||
| * - this way we only need to test for the wrapper class. | * - this way we only need to test for the wrapper class. | ||||
| */ | */ | ||||
| private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPE_MAP = new HashMap<Class<?>, Class<?>>(8); | |||||
| private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPE_MAP = new HashMap<>(8); | |||||
| // Set up PRIMITIVE_TYPE_MAP | // Set up PRIMITIVE_TYPE_MAP | ||||
| static { | static { | ||||
| @@ -91,30 +91,30 @@ public final class IntrospectionHelper { | |||||
| * Map from attribute names to attribute types | * Map from attribute names to attribute types | ||||
| * (String to Class). | * (String to Class). | ||||
| */ | */ | ||||
| private final Hashtable<String, Class<?>> attributeTypes = new Hashtable<String, Class<?>>(); | |||||
| private final Map<String, Class<?>> attributeTypes = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map from attribute names to attribute setter methods | * Map from attribute names to attribute setter methods | ||||
| * (String to AttributeSetter). | * (String to AttributeSetter). | ||||
| */ | */ | ||||
| private final Hashtable<String, AttributeSetter> attributeSetters = new Hashtable<String, AttributeSetter>(); | |||||
| private final Map<String, AttributeSetter> attributeSetters = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map from attribute names to nested types | * Map from attribute names to nested types | ||||
| * (String to Class). | * (String to Class). | ||||
| */ | */ | ||||
| private final Hashtable<String, Class<?>> nestedTypes = new Hashtable<String, Class<?>>(); | |||||
| private final Map<String, Class<?>> nestedTypes = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map from attribute names to methods to create nested types | * Map from attribute names to methods to create nested types | ||||
| * (String to NestedCreator). | * (String to NestedCreator). | ||||
| */ | */ | ||||
| private final Hashtable<String, NestedCreator> nestedCreators = new Hashtable<String, NestedCreator>(); | |||||
| private final Map<String, NestedCreator> nestedCreators = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Vector of methods matching add[Configured](Class) pattern. | * Vector of methods matching add[Configured](Class) pattern. | ||||
| */ | */ | ||||
| private final List<Method> addTypeMethods = new ArrayList<Method>(); | |||||
| private final List<Method> addTypeMethods = new ArrayList<>(); | |||||
| /** | /** | ||||
| * The method to invoke to add PCDATA. | * The method to invoke to add PCDATA. | ||||
| @@ -706,7 +706,7 @@ public final class IntrospectionHelper { | |||||
| * @return true if the given nested element is supported | * @return true if the given nested element is supported | ||||
| */ | */ | ||||
| public boolean supportsNestedElement(final String parentUri, final String elementName) { | public boolean supportsNestedElement(final String parentUri, final String elementName) { | ||||
| if (isDynamic() || addTypeMethods.size() > 0) { | |||||
| if (isDynamic() || !addTypeMethods.isEmpty()) { | |||||
| return true; | return true; | ||||
| } | } | ||||
| return supportsReflectElement(parentUri, elementName); | return supportsReflectElement(parentUri, elementName); | ||||
| @@ -731,7 +731,7 @@ public final class IntrospectionHelper { | |||||
| */ | */ | ||||
| public boolean supportsNestedElement(final String parentUri, final String elementName, | public boolean supportsNestedElement(final String parentUri, final String elementName, | ||||
| final Project project, final Object parent) { | final Project project, final Object parent) { | ||||
| if (addTypeMethods.size() > 0 | |||||
| if (!addTypeMethods.isEmpty() | |||||
| && createAddTypeCreator(project, parent, elementName) != null) { | && createAddTypeCreator(project, parent, elementName) != null) { | ||||
| return true; | return true; | ||||
| } | } | ||||
| @@ -944,7 +944,7 @@ public final class IntrospectionHelper { | |||||
| * @see #getAttributeMap | * @see #getAttributeMap | ||||
| */ | */ | ||||
| public Enumeration<String> getAttributes() { | public Enumeration<String> getAttributes() { | ||||
| return attributeSetters.keys(); | |||||
| return Collections.enumeration(attributeSetters.keySet()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -968,7 +968,7 @@ public final class IntrospectionHelper { | |||||
| * @see #getNestedElementMap | * @see #getNestedElementMap | ||||
| */ | */ | ||||
| public Enumeration<String> getNestedElements() { | public Enumeration<String> getNestedElements() { | ||||
| return nestedTypes.keys(); | |||||
| return Collections.enumeration(nestedTypes.keySet()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1533,7 +1533,7 @@ public final class IntrospectionHelper { | |||||
| */ | */ | ||||
| private NestedCreator createAddTypeCreator( | private NestedCreator createAddTypeCreator( | ||||
| final Project project, final Object parent, final String elementName) throws BuildException { | final Project project, final Object parent, final String elementName) throws BuildException { | ||||
| if (addTypeMethods.size() == 0) { | |||||
| if (addTypeMethods.isEmpty()) { | |||||
| return null; | return null; | ||||
| } | } | ||||
| final ComponentHelper helper = ComponentHelper.getComponentHelper(project); | final ComponentHelper helper = ComponentHelper.getComponentHelper(project); | ||||
| @@ -1602,7 +1602,7 @@ public final class IntrospectionHelper { | |||||
| for (int c = 0; c < size; ++c) { | for (int c = 0; c < size; ++c) { | ||||
| final Method current = addTypeMethods.get(c); | final Method current = addTypeMethods.get(c); | ||||
| if (current.getParameterTypes()[0].equals(argClass)) { | if (current.getParameterTypes()[0].equals(argClass)) { | ||||
| if (method.getName().equals("addConfigured")) { | |||||
| if ("addConfigured".equals(method.getName())) { | |||||
| // add configured replaces the add method | // add configured replaces the add method | ||||
| addTypeMethods.set(c, method); | addTypeMethods.set(c, method); | ||||
| } | } | ||||
| @@ -19,6 +19,7 @@ | |||||
| package org.apache.tools.ant; | package org.apache.tools.ant; | ||||
| import java.io.Serializable; | import java.io.Serializable; | ||||
| import java.util.Objects; | |||||
| import org.apache.tools.ant.util.FileUtils; | import org.apache.tools.ant.util.FileUtils; | ||||
| import org.xml.sax.Locator; | import org.xml.sax.Locator; | ||||
| @@ -131,8 +132,9 @@ public class Location implements Serializable { | |||||
| * <code>"fileName: "</code> if only the file name is known, | * <code>"fileName: "</code> if only the file name is known, | ||||
| * and the empty string for unknown locations. | * and the empty string for unknown locations. | ||||
| */ | */ | ||||
| @Override | |||||
| public String toString() { | public String toString() { | ||||
| StringBuffer buf = new StringBuffer(); | |||||
| StringBuilder buf = new StringBuilder(); | |||||
| if (fileName != null) { | if (fileName != null) { | ||||
| buf.append(fileName); | buf.append(fileName); | ||||
| @@ -155,6 +157,7 @@ public class Location implements Serializable { | |||||
| * as this object. | * as this object. | ||||
| * @since Ant 1.6.3 | * @since Ant 1.6.3 | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean equals(Object other) { | public boolean equals(Object other) { | ||||
| if (this == other) { | if (this == other) { | ||||
| return true; | return true; | ||||
| @@ -173,7 +176,8 @@ public class Location implements Serializable { | |||||
| * @return a hash code value for this location. | * @return a hash code value for this location. | ||||
| * @since Ant 1.6.3 | * @since Ant 1.6.3 | ||||
| */ | */ | ||||
| @Override | |||||
| public int hashCode() { | public int hashCode() { | ||||
| return toString().hashCode(); | |||||
| return Objects.hash(fileName, lineNumber); | |||||
| } | } | ||||
| } | } | ||||
| @@ -87,16 +87,16 @@ public class Main implements AntMain { | |||||
| private PrintStream err = System.err; | private PrintStream err = System.err; | ||||
| /** The build targets. */ | /** The build targets. */ | ||||
| private final Vector<String> targets = new Vector<String>(); | |||||
| private final Vector<String> targets = new Vector<>(); | |||||
| /** Set of properties that can be used by tasks. */ | /** Set of properties that can be used by tasks. */ | ||||
| private final Properties definedProps = new Properties(); | private final Properties definedProps = new Properties(); | ||||
| /** Names of classes to add as listeners to project. */ | /** Names of classes to add as listeners to project. */ | ||||
| private final Vector<String> listeners = new Vector<String>(1); | |||||
| private final Vector<String> listeners = new Vector<>(1); | |||||
| /** File names of property files to load on startup. */ | /** File names of property files to load on startup. */ | ||||
| private final Vector<String> propertyFiles = new Vector<String>(1); | |||||
| private final Vector<String> propertyFiles = new Vector<>(1); | |||||
| /** Indicates whether this build is to support interactive input */ | /** Indicates whether this build is to support interactive input */ | ||||
| private boolean allowInput = true; | private boolean allowInput = true; | ||||
| @@ -155,17 +155,9 @@ public class Main implements AntMain { | |||||
| */ | */ | ||||
| private boolean proxy = false; | private boolean proxy = false; | ||||
| private final Map<Class<?>, List<String>> extraArguments = new HashMap<Class<?>, List<String>>(); | |||||
| private static final GetProperty NOPROPERTIES = new GetProperty() { | |||||
| public Object getProperty(final String aName) { | |||||
| // No existing property takes precedence | |||||
| return null; | |||||
| } | |||||
| }; | |||||
| private final Map<Class<?>, List<String>> extraArguments = new HashMap<>(); | |||||
| private static final GetProperty NOPROPERTIES = aName -> null; | |||||
| /** | /** | ||||
| * Prints the message of the Throwable if it (the message) is not | * Prints the message of the Throwable if it (the message) is not | ||||
| @@ -569,8 +561,8 @@ public class Main implements AntMain { | |||||
| */ | */ | ||||
| final String arg = args[argPos]; | final String arg = args[argPos]; | ||||
| String name = arg.substring(2, arg.length()); | String name = arg.substring(2, arg.length()); | ||||
| String value = null; | |||||
| final int posEq = name.indexOf("="); | |||||
| String value; | |||||
| final int posEq = name.indexOf('='); | |||||
| if (posEq > 0) { | if (posEq > 0) { | ||||
| value = name.substring(posEq + 1); | value = name.substring(posEq + 1); | ||||
| name = name.substring(0, posEq); | name = name.substring(0, posEq); | ||||
| @@ -1153,7 +1145,7 @@ public class Main implements AntMain { | |||||
| * @return the filtered targets. | * @return the filtered targets. | ||||
| */ | */ | ||||
| private static Map<String, Target> removeDuplicateTargets(final Map<String, Target> targets) { | private static Map<String, Target> removeDuplicateTargets(final Map<String, Target> targets) { | ||||
| final Map<Location, Target> locationMap = new HashMap<Location, Target>(); | |||||
| final Map<Location, Target> locationMap = new HashMap<>(); | |||||
| for (final Entry<String, Target> entry : targets.entrySet()) { | for (final Entry<String, Target> entry : targets.entrySet()) { | ||||
| final String name = entry.getKey(); | final String name = entry.getKey(); | ||||
| final Target target = entry.getValue(); | final Target target = entry.getValue(); | ||||
| @@ -1168,7 +1160,7 @@ public class Main implements AntMain { | |||||
| target.getLocation(), target); // Smallest name wins | target.getLocation(), target); // Smallest name wins | ||||
| } | } | ||||
| } | } | ||||
| final Map<String, Target> ret = new HashMap<String, Target>(); | |||||
| final Map<String, Target> ret = new HashMap<>(); | |||||
| for (final Target target : locationMap.values()) { | for (final Target target : locationMap.values()) { | ||||
| ret.put(target.getName(), target); | ret.put(target.getName(), target); | ||||
| } | } | ||||
| @@ -1191,15 +1183,15 @@ public class Main implements AntMain { | |||||
| final Map<String, Target> ptargets = removeDuplicateTargets(project.getTargets()); | final Map<String, Target> ptargets = removeDuplicateTargets(project.getTargets()); | ||||
| // split the targets in top-level and sub-targets depending | // split the targets in top-level and sub-targets depending | ||||
| // on the presence of a description | // on the presence of a description | ||||
| final Vector<String> topNames = new Vector<String>(); | |||||
| final Vector<String> topDescriptions = new Vector<String>(); | |||||
| final Vector<Enumeration<String>> topDependencies = new Vector<Enumeration<String>>(); | |||||
| final Vector<String> subNames = new Vector<String>(); | |||||
| final Vector<Enumeration<String>> subDependencies = new Vector<Enumeration<String>>(); | |||||
| final Vector<String> topNames = new Vector<>(); | |||||
| final Vector<String> topDescriptions = new Vector<>(); | |||||
| final Vector<Enumeration<String>> topDependencies = new Vector<>(); | |||||
| final Vector<String> subNames = new Vector<>(); | |||||
| final Vector<Enumeration<String>> subDependencies = new Vector<>(); | |||||
| for (final Target currentTarget : ptargets.values()) { | for (final Target currentTarget : ptargets.values()) { | ||||
| final String targetName = currentTarget.getName(); | final String targetName = currentTarget.getName(); | ||||
| if (targetName.equals("")) { | |||||
| if ("".equals(targetName)) { | |||||
| continue; | continue; | ||||
| } | } | ||||
| final String targetDescription = currentTarget.getDescription(); | final String targetDescription = currentTarget.getDescription(); | ||||
| @@ -1227,7 +1219,7 @@ public class Main implements AntMain { | |||||
| "Main targets:", maxLength); | "Main targets:", maxLength); | ||||
| //if there were no main targets, we list all subtargets | //if there were no main targets, we list all subtargets | ||||
| //as it means nothing has a description | //as it means nothing has a description | ||||
| if (topNames.size() == 0) { | |||||
| if (topNames.isEmpty()) { | |||||
| printSubTargets = true; | printSubTargets = true; | ||||
| } | } | ||||
| if (printSubTargets) { | if (printSubTargets) { | ||||
| @@ -127,7 +127,7 @@ public class PathTokenizer { | |||||
| } else { | } else { | ||||
| // we are on NetWare, tokenizing is handled a little differently, | // we are on NetWare, tokenizing is handled a little differently, | ||||
| // due to the fact that NetWare has multiple-character volume names. | // due to the fact that NetWare has multiple-character volume names. | ||||
| if (token.equals(File.pathSeparator) || token.equals(":")) { | |||||
| if (token.equals(File.pathSeparator) || ":".equals(token)) { | |||||
| // ignore ";" and get the next token | // ignore ";" and get the next token | ||||
| token = tokenizer.nextToken().trim(); | token = tokenizer.nextToken().trim(); | ||||
| } | } | ||||
| @@ -138,7 +138,7 @@ public class PathTokenizer { | |||||
| // make sure we aren't going to get the path separator next | // make sure we aren't going to get the path separator next | ||||
| if (!nextToken.equals(File.pathSeparator)) { | if (!nextToken.equals(File.pathSeparator)) { | ||||
| if (nextToken.equals(":")) { | |||||
| if (":".equals(nextToken)) { | |||||
| if (!token.startsWith("/") && !token.startsWith("\\") | if (!token.startsWith("/") && !token.startsWith("\\") | ||||
| && !token.startsWith(".") | && !token.startsWith(".") | ||||
| && !token.startsWith("..")) { | && !token.startsWith("..")) { | ||||
| @@ -163,4 +163,3 @@ public class PathTokenizer { | |||||
| return token; | return token; | ||||
| } | } | ||||
| } | } | ||||
| @@ -144,13 +144,13 @@ public class Project implements ResourceFactory { | |||||
| private final Hashtable<String, Object> references = new AntRefTable(); | private final Hashtable<String, Object> references = new AntRefTable(); | ||||
| /** Map of id references - used for indicating broken build files */ | /** Map of id references - used for indicating broken build files */ | ||||
| private final HashMap<String, Object> idReferences = new HashMap<String, Object>(); | |||||
| private final HashMap<String, Object> idReferences = new HashMap<>(); | |||||
| /** Name of the project's default target. */ | /** Name of the project's default target. */ | ||||
| private String defaultTarget; | private String defaultTarget; | ||||
| /** Map from target names to targets (String to Target). */ | /** Map from target names to targets (String to Target). */ | ||||
| private final Hashtable<String, Target> targets = new Hashtable<String, Target>(); | |||||
| private final Hashtable<String, Target> targets = new Hashtable<>(); | |||||
| /** Set of global filters. */ | /** Set of global filters. */ | ||||
| private final FilterSet globalFilterSet = new FilterSet(); | private final FilterSet globalFilterSet = new FilterSet(); | ||||
| @@ -193,11 +193,11 @@ public class Project implements ResourceFactory { | |||||
| /** Records the latest task to be executed on a thread. */ | /** Records the latest task to be executed on a thread. */ | ||||
| private final Map<Thread,Task> threadTasks = | private final Map<Thread,Task> threadTasks = | ||||
| Collections.synchronizedMap(new WeakHashMap<Thread, Task>()); | |||||
| Collections.synchronizedMap(new WeakHashMap<>()); | |||||
| /** Records the latest task to be executed on a thread group. */ | /** Records the latest task to be executed on a thread group. */ | ||||
| private final Map<ThreadGroup,Task> threadGroupTasks | private final Map<ThreadGroup,Task> threadGroupTasks | ||||
| = Collections.synchronizedMap(new WeakHashMap<ThreadGroup,Task>()); | |||||
| = Collections.synchronizedMap(new WeakHashMap<>()); | |||||
| /** | /** | ||||
| * Called to handle any input requests. | * Called to handle any input requests. | ||||
| @@ -437,7 +437,7 @@ public class Project implements ResourceFactory { | |||||
| */ | */ | ||||
| public Vector<BuildListener> getBuildListeners() { | public Vector<BuildListener> getBuildListeners() { | ||||
| synchronized (listenersLock) { | synchronized (listenersLock) { | ||||
| final Vector<BuildListener> r = new Vector<BuildListener>(listeners.length); | |||||
| final Vector<BuildListener> r = new Vector<>(listeners.length); | |||||
| for (int i = 0; i < listeners.length; i++) { | for (int i = 0; i < listeners.length; i++) { | ||||
| r.add(listeners[i]); | r.add(listeners[i]); | ||||
| } | } | ||||
| @@ -1046,7 +1046,7 @@ public class Project implements ResourceFactory { | |||||
| * @since Ant 1.8.1 | * @since Ant 1.8.1 | ||||
| */ | */ | ||||
| public Map<String, Class<?>> getCopyOfTaskDefinitions() { | public Map<String, Class<?>> getCopyOfTaskDefinitions() { | ||||
| return new HashMap<String, Class<?>>(getTaskDefinitions()); | |||||
| return new HashMap<>(getTaskDefinitions()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1088,7 +1088,7 @@ public class Project implements ResourceFactory { | |||||
| * @since Ant 1.8.1 | * @since Ant 1.8.1 | ||||
| */ | */ | ||||
| public Map<String, Class<?>> getCopyOfDataTypeDefinitions() { | public Map<String, Class<?>> getCopyOfDataTypeDefinitions() { | ||||
| return new HashMap<String, Class<?>>(getDataTypeDefinitions()); | |||||
| return new HashMap<>(getDataTypeDefinitions()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1168,7 +1168,7 @@ public class Project implements ResourceFactory { | |||||
| * @since Ant 1.8.1 | * @since Ant 1.8.1 | ||||
| */ | */ | ||||
| public Map<String, Target> getCopyOfTargets() { | public Map<String, Target> getCopyOfTargets() { | ||||
| return new HashMap<String, Target>(targets); | |||||
| return new HashMap<>(targets); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1273,12 +1273,10 @@ public class Project implements ResourceFactory { | |||||
| final Task task = getThreadTask(Thread.currentThread()); | final Task task = getThreadTask(Thread.currentThread()); | ||||
| if (task == null) { | if (task == null) { | ||||
| log(output, isWarning ? MSG_WARN : MSG_INFO); | log(output, isWarning ? MSG_WARN : MSG_INFO); | ||||
| } else if (isWarning) { | |||||
| task.handleErrorOutput(output); | |||||
| } else { | } else { | ||||
| if (isWarning) { | |||||
| task.handleErrorOutput(output); | |||||
| } else { | |||||
| task.handleOutput(output); | |||||
| } | |||||
| task.handleOutput(output); | |||||
| } | } | ||||
| } | } | ||||
| @@ -1297,12 +1295,11 @@ public class Project implements ResourceFactory { | |||||
| */ | */ | ||||
| public int defaultInput(final byte[] buffer, final int offset, final int length) | public int defaultInput(final byte[] buffer, final int offset, final int length) | ||||
| throws IOException { | throws IOException { | ||||
| if (defaultInputStream != null) { | |||||
| System.out.flush(); | |||||
| return defaultInputStream.read(buffer, offset, length); | |||||
| } else { | |||||
| if (defaultInputStream == null) { | |||||
| throw new EOFException("No input provided for project"); | throw new EOFException("No input provided for project"); | ||||
| } | } | ||||
| System.out.flush(); | |||||
| return defaultInputStream.read(buffer, offset, length); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1322,9 +1319,8 @@ public class Project implements ResourceFactory { | |||||
| final Task task = getThreadTask(Thread.currentThread()); | final Task task = getThreadTask(Thread.currentThread()); | ||||
| if (task == null) { | if (task == null) { | ||||
| return defaultInput(buffer, offset, length); | return defaultInput(buffer, offset, length); | ||||
| } else { | |||||
| return task.handleInput(buffer, offset, length); | |||||
| } | } | ||||
| return task.handleInput(buffer, offset, length); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1342,12 +1338,10 @@ public class Project implements ResourceFactory { | |||||
| final Task task = getThreadTask(Thread.currentThread()); | final Task task = getThreadTask(Thread.currentThread()); | ||||
| if (task == null) { | if (task == null) { | ||||
| fireMessageLogged(this, output, isError ? MSG_ERR : MSG_INFO); | fireMessageLogged(this, output, isError ? MSG_ERR : MSG_INFO); | ||||
| } else if (isError) { | |||||
| task.handleErrorFlush(output); | |||||
| } else { | } else { | ||||
| if (isError) { | |||||
| task.handleErrorFlush(output); | |||||
| } else { | |||||
| task.handleFlush(output); | |||||
| } | |||||
| task.handleFlush(output); | |||||
| } | } | ||||
| } | } | ||||
| @@ -1383,7 +1377,7 @@ public class Project implements ResourceFactory { | |||||
| */ | */ | ||||
| public void executeSortedTargets(final Vector<Target> sortedTargets) | public void executeSortedTargets(final Vector<Target> sortedTargets) | ||||
| throws BuildException { | throws BuildException { | ||||
| final Set<String> succeededTargets = new HashSet<String>(); | |||||
| final Set<String> succeededTargets = new HashSet<>(); | |||||
| BuildException buildException = null; // first build exception | BuildException buildException = null; // first build exception | ||||
| for (final Target curtarget : sortedTargets) { | for (final Target curtarget : sortedTargets) { | ||||
| boolean canExecute = true; | boolean canExecute = true; | ||||
| @@ -1749,9 +1743,9 @@ public class Project implements ResourceFactory { | |||||
| return ((ProjectComponent) o).getProject(); | return ((ProjectComponent) o).getProject(); | ||||
| } | } | ||||
| try { | try { | ||||
| final Method m = o.getClass().getMethod("getProject", (Class[]) null); | |||||
| if (Project.class == m.getReturnType()) { | |||||
| return (Project) m.invoke(o, (Object[]) null); | |||||
| final Method m = o.getClass().getMethod("getProject"); | |||||
| if (Project.class.equals(m.getReturnType())) { | |||||
| return (Project) m.invoke(o); | |||||
| } | } | ||||
| } catch (final Exception e) { | } catch (final Exception e) { | ||||
| //too bad | //too bad | ||||
| @@ -1819,9 +1813,9 @@ public class Project implements ResourceFactory { | |||||
| */ | */ | ||||
| public final Vector<Target> topoSort(final String[] root, final Hashtable<String, Target> targetTable, | public final Vector<Target> topoSort(final String[] root, final Hashtable<String, Target> targetTable, | ||||
| final boolean returnAll) throws BuildException { | final boolean returnAll) throws BuildException { | ||||
| final Vector<Target> ret = new VectorSet<Target>(); | |||||
| final Hashtable<String, String> state = new Hashtable<String, String>(); | |||||
| final Stack<String> visiting = new Stack<String>(); | |||||
| final Vector<Target> ret = new VectorSet<>(); | |||||
| final Hashtable<String, String> state = new Hashtable<>(); | |||||
| final Stack<String> visiting = new Stack<>(); | |||||
| // We first run a DFS based sort using each root as a starting node. | // We first run a DFS based sort using each root as a starting node. | ||||
| // This creates the minimum sequence of Targets to the root node(s). | // This creates the minimum sequence of Targets to the root node(s). | ||||
| @@ -1832,7 +1826,7 @@ public class Project implements ResourceFactory { | |||||
| // build Target. | // build Target. | ||||
| for (int i = 0; i < root.length; i++) { | for (int i = 0; i < root.length; i++) { | ||||
| final String st = (state.get(root[i])); | |||||
| final String st = state.get(root[i]); | |||||
| if (st == null) { | if (st == null) { | ||||
| tsort(root[i], targetTable, state, visiting, ret); | tsort(root[i], targetTable, state, visiting, ret); | ||||
| } else if (st == VISITING) { | } else if (st == VISITING) { | ||||
| @@ -1840,7 +1834,7 @@ public class Project implements ResourceFactory { | |||||
| + root[i]); | + root[i]); | ||||
| } | } | ||||
| } | } | ||||
| final StringBuffer buf = new StringBuffer("Build sequence for target(s)"); | |||||
| final StringBuilder buf = new StringBuilder("Build sequence for target(s)"); | |||||
| for (int j = 0; j < root.length; j++) { | for (int j = 0; j < root.length; j++) { | ||||
| buf.append((j == 0) ? " `" : ", `").append(root[j]).append('\''); | buf.append((j == 0) ? " `" : ", `").append(root[j]).append('\''); | ||||
| @@ -1848,7 +1842,7 @@ public class Project implements ResourceFactory { | |||||
| buf.append(" is ").append(ret); | buf.append(" is ").append(ret); | ||||
| log(buf.toString(), MSG_VERBOSE); | log(buf.toString(), MSG_VERBOSE); | ||||
| final Vector<Target> complete = (returnAll) ? ret : new Vector<Target>(ret); | |||||
| final Vector<Target> complete = (returnAll) ? ret : new Vector<>(ret); | |||||
| for (final Enumeration<String> en = targetTable.keys(); en.hasMoreElements();) { | for (final Enumeration<String> en = targetTable.keys(); en.hasMoreElements();) { | ||||
| final String curTarget = en.nextElement(); | final String curTarget = en.nextElement(); | ||||
| final String st = state.get(curTarget); | final String st = state.get(curTarget); | ||||
| @@ -2035,7 +2029,7 @@ public class Project implements ResourceFactory { | |||||
| * @since Ant 1.8.1 | * @since Ant 1.8.1 | ||||
| */ | */ | ||||
| public Map<String, Object> getCopyOfReferences() { | public Map<String, Object> getCopyOfReferences() { | ||||
| return new HashMap<String, Object>(references); | |||||
| return new HashMap<>(references); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -2488,6 +2482,7 @@ public class Project implements ResourceFactory { | |||||
| * @return the file resource. | * @return the file resource. | ||||
| * @since Ant 1.7 | * @since Ant 1.7 | ||||
| */ | */ | ||||
| @Override | |||||
| public Resource getResource(final String name) { | public Resource getResource(final String name) { | ||||
| return new FileResource(getBaseDir(), name); | return new FileResource(getBaseDir(), name); | ||||
| } | } | ||||
| @@ -160,6 +160,7 @@ public abstract class ProjectComponent implements Cloneable { | |||||
| * @throws CloneNotSupportedException does not happen, | * @throws CloneNotSupportedException does not happen, | ||||
| * but is declared to allow subclasses to do so. | * but is declared to allow subclasses to do so. | ||||
| */ | */ | ||||
| @Override | |||||
| public Object clone() throws CloneNotSupportedException { | public Object clone() throws CloneNotSupportedException { | ||||
| ProjectComponent pc = (ProjectComponent) super.clone(); | ProjectComponent pc = (ProjectComponent) super.clone(); | ||||
| pc.setLocation(getLocation()); | pc.setLocation(getLocation()); | ||||
| @@ -146,16 +146,12 @@ public class ProjectHelper { | |||||
| } | } | ||||
| } | } | ||||
| /** Default constructor */ | |||||
| public ProjectHelper() { | |||||
| } | |||||
| // -------------------- Common properties -------------------- | // -------------------- Common properties -------------------- | ||||
| // The following properties are required by import ( and other tasks | // The following properties are required by import ( and other tasks | ||||
| // that read build files using ProjectHelper ). | // that read build files using ProjectHelper ). | ||||
| private Vector<Object> importStack = new Vector<Object>(); | |||||
| private List<String[]> extensionStack = new LinkedList<String[]>(); | |||||
| private Vector<Object> importStack = new Vector<>(); | |||||
| private List<String[]> extensionStack = new LinkedList<>(); | |||||
| /** | /** | ||||
| * Import stack. | * Import stack. | ||||
| @@ -181,7 +177,7 @@ public class ProjectHelper { | |||||
| return extensionStack; | return extensionStack; | ||||
| } | } | ||||
| private static final ThreadLocal<String> targetPrefix = new ThreadLocal<String>(); | |||||
| private static final ThreadLocal<String> targetPrefix = new ThreadLocal<>(); | |||||
| /** | /** | ||||
| * The prefix to prepend to imported target names. | * The prefix to prepend to imported target names. | ||||
| @@ -292,7 +288,7 @@ public class ProjectHelper { | |||||
| * @see org.apache.tools.ant.ProjectHelperRepository#getHelpers() | * @see org.apache.tools.ant.ProjectHelperRepository#getHelpers() | ||||
| */ | */ | ||||
| public static ProjectHelper getProjectHelper() { | public static ProjectHelper getProjectHelper() { | ||||
| return (ProjectHelper) ProjectHelperRepository.getInstance().getHelpers().next(); | |||||
| return ProjectHelperRepository.getInstance().getHelpers().next(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -496,7 +492,7 @@ public class ProjectHelper { | |||||
| * @return The stringified form of the ns name | * @return The stringified form of the ns name | ||||
| */ | */ | ||||
| public static String genComponentName(String uri, String name) { | public static String genComponentName(String uri, String name) { | ||||
| if (uri == null || uri.equals("") || uri.equals(ANT_CORE_URI)) { | |||||
| if (uri == null || "".equals(uri) || uri.equals(ANT_CORE_URI)) { | |||||
| return name; | return name; | ||||
| } | } | ||||
| return uri + ":" + name; | return uri + ":" + name; | ||||
| @@ -27,6 +27,7 @@ import java.util.ArrayList; | |||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.helper.ProjectHelper2; | import org.apache.tools.ant.helper.ProjectHelper2; | ||||
| import org.apache.tools.ant.types.Resource; | import org.apache.tools.ant.types.Resource; | ||||
| @@ -53,7 +54,7 @@ public class ProjectHelperRepository { | |||||
| private static ProjectHelperRepository instance = | private static ProjectHelperRepository instance = | ||||
| new ProjectHelperRepository(); | new ProjectHelperRepository(); | ||||
| private List<Constructor<? extends ProjectHelper>> helpers = new ArrayList<Constructor<? extends ProjectHelper>>(); | |||||
| private List<Constructor<? extends ProjectHelper>> helpers = new ArrayList<>(); | |||||
| private static Constructor<ProjectHelper2> PROJECTHELPER2_CONSTRUCTOR; | private static Constructor<ProjectHelper2> PROJECTHELPER2_CONSTRUCTOR; | ||||
| @@ -298,40 +299,15 @@ public class ProjectHelperRepository { | |||||
| * @return an iterator of {@link ProjectHelper} | * @return an iterator of {@link ProjectHelper} | ||||
| */ | */ | ||||
| public Iterator<ProjectHelper> getHelpers() { | public Iterator<ProjectHelper> getHelpers() { | ||||
| return new ConstructingIterator(helpers.iterator()); | |||||
| } | |||||
| private static class ConstructingIterator implements Iterator<ProjectHelper> { | |||||
| private final Iterator<Constructor<? extends ProjectHelper>> nested; | |||||
| private boolean empty = false; | |||||
| ConstructingIterator(Iterator<Constructor<? extends ProjectHelper>> nested) { | |||||
| this.nested = nested; | |||||
| } | |||||
| public boolean hasNext() { | |||||
| return nested.hasNext() || !empty; | |||||
| } | |||||
| public ProjectHelper next() { | |||||
| Constructor<? extends ProjectHelper> c; | |||||
| if (nested.hasNext()) { | |||||
| c = nested.next(); | |||||
| } else { | |||||
| // last but not least, ant default project helper | |||||
| empty = true; | |||||
| c = PROJECTHELPER2_CONSTRUCTOR; | |||||
| } | |||||
| Stream.Builder<Constructor<? extends ProjectHelper>> b = Stream.builder(); | |||||
| helpers.forEach(b::add); | |||||
| return b.add(PROJECTHELPER2_CONSTRUCTOR).build().map(c -> { | |||||
| try { | try { | ||||
| return c.newInstance(); | return c.newInstance(); | ||||
| } catch (Exception e) { | } catch (Exception e) { | ||||
| throw new BuildException("Failed to invoke no-arg constructor" | throw new BuildException("Failed to invoke no-arg constructor" | ||||
| + " on " + c.getName()); | |||||
| + " on " + c.getName()); | |||||
| } | } | ||||
| } | |||||
| public void remove() { | |||||
| throw new UnsupportedOperationException("remove is not supported"); | |||||
| } | |||||
| }).map(ProjectHelper.class::cast).iterator(); | |||||
| } | } | ||||
| } | } | ||||
| @@ -17,7 +17,6 @@ | |||||
| */ | */ | ||||
| package org.apache.tools.ant; | package org.apache.tools.ant; | ||||
| import java.text.ParsePosition; | |||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Collection; | import java.util.Collection; | ||||
| import java.util.Collections; | import java.util.Collections; | ||||
| @@ -30,7 +29,6 @@ import java.util.Vector; | |||||
| import org.apache.tools.ant.property.GetProperty; | import org.apache.tools.ant.property.GetProperty; | ||||
| import org.apache.tools.ant.property.NullReturn; | import org.apache.tools.ant.property.NullReturn; | ||||
| import org.apache.tools.ant.property.ParseNextProperty; | |||||
| import org.apache.tools.ant.property.ParseProperties; | import org.apache.tools.ant.property.ParseProperties; | ||||
| import org.apache.tools.ant.property.PropertyExpander; | import org.apache.tools.ant.property.PropertyExpander; | ||||
| @@ -184,52 +182,41 @@ public class PropertyHelper implements GetProperty { | |||||
| } | } | ||||
| }; | }; | ||||
| private static final PropertyExpander DEFAULT_EXPANDER = new PropertyExpander() { | |||||
| public String parsePropertyName( | |||||
| String s, ParsePosition pos, ParseNextProperty notUsed) { | |||||
| private static final PropertyExpander DEFAULT_EXPANDER = | |||||
| (s, pos, notUsed) -> { | |||||
| int index = pos.getIndex(); | int index = pos.getIndex(); | ||||
| //directly check near, triggering characters: | //directly check near, triggering characters: | ||||
| if (s.length() - index >= 3 | |||||
| && '$' == s.charAt(index) && '{' == s.charAt(index + 1)) { | |||||
| if (s.length() - index >= 3 && '$' == s.charAt(index) | |||||
| && '{' == s.charAt(index + 1)) { | |||||
| int start = index + 2; | int start = index + 2; | ||||
| //defer to String.indexOf() for protracted check: | //defer to String.indexOf() for protracted check: | ||||
| int end = s.indexOf('}', start); | int end = s.indexOf('}', start); | ||||
| if (end < 0) { | if (end < 0) { | ||||
| throw new BuildException("Syntax error in property: " | |||||
| + s.substring(index)); | |||||
| throw new BuildException( | |||||
| "Syntax error in property: " + s.substring(index)); | |||||
| } | } | ||||
| pos.setIndex(end + 1); | pos.setIndex(end + 1); | ||||
| return start == end ? "" : s.substring(start, end); | |||||
| return start == end ? "" : s.substring(start, end); | |||||
| } | } | ||||
| return null; | return null; | ||||
| } | |||||
| }; | |||||
| }; | |||||
| /** dummy */ | /** dummy */ | ||||
| private static final PropertyExpander SKIP_DOUBLE_DOLLAR | |||||
| = new PropertyExpander() { | |||||
| // CheckStyle:LineLengthCheck OFF see too long | |||||
| /** | |||||
| * {@inheritDoc} | |||||
| * @see org.apache.tools.ant.property.PropertyExpander#parsePropertyName(java.lang.String, java.text.ParsePosition, org.apache.tools.ant.PropertyHelper) | |||||
| */ | |||||
| // CheckStyle:LineLengthCheck ON | |||||
| public String parsePropertyName( | |||||
| String s, ParsePosition pos, ParseNextProperty notUsed) { | |||||
| int index = pos.getIndex(); | |||||
| if (s.length() - index >= 2) { | |||||
| /* check for $$; if found, advance by one-- | |||||
| * this expander is at the bottom of the stack | |||||
| * and will thus be the last consulted, | |||||
| * so the next thing that ParseProperties will do | |||||
| * is advance the parse position beyond the second $ | |||||
| */ | |||||
| if ('$' == s.charAt(index) && '$' == s.charAt(++index)) { | |||||
| pos.setIndex(index); | |||||
| } | |||||
| private static final PropertyExpander SKIP_DOUBLE_DOLLAR = | |||||
| (s, pos, notUsed) -> { | |||||
| int index = pos.getIndex(); | |||||
| if (s.length() - index >= 2) { | |||||
| /* check for $$; if found, advance by one-- | |||||
| * this expander is at the bottom of the stack | |||||
| * and will thus be the last consulted, | |||||
| * so the next thing that ParseProperties will do | |||||
| * is advance the parse position beyond the second $ | |||||
| */ | |||||
| if ('$' == s.charAt(index) && '$' == s.charAt(++index)) { | |||||
| pos.setIndex(index); | |||||
| } | } | ||||
| return null; | |||||
| } | } | ||||
| return null; | |||||
| }; | }; | ||||
| /** | /** | ||||
| @@ -248,24 +235,24 @@ public class PropertyHelper implements GetProperty { | |||||
| private Project project; | private Project project; | ||||
| private PropertyHelper next; | private PropertyHelper next; | ||||
| private final Hashtable<Class<? extends Delegate>, List<Delegate>> delegates = new Hashtable<Class<? extends Delegate>, List<Delegate>>(); | |||||
| private final Hashtable<Class<? extends Delegate>, List<Delegate>> delegates = new Hashtable<>(); | |||||
| /** Project properties map (usually String to String). */ | /** Project properties map (usually String to String). */ | ||||
| private Hashtable<String, Object> properties = new Hashtable<String, Object>(); | |||||
| private Hashtable<String, Object> properties = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map of "user" properties (as created in the Ant task, for example). | * Map of "user" properties (as created in the Ant task, for example). | ||||
| * Note that these key/value pairs are also always put into the | * Note that these key/value pairs are also always put into the | ||||
| * project properties, so only the project properties need to be queried. | * project properties, so only the project properties need to be queried. | ||||
| */ | */ | ||||
| private Hashtable<String, Object> userProperties = new Hashtable<String, Object>(); | |||||
| private Hashtable<String, Object> userProperties = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Map of inherited "user" properties - that are those "user" | * Map of inherited "user" properties - that are those "user" | ||||
| * properties that have been created by tasks and not been set | * properties that have been created by tasks and not been set | ||||
| * from the command line or a GUI tool. | * from the command line or a GUI tool. | ||||
| */ | */ | ||||
| private Hashtable<String, Object> inheritedProperties = new Hashtable<String, Object>(); | |||||
| private Hashtable<String, Object> inheritedProperties = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Default constructor. | * Default constructor. | ||||
| @@ -900,7 +887,7 @@ public class PropertyHelper implements GetProperty { | |||||
| public Hashtable<String, Object> getProperties() { | public Hashtable<String, Object> getProperties() { | ||||
| //avoid concurrent modification: | //avoid concurrent modification: | ||||
| synchronized (properties) { | synchronized (properties) { | ||||
| return new Hashtable<String, Object>(properties); | |||||
| return new Hashtable<>(properties); | |||||
| } | } | ||||
| // There is a better way to save the context. This shouldn't | // There is a better way to save the context. This shouldn't | ||||
| // delegate to next, it's for backward compatibility only. | // delegate to next, it's for backward compatibility only. | ||||
| @@ -917,7 +904,7 @@ public class PropertyHelper implements GetProperty { | |||||
| public Hashtable<String, Object> getUserProperties() { | public Hashtable<String, Object> getUserProperties() { | ||||
| //avoid concurrent modification: | //avoid concurrent modification: | ||||
| synchronized (userProperties) { | synchronized (userProperties) { | ||||
| return new Hashtable<String, Object>(userProperties); | |||||
| return new Hashtable<>(userProperties); | |||||
| } | } | ||||
| } | } | ||||
| @@ -932,7 +919,7 @@ public class PropertyHelper implements GetProperty { | |||||
| public Hashtable<String, Object> getInheritedProperties() { | public Hashtable<String, Object> getInheritedProperties() { | ||||
| //avoid concurrent modification: | //avoid concurrent modification: | ||||
| synchronized (inheritedProperties) { | synchronized (inheritedProperties) { | ||||
| return new Hashtable<String, Object>(inheritedProperties); | |||||
| return new Hashtable<>(inheritedProperties); | |||||
| } | } | ||||
| } | } | ||||
| @@ -982,7 +969,7 @@ public class PropertyHelper implements GetProperty { | |||||
| synchronized (inheritedProperties) { | synchronized (inheritedProperties) { | ||||
| Enumeration<String> e = inheritedProperties.keys(); | Enumeration<String> e = inheritedProperties.keys(); | ||||
| while (e.hasMoreElements()) { | while (e.hasMoreElements()) { | ||||
| String arg = e.nextElement().toString(); | |||||
| String arg = e.nextElement(); | |||||
| if (other.getUserProperty(arg) != null) { | if (other.getUserProperty(arg) != null) { | ||||
| continue; | continue; | ||||
| } | } | ||||
| @@ -1036,7 +1023,7 @@ public class PropertyHelper implements GetProperty { | |||||
| int prev = 0; | int prev = 0; | ||||
| int pos; | int pos; | ||||
| //search for the next instance of $ from the 'prev' position | //search for the next instance of $ from the 'prev' position | ||||
| while ((pos = value.indexOf("$", prev)) >= 0) { | |||||
| while ((pos = value.indexOf('$', prev)) >= 0) { | |||||
| //if there was any text before this, add it as a fragment | //if there was any text before this, add it as a fragment | ||||
| //TODO, this check could be modified to go if pos>prev; | //TODO, this check could be modified to go if pos>prev; | ||||
| @@ -1096,10 +1083,10 @@ public class PropertyHelper implements GetProperty { | |||||
| for (Class<? extends Delegate> key : getDelegateInterfaces(delegate)) { | for (Class<? extends Delegate> key : getDelegateInterfaces(delegate)) { | ||||
| List<Delegate> list = delegates.get(key); | List<Delegate> list = delegates.get(key); | ||||
| if (list == null) { | if (list == null) { | ||||
| list = new ArrayList<Delegate>(); | |||||
| list = new ArrayList<>(); | |||||
| } else { | } else { | ||||
| //copy on write, top priority | //copy on write, top priority | ||||
| list = new ArrayList<Delegate>(list); | |||||
| list = new ArrayList<>(list); | |||||
| list.remove(delegate); | list.remove(delegate); | ||||
| } | } | ||||
| list.add(0, delegate); | list.add(0, delegate); | ||||
| @@ -1129,7 +1116,7 @@ public class PropertyHelper implements GetProperty { | |||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| protected static Set<Class<? extends Delegate>> getDelegateInterfaces(Delegate d) { | protected static Set<Class<? extends Delegate>> getDelegateInterfaces(Delegate d) { | ||||
| final HashSet<Class<? extends Delegate>> result = new HashSet<Class<? extends Delegate>>(); | |||||
| final HashSet<Class<? extends Delegate>> result = new HashSet<>(); | |||||
| Class<?> c = d.getClass(); | Class<?> c = d.getClass(); | ||||
| while (c != null) { | while (c != null) { | ||||
| Class<?>[] ifs = c.getInterfaces(); | Class<?>[] ifs = c.getInterfaces(); | ||||
| @@ -25,12 +25,11 @@ import java.util.Enumeration; | |||||
| import java.util.Hashtable; | import java.util.Hashtable; | ||||
| import java.util.LinkedHashMap; | import java.util.LinkedHashMap; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Map.Entry; | |||||
| import java.util.Map; | |||||
| import org.apache.tools.ant.attribute.EnableAttribute; | import org.apache.tools.ant.attribute.EnableAttribute; | ||||
| import org.apache.tools.ant.taskdefs.MacroDef.Attribute; | import org.apache.tools.ant.taskdefs.MacroDef.Attribute; | ||||
| import org.apache.tools.ant.taskdefs.MacroInstance; | import org.apache.tools.ant.taskdefs.MacroInstance; | ||||
| import org.apache.tools.ant.util.CollectionUtils; | |||||
| import org.xml.sax.AttributeList; | import org.xml.sax.AttributeList; | ||||
| import org.xml.sax.helpers.AttributeListImpl; | import org.xml.sax.helpers.AttributeListImpl; | ||||
| @@ -46,14 +45,14 @@ public class RuntimeConfigurable implements Serializable { | |||||
| /** Empty Hashtable. */ | /** Empty Hashtable. */ | ||||
| private static final Hashtable<String, Object> EMPTY_HASHTABLE = | private static final Hashtable<String, Object> EMPTY_HASHTABLE = | ||||
| new Hashtable<String, Object>(0); | |||||
| new Hashtable<>(0); | |||||
| /** Name of the element to configure. */ | /** Name of the element to configure. */ | ||||
| private String elementTag = null; | private String elementTag = null; | ||||
| /** List of child element wrappers. */ | /** List of child element wrappers. */ | ||||
| // picking ArrayList rather than List as arrayList is Serializable | // picking ArrayList rather than List as arrayList is Serializable | ||||
| private ArrayList<RuntimeConfigurable> children = null; | |||||
| private List<RuntimeConfigurable> children = null; | |||||
| /** The element to configure. It is only used during | /** The element to configure. It is only used during | ||||
| * maybeConfigure. | * maybeConfigure. | ||||
| @@ -303,17 +302,17 @@ public class RuntimeConfigurable implements Serializable { | |||||
| this.polyType = value == null ? null : value.toString(); | this.polyType = value == null ? null : value.toString(); | ||||
| } else { | } else { | ||||
| if (attributeMap == null) { | if (attributeMap == null) { | ||||
| attributeMap = new LinkedHashMap<String, Object>(); | |||||
| attributeMap = new LinkedHashMap<>(); | |||||
| } | } | ||||
| if (name.equalsIgnoreCase("refid") && !attributeMap.isEmpty()) { | |||||
| LinkedHashMap<String, Object> newAttributeMap = new LinkedHashMap<String, Object>(); | |||||
| if ("refid".equalsIgnoreCase(name) && !attributeMap.isEmpty()) { | |||||
| LinkedHashMap<String, Object> newAttributeMap = new LinkedHashMap<>(); | |||||
| newAttributeMap.put(name, value); | newAttributeMap.put(name, value); | ||||
| newAttributeMap.putAll(attributeMap); | newAttributeMap.putAll(attributeMap); | ||||
| attributeMap = newAttributeMap; | attributeMap = newAttributeMap; | ||||
| } else { | } else { | ||||
| attributeMap.put(name, value); | attributeMap.put(name, value); | ||||
| } | } | ||||
| if (name.equals("id")) { | |||||
| if ("id".equals(name)) { | |||||
| this.id = value == null ? null : value.toString(); | this.id = value == null ? null : value.toString(); | ||||
| } | } | ||||
| } | } | ||||
| @@ -335,7 +334,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| */ | */ | ||||
| public synchronized Hashtable<String, Object> getAttributeMap() { | public synchronized Hashtable<String, Object> getAttributeMap() { | ||||
| return (attributeMap == null) | return (attributeMap == null) | ||||
| ? EMPTY_HASHTABLE : new Hashtable<String, Object>(attributeMap); | |||||
| ? EMPTY_HASHTABLE : new Hashtable<>(attributeMap); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -356,7 +355,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| * Must not be <code>null</code>. | * Must not be <code>null</code>. | ||||
| */ | */ | ||||
| public synchronized void addChild(RuntimeConfigurable child) { | public synchronized void addChild(RuntimeConfigurable child) { | ||||
| children = (children == null) ? new ArrayList<RuntimeConfigurable>() : children; | |||||
| children = (children == null) ? new ArrayList<>() : children; | |||||
| children.add(child); | children.add(child); | ||||
| } | } | ||||
| @@ -378,7 +377,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| public synchronized Enumeration<RuntimeConfigurable> getChildren() { | public synchronized Enumeration<RuntimeConfigurable> getChildren() { | ||||
| return (children == null) ? new CollectionUtils.EmptyEnumeration<RuntimeConfigurable>() | |||||
| return (children == null) ? Collections.emptyEnumeration() | |||||
| : Collections.enumeration(children); | : Collections.enumeration(children); | ||||
| } | } | ||||
| @@ -497,7 +496,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| IntrospectionHelper.getHelper(p, target.getClass()); | IntrospectionHelper.getHelper(p, target.getClass()); | ||||
| ComponentHelper componentHelper = ComponentHelper.getComponentHelper(p); | ComponentHelper componentHelper = ComponentHelper.getComponentHelper(p); | ||||
| if (attributeMap != null) { | if (attributeMap != null) { | ||||
| for (Entry<String, Object> entry : attributeMap.entrySet()) { | |||||
| for (Map.Entry<String, Object> entry : attributeMap.entrySet()) { | |||||
| String name = entry.getKey(); | String name = entry.getKey(); | ||||
| // skip restricted attributes such as if:set | // skip restricted attributes such as if:set | ||||
| AttributeComponentInformation attributeComponentInformation = isRestrictedAttribute(name, componentHelper); | AttributeComponentInformation attributeComponentInformation = isRestrictedAttribute(name, componentHelper); | ||||
| @@ -509,8 +508,8 @@ public class RuntimeConfigurable implements Serializable { | |||||
| // MacroInstance where properties are expanded for the | // MacroInstance where properties are expanded for the | ||||
| // nested sequential | // nested sequential | ||||
| Object attrValue; | Object attrValue; | ||||
| if (value instanceof Evaluable) { | |||||
| attrValue = ((Evaluable) value).eval(); | |||||
| if (value instanceof Evaluable<?>) { | |||||
| attrValue = ((Evaluable<?>) value).eval(); | |||||
| } else { | } else { | ||||
| attrValue = PropertyHelper.getPropertyHelper(p).parseProperties(value.toString()); | attrValue = PropertyHelper.getPropertyHelper(p).parseProperties(value.toString()); | ||||
| } | } | ||||
| @@ -528,7 +527,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| ih.setAttribute(p, target, name, attrValue); | ih.setAttribute(p, target, name, attrValue); | ||||
| } catch (UnsupportedAttributeException be) { | } catch (UnsupportedAttributeException be) { | ||||
| // id attribute must be set externally | // id attribute must be set externally | ||||
| if (name.equals("id")) { | |||||
| if ("id".equals(name)) { | |||||
| // Do nothing | // Do nothing | ||||
| } else if (getElementTag() == null) { | } else if (getElementTag() == null) { | ||||
| throw be; | throw be; | ||||
| @@ -538,7 +537,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| + be.getAttribute() + "\" attribute", be); | + be.getAttribute() + "\" attribute", be); | ||||
| } | } | ||||
| } catch (BuildException be) { | } catch (BuildException be) { | ||||
| if (name.equals("id")) { | |||||
| if ("id".equals(name)) { | |||||
| // Assume that this is an not supported attribute type | // Assume that this is an not supported attribute type | ||||
| // thrown for example by a dymanic attribute task | // thrown for example by a dymanic attribute task | ||||
| // Do nothing | // Do nothing | ||||
| @@ -590,7 +589,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| // Children (this is a shadow of UnknownElement#children) | // Children (this is a shadow of UnknownElement#children) | ||||
| if (r.children != null) { | if (r.children != null) { | ||||
| ArrayList<RuntimeConfigurable> newChildren = new ArrayList<RuntimeConfigurable>(); | |||||
| List<RuntimeConfigurable> newChildren = new ArrayList<>(); | |||||
| newChildren.addAll(r.children); | newChildren.addAll(r.children); | ||||
| if (children != null) { | if (children != null) { | ||||
| newChildren.addAll(children); | newChildren.addAll(children); | ||||
| @@ -601,7 +600,7 @@ public class RuntimeConfigurable implements Serializable { | |||||
| // Text | // Text | ||||
| if (r.characters != null) { | if (r.characters != null) { | ||||
| if (characters == null | if (characters == null | ||||
| || characters.toString().trim().length() == 0) { | |||||
| || characters.toString().trim().isEmpty()) { | |||||
| characters = new StringBuffer(r.characters.toString()); | characters = new StringBuffer(r.characters.toString()); | ||||
| } | } | ||||
| } | } | ||||
| @@ -55,7 +55,7 @@ public class Target implements TaskContainer { | |||||
| private List<String> dependencies = null; | private List<String> dependencies = null; | ||||
| /** Children of this target (tasks and data types). */ | /** Children of this target (tasks and data types). */ | ||||
| private List<Object> children = new ArrayList<Object>(); | |||||
| private List<Object> children = new ArrayList<>(); | |||||
| /** Since Ant 1.6.2 */ | /** Since Ant 1.6.2 */ | ||||
| private Location location = Location.UNKNOWN_LOCATION; | private Location location = Location.UNKNOWN_LOCATION; | ||||
| @@ -145,7 +145,7 @@ public class Target implements TaskContainer { | |||||
| public static List<String> parseDepends(String depends, | public static List<String> parseDepends(String depends, | ||||
| String targetName, | String targetName, | ||||
| String attributeName) { | String attributeName) { | ||||
| List<String> list = new ArrayList<String>(); | |||||
| List<String> list = new ArrayList<>(); | |||||
| if (depends.length() > 0) { | if (depends.length() > 0) { | ||||
| StringTokenizer tok = | StringTokenizer tok = | ||||
| new StringTokenizer(depends, ",", true); | new StringTokenizer(depends, ",", true); | ||||
| @@ -225,7 +225,7 @@ public class Target implements TaskContainer { | |||||
| * @return an array of the tasks currently within this target | * @return an array of the tasks currently within this target | ||||
| */ | */ | ||||
| public Task[] getTasks() { | public Task[] getTasks() { | ||||
| List<Task> tasks = new ArrayList<Task>(children.size()); | |||||
| List<Task> tasks = new ArrayList<>(children.size()); | |||||
| for (Object o : children) { | for (Object o : children) { | ||||
| if (o instanceof Task) { | if (o instanceof Task) { | ||||
| tasks.add((Task) o); | tasks.add((Task) o); | ||||
| @@ -242,7 +242,7 @@ public class Target implements TaskContainer { | |||||
| */ | */ | ||||
| public void addDependency(String dependency) { | public void addDependency(String dependency) { | ||||
| if (dependencies == null) { | if (dependencies == null) { | ||||
| dependencies = new ArrayList<String>(2); | |||||
| dependencies = new ArrayList<>(2); | |||||
| } | } | ||||
| dependencies.add(dependency); | dependencies.add(dependency); | ||||
| } | } | ||||
| @@ -253,8 +253,8 @@ public class Target implements TaskContainer { | |||||
| * @return an enumeration of the dependencies of this target (enumeration of String) | * @return an enumeration of the dependencies of this target (enumeration of String) | ||||
| */ | */ | ||||
| public Enumeration<String> getDependencies() { | public Enumeration<String> getDependencies() { | ||||
| return Collections | |||||
| .enumeration(dependencies == null ? Collections.<String> emptyList() : dependencies); | |||||
| return dependencies == null ? Collections.emptyEnumeration() | |||||
| : Collections.enumeration(dependencies); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -284,7 +284,12 @@ public class Target implements TaskContainer { | |||||
| */ | */ | ||||
| public void setIf(String property) { | public void setIf(String property) { | ||||
| ifString = property == null ? "" : property; | ifString = property == null ? "" : property; | ||||
| setIf(new IfStringCondition(ifString)); | |||||
| setIf(() -> { | |||||
| PropertyHelper propertyHelper = | |||||
| PropertyHelper.getPropertyHelper(getProject()); | |||||
| Object o = propertyHelper.parseProperties(ifString); | |||||
| return propertyHelper.testIfCondition(o); | |||||
| }); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -331,7 +336,12 @@ public class Target implements TaskContainer { | |||||
| */ | */ | ||||
| public void setUnless(String property) { | public void setUnless(String property) { | ||||
| unlessString = property == null ? "" : property; | unlessString = property == null ? "" : property; | ||||
| setUnless(new UnlessStringCondition(unlessString)); | |||||
| setUnless(() -> { | |||||
| PropertyHelper propertyHelper = | |||||
| PropertyHelper.getPropertyHelper(getProject()); | |||||
| Object o = propertyHelper.parseProperties(unlessString); | |||||
| return !propertyHelper.testUnlessCondition(o); | |||||
| }); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -390,6 +400,7 @@ public class Target implements TaskContainer { | |||||
| * @return the name of this target, or <code>null</code> if the | * @return the name of this target, or <code>null</code> if the | ||||
| * name has not been set yet. | * name has not been set yet. | ||||
| */ | */ | ||||
| @Override | |||||
| public String toString() { | public String toString() { | ||||
| return name; | return name; | ||||
| } | } | ||||
| @@ -491,42 +502,4 @@ public class Target implements TaskContainer { | |||||
| children.set(index, o); | children.set(index, o); | ||||
| } | } | ||||
| } | } | ||||
| /** | |||||
| * Condition evaluating the 'if' attribute with the PropertyHelper. | |||||
| */ | |||||
| private class IfStringCondition implements Condition { | |||||
| private String condition; | |||||
| public IfStringCondition(String condition) { | |||||
| this.condition = condition; | |||||
| } | |||||
| public boolean eval() throws BuildException { | |||||
| PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(getProject()); | |||||
| Object o = propertyHelper.parseProperties(condition); | |||||
| return propertyHelper.testIfCondition(o); | |||||
| } | |||||
| } | |||||
| /** | |||||
| * Condition evaluating the 'unless' attribute with the PropertyHelper. | |||||
| */ | |||||
| private class UnlessStringCondition implements Condition { | |||||
| private String condition; | |||||
| public UnlessStringCondition(String condition) { | |||||
| this.condition = condition; | |||||
| } | |||||
| public boolean eval() throws BuildException { | |||||
| PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(getProject()); | |||||
| Object o = propertyHelper.parseProperties(condition); | |||||
| return !propertyHelper.testUnlessCondition(o); | |||||
| } | |||||
| } | |||||
| } | } | ||||
| @@ -81,10 +81,6 @@ public abstract class Task extends ProjectComponent { | |||||
| */ | */ | ||||
| private boolean invalid; | private boolean invalid; | ||||
| /** Sole constructor. */ | |||||
| public Task() { | |||||
| } | |||||
| /** | /** | ||||
| * Sets the target container of this task. | * Sets the target container of this task. | ||||
| * | * | ||||
| @@ -197,12 +193,10 @@ public abstract class Task extends ProjectComponent { | |||||
| * @exception BuildException if the task cannot be configured. | * @exception BuildException if the task cannot be configured. | ||||
| */ | */ | ||||
| public void maybeConfigure() throws BuildException { | public void maybeConfigure() throws BuildException { | ||||
| if (!invalid) { | |||||
| if (wrapper != null) { | |||||
| wrapper.maybeConfigure(getProject()); | |||||
| } | |||||
| } else { | |||||
| if (invalid) { | |||||
| getReplacement(); | getReplacement(); | ||||
| } else if (wrapper != null) { | |||||
| wrapper.maybeConfigure(getProject()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -290,10 +284,10 @@ public abstract class Task extends ProjectComponent { | |||||
| * be logged. | * be logged. | ||||
| */ | */ | ||||
| public void log(String msg, int msgLevel) { | public void log(String msg, int msgLevel) { | ||||
| if (getProject() != null) { | |||||
| getProject().log(this, msg, msgLevel); | |||||
| } else { | |||||
| if (getProject() == null) { | |||||
| super.log(msg, msgLevel); | super.log(msg, msgLevel); | ||||
| } else { | |||||
| getProject().log(this, msg, msgLevel); | |||||
| } | } | ||||
| } | } | ||||
| @@ -323,10 +317,10 @@ public abstract class Task extends ProjectComponent { | |||||
| * @since 1.7 | * @since 1.7 | ||||
| */ | */ | ||||
| public void log(String msg, Throwable t, int msgLevel) { | public void log(String msg, Throwable t, int msgLevel) { | ||||
| if (getProject() != null) { | |||||
| getProject().log(this, msg, t, msgLevel); | |||||
| } else { | |||||
| if (getProject() == null) { | |||||
| super.log(msg, msgLevel); | super.log(msg, msgLevel); | ||||
| } else { | |||||
| getProject().log(this, msg, t, msgLevel); | |||||
| } | } | ||||
| } | } | ||||
| @@ -340,7 +334,11 @@ public abstract class Task extends ProjectComponent { | |||||
| * is still fired, but with the exception as the cause. | * is still fired, but with the exception as the cause. | ||||
| */ | */ | ||||
| public final void perform() { | public final void perform() { | ||||
| if (!invalid) { | |||||
| if (invalid) { | |||||
| UnknownElement ue = getReplacement(); | |||||
| Task task = ue.getTask(); | |||||
| task.perform(); | |||||
| } else { | |||||
| getProject().fireTaskStarted(this); | getProject().fireTaskStarted(this); | ||||
| Throwable reason = null; | Throwable reason = null; | ||||
| try { | try { | ||||
| @@ -363,10 +361,6 @@ public abstract class Task extends ProjectComponent { | |||||
| } finally { | } finally { | ||||
| getProject().fireTaskFinished(this, reason); | getProject().fireTaskFinished(this, reason); | ||||
| } | } | ||||
| } else { | |||||
| UnknownElement ue = getReplacement(); | |||||
| Task task = ue.getTask(); | |||||
| task.perform(); | |||||
| } | } | ||||
| } | } | ||||
| @@ -81,7 +81,7 @@ public class TaskAdapter extends Task implements TypeAdapter { | |||||
| // don't have to check for interface, since then | // don't have to check for interface, since then | ||||
| // taskClass would be abstract too. | // taskClass would be abstract too. | ||||
| try { | try { | ||||
| final Method executeM = taskClass.getMethod("execute", (Class[]) null); | |||||
| final Method executeM = taskClass.getMethod("execute"); | |||||
| // don't have to check for public, since | // don't have to check for public, since | ||||
| // getMethod finds public method only. | // getMethod finds public method only. | ||||
| // don't have to check for abstract, since then | // don't have to check for abstract, since then | ||||
| @@ -122,10 +122,10 @@ public class TaskAdapter extends Task implements TypeAdapter { | |||||
| */ | */ | ||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| try { | try { | ||||
| Method setLocationM = proxy.getClass().getMethod( | |||||
| "setLocation", new Class[] {Location.class}); | |||||
| Method setLocationM = | |||||
| proxy.getClass().getMethod("setLocation", Location.class); | |||||
| if (setLocationM != null) { | if (setLocationM != null) { | ||||
| setLocationM.invoke(proxy, new Object[] {getLocation()}); | |||||
| setLocationM.invoke(proxy, getLocation()); | |||||
| } | } | ||||
| } catch (NoSuchMethodException e) { | } catch (NoSuchMethodException e) { | ||||
| // ignore this if the class being used as a task does not have | // ignore this if the class being used as a task does not have | ||||
| @@ -137,10 +137,10 @@ public class TaskAdapter extends Task implements TypeAdapter { | |||||
| } | } | ||||
| try { | try { | ||||
| Method setProjectM = proxy.getClass().getMethod( | |||||
| "setProject", new Class[] {Project.class}); | |||||
| Method setProjectM = | |||||
| proxy.getClass().getMethod("setProject", Project.class); | |||||
| if (setProjectM != null) { | if (setProjectM != null) { | ||||
| setProjectM.invoke(proxy, new Object[] {getProject()}); | |||||
| setProjectM.invoke(proxy, getProject()); | |||||
| } | } | ||||
| } catch (NoSuchMethodException e) { | } catch (NoSuchMethodException e) { | ||||
| // ignore this if the class being used as a task does not have | // ignore this if the class being used as a task does not have | ||||
| @@ -55,7 +55,7 @@ import java.util.List; | |||||
| public class TaskConfigurationChecker { | public class TaskConfigurationChecker { | ||||
| /** List of all collected error messages. */ | /** List of all collected error messages. */ | ||||
| private List<String> errors = new ArrayList<String>(); | |||||
| private List<String> errors = new ArrayList<>(); | |||||
| /** Task for which the configuration should be checked. */ | /** Task for which the configuration should be checked. */ | ||||
| private final Task task; | private final Task task; | ||||
| @@ -94,8 +94,7 @@ public class TaskConfigurationChecker { | |||||
| */ | */ | ||||
| public void checkErrors() throws BuildException { | public void checkErrors() throws BuildException { | ||||
| if (!errors.isEmpty()) { | if (!errors.isEmpty()) { | ||||
| StringBuffer sb = new StringBuffer(); | |||||
| sb.append("Configurationerror on <"); | |||||
| StringBuilder sb = new StringBuilder("Configurationerror on <"); | |||||
| sb.append(task.getTaskName()); | sb.append(task.getTaskName()); | ||||
| sb.append(">:"); | sb.append(">:"); | ||||
| sb.append(System.getProperty("line.separator")); | sb.append(System.getProperty("line.separator")); | ||||
| @@ -24,6 +24,7 @@ import java.util.Enumeration; | |||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| import java.util.Objects; | |||||
| import org.apache.tools.ant.taskdefs.PreSetDef; | import org.apache.tools.ant.taskdefs.PreSetDef; | ||||
| @@ -234,10 +235,8 @@ public class UnknownElement extends Task { | |||||
| throws IOException { | throws IOException { | ||||
| if (realThing instanceof Task) { | if (realThing instanceof Task) { | ||||
| return ((Task) realThing).handleInput(buffer, offset, length); | return ((Task) realThing).handleInput(buffer, offset, length); | ||||
| } else { | |||||
| return super.handleInput(buffer, offset, length); | |||||
| } | } | ||||
| return super.handleInput(buffer, offset, length); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -311,7 +310,7 @@ public class UnknownElement extends Task { | |||||
| */ | */ | ||||
| public void addChild(UnknownElement child) { | public void addChild(UnknownElement child) { | ||||
| if (children == null) { | if (children == null) { | ||||
| children = new ArrayList<UnknownElement>(); | |||||
| children = new ArrayList<>(); | |||||
| } | } | ||||
| children.add(child); | children.add(child); | ||||
| } | } | ||||
| @@ -341,7 +340,6 @@ public class UnknownElement extends Task { | |||||
| Class<?> parentClass = parent.getClass(); | Class<?> parentClass = parent.getClass(); | ||||
| IntrospectionHelper ih = IntrospectionHelper.getHelper(getProject(), parentClass); | IntrospectionHelper ih = IntrospectionHelper.getHelper(getProject(), parentClass); | ||||
| if (children != null) { | if (children != null) { | ||||
| Iterator<UnknownElement> it = children.iterator(); | Iterator<UnknownElement> it = children.iterator(); | ||||
| for (int i = 0; it.hasNext(); i++) { | for (int i = 0; it.hasNext(); i++) { | ||||
| @@ -400,7 +398,7 @@ public class UnknownElement extends Task { | |||||
| // Do the runtime | // Do the runtime | ||||
| getWrapper().applyPreSet(u.getWrapper()); | getWrapper().applyPreSet(u.getWrapper()); | ||||
| if (u.children != null) { | if (u.children != null) { | ||||
| List<UnknownElement> newChildren = new ArrayList<UnknownElement>(); | |||||
| List<UnknownElement> newChildren = new ArrayList<>(); | |||||
| newChildren.addAll(u.children); | newChildren.addAll(u.children); | ||||
| if (children != null) { | if (children != null) { | ||||
| newChildren.addAll(children); | newChildren.addAll(children); | ||||
| @@ -506,7 +504,6 @@ public class UnknownElement extends Task { | |||||
| * @return the name to use in logging messages. | * @return the name to use in logging messages. | ||||
| */ | */ | ||||
| public String getTaskName() { | public String getTaskName() { | ||||
| //return elementName; | |||||
| return realThing == null | return realThing == null | ||||
| || !(realThing instanceof Task) ? super.getTaskName() | || !(realThing instanceof Task) ? super.getTaskName() | ||||
| : ((Task) realThing).getTaskName(); | : ((Task) realThing).getTaskName(); | ||||
| @@ -612,7 +609,7 @@ public class UnknownElement extends Task { | |||||
| } | } | ||||
| UnknownElement other = (UnknownElement) obj; | UnknownElement other = (UnknownElement) obj; | ||||
| // Are the names the same ? | // Are the names the same ? | ||||
| if (!equalsString(elementName, other.elementName)) { | |||||
| if (!Objects.equals(elementName, other.elementName)) { | |||||
| return false; | return false; | ||||
| } | } | ||||
| if (!namespace.equals(other.namespace)) { | if (!namespace.equals(other.namespace)) { | ||||
| @@ -637,7 +634,7 @@ public class UnknownElement extends Task { | |||||
| // Are the sub elements the same ? | // Are the sub elements the same ? | ||||
| final int childrenSize = children == null ? 0 : children.size(); | final int childrenSize = children == null ? 0 : children.size(); | ||||
| if (childrenSize == 0) { | if (childrenSize == 0) { | ||||
| return other.children == null || other.children.size() == 0; | |||||
| return other.children == null || other.children.isEmpty(); | |||||
| } | } | ||||
| if (other.children == null) { | if (other.children == null) { | ||||
| return false; | return false; | ||||
| @@ -655,10 +652,6 @@ public class UnknownElement extends Task { | |||||
| return true; | return true; | ||||
| } | } | ||||
| private static boolean equalsString(String a, String b) { | |||||
| return (a == null) ? (b == null) : a.equals(b); | |||||
| } | |||||
| /** | /** | ||||
| * Make a copy of the unknown element and set it in the new project. | * Make a copy of the unknown element and set it in the new project. | ||||
| * @param newProject the project to create the UE in. | * @param newProject the project to create the UE in. | ||||
| @@ -32,7 +32,6 @@ import javax.xml.parsers.DocumentBuilder; | |||||
| import javax.xml.parsers.DocumentBuilderFactory; | import javax.xml.parsers.DocumentBuilderFactory; | ||||
| import org.apache.tools.ant.util.DOMElementWriter; | import org.apache.tools.ant.util.DOMElementWriter; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| import org.apache.tools.ant.util.StringUtils; | import org.apache.tools.ant.util.StringUtils; | ||||
| import org.w3c.dom.Document; | import org.w3c.dom.Document; | ||||
| import org.w3c.dom.Element; | import org.w3c.dom.Element; | ||||
| @@ -109,16 +108,16 @@ public class XmlLogger implements BuildLogger { | |||||
| private Document doc = builder.newDocument(); | private Document doc = builder.newDocument(); | ||||
| /** Mapping for when tasks started (Task to TimedElement). */ | /** Mapping for when tasks started (Task to TimedElement). */ | ||||
| private Hashtable<Task, TimedElement> tasks = new Hashtable<Task, TimedElement>(); | |||||
| private Hashtable<Task, TimedElement> tasks = new Hashtable<>(); | |||||
| /** Mapping for when targets started (Target to TimedElement). */ | /** Mapping for when targets started (Target to TimedElement). */ | ||||
| private Hashtable<Target, TimedElement> targets = new Hashtable<Target, XmlLogger.TimedElement>(); | |||||
| private Hashtable<Target, TimedElement> targets = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Mapping of threads to stacks of elements | * Mapping of threads to stacks of elements | ||||
| * (Thread to Stack of TimedElement). | * (Thread to Stack of TimedElement). | ||||
| */ | */ | ||||
| private Hashtable<Thread, Stack<TimedElement>> threadStacks = new Hashtable<Thread, Stack<TimedElement>>(); | |||||
| private Hashtable<Thread, Stack<TimedElement>> threadStacks = new Hashtable<>(); | |||||
| /** | /** | ||||
| * When the build started. | * When the build started. | ||||
| @@ -134,23 +133,20 @@ public class XmlLogger implements BuildLogger { | |||||
| private long startTime; | private long startTime; | ||||
| /** Element created at the start time. */ | /** Element created at the start time. */ | ||||
| private Element element; | private Element element; | ||||
| @Override | |||||
| public String toString() { | public String toString() { | ||||
| return element.getTagName() + ":" + element.getAttribute("name"); | return element.getTagName() + ":" + element.getAttribute("name"); | ||||
| } | } | ||||
| } | } | ||||
| /** | |||||
| * Constructs a new BuildListener that logs build events to an XML file. | |||||
| */ | |||||
| public XmlLogger() { | |||||
| } | |||||
| /** | /** | ||||
| * Fired when the build starts, this builds the top-level element for the | * Fired when the build starts, this builds the top-level element for the | ||||
| * document and remembers the time of the start of the build. | * document and remembers the time of the start of the build. | ||||
| * | * | ||||
| * @param event Ignored. | * @param event Ignored. | ||||
| */ | */ | ||||
| @Override | |||||
| public void buildStarted(BuildEvent event) { | public void buildStarted(BuildEvent event) { | ||||
| buildElement = new TimedElement(); | buildElement = new TimedElement(); | ||||
| buildElement.startTime = System.currentTimeMillis(); | buildElement.startTime = System.currentTimeMillis(); | ||||
| @@ -164,6 +160,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void buildFinished(BuildEvent event) { | public void buildFinished(BuildEvent event) { | ||||
| long totalTime = System.currentTimeMillis() - buildElement.startTime; | long totalTime = System.currentTimeMillis() - buildElement.startTime; | ||||
| buildElement.element.setAttribute(TIME_ATTR, DefaultLogger.formatTime(totalTime)); | buildElement.element.setAttribute(TIME_ATTR, DefaultLogger.formatTime(totalTime)); | ||||
| @@ -180,25 +177,19 @@ public class XmlLogger implements BuildLogger { | |||||
| } | } | ||||
| String outFilename = getProperty(event, "XmlLogger.file", "log.xml"); | String outFilename = getProperty(event, "XmlLogger.file", "log.xml"); | ||||
| String xslUri = getProperty(event, "ant.XmlLogger.stylesheet.uri", "log.xsl"); | String xslUri = getProperty(event, "ant.XmlLogger.stylesheet.uri", "log.xsl"); | ||||
| Writer out = null; | |||||
| try { | |||||
| // specify output in UTF8 otherwise accented characters will blow | |||||
| // up everything | |||||
| OutputStream stream = outStream; | |||||
| if (stream == null) { | |||||
| stream = Files.newOutputStream(Paths.get(outFilename)); | |||||
| } | |||||
| out = new OutputStreamWriter(stream, "UTF8"); | |||||
| try (OutputStream stream = | |||||
| outStream == null ? Files.newOutputStream(Paths.get(outFilename)) : outStream; | |||||
| Writer out = new OutputStreamWriter(stream, "UTF8")) { | |||||
| out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); | out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); | ||||
| if (xslUri.length() > 0) { | if (xslUri.length() > 0) { | ||||
| out.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslUri + "\"?>\n\n"); | |||||
| out.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslUri | |||||
| + "\"?>\n\n"); | |||||
| } | } | ||||
| new DOMElementWriter().write(buildElement.element, out, 0, "\t"); | new DOMElementWriter().write(buildElement.element, out, 0, "\t"); | ||||
| out.flush(); | out.flush(); | ||||
| } catch (IOException exc) { | } catch (IOException exc) { | ||||
| throw new BuildException("Unable to write log file", exc); | throw new BuildException("Unable to write log file", exc); | ||||
| } finally { | |||||
| FileUtils.close(out); | |||||
| } | } | ||||
| buildElement = null; | buildElement = null; | ||||
| } | } | ||||
| @@ -218,7 +209,7 @@ public class XmlLogger implements BuildLogger { | |||||
| private Stack<TimedElement> getStack() { | private Stack<TimedElement> getStack() { | ||||
| Stack<TimedElement> threadStack = threadStacks.get(Thread.currentThread()); | Stack<TimedElement> threadStack = threadStacks.get(Thread.currentThread()); | ||||
| if (threadStack == null) { | if (threadStack == null) { | ||||
| threadStack = new Stack<TimedElement>(); | |||||
| threadStack = new Stack<>(); | |||||
| threadStacks.put(Thread.currentThread(), threadStack); | threadStacks.put(Thread.currentThread(), threadStack); | ||||
| } | } | ||||
| /* For debugging purposes uncomment: | /* For debugging purposes uncomment: | ||||
| @@ -236,6 +227,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void targetStarted(BuildEvent event) { | public void targetStarted(BuildEvent event) { | ||||
| Target target = event.getTarget(); | Target target = event.getTarget(); | ||||
| TimedElement targetElement = new TimedElement(); | TimedElement targetElement = new TimedElement(); | ||||
| @@ -253,6 +245,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void targetFinished(BuildEvent event) { | public void targetFinished(BuildEvent event) { | ||||
| Target target = event.getTarget(); | Target target = event.getTarget(); | ||||
| TimedElement targetElement = targets.get(target); | TimedElement targetElement = targets.get(target); | ||||
| @@ -290,6 +283,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void taskStarted(BuildEvent event) { | public void taskStarted(BuildEvent event) { | ||||
| TimedElement taskElement = new TimedElement(); | TimedElement taskElement = new TimedElement(); | ||||
| taskElement.startTime = System.currentTimeMillis(); | taskElement.startTime = System.currentTimeMillis(); | ||||
| @@ -313,6 +307,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void taskFinished(BuildEvent event) { | public void taskFinished(BuildEvent event) { | ||||
| Task task = event.getTask(); | Task task = event.getTask(); | ||||
| TimedElement taskElement = tasks.get(task); | TimedElement taskElement = tasks.get(task); | ||||
| @@ -355,10 +350,9 @@ public class XmlLogger implements BuildLogger { | |||||
| } | } | ||||
| for (Enumeration<Task> e = tasks.keys(); e.hasMoreElements();) { | for (Enumeration<Task> e = tasks.keys(); e.hasMoreElements();) { | ||||
| Task key = e.nextElement(); | Task key = e.nextElement(); | ||||
| if (key instanceof UnknownElement) { | |||||
| if (((UnknownElement) key).getTask() == task) { | |||||
| return tasks.get(key); | |||||
| } | |||||
| if (key instanceof UnknownElement | |||||
| && ((UnknownElement) key).getTask() == task) { | |||||
| return tasks.get(key); | |||||
| } | } | ||||
| } | } | ||||
| return null; | return null; | ||||
| @@ -372,6 +366,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param event An event with any relevant extra information. | * @param event An event with any relevant extra information. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void messageLogged(BuildEvent event) { | public void messageLogged(BuildEvent event) { | ||||
| int priority = event.getPriority(); | int priority = event.getPriority(); | ||||
| if (priority > msgOutputLevel) { | if (priority > msgOutputLevel) { | ||||
| @@ -379,7 +374,7 @@ public class XmlLogger implements BuildLogger { | |||||
| } | } | ||||
| Element messageElement = doc.createElement(MESSAGE_TAG); | Element messageElement = doc.createElement(MESSAGE_TAG); | ||||
| String name = "debug"; | |||||
| String name; | |||||
| switch (priority) { | switch (priority) { | ||||
| case Project.MSG_ERR: | case Project.MSG_ERR: | ||||
| name = "error"; | name = "error"; | ||||
| @@ -433,6 +428,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * see {@link org.apache.tools.ant.Project#MSG_ERR Project} | * see {@link org.apache.tools.ant.Project#MSG_ERR Project} | ||||
| * class for level definitions | * class for level definitions | ||||
| */ | */ | ||||
| @Override | |||||
| public void setMessageOutputLevel(int level) { | public void setMessageOutputLevel(int level) { | ||||
| msgOutputLevel = level; | msgOutputLevel = level; | ||||
| } | } | ||||
| @@ -443,6 +439,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * | * | ||||
| * @param output the output PrintStream. | * @param output the output PrintStream. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setOutputPrintStream(PrintStream output) { | public void setOutputPrintStream(PrintStream output) { | ||||
| this.outStream = new PrintStream(output, true); | this.outStream = new PrintStream(output, true); | ||||
| } | } | ||||
| @@ -453,6 +450,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * @param emacsMode true if logger should produce emacs compatible | * @param emacsMode true if logger should produce emacs compatible | ||||
| * output | * output | ||||
| */ | */ | ||||
| @Override | |||||
| public void setEmacsMode(boolean emacsMode) { | public void setEmacsMode(boolean emacsMode) { | ||||
| } | } | ||||
| @@ -463,6 +461,7 @@ public class XmlLogger implements BuildLogger { | |||||
| * | * | ||||
| * @param err the stream we are going to ignore. | * @param err the stream we are going to ignore. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setErrorPrintStream(PrintStream err) { | public void setErrorPrintStream(PrintStream err) { | ||||
| } | } | ||||
| @@ -19,6 +19,7 @@ | |||||
| package org.apache.tools.ant.attribute; | package org.apache.tools.ant.attribute; | ||||
| import java.util.HashMap; | import java.util.HashMap; | ||||
| import java.util.Hashtable; | |||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| @@ -67,18 +68,19 @@ public abstract class BaseIfAttribute | |||||
| * @param el the element this attribute is in. | * @param el the element this attribute is in. | ||||
| * @return a map of attributes. | * @return a map of attributes. | ||||
| */ | */ | ||||
| protected Map getParams(UnknownElement el) { | |||||
| Map ret = new HashMap(); | |||||
| protected Map<String, String> getParams(UnknownElement el) { | |||||
| Map<String, String> ret = new HashMap<>(); | |||||
| RuntimeConfigurable rc = el.getWrapper(); | RuntimeConfigurable rc = el.getWrapper(); | ||||
| Map attributes = rc.getAttributeMap(); // This does a copy! | |||||
| for (Iterator i = attributes.entrySet().iterator(); i.hasNext();) { | |||||
| Map.Entry entry = (Map.Entry) i.next(); | |||||
| String key = (String) entry.getKey(); | |||||
| Hashtable<String, Object> attributes = rc.getAttributeMap(); // This does a copy! | |||||
| for (Iterator<Map.Entry<String, Object>> i = | |||||
| attributes.entrySet().iterator(); i.hasNext();) { | |||||
| Map.Entry<String, Object> entry = i.next(); | |||||
| String key = entry.getKey(); | |||||
| String value = (String) entry.getValue(); | String value = (String) entry.getValue(); | ||||
| if (key.startsWith("ant-attribute:param")) { | if (key.startsWith("ant-attribute:param")) { | ||||
| int pos = key.lastIndexOf(':'); | int pos = key.lastIndexOf(':'); | ||||
| ret.put(key.substring(pos + 1), | ret.put(key.substring(pos + 1), | ||||
| el.getProject().replaceProperties(value)); | |||||
| el.getProject().replaceProperties(value)); | |||||
| } | } | ||||
| } | } | ||||
| return ret; | return ret; | ||||
| @@ -37,6 +37,7 @@ public abstract class DispatchTask extends Task implements Dispatchable { | |||||
| * Get the action parameter name. | * Get the action parameter name. | ||||
| * @return the <code>String</code> "action" by default (can be overridden). | * @return the <code>String</code> "action" by default (can be overridden). | ||||
| */ | */ | ||||
| @Override | |||||
| public String getActionParameterName() { | public String getActionParameterName() { | ||||
| return "action"; | return "action"; | ||||
| } | } | ||||
| @@ -98,12 +98,12 @@ public class DispatchUtils { | |||||
| } | } | ||||
| } else { | } else { | ||||
| Method executeM = null; | Method executeM = null; | ||||
| executeM = task.getClass().getMethod(methodName, new Class[0]); | |||||
| executeM = task.getClass().getMethod(methodName); | |||||
| if (executeM == null) { | if (executeM == null) { | ||||
| throw new BuildException("No public " + methodName + "() in " | throw new BuildException("No public " + methodName + "() in " | ||||
| + task.getClass()); | + task.getClass()); | ||||
| } | } | ||||
| executeM.invoke(task, (Object[]) null); | |||||
| executeM.invoke(task); | |||||
| if (task instanceof UnknownElement) { | if (task instanceof UnknownElement) { | ||||
| ((UnknownElement) task).setRealThing(null); | ((UnknownElement) task).setRealThing(null); | ||||
| } | } | ||||
| @@ -23,9 +23,13 @@ import java.io.Reader; | |||||
| import java.lang.reflect.Constructor; | import java.lang.reflect.Constructor; | ||||
| import java.lang.reflect.InvocationTargetException; | import java.lang.reflect.InvocationTargetException; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Iterator; | |||||
| import java.util.Collection; | |||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Optional; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import java.util.function.Consumer; | |||||
| import java.util.stream.Collectors; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.AntClassLoader; | import org.apache.tools.ant.AntClassLoader; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -34,7 +38,6 @@ import org.apache.tools.ant.filters.BaseFilterReader; | |||||
| import org.apache.tools.ant.filters.ChainableReader; | import org.apache.tools.ant.filters.ChainableReader; | ||||
| import org.apache.tools.ant.types.AntFilterReader; | import org.apache.tools.ant.types.AntFilterReader; | ||||
| import org.apache.tools.ant.types.FilterChain; | import org.apache.tools.ant.types.FilterChain; | ||||
| import org.apache.tools.ant.types.Parameter; | |||||
| import org.apache.tools.ant.types.Parameterizable; | import org.apache.tools.ant.types.Parameterizable; | ||||
| import org.apache.tools.ant.types.Path; | import org.apache.tools.ant.types.Path; | ||||
| import org.apache.tools.ant.util.FileUtils; | import org.apache.tools.ant.util.FileUtils; | ||||
| @@ -44,6 +47,37 @@ import org.apache.tools.ant.util.FileUtils; | |||||
| * | * | ||||
| */ | */ | ||||
| public final class ChainReaderHelper { | public final class ChainReaderHelper { | ||||
| /** | |||||
| * Created type. | |||||
| */ | |||||
| public class ChainReader extends FilterReader { | |||||
| private List<AntClassLoader> cleanupLoaders; | |||||
| private ChainReader(Reader in, List<AntClassLoader> cleanupLoaders) { | |||||
| super(in); | |||||
| this.cleanupLoaders = cleanupLoaders; | |||||
| } | |||||
| public String readFully() throws IOException { | |||||
| return ChainReaderHelper.this.readFully(this); | |||||
| } | |||||
| @Override | |||||
| public void close() throws IOException { | |||||
| cleanUpClassLoaders(cleanupLoaders); | |||||
| super.close(); | |||||
| } | |||||
| @Override | |||||
| protected void finalize() throws Throwable { | |||||
| try { | |||||
| close(); | |||||
| } finally { | |||||
| super.finalize(); | |||||
| } | |||||
| } | |||||
| } | |||||
| // default buffer size | // default buffer size | ||||
| private static final int DEFAULT_BUFFER_SIZE = 8192; | private static final int DEFAULT_BUFFER_SIZE = 8192; | ||||
| @@ -61,7 +95,7 @@ public final class ChainReaderHelper { | |||||
| /** | /** | ||||
| * Chain of filters | * Chain of filters | ||||
| */ | */ | ||||
| public Vector<FilterChain> filterChains = new Vector<FilterChain>(); | |||||
| public Vector<FilterChain> filterChains = new Vector<>(); | |||||
| /** The Ant project */ | /** The Ant project */ | ||||
| private Project project = null; | private Project project = null; | ||||
| @@ -69,13 +103,41 @@ public final class ChainReaderHelper { | |||||
| // CheckStyle:VisibilityModifier ON | // CheckStyle:VisibilityModifier ON | ||||
| /** | /** | ||||
| * Sets the primary reader | |||||
| * Default constructor. | |||||
| */ | |||||
| public ChainReaderHelper() { | |||||
| } | |||||
| /** | |||||
| * Convenience constructor. | |||||
| * @param project | |||||
| * @param primaryReader | |||||
| * @param filterChains | |||||
| */ | |||||
| public ChainReaderHelper(Project project, Reader primaryReader, | |||||
| Iterable<FilterChain> filterChains) { | |||||
| withProject(project).withPrimaryReader(primaryReader) | |||||
| .withFilterChains(filterChains); | |||||
| } | |||||
| /** | |||||
| * Sets the primary {@link Reader} | |||||
| * @param rdr the reader object | * @param rdr the reader object | ||||
| */ | */ | ||||
| public void setPrimaryReader(Reader rdr) { | public void setPrimaryReader(Reader rdr) { | ||||
| primaryReader = rdr; | primaryReader = rdr; | ||||
| } | } | ||||
| /** | |||||
| * Fluent primary {@link Reader} mutator. | |||||
| * @param rdr | |||||
| * @return {@code this} | |||||
| */ | |||||
| public ChainReaderHelper withPrimaryReader(Reader rdr) { | |||||
| setPrimaryReader(rdr); | |||||
| return this; | |||||
| } | |||||
| /** | /** | ||||
| * Set the project to work with | * Set the project to work with | ||||
| * @param project the current project | * @param project the current project | ||||
| @@ -84,6 +146,16 @@ public final class ChainReaderHelper { | |||||
| this.project = project; | this.project = project; | ||||
| } | } | ||||
| /** | |||||
| * Fluent {@link Project} mutator. | |||||
| * @param project | |||||
| * @return {@code this} | |||||
| */ | |||||
| public ChainReaderHelper withProject(Project project) { | |||||
| setProject(project); | |||||
| return this; | |||||
| } | |||||
| /** | /** | ||||
| * Get the project | * Get the project | ||||
| * | * | ||||
| @@ -102,6 +174,16 @@ public final class ChainReaderHelper { | |||||
| bufferSize = size; | bufferSize = size; | ||||
| } | } | ||||
| /** | |||||
| * Fluent buffer size mutator. | |||||
| * @param size | |||||
| * @return {@code this} | |||||
| */ | |||||
| public ChainReaderHelper withBufferSize(int size) { | |||||
| setBufferSize(size); | |||||
| return this; | |||||
| } | |||||
| /** | /** | ||||
| * Sets the collection of filter reader sets | * Sets the collection of filter reader sets | ||||
| * | * | ||||
| @@ -111,43 +193,57 @@ public final class ChainReaderHelper { | |||||
| filterChains = fchain; | filterChains = fchain; | ||||
| } | } | ||||
| /** | |||||
| * Fluent {@code filterChains} mutator. | |||||
| * @param filterChains | |||||
| * @return {@code this} | |||||
| */ | |||||
| public ChainReaderHelper withFilterChains(Iterable<FilterChain> filterChains) { | |||||
| final Vector<FilterChain> fcs; | |||||
| if (filterChains instanceof Vector<?>) { | |||||
| fcs = (Vector<FilterChain>) filterChains; | |||||
| } else { | |||||
| fcs = new Vector<>(); | |||||
| filterChains.forEach(fcs::add); | |||||
| } | |||||
| setFilterChains(fcs); | |||||
| return this; | |||||
| } | |||||
| /** | |||||
| * Fluent mechanism to apply some {@link Consumer}. | |||||
| * @param consumer | |||||
| * @return {@code this} | |||||
| */ | |||||
| public ChainReaderHelper with(Consumer<ChainReaderHelper> consumer) { | |||||
| consumer.accept(this); | |||||
| return this; | |||||
| } | |||||
| /** | /** | ||||
| * Assemble the reader | * Assemble the reader | ||||
| * @return the assembled reader | * @return the assembled reader | ||||
| * @exception BuildException if an error occurs | * @exception BuildException if an error occurs | ||||
| */ | */ | ||||
| public Reader getAssembledReader() throws BuildException { | |||||
| public ChainReader getAssembledReader() throws BuildException { | |||||
| if (primaryReader == null) { | if (primaryReader == null) { | ||||
| throw new BuildException("primaryReader must not be null."); | throw new BuildException("primaryReader must not be null."); | ||||
| } | } | ||||
| Reader instream = primaryReader; | Reader instream = primaryReader; | ||||
| final int filterReadersCount = filterChains.size(); | |||||
| final Vector<Object> finalFilters = new Vector<Object>(); | |||||
| final ArrayList<AntClassLoader> classLoadersToCleanUp = | |||||
| new ArrayList<AntClassLoader>(); | |||||
| for (int i = 0; i < filterReadersCount; i++) { | |||||
| final FilterChain filterchain = | |||||
| filterChains.elementAt(i); | |||||
| final Vector<Object> filterReaders = filterchain.getFilterReaders(); | |||||
| final int readerCount = filterReaders.size(); | |||||
| for (int j = 0; j < readerCount; j++) { | |||||
| finalFilters.addElement(filterReaders.elementAt(j)); | |||||
| } | |||||
| } | |||||
| final List<AntClassLoader> classLoadersToCleanUp = new ArrayList<>(); | |||||
| final int filtersCount = finalFilters.size(); | |||||
| if (filtersCount > 0) { | |||||
| final List<Object> finalFilters = | |||||
| filterChains.stream().map(FilterChain::getFilterReaders) | |||||
| .flatMap(Collection::stream).collect(Collectors.toList()); | |||||
| if (!finalFilters.isEmpty()) { | |||||
| boolean success = false; | boolean success = false; | ||||
| try { | try { | ||||
| for (int i = 0; i < filtersCount; i++) { | |||||
| Object o = finalFilters.elementAt(i); | |||||
| for (Object o : finalFilters) { | |||||
| if (o instanceof AntFilterReader) { | if (o instanceof AntFilterReader) { | ||||
| instream = | instream = | ||||
| expandReader((AntFilterReader) finalFilters.elementAt(i), | |||||
| expandReader((AntFilterReader) o, | |||||
| instream, classLoadersToCleanUp); | instream, classLoadersToCleanUp); | ||||
| } else if (o instanceof ChainableReader) { | } else if (o instanceof ChainableReader) { | ||||
| setProjectOnObject(o); | setProjectOnObject(o); | ||||
| @@ -157,26 +253,12 @@ public final class ChainReaderHelper { | |||||
| } | } | ||||
| success = true; | success = true; | ||||
| } finally { | } finally { | ||||
| if (!success && classLoadersToCleanUp.size() > 0) { | |||||
| if (!(success || classLoadersToCleanUp.isEmpty())) { | |||||
| cleanUpClassLoaders(classLoadersToCleanUp); | cleanUpClassLoaders(classLoadersToCleanUp); | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| final Reader finalReader = instream; | |||||
| return classLoadersToCleanUp.size() == 0 ? finalReader | |||||
| : new FilterReader(finalReader) { | |||||
| public void close() throws IOException { | |||||
| FileUtils.close(in); | |||||
| cleanUpClassLoaders(classLoadersToCleanUp); | |||||
| } | |||||
| protected void finalize() throws Throwable { | |||||
| try { | |||||
| close(); | |||||
| } finally { | |||||
| super.finalize(); | |||||
| } | |||||
| } | |||||
| }; | |||||
| return new ChainReader(instream, classLoadersToCleanUp); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -199,9 +281,7 @@ public final class ChainReaderHelper { | |||||
| * Deregisters Classloaders from the project so GC can remove them later. | * Deregisters Classloaders from the project so GC can remove them later. | ||||
| */ | */ | ||||
| private static void cleanUpClassLoaders(List<AntClassLoader> loaders) { | private static void cleanUpClassLoaders(List<AntClassLoader> loaders) { | ||||
| for (Iterator<AntClassLoader> it = loaders.iterator(); it.hasNext();) { | |||||
| it.next().cleanup(); | |||||
| } | |||||
| loaders.forEach(AntClassLoader::cleanup); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -211,8 +291,7 @@ public final class ChainReaderHelper { | |||||
| * @return the contents of the file as a string | * @return the contents of the file as a string | ||||
| * @exception IOException if an error occurs | * @exception IOException if an error occurs | ||||
| */ | */ | ||||
| public String readFully(Reader rdr) | |||||
| throws IOException { | |||||
| public String readFully(Reader rdr) throws IOException { | |||||
| return FileUtils.readFully(rdr, bufferSize); | return FileUtils.readFully(rdr, bufferSize); | ||||
| } | } | ||||
| @@ -227,57 +306,45 @@ public final class ChainReaderHelper { | |||||
| final List<AntClassLoader> classLoadersToCleanUp) { | final List<AntClassLoader> classLoadersToCleanUp) { | ||||
| final String className = filter.getClassName(); | final String className = filter.getClassName(); | ||||
| final Path classpath = filter.getClasspath(); | final Path classpath = filter.getClasspath(); | ||||
| final Project pro = filter.getProject(); | |||||
| if (className != null) { | if (className != null) { | ||||
| try { | try { | ||||
| Class<?> clazz = null; | |||||
| if (classpath == null) { | |||||
| clazz = Class.forName(className); | |||||
| } else { | |||||
| AntClassLoader al = pro.createClassLoader(classpath); | |||||
| classLoadersToCleanUp.add(al); | |||||
| clazz = Class.forName(className, true, al); | |||||
| } | |||||
| if (clazz != null) { | |||||
| if (!FilterReader.class.isAssignableFrom(clazz)) { | |||||
| throw new BuildException(className + " does not extend" | |||||
| + " java.io.FilterReader"); | |||||
| } | |||||
| final Constructor<?>[] constructors = clazz.getConstructors(); | |||||
| int j = 0; | |||||
| boolean consPresent = false; | |||||
| for (; j < constructors.length; j++) { | |||||
| Class<?>[] types = constructors[j].getParameterTypes(); | |||||
| if (types.length == 1 | |||||
| && types[0].isAssignableFrom(Reader.class)) { | |||||
| consPresent = true; | |||||
| break; | |||||
| } | |||||
| } | |||||
| if (!consPresent) { | |||||
| throw new BuildException(className + " does not define" | |||||
| + " a public constructor" | |||||
| + " that takes in a Reader" | |||||
| + " as its single argument."); | |||||
| } | |||||
| final Reader[] rdr = {ancestor}; | |||||
| Reader instream = | |||||
| (Reader) constructors[j].newInstance((Object[]) rdr); | |||||
| setProjectOnObject(instream); | |||||
| if (Parameterizable.class.isAssignableFrom(clazz)) { | |||||
| final Parameter[] params = filter.getParams(); | |||||
| ((Parameterizable) instream).setParameters(params); | |||||
| Class<? extends FilterReader> clazz; | |||||
| try { | |||||
| if (classpath == null) { | |||||
| clazz = Class.forName(className) | |||||
| .asSubclass(FilterReader.class); | |||||
| } else { | |||||
| AntClassLoader al = | |||||
| filter.getProject().createClassLoader(classpath); | |||||
| classLoadersToCleanUp.add(al); | |||||
| clazz = Class.forName(className, true, al) | |||||
| .asSubclass(FilterReader.class); | |||||
| } | } | ||||
| return instream; | |||||
| } catch (ClassCastException ex) { | |||||
| throw new BuildException("%s does not extend %s", className, | |||||
| FilterReader.class.getName()); | |||||
| } | |||||
| Optional<Constructor<?>> ctor = | |||||
| Stream.of(clazz.getConstructors()) | |||||
| .filter(c -> c.getParameterCount() == 1 | |||||
| && c.getParameterTypes()[0] | |||||
| .isAssignableFrom(Reader.class)) | |||||
| .findFirst(); | |||||
| Object instream = ctor | |||||
| .orElseThrow(() -> new BuildException( | |||||
| "%s does not define a public constructor that takes in a %s as its single argument.", | |||||
| className, Reader.class.getSimpleName())) | |||||
| .newInstance(ancestor); | |||||
| setProjectOnObject(instream); | |||||
| if (Parameterizable.class.isAssignableFrom(clazz)) { | |||||
| ((Parameterizable) instream).setParameters(filter.getParams()); | |||||
| } | } | ||||
| } catch (final ClassNotFoundException cnfe) { | |||||
| throw new BuildException(cnfe); | |||||
| } catch (final InstantiationException ie) { | |||||
| throw new BuildException(ie); | |||||
| } catch (final IllegalAccessException iae) { | |||||
| throw new BuildException(iae); | |||||
| } catch (final InvocationTargetException ite) { | |||||
| throw new BuildException(ite); | |||||
| return (Reader) instream; | |||||
| } catch (ClassNotFoundException | InstantiationException | |||||
| | IllegalAccessException | InvocationTargetException ex) { | |||||
| throw new BuildException(ex); | |||||
| } | } | ||||
| } | } | ||||
| // Ant 1.7.1 and earlier ignore <filterreader> without a | // Ant 1.7.1 and earlier ignore <filterreader> without a | ||||
| @@ -88,6 +88,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean canParseAntlibDescriptor(Resource resource) { | public boolean canParseAntlibDescriptor(Resource resource) { | ||||
| return true; | return true; | ||||
| } | } | ||||
| @@ -102,6 +103,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| @Override | |||||
| public UnknownElement parseAntlibDescriptor(Project containingProject, | public UnknownElement parseAntlibDescriptor(Project containingProject, | ||||
| Resource resource) { | Resource resource) { | ||||
| URLProvider up = resource.as(URLProvider.class); | URLProvider up = resource.as(URLProvider.class); | ||||
| @@ -143,6 +145,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param source the xml source | * @param source the xml source | ||||
| * @exception BuildException if an error occurs | * @exception BuildException if an error occurs | ||||
| */ | */ | ||||
| @Override | |||||
| public void parse(Project project, Object source) throws BuildException { | public void parse(Project project, Object source) throws BuildException { | ||||
| getImportStack().addElement(source); | getImportStack().addElement(source); | ||||
| AntXMLContext context = null; | AntXMLContext context = null; | ||||
| @@ -256,7 +259,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| zf = new ZipFile(org.apache.tools.ant.launch.Locator | zf = new ZipFile(org.apache.tools.ant.launch.Locator | ||||
| .fromJarURI(uri), "UTF-8"); | .fromJarURI(uri), "UTF-8"); | ||||
| inputStream = | inputStream = | ||||
| zf.getInputStream(zf.getEntry(uri.substring(pling + 1))); | |||||
| zf.getInputStream(zf.getEntry(uri.substring(pling + 2))); | |||||
| } else { | } else { | ||||
| URLConnection conn = url.openConnection(); | URLConnection conn = url.openConnection(); | ||||
| conn.setUseCaches(false); | conn.setUseCaches(false); | ||||
| @@ -521,6 +524,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * document. Will not be <code>null</code>. | * document. Will not be <code>null</code>. | ||||
| * @return an inputsource for this identifier | * @return an inputsource for this identifier | ||||
| */ | */ | ||||
| @Override | |||||
| public InputSource resolveEntity(String publicId, String systemId) { | public InputSource resolveEntity(String publicId, String systemId) { | ||||
| context.getProject().log("resolving systemId: " + systemId, Project.MSG_VERBOSE); | context.getProject().log("resolving systemId: " + systemId, Project.MSG_VERBOSE); | ||||
| @@ -566,6 +570,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @exception org.xml.sax.SAXParseException if the tag given is not | * @exception org.xml.sax.SAXParseException if the tag given is not | ||||
| * <code>"project"</code> | * <code>"project"</code> | ||||
| */ | */ | ||||
| @Override | |||||
| public void startElement(String uri, String tag, String qname, Attributes attrs) | public void startElement(String uri, String tag, String qname, Attributes attrs) | ||||
| throws SAXParseException { | throws SAXParseException { | ||||
| AntHandler next = currentHandler.onStartChild(uri, tag, qname, attrs, context); | AntHandler next = currentHandler.onStartChild(uri, tag, qname, attrs, context); | ||||
| @@ -580,6 +585,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param locator The locator used by the parser. | * @param locator The locator used by the parser. | ||||
| * Will not be <code>null</code>. | * Will not be <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setDocumentLocator(Locator locator) { | public void setDocumentLocator(Locator locator) { | ||||
| context.setLocator(locator); | context.setLocator(locator); | ||||
| } | } | ||||
| @@ -595,9 +601,10 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * | * | ||||
| * @exception SAXException in case of error (not thrown in this implementation) | * @exception SAXException in case of error (not thrown in this implementation) | ||||
| */ | */ | ||||
| @Override | |||||
| public void endElement(String uri, String name, String qName) throws SAXException { | public void endElement(String uri, String name, String qName) throws SAXException { | ||||
| currentHandler.onEndElement(uri, name, context); | currentHandler.onEndElement(uri, name, context); | ||||
| AntHandler prev = (AntHandler) antHandlers.pop(); | |||||
| AntHandler prev = antHandlers.pop(); | |||||
| currentHandler = prev; | currentHandler = prev; | ||||
| if (currentHandler != null) { | if (currentHandler != null) { | ||||
| currentHandler.onEndChild(uri, name, qName, context); | currentHandler.onEndChild(uri, name, qName, context); | ||||
| @@ -612,6 +619,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param count The number of characters to read. | * @param count The number of characters to read. | ||||
| * @exception SAXParseException if an error occurs | * @exception SAXParseException if an error occurs | ||||
| */ | */ | ||||
| @Override | |||||
| public void characters(char[] buf, int start, int count) throws SAXParseException { | public void characters(char[] buf, int start, int count) throws SAXParseException { | ||||
| currentHandler.characters(buf, start, count, context); | currentHandler.characters(buf, start, count, context); | ||||
| } | } | ||||
| @@ -622,6 +630,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param prefix the namespace prefix | * @param prefix the namespace prefix | ||||
| * @param uri the namespace uri | * @param uri the namespace uri | ||||
| */ | */ | ||||
| @Override | |||||
| public void startPrefixMapping(String prefix, String uri) { | public void startPrefixMapping(String prefix, String uri) { | ||||
| context.startPrefixMapping(prefix, uri); | context.startPrefixMapping(prefix, uri); | ||||
| } | } | ||||
| @@ -631,6 +640,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * | * | ||||
| * @param prefix the prefix that is not mapped anymore | * @param prefix the prefix that is not mapped anymore | ||||
| */ | */ | ||||
| @Override | |||||
| public void endPrefixMapping(String prefix) { | public void endPrefixMapping(String prefix) { | ||||
| context.endPrefixMapping(prefix); | context.endPrefixMapping(prefix); | ||||
| } | } | ||||
| @@ -654,6 +664,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @return The project handler that handles subelements of project | * @return The project handler that handles subelements of project | ||||
| * @exception SAXParseException if the qualified name is not "project". | * @exception SAXParseException if the qualified name is not "project". | ||||
| */ | */ | ||||
| @Override | |||||
| public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| if (name.equals("project") | if (name.equals("project") | ||||
| @@ -693,6 +704,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * encountered or if the <code>"default"</code> attribute | * encountered or if the <code>"default"</code> attribute | ||||
| * is missing. | * is missing. | ||||
| */ | */ | ||||
| @Override | |||||
| public void onStartElement(String uri, String tag, String qname, Attributes attrs, | public void onStartElement(String uri, String tag, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| String baseDir = null; | String baseDir = null; | ||||
| @@ -849,6 +861,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * <code>"extension-point"</code> | * <code>"extension-point"</code> | ||||
| * or a data type definition | * or a data type definition | ||||
| */ | */ | ||||
| @Override | |||||
| public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| return (name.equals("target") || name.equals("extension-point")) | return (name.equals("target") || name.equals("extension-point")) | ||||
| @@ -882,6 +895,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @exception SAXParseException if an unexpected attribute is encountered | * @exception SAXParseException if an unexpected attribute is encountered | ||||
| * or if the <code>"name"</code> attribute is missing. | * or if the <code>"name"</code> attribute is missing. | ||||
| */ | */ | ||||
| @Override | |||||
| public void onStartElement(String uri, String tag, String qname, Attributes attrs, | public void onStartElement(String uri, String tag, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| String name = null; | String name = null; | ||||
| @@ -1062,6 +1076,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @exception SAXParseException if an error occurs when initialising | * @exception SAXParseException if an error occurs when initialising | ||||
| * the appropriate child handler | * the appropriate child handler | ||||
| */ | */ | ||||
| @Override | |||||
| public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | public AntHandler onStartChild(String uri, String name, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| return ProjectHelper2.elementHandler; | return ProjectHelper2.elementHandler; | ||||
| @@ -1075,6 +1090,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param tag The name of the element. | * @param tag The name of the element. | ||||
| * @param context The current context. | * @param context The current context. | ||||
| */ | */ | ||||
| @Override | |||||
| public void onEndElement(String uri, String tag, AntXMLContext context) { | public void onEndElement(String uri, String tag, AntXMLContext context) { | ||||
| context.setCurrentTarget(context.getImplicitTarget()); | context.setCurrentTarget(context.getImplicitTarget()); | ||||
| } | } | ||||
| @@ -1109,6 +1125,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @exception SAXParseException in case of error (not thrown in | * @exception SAXParseException in case of error (not thrown in | ||||
| * this implementation) | * this implementation) | ||||
| */ | */ | ||||
| @Override | |||||
| public void onStartElement(String uri, String tag, String qname, Attributes attrs, | public void onStartElement(String uri, String tag, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| RuntimeConfigurable parentWrapper = context.currentWrapper(); | RuntimeConfigurable parentWrapper = context.currentWrapper(); | ||||
| @@ -1195,6 +1212,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * | * | ||||
| * @see ProjectHelper#addText(Project,java.lang.Object,char[],int,int) | * @see ProjectHelper#addText(Project,java.lang.Object,char[],int,int) | ||||
| */ | */ | ||||
| @Override | |||||
| public void characters(char[] buf, int start, int count, | public void characters(char[] buf, int start, int count, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| RuntimeConfigurable wrapper = context.currentWrapper(); | RuntimeConfigurable wrapper = context.currentWrapper(); | ||||
| @@ -1218,6 +1236,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @exception SAXParseException if an error occurs when initialising | * @exception SAXParseException if an error occurs when initialising | ||||
| * the appropriate child handler | * the appropriate child handler | ||||
| */ | */ | ||||
| @Override | |||||
| public AntHandler onStartChild(String uri, String tag, String qname, Attributes attrs, | public AntHandler onStartChild(String uri, String tag, String qname, Attributes attrs, | ||||
| AntXMLContext context) throws SAXParseException { | AntXMLContext context) throws SAXParseException { | ||||
| return ProjectHelper2.elementHandler; | return ProjectHelper2.elementHandler; | ||||
| @@ -1231,6 +1250,7 @@ public class ProjectHelper2 extends ProjectHelper { | |||||
| * @param tag The name of the element. | * @param tag The name of the element. | ||||
| * @param context The current context. | * @param context The current context. | ||||
| */ | */ | ||||
| @Override | |||||
| public void onEndElement(String uri, String tag, AntXMLContext context) { | public void onEndElement(String uri, String tag, AntXMLContext context) { | ||||
| context.popWrapper(); | context.popWrapper(); | ||||
| } | } | ||||
| @@ -18,6 +18,7 @@ | |||||
| package org.apache.tools.ant.input; | package org.apache.tools.ant.input; | ||||
| import java.util.Collection; | |||||
| import java.util.LinkedHashSet; | import java.util.LinkedHashSet; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| @@ -33,26 +34,39 @@ public class MultipleChoiceInputRequest extends InputRequest { | |||||
| * @param prompt The prompt to show to the user. Must not be null. | * @param prompt The prompt to show to the user. Must not be null. | ||||
| * @param choices holds all input values that are allowed. | * @param choices holds all input values that are allowed. | ||||
| * Must not be null. | * Must not be null. | ||||
| * @deprecated Use {@link #MultipleChoiceInputRequest(String,Collection)} instead | |||||
| */ | */ | ||||
| @Deprecated | |||||
| public MultipleChoiceInputRequest(String prompt, Vector<String> choices) { | public MultipleChoiceInputRequest(String prompt, Vector<String> choices) { | ||||
| this(prompt, (Collection<String>) choices); | |||||
| } | |||||
| /** | |||||
| * @param prompt The prompt to show to the user. Must not be null. | |||||
| * @param choices holds all input values that are allowed. | |||||
| * Must not be null. | |||||
| */ | |||||
| public MultipleChoiceInputRequest(String prompt, Collection<String> choices) { | |||||
| super(prompt); | super(prompt); | ||||
| if (choices == null) { | if (choices == null) { | ||||
| throw new IllegalArgumentException("choices must not be null"); | throw new IllegalArgumentException("choices must not be null"); | ||||
| } | } | ||||
| this.choices = new LinkedHashSet<String>(choices); | |||||
| this.choices = new LinkedHashSet<>(choices); | |||||
| } | } | ||||
| /** | /** | ||||
| * @return The possible values. | * @return The possible values. | ||||
| */ | */ | ||||
| public Vector<String> getChoices() { | public Vector<String> getChoices() { | ||||
| return new Vector<String>(choices); | |||||
| return new Vector<>(choices); | |||||
| } | } | ||||
| /** | /** | ||||
| * @return true if the input is one of the allowed values. | * @return true if the input is one of the allowed values. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean isInputValid() { | public boolean isInputValid() { | ||||
| return choices.contains(getInput()) || ("".equals(getInput()) && getDefaultValue() != null); | |||||
| return choices.contains(getInput()) | |||||
| || ("".equals(getInput()) && getDefaultValue() != null); | |||||
| } | } | ||||
| } | } | ||||
| @@ -25,9 +25,6 @@ import java.util.ArrayList; | |||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.StringTokenizer; | import java.util.StringTokenizer; | ||||
| /** | /** | ||||
| * This is a launcher for Ant. | * This is a launcher for Ant. | ||||
| * | * | ||||
| @@ -35,9 +32,6 @@ import java.util.StringTokenizer; | |||||
| */ | */ | ||||
| public class Launcher { | public class Launcher { | ||||
| private Launcher() { | |||||
| } | |||||
| /** | /** | ||||
| * The Ant Home (installation) Directory property. | * The Ant Home (installation) Directory property. | ||||
| * {@value} | * {@value} | ||||
| @@ -62,11 +56,6 @@ public class Launcher { | |||||
| */ | */ | ||||
| public static final String ANT_PRIVATELIB = "lib"; | public static final String ANT_PRIVATELIB = "lib"; | ||||
| /** | |||||
| * launch diagnostics flag; for debugging trouble at launch time. | |||||
| */ | |||||
| public boolean launchDiag = false; | |||||
| /** | /** | ||||
| * The location of a per-user library directory. | * The location of a per-user library directory. | ||||
| * <p> | * <p> | ||||
| @@ -127,6 +116,13 @@ public class Launcher { | |||||
| } | } | ||||
| } | } | ||||
| /** | |||||
| * launch diagnostics flag; for debugging trouble at launch time. | |||||
| */ | |||||
| public boolean launchDiag = false; | |||||
| private Launcher() { | |||||
| } | |||||
| /** | /** | ||||
| * Add a CLASSPATH or -lib to lib path urls. | * Add a CLASSPATH or -lib to lib path urls. | ||||
| @@ -156,7 +152,7 @@ public class Launcher { | |||||
| } | } | ||||
| } | } | ||||
| final URL url = Locator.fileToURL(element); | |||||
| final URL url = new URL(element.toURI().toASCIIString()); | |||||
| if (launchDiag) { | if (launchDiag) { | ||||
| System.out.println("adding library URL: " + url); | System.out.println("adding library URL: " + url); | ||||
| } | } | ||||
| @@ -193,44 +189,45 @@ public class Launcher { | |||||
| } | } | ||||
| if (!antHome.exists()) { | if (!antHome.exists()) { | ||||
| throw new LaunchException("Ant home is set incorrectly or " | |||||
| + "ant could not be located (estimated value="+antHome.getAbsolutePath()+")"); | |||||
| throw new LaunchException( | |||||
| "Ant home is set incorrectly or ant could not be located (estimated value=" | |||||
| + antHome.getAbsolutePath() + ")"); | |||||
| } | } | ||||
| final List<String> libPaths = new ArrayList<String>(); | |||||
| final List<String> libPaths = new ArrayList<>(); | |||||
| String cpString = null; | String cpString = null; | ||||
| final List<String> argList = new ArrayList<String>(); | |||||
| final List<String> argList = new ArrayList<>(); | |||||
| String[] newArgs; | String[] newArgs; | ||||
| boolean noUserLib = false; | boolean noUserLib = false; | ||||
| boolean noClassPath = false; | boolean noClassPath = false; | ||||
| for (int i = 0; i < args.length; ++i) { | for (int i = 0; i < args.length; ++i) { | ||||
| if (args[i].equals("-lib")) { | |||||
| if ("-lib".equals(args[i])) { | |||||
| if (i == args.length - 1) { | if (i == args.length - 1) { | ||||
| throw new LaunchException("The -lib argument must " | |||||
| + "be followed by a library location"); | |||||
| throw new LaunchException( | |||||
| "The -lib argument must be followed by a library location"); | |||||
| } | } | ||||
| libPaths.add(args[++i]); | libPaths.add(args[++i]); | ||||
| } else if (args[i].equals("-cp")) { | |||||
| } else if ("-cp".equals(args[i])) { | |||||
| if (i == args.length - 1) { | if (i == args.length - 1) { | ||||
| throw new LaunchException("The -cp argument must " | |||||
| + "be followed by a classpath expression"); | |||||
| throw new LaunchException( | |||||
| "The -cp argument must be followed by a classpath expression"); | |||||
| } | } | ||||
| if (cpString != null) { | if (cpString != null) { | ||||
| throw new LaunchException("The -cp argument must " | |||||
| + "not be repeated"); | |||||
| throw new LaunchException( | |||||
| "The -cp argument must not be repeated"); | |||||
| } | } | ||||
| cpString = args[++i]; | cpString = args[++i]; | ||||
| } else if (args[i].equals("--nouserlib") || args[i].equals("-nouserlib")) { | |||||
| } else if ("--nouserlib".equals(args[i]) || "-nouserlib".equals(args[i])) { | |||||
| noUserLib = true; | noUserLib = true; | ||||
| } else if (args[i].equals("--launchdiag")) { | |||||
| } else if ("--launchdiag".equals(args[i])) { | |||||
| launchDiag = true; | launchDiag = true; | ||||
| } else if (args[i].equals("--noclasspath") || args[i].equals("-noclasspath")) { | |||||
| } else if ("--noclasspath".equals(args[i]) || "-noclasspath".equals(args[i])) { | |||||
| noClassPath = true; | noClassPath = true; | ||||
| } else if (args[i].equals("-main")) { | |||||
| } else if ("-main".equals(args[i])) { | |||||
| if (i == args.length - 1) { | if (i == args.length - 1) { | ||||
| throw new LaunchException("The -main argument must " | |||||
| + "be followed by a library location"); | |||||
| throw new LaunchException( | |||||
| "The -main argument must be followed by a library location"); | |||||
| } | } | ||||
| mainClassname = args[++i]; | mainClassname = args[++i]; | ||||
| } else { | } else { | ||||
| @@ -262,8 +259,8 @@ public class Launcher { | |||||
| libURLs, userURLs, systemURLs, toolsJAR); | libURLs, userURLs, systemURLs, toolsJAR); | ||||
| // now update the class.path property | // now update the class.path property | ||||
| final StringBuffer baseClassPath | |||||
| = new StringBuffer(System.getProperty(JAVA_CLASS_PATH)); | |||||
| final StringBuilder baseClassPath | |||||
| = new StringBuilder(System.getProperty(JAVA_CLASS_PATH)); | |||||
| if (baseClassPath.charAt(baseClassPath.length() - 1) | if (baseClassPath.charAt(baseClassPath.length() - 1) | ||||
| == File.pathSeparatorChar) { | == File.pathSeparatorChar) { | ||||
| baseClassPath.setLength(baseClassPath.length() - 1); | baseClassPath.setLength(baseClassPath.length() - 1); | ||||
| @@ -278,12 +275,12 @@ public class Launcher { | |||||
| final URLClassLoader loader = new URLClassLoader(jars, Launcher.class.getClassLoader()); | final URLClassLoader loader = new URLClassLoader(jars, Launcher.class.getClassLoader()); | ||||
| Thread.currentThread().setContextClassLoader(loader); | Thread.currentThread().setContextClassLoader(loader); | ||||
| Class<?> mainClass = null; | |||||
| Class<? extends AntMain> mainClass = null; | |||||
| int exitCode = 0; | int exitCode = 0; | ||||
| Throwable thrown=null; | Throwable thrown=null; | ||||
| try { | try { | ||||
| mainClass = loader.loadClass(mainClassname); | |||||
| final AntMain main = (AntMain) mainClass.newInstance(); | |||||
| mainClass = loader.loadClass(mainClassname).asSubclass(AntMain.class); | |||||
| final AntMain main = mainClass.newInstance(); | |||||
| main.startAnt(newArgs, null, null); | main.startAnt(newArgs, null, null); | ||||
| } catch (final InstantiationException ex) { | } catch (final InstantiationException ex) { | ||||
| System.err.println( | System.err.println( | ||||
| @@ -320,7 +317,7 @@ public class Launcher { | |||||
| */ | */ | ||||
| private URL[] getLibPathURLs(final String cpString, final List<String> libPaths) | private URL[] getLibPathURLs(final String cpString, final List<String> libPaths) | ||||
| throws MalformedURLException { | throws MalformedURLException { | ||||
| final List<URL> libPathURLs = new ArrayList<URL>(); | |||||
| final List<URL> libPathURLs = new ArrayList<>(); | |||||
| if (cpString != null) { | if (cpString != null) { | ||||
| addPath(cpString, false, libPathURLs); | addPath(cpString, false, libPathURLs); | ||||
| @@ -389,7 +386,7 @@ public class Launcher { | |||||
| systemJars.length); | systemJars.length); | ||||
| if (toolsJar != null) { | if (toolsJar != null) { | ||||
| jars[jars.length - 1] = Locator.fileToURL(toolsJar); | |||||
| jars[jars.length - 1] = new URL(toolsJar.toURI().toASCIIString()); | |||||
| } | } | ||||
| return jars; | return jars; | ||||
| } | } | ||||
| @@ -407,8 +404,8 @@ public class Launcher { | |||||
| } | } | ||||
| private void logPath(final String name,final File path) { | private void logPath(final String name,final File path) { | ||||
| if(launchDiag) { | |||||
| System.out.println(name+"= \""+path+"\""); | |||||
| if (launchDiag) { | |||||
| System.out.println(name + "= \"" + path + "\""); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -19,7 +19,6 @@ package org.apache.tools.ant.launch; | |||||
| import java.io.ByteArrayOutputStream; | import java.io.ByteArrayOutputStream; | ||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.FilenameFilter; | |||||
| import java.io.UnsupportedEncodingException; | import java.io.UnsupportedEncodingException; | ||||
| import java.net.MalformedURLException; | import java.net.MalformedURLException; | ||||
| import java.net.URL; | import java.net.URL; | ||||
| @@ -27,6 +26,7 @@ import java.nio.charset.StandardCharsets; | |||||
| import java.text.CharacterIterator; | import java.text.CharacterIterator; | ||||
| import java.text.StringCharacterIterator; | import java.text.StringCharacterIterator; | ||||
| import java.util.Locale; | import java.util.Locale; | ||||
| import java.util.stream.Stream; | |||||
| // CheckStyle:LineLengthCheck OFF - urls are long! | // CheckStyle:LineLengthCheck OFF - urls are long! | ||||
| /** | /** | ||||
| @@ -95,11 +95,6 @@ public final class Locator { | |||||
| gAfterEscaping2[ch] = gHexChs[ch & NIBBLE_MASK]; | gAfterEscaping2[ch] = gHexChs[ch & NIBBLE_MASK]; | ||||
| } | } | ||||
| } | } | ||||
| /** | |||||
| * Not instantiable | |||||
| */ | |||||
| private Locator() { | |||||
| } | |||||
| /** | /** | ||||
| * Find the directory or jar file the class has been loaded from. | * Find the directory or jar file the class has been loaded from. | ||||
| @@ -130,7 +125,7 @@ public final class Locator { | |||||
| if (c == null) { | if (c == null) { | ||||
| c = Locator.class.getClassLoader(); | c = Locator.class.getClassLoader(); | ||||
| } | } | ||||
| URL url = null; | |||||
| URL url; | |||||
| if (c == null) { | if (c == null) { | ||||
| url = ClassLoader.getSystemResource(resource); | url = ClassLoader.getSystemResource(resource); | ||||
| } else { | } else { | ||||
| @@ -141,21 +136,19 @@ public final class Locator { | |||||
| try { | try { | ||||
| if (u.startsWith("jar:file:")) { | if (u.startsWith("jar:file:")) { | ||||
| return new File(fromJarURI(u)); | return new File(fromJarURI(u)); | ||||
| } else if (u.startsWith("file:")) { | |||||
| } | |||||
| if (u.startsWith("file:")) { | |||||
| int tail = u.indexOf(resource); | int tail = u.indexOf(resource); | ||||
| String dirName = u.substring(0, tail); | String dirName = u.substring(0, tail); | ||||
| return new File(fromURI(dirName)); | return new File(fromURI(dirName)); | ||||
| } | } | ||||
| } catch (IllegalArgumentException e) { | } catch (IllegalArgumentException e) { | ||||
| //unable to determine the URI for reasons unknown. | //unable to determine the URI for reasons unknown. | ||||
| return null; | |||||
| } | } | ||||
| } | } | ||||
| return null; | return null; | ||||
| } | } | ||||
| /** | /** | ||||
| * Constructs a file path from a <code>file:</code> URI. | * Constructs a file path from a <code>file:</code> URI. | ||||
| * | * | ||||
| @@ -234,7 +227,7 @@ public final class Locator { | |||||
| if (url == null || !("file".equals(url.getProtocol()))) { | if (url == null || !("file".equals(url.getProtocol()))) { | ||||
| throw new IllegalArgumentException(ERROR_NOT_FILE_URI + uri); | throw new IllegalArgumentException(ERROR_NOT_FILE_URI + uri); | ||||
| } | } | ||||
| StringBuffer buf = new StringBuffer(url.getHost()); | |||||
| StringBuilder buf = new StringBuilder(url.getHost()); | |||||
| if (buf.length() > 0) { | if (buf.length() > 0) { | ||||
| buf.insert(0, File.separatorChar).insert(0, File.separatorChar); | buf.insert(0, File.separatorChar).insert(0, File.separatorChar); | ||||
| } | } | ||||
| @@ -330,7 +323,7 @@ public final class Locator { | |||||
| int i = 0; | int i = 0; | ||||
| int len = path.length(); | int len = path.length(); | ||||
| int ch = 0; | int ch = 0; | ||||
| StringBuffer sb = null; | |||||
| StringBuilder sb = null; | |||||
| for (; i < len; i++) { | for (; i < len; i++) { | ||||
| ch = path.charAt(i); | ch = path.charAt(i); | ||||
| // if it's not an ASCII character, break here, and use UTF-8 encoding | // if it's not an ASCII character, break here, and use UTF-8 encoding | ||||
| @@ -339,7 +332,7 @@ public final class Locator { | |||||
| } | } | ||||
| if (gNeedEscaping[ch]) { | if (gNeedEscaping[ch]) { | ||||
| if (sb == null) { | if (sb == null) { | ||||
| sb = new StringBuffer(path.substring(0, i)); | |||||
| sb = new StringBuilder(path.substring(0, i)); | |||||
| } | } | ||||
| sb.append('%'); | sb.append('%'); | ||||
| sb.append(gAfterEscaping1[ch]); | sb.append(gAfterEscaping1[ch]); | ||||
| @@ -353,17 +346,15 @@ public final class Locator { | |||||
| // we saw some non-ascii character | // we saw some non-ascii character | ||||
| if (i < len) { | if (i < len) { | ||||
| if (sb == null) { | if (sb == null) { | ||||
| sb = new StringBuffer(path.substring(0, i)); | |||||
| sb = new StringBuilder(path.substring(0, i)); | |||||
| } | } | ||||
| // get UTF-8 bytes for the remaining sub-string | // get UTF-8 bytes for the remaining sub-string | ||||
| byte[] bytes = null; | |||||
| byte b; | |||||
| bytes = path.substring(i).getBytes(StandardCharsets.UTF_8); | |||||
| byte[] bytes = path.substring(i).getBytes(StandardCharsets.UTF_8); | |||||
| len = bytes.length; | len = bytes.length; | ||||
| // for each byte | // for each byte | ||||
| for (i = 0; i < len; i++) { | for (i = 0; i < len; i++) { | ||||
| b = bytes[i]; | |||||
| byte b = bytes[i]; | |||||
| // for non-ascii character: make it positive, then escape | // for non-ascii character: make it positive, then escape | ||||
| if (b < 0) { | if (b < 0) { | ||||
| ch = b + BYTE_SIZE; | ch = b + BYTE_SIZE; | ||||
| @@ -466,7 +457,7 @@ public final class Locator { | |||||
| */ | */ | ||||
| public static URL[] getLocationURLs(File location) | public static URL[] getLocationURLs(File location) | ||||
| throws MalformedURLException { | throws MalformedURLException { | ||||
| return getLocationURLs(location, new String[]{".jar"}); | |||||
| return getLocationURLs(location, ".jar"); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -484,7 +475,7 @@ public final class Locator { | |||||
| * formed. | * formed. | ||||
| */ | */ | ||||
| public static URL[] getLocationURLs(File location, | public static URL[] getLocationURLs(File location, | ||||
| final String[] extensions) | |||||
| final String... extensions) | |||||
| throws MalformedURLException { | throws MalformedURLException { | ||||
| URL[] urls = new URL[0]; | URL[] urls = new URL[0]; | ||||
| @@ -503,22 +494,21 @@ public final class Locator { | |||||
| } | } | ||||
| return urls; | return urls; | ||||
| } | } | ||||
| File[] matches = location.listFiles( | |||||
| new FilenameFilter() { | |||||
| public boolean accept(File dir, String name) { | |||||
| String littleName = name.toLowerCase(Locale.ENGLISH); | |||||
| for (int i = 0; i < extensions.length; ++i) { | |||||
| if (littleName.endsWith(extensions[i])) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| return false; | |||||
| } | |||||
| }); | |||||
| File[] matches = location.listFiles((dir, name) -> { | |||||
| String littleName = name.toLowerCase(Locale.ENGLISH); | |||||
| return Stream.of(extensions).anyMatch(x -> littleName.endsWith(x)); | |||||
| }); | |||||
| urls = new URL[matches.length]; | urls = new URL[matches.length]; | ||||
| for (int i = 0; i < matches.length; ++i) { | for (int i = 0; i < matches.length; ++i) { | ||||
| urls[i] = fileToURL(matches[i]); | urls[i] = fileToURL(matches[i]); | ||||
| } | } | ||||
| return urls; | return urls; | ||||
| } | } | ||||
| /** | |||||
| * Not instantiable | |||||
| */ | |||||
| private Locator() { | |||||
| } | |||||
| } | } | ||||
| @@ -213,7 +213,7 @@ public class AnsiColorLogger extends DefaultLogger { | |||||
| colorsSet = true; | colorsSet = true; | ||||
| } | } | ||||
| final StringBuffer msg = new StringBuffer(message); | |||||
| final StringBuilder msg = new StringBuilder(message); | |||||
| switch (priority) { | switch (priority) { | ||||
| case Project.MSG_ERR: | case Project.MSG_ERR: | ||||
| msg.insert(0, errColor); | msg.insert(0, errColor); | ||||
| @@ -102,6 +102,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| } | } | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void buildStarted(final BuildEvent event) { | public void buildStarted(final BuildEvent event) { | ||||
| final String categoryString = PROJECT_LOG; | final String categoryString = PROJECT_LOG; | ||||
| final Log log = getLog(categoryString, null); | final Log log = getLog(categoryString, null); | ||||
| @@ -112,6 +113,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| } | } | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void buildFinished(final BuildEvent event) { | public void buildFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final String categoryString = PROJECT_LOG; | final String categoryString = PROJECT_LOG; | ||||
| @@ -130,6 +132,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * @see BuildListener#targetStarted | * @see BuildListener#targetStarted | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void targetStarted(final BuildEvent event) { | public void targetStarted(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Log log = getLog(TARGET_LOG, | final Log log = getLog(TARGET_LOG, | ||||
| @@ -145,6 +148,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * @see BuildListener#targetFinished | * @see BuildListener#targetFinished | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void targetFinished(final BuildEvent event) { | public void targetFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final String targetName = event.getTarget().getName(); | final String targetName = event.getTarget().getName(); | ||||
| @@ -164,6 +168,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * @see BuildListener#taskStarted | * @see BuildListener#taskStarted | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void taskStarted(final BuildEvent event) { | public void taskStarted(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Task task = event.getTask(); | final Task task = event.getTask(); | ||||
| @@ -186,6 +191,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * @see BuildListener#taskFinished | * @see BuildListener#taskFinished | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void taskFinished(final BuildEvent event) { | public void taskFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Task task = event.getTask(); | final Task task = event.getTask(); | ||||
| @@ -215,16 +221,16 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * @see BuildListener#messageLogged | * @see BuildListener#messageLogged | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void messageLogged(final BuildEvent event) { | public void messageLogged(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| Object categoryObject = event.getTask(); | Object categoryObject = event.getTask(); | ||||
| String categoryString = null; | |||||
| String categoryString; | |||||
| String categoryDetail = null; | String categoryDetail = null; | ||||
| if (categoryObject == null) { | if (categoryObject == null) { | ||||
| categoryObject = event.getTarget(); | categoryObject = event.getTarget(); | ||||
| if (categoryObject == null) { | if (categoryObject == null) { | ||||
| categoryObject = event.getProject(); | |||||
| categoryString = PROJECT_LOG; | categoryString = PROJECT_LOG; | ||||
| categoryDetail = event.getProject().getName(); | categoryDetail = event.getProject().getName(); | ||||
| } else { | } else { | ||||
| @@ -300,6 +306,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * This is not used, the logger config is used instead. | * This is not used, the logger config is used instead. | ||||
| * @param level ignored | * @param level ignored | ||||
| */ | */ | ||||
| @Override | |||||
| public void setMessageOutputLevel(final int level) { | public void setMessageOutputLevel(final int level) { | ||||
| // Use the logger config | // Use the logger config | ||||
| } | } | ||||
| @@ -308,6 +315,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * Set the output print stream. | * Set the output print stream. | ||||
| * @param output the output stream | * @param output the output stream | ||||
| */ | */ | ||||
| @Override | |||||
| public void setOutputPrintStream(final PrintStream output) { | public void setOutputPrintStream(final PrintStream output) { | ||||
| this.out = output; | this.out = output; | ||||
| } | } | ||||
| @@ -317,6 +325,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * This is ignored. | * This is ignored. | ||||
| * @param emacsMode ignored | * @param emacsMode ignored | ||||
| */ | */ | ||||
| @Override | |||||
| public void setEmacsMode(final boolean emacsMode) { | public void setEmacsMode(final boolean emacsMode) { | ||||
| // Doesn't make sense for c-l. Use the logger config | // Doesn't make sense for c-l. Use the logger config | ||||
| } | } | ||||
| @@ -325,6 +334,7 @@ public class CommonsLoggingListener implements BuildListener, BuildLogger { | |||||
| * Set the error print stream. | * Set the error print stream. | ||||
| * @param err the error stream | * @param err the error stream | ||||
| */ | */ | ||||
| @Override | |||||
| public void setErrorPrintStream(final PrintStream err) { | public void setErrorPrintStream(final PrintStream err) { | ||||
| this.err = err; | this.err = err; | ||||
| } | } | ||||
| @@ -33,14 +33,14 @@ import org.apache.tools.ant.Task; | |||||
| */ | */ | ||||
| public class Log4jListener implements BuildListener { | public class Log4jListener implements BuildListener { | ||||
| /** Indicates if the listener was initialized. */ | |||||
| private final boolean initialized; | |||||
| /** | /** | ||||
| * log category we log into | * log category we log into | ||||
| */ | */ | ||||
| public static final String LOG_ANT = "org.apache.tools.ant"; | public static final String LOG_ANT = "org.apache.tools.ant"; | ||||
| /** Indicates if the listener was initialized. */ | |||||
| private final boolean initialized; | |||||
| /** | /** | ||||
| * Construct the listener and make sure there is a valid appender. | * Construct the listener and make sure there is a valid appender. | ||||
| */ | */ | ||||
| @@ -57,6 +57,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#buildStarted | * @see BuildListener#buildStarted | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void buildStarted(final BuildEvent event) { | public void buildStarted(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Logger log = Logger.getLogger(Project.class.getName()); | final Logger log = Logger.getLogger(Project.class.getName()); | ||||
| @@ -68,6 +69,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#buildFinished | * @see BuildListener#buildFinished | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void buildFinished(final BuildEvent event) { | public void buildFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Logger log = Logger.getLogger(Project.class.getName()); | final Logger log = Logger.getLogger(Project.class.getName()); | ||||
| @@ -83,6 +85,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#targetStarted | * @see BuildListener#targetStarted | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void targetStarted(final BuildEvent event) { | public void targetStarted(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Logger log = Logger.getLogger(Target.class.getName()); | final Logger log = Logger.getLogger(Target.class.getName()); | ||||
| @@ -94,6 +97,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#targetFinished | * @see BuildListener#targetFinished | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void targetFinished(final BuildEvent event) { | public void targetFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final String targetName = event.getTarget().getName(); | final String targetName = event.getTarget().getName(); | ||||
| @@ -111,6 +115,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#taskStarted | * @see BuildListener#taskStarted | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void taskStarted(final BuildEvent event) { | public void taskStarted(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Task task = event.getTask(); | final Task task = event.getTask(); | ||||
| @@ -123,6 +128,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#taskFinished | * @see BuildListener#taskFinished | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void taskFinished(final BuildEvent event) { | public void taskFinished(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| final Task task = event.getTask(); | final Task task = event.getTask(); | ||||
| @@ -140,6 +146,7 @@ public class Log4jListener implements BuildListener { | |||||
| * @see BuildListener#messageLogged | * @see BuildListener#messageLogged | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public void messageLogged(final BuildEvent event) { | public void messageLogged(final BuildEvent event) { | ||||
| if (initialized) { | if (initialized) { | ||||
| Object categoryObject = event.getTask(); | Object categoryObject = event.getTask(); | ||||
| @@ -24,10 +24,12 @@ import java.io.PrintStream; | |||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.nio.file.Paths; | import java.nio.file.Paths; | ||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.Hashtable; | |||||
| import java.util.Map; | |||||
| import java.util.Properties; | import java.util.Properties; | ||||
| import java.util.StringTokenizer; | import java.util.StringTokenizer; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import java.util.stream.Collectors; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.BuildEvent; | import org.apache.tools.ant.BuildEvent; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -97,21 +99,22 @@ import org.apache.tools.mail.MailMessage; | |||||
| * | * | ||||
| */ | */ | ||||
| public class MailLogger extends DefaultLogger { | public class MailLogger extends DefaultLogger { | ||||
| private static final String DEFAULT_MIME_TYPE = "text/plain"; | |||||
| /** Buffer in which the message is constructed prior to sending */ | /** Buffer in which the message is constructed prior to sending */ | ||||
| private StringBuffer buffer = new StringBuffer(); | private StringBuffer buffer = new StringBuffer(); | ||||
| private static final String DEFAULT_MIME_TYPE = "text/plain"; | |||||
| /** | /** | ||||
| * Sends an e-mail with the log results. | * Sends an e-mail with the log results. | ||||
| * | * | ||||
| * @param event the build finished event | * @param event the build finished event | ||||
| */ | */ | ||||
| @Override | |||||
| public void buildFinished(BuildEvent event) { | public void buildFinished(BuildEvent event) { | ||||
| super.buildFinished(event); | super.buildFinished(event); | ||||
| Project project = event.getProject(); | Project project = event.getProject(); | ||||
| Hashtable<String, Object> properties = project.getProperties(); | |||||
| Map<String, Object> properties = project.getProperties(); | |||||
| // overlay specified properties file (if any), which overrides project | // overlay specified properties file (if any), which overrides project | ||||
| // settings | // settings | ||||
| @@ -168,8 +171,8 @@ public class MailLogger extends DefaultLogger { | |||||
| .subject(getValue( | .subject(getValue( | ||||
| properties, prefix + ".subject", | properties, prefix + ".subject", | ||||
| (success) ? "Build Success" : "Build Failure")); | (success) ? "Build Success" : "Build Failure")); | ||||
| if (values.user().equals("") | |||||
| && values.password().equals("") | |||||
| if (values.user().isEmpty() | |||||
| && values.password().isEmpty() | |||||
| && !values.ssl() && !values.starttls()) { | && !values.ssl() && !values.starttls()) { | ||||
| sendMail(values, buffer.substring(0)); | sendMail(values, buffer.substring(0)); | ||||
| } else { | } else { | ||||
| @@ -310,6 +313,7 @@ public class MailLogger extends DefaultLogger { | |||||
| * | * | ||||
| * @param message the message being logger | * @param message the message being logger | ||||
| */ | */ | ||||
| @Override | |||||
| protected void log(String message) { | protected void log(String message) { | ||||
| buffer.append(message).append(StringUtils.LINE_SEP); | buffer.append(message).append(StringUtils.LINE_SEP); | ||||
| } | } | ||||
| @@ -327,7 +331,7 @@ public class MailLogger extends DefaultLogger { | |||||
| * @exception Exception thrown if no default value is specified and the | * @exception Exception thrown if no default value is specified and the | ||||
| * property is not present in properties. | * property is not present in properties. | ||||
| */ | */ | ||||
| private String getValue(Hashtable<String, Object> properties, String name, | |||||
| private String getValue(Map<String, Object> properties, String name, | |||||
| String defaultValue) { | String defaultValue) { | ||||
| String propertyName = "MailLogger." + name; | String propertyName = "MailLogger." + name; | ||||
| String value = (String) properties.get(propertyName); | String value = (String) properties.get(propertyName); | ||||
| @@ -356,7 +360,7 @@ public class MailLogger extends DefaultLogger { | |||||
| mailMessage.setHeader("Date", DateUtils.getDateForHeader()); | mailMessage.setHeader("Date", DateUtils.getDateForHeader()); | ||||
| mailMessage.from(values.from()); | mailMessage.from(values.from()); | ||||
| if (!values.replytoList().equals("")) { | |||||
| if (!values.replytoList().isEmpty()) { | |||||
| StringTokenizer t = new StringTokenizer( | StringTokenizer t = new StringTokenizer( | ||||
| values.replytoList(), ", ", false); | values.replytoList(), ", ", false); | ||||
| while (t.hasMoreTokens()) { | while (t.hasMoreTokens()) { | ||||
| @@ -391,7 +395,7 @@ public class MailLogger extends DefaultLogger { | |||||
| private void sendMimeMail(Project project, Values values, String message) { | private void sendMimeMail(Project project, Values values, String message) { | ||||
| Mailer mailer = null; | Mailer mailer = null; | ||||
| try { | try { | ||||
| mailer = (Mailer) ClasspathUtils.newInstance( | |||||
| mailer = ClasspathUtils.newInstance( | |||||
| "org.apache.tools.ant.taskdefs.email.MimeMailer", | "org.apache.tools.ant.taskdefs.email.MimeMailer", | ||||
| MailLogger.class.getClassLoader(), Mailer.class); | MailLogger.class.getClassLoader(), Mailer.class); | ||||
| } catch (BuildException e) { | } catch (BuildException e) { | ||||
| @@ -400,7 +404,7 @@ public class MailLogger extends DefaultLogger { | |||||
| return; | return; | ||||
| } | } | ||||
| // convert the replyTo string into a vector of emailaddresses | // convert the replyTo string into a vector of emailaddresses | ||||
| Vector<EmailAddress> replyToList = vectorizeEmailAddresses(values.replytoList()); | |||||
| Vector<EmailAddress> replyToList = splitEmailAddresses(values.replytoList()); | |||||
| mailer.setHost(values.mailhost()); | mailer.setHost(values.mailhost()); | ||||
| mailer.setPort(values.port()); | mailer.setPort(values.port()); | ||||
| mailer.setUser(values.user()); | mailer.setUser(values.user()); | ||||
| @@ -417,25 +421,20 @@ public class MailLogger extends DefaultLogger { | |||||
| mailer.setMessage(mymessage); | mailer.setMessage(mymessage); | ||||
| mailer.setFrom(new EmailAddress(values.from())); | mailer.setFrom(new EmailAddress(values.from())); | ||||
| mailer.setReplyToList(replyToList); | mailer.setReplyToList(replyToList); | ||||
| Vector<EmailAddress> toList = vectorizeEmailAddresses(values.toList()); | |||||
| Vector<EmailAddress> toList = splitEmailAddresses(values.toList()); | |||||
| mailer.setToList(toList); | mailer.setToList(toList); | ||||
| Vector<EmailAddress> toCcList = vectorizeEmailAddresses(values.toCcList()); | |||||
| Vector<EmailAddress> toCcList = splitEmailAddresses(values.toCcList()); | |||||
| mailer.setCcList(toCcList); | mailer.setCcList(toCcList); | ||||
| Vector<EmailAddress> toBccList = vectorizeEmailAddresses(values.toBccList()); | |||||
| Vector<EmailAddress> toBccList = splitEmailAddresses(values.toBccList()); | |||||
| mailer.setBccList(toBccList); | mailer.setBccList(toBccList); | ||||
| mailer.setFiles(new Vector<File>()); | mailer.setFiles(new Vector<File>()); | ||||
| mailer.setSubject(values.subject()); | mailer.setSubject(values.subject()); | ||||
| mailer.setHeaders(new Vector<Header>()); | mailer.setHeaders(new Vector<Header>()); | ||||
| mailer.send(); | mailer.send(); | ||||
| } | } | ||||
| private Vector<EmailAddress> vectorizeEmailAddresses(String listString) { | |||||
| Vector<EmailAddress> emailList = new Vector<EmailAddress>(); | |||||
| StringTokenizer tokens = new StringTokenizer(listString, ","); | |||||
| while (tokens.hasMoreTokens()) { | |||||
| emailList.addElement(new EmailAddress(tokens.nextToken())); | |||||
| } | |||||
| return emailList; | |||||
| private Vector<EmailAddress> splitEmailAddresses(String listString) { | |||||
| return Stream.of(listString.split(",")).map(EmailAddress::new) | |||||
| .collect(Collectors.toCollection(Vector::new)); | |||||
| } | } | ||||
| } | } | ||||
| @@ -32,7 +32,7 @@ import org.apache.tools.ant.util.StringUtils; | |||||
| */ | */ | ||||
| public class ProfileLogger extends DefaultLogger { | public class ProfileLogger extends DefaultLogger { | ||||
| private Map<Object, Date> profileData = new ConcurrentHashMap<Object, Date>(); | |||||
| private Map<Object, Date> profileData = new ConcurrentHashMap<>(); | |||||
| /** | /** | ||||
| * Logs a message to say that the target has started. | * Logs a message to say that the target has started. | ||||
| @@ -41,6 +41,7 @@ public class ProfileLogger extends DefaultLogger { | |||||
| * An event with any relevant extra information. Must not be | * An event with any relevant extra information. Must not be | ||||
| * <code>null</code>. | * <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void targetStarted(BuildEvent event) { | public void targetStarted(BuildEvent event) { | ||||
| Date now = new Date(); | Date now = new Date(); | ||||
| String name = "Target " + event.getTarget().getName(); | String name = "Target " + event.getTarget().getName(); | ||||
| @@ -55,8 +56,9 @@ public class ProfileLogger extends DefaultLogger { | |||||
| * An event with any relevant extra information. Must not be | * An event with any relevant extra information. Must not be | ||||
| * <code>null</code>. | * <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void targetFinished(BuildEvent event) { | public void targetFinished(BuildEvent event) { | ||||
| Date start = (Date) profileData.remove(event.getTarget()); | |||||
| Date start = profileData.remove(event.getTarget()); | |||||
| String name = "Target " + event.getTarget().getName(); | String name = "Target " + event.getTarget().getName(); | ||||
| logFinish(event, start, name); | logFinish(event, start, name); | ||||
| } | } | ||||
| @@ -68,6 +70,7 @@ public class ProfileLogger extends DefaultLogger { | |||||
| * An event with any relevant extra information. Must not be | * An event with any relevant extra information. Must not be | ||||
| * <code>null</code>. | * <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void taskStarted(BuildEvent event) { | public void taskStarted(BuildEvent event) { | ||||
| String name = event.getTask().getTaskName(); | String name = event.getTask().getTaskName(); | ||||
| Date now = new Date(); | Date now = new Date(); | ||||
| @@ -82,15 +85,16 @@ public class ProfileLogger extends DefaultLogger { | |||||
| * An event with any relevant extra information. Must not be | * An event with any relevant extra information. Must not be | ||||
| * <code>null</code>. | * <code>null</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public void taskFinished(BuildEvent event) { | public void taskFinished(BuildEvent event) { | ||||
| Date start = (Date) profileData.remove(event.getTask()); | |||||
| Date start = profileData.remove(event.getTask()); | |||||
| String name = event.getTask().getTaskName(); | String name = event.getTask().getTaskName(); | ||||
| logFinish(event, start, name); | logFinish(event, start, name); | ||||
| } | } | ||||
| private void logFinish(BuildEvent event, Date start, String name) { | private void logFinish(BuildEvent event, Date start, String name) { | ||||
| Date now = new Date(); | Date now = new Date(); | ||||
| String msg = null; | |||||
| String msg; | |||||
| if (start != null) { | if (start != null) { | ||||
| long diff = now.getTime() - start.getTime(); | long diff = now.getTime() - start.getTime(); | ||||
| msg = StringUtils.LINE_SEP + name + ": finished " + now + " (" | msg = StringUtils.LINE_SEP + name + ": finished " + now + " (" | ||||
| @@ -33,14 +33,14 @@ public class SimpleBigProjectLogger extends NoBannerLogger { | |||||
| * @param event the event to work on | * @param event the event to work on | ||||
| * @return the target name -including the owning project name (if non-null) | * @return the target name -including the owning project name (if non-null) | ||||
| */ | */ | ||||
| @Override | |||||
| protected String extractTargetName(BuildEvent event) { | protected String extractTargetName(BuildEvent event) { | ||||
| String targetName = super.extractTargetName(event); | String targetName = super.extractTargetName(event); | ||||
| String projectName = extractProjectName(event); | String projectName = extractProjectName(event); | ||||
| if (projectName != null && targetName != null) { | |||||
| return projectName + '.' + targetName; | |||||
| } else { | |||||
| if (projectName == null || targetName == null) { | |||||
| return targetName; | return targetName; | ||||
| } | } | ||||
| return projectName + '.' + targetName; | |||||
| } | } | ||||
| } | } | ||||
| @@ -30,13 +30,13 @@ public class TimestampedLogger extends DefaultLogger { | |||||
| */ | */ | ||||
| public static final String SPACER = " - at "; | public static final String SPACER = " - at "; | ||||
| /** | /** | ||||
| * This is an override point: the message that indicates whether a build failed. | * This is an override point: the message that indicates whether a build failed. | ||||
| * Subclasses can change/enhance the message. | * Subclasses can change/enhance the message. | ||||
| * | * | ||||
| * @return The classic "BUILD FAILED" plus a timestamp | * @return The classic "BUILD FAILED" plus a timestamp | ||||
| */ | */ | ||||
| @Override | |||||
| protected String getBuildFailedMessage() { | protected String getBuildFailedMessage() { | ||||
| return super.getBuildFailedMessage() + SPACER + getTimestamp(); | return super.getBuildFailedMessage() + SPACER + getTimestamp(); | ||||
| } | } | ||||
| @@ -47,6 +47,7 @@ public class TimestampedLogger extends DefaultLogger { | |||||
| * | * | ||||
| * @return The classic "BUILD SUCCESSFUL" plus a timestamp | * @return The classic "BUILD SUCCESSFUL" plus a timestamp | ||||
| */ | */ | ||||
| @Override | |||||
| protected String getBuildSuccessfulMessage() { | protected String getBuildSuccessfulMessage() { | ||||
| return super.getBuildSuccessfulMessage() + SPACER + getTimestamp(); | return super.getBuildSuccessfulMessage() + SPACER + getTimestamp(); | ||||
| } | } | ||||
| @@ -36,8 +36,8 @@ public class LocalProperties | |||||
| * @return the localproperties. | * @return the localproperties. | ||||
| */ | */ | ||||
| public static synchronized LocalProperties get(Project project) { | public static synchronized LocalProperties get(Project project) { | ||||
| LocalProperties l = (LocalProperties) project.getReference( | |||||
| MagicNames.REFID_LOCAL_PROPERTIES); | |||||
| LocalProperties l = | |||||
| project.getReference(MagicNames.REFID_LOCAL_PROPERTIES); | |||||
| if (l == null) { | if (l == null) { | ||||
| l = new LocalProperties(); | l = new LocalProperties(); | ||||
| project.addReference(MagicNames.REFID_LOCAL_PROPERTIES, l); | project.addReference(MagicNames.REFID_LOCAL_PROPERTIES, l); | ||||
| @@ -62,14 +62,11 @@ public class LocalProperties | |||||
| * Get the initial value. | * Get the initial value. | ||||
| * @return a new localproperties stack. | * @return a new localproperties stack. | ||||
| */ | */ | ||||
| @Override | |||||
| protected synchronized LocalPropertyStack initialValue() { | protected synchronized LocalPropertyStack initialValue() { | ||||
| return new LocalPropertyStack(); | return new LocalPropertyStack(); | ||||
| } | } | ||||
| private LocalPropertyStack current() { | |||||
| return (LocalPropertyStack) get(); | |||||
| } | |||||
| // -------------------------------------------------- | // -------------------------------------------------- | ||||
| // | // | ||||
| // Local property adding and scoping | // Local property adding and scoping | ||||
| @@ -81,17 +78,17 @@ public class LocalProperties | |||||
| * @param property the property name to add. | * @param property the property name to add. | ||||
| */ | */ | ||||
| public void addLocal(String property) { | public void addLocal(String property) { | ||||
| current().addLocal(property); | |||||
| get().addLocal(property); | |||||
| } | } | ||||
| /** enter the scope */ | /** enter the scope */ | ||||
| public void enterScope() { | public void enterScope() { | ||||
| current().enterScope(); | |||||
| get().enterScope(); | |||||
| } | } | ||||
| /** exit the scope */ | /** exit the scope */ | ||||
| public void exitScope() { | public void exitScope() { | ||||
| current().exitScope(); | |||||
| get().exitScope(); | |||||
| } | } | ||||
| // -------------------------------------------------- | // -------------------------------------------------- | ||||
| @@ -105,7 +102,7 @@ public class LocalProperties | |||||
| * To be called from the parallel thread itself. | * To be called from the parallel thread itself. | ||||
| */ | */ | ||||
| public void copy() { | public void copy() { | ||||
| set(current().copy()); | |||||
| set(get().copy()); | |||||
| } | } | ||||
| // -------------------------------------------------- | // -------------------------------------------------- | ||||
| @@ -120,8 +117,9 @@ public class LocalProperties | |||||
| * @param helper the invoking PropertyHelper. | * @param helper the invoking PropertyHelper. | ||||
| * @return Object value. | * @return Object value. | ||||
| */ | */ | ||||
| @Override | |||||
| public Object evaluate(String property, PropertyHelper helper) { | public Object evaluate(String property, PropertyHelper helper) { | ||||
| return current().evaluate(property, helper); | |||||
| return get().evaluate(property, helper); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -131,9 +129,10 @@ public class LocalProperties | |||||
| * @param propertyHelper the invoking PropertyHelper. | * @param propertyHelper the invoking PropertyHelper. | ||||
| * @return true if this entity 'owns' the property. | * @return true if this entity 'owns' the property. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean setNew( | public boolean setNew( | ||||
| String property, Object value, PropertyHelper propertyHelper) { | String property, Object value, PropertyHelper propertyHelper) { | ||||
| return current().setNew(property, value, propertyHelper); | |||||
| return get().setNew(property, value, propertyHelper); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -143,10 +142,9 @@ public class LocalProperties | |||||
| * @param propertyHelper the invoking PropertyHelper. | * @param propertyHelper the invoking PropertyHelper. | ||||
| * @return true if this entity 'owns' the property. | * @return true if this entity 'owns' the property. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean set( | public boolean set( | ||||
| String property, Object value, PropertyHelper propertyHelper) { | String property, Object value, PropertyHelper propertyHelper) { | ||||
| return current().set(property, value, propertyHelper); | |||||
| return get().set(property, value, propertyHelper); | |||||
| } | } | ||||
| } | } | ||||
| @@ -17,6 +17,7 @@ | |||||
| */ | */ | ||||
| package org.apache.tools.ant.property; | package org.apache.tools.ant.property; | ||||
| import java.util.Deque; | |||||
| import java.util.LinkedList; | import java.util.LinkedList; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| import java.util.concurrent.ConcurrentHashMap; | import java.util.concurrent.ConcurrentHashMap; | ||||
| @@ -29,7 +30,7 @@ import org.apache.tools.ant.PropertyHelper; | |||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| public class LocalPropertyStack { | public class LocalPropertyStack { | ||||
| private final LinkedList<Map<String, Object>> stack = new LinkedList<Map<String, Object>>(); | |||||
| private final Deque<Map<String, Object>> stack = new LinkedList<>(); | |||||
| private final Object LOCK = new Object(); | private final Object LOCK = new Object(); | ||||
| // -------------------------------------------------- | // -------------------------------------------------- | ||||
| @@ -32,6 +32,7 @@ public final class NullReturn { | |||||
| /** | /** | ||||
| * {@inheritDoc} | * {@inheritDoc} | ||||
| */ | */ | ||||
| @Override | |||||
| public String toString() { | public String toString() { | ||||
| return "null"; | return "null"; | ||||
| } | } | ||||
| @@ -19,6 +19,7 @@ package org.apache.tools.ant.property; | |||||
| import java.text.ParsePosition; | import java.text.ParsePosition; | ||||
| import java.util.Collection; | import java.util.Collection; | ||||
| import java.util.Objects; | |||||
| import org.apache.tools.ant.Project; | import org.apache.tools.ant.Project; | ||||
| @@ -49,6 +50,7 @@ public class ParseProperties implements ParseNextProperty { | |||||
| * Get the project. | * Get the project. | ||||
| * @return the current Ant project. | * @return the current Ant project. | ||||
| */ | */ | ||||
| @Override | |||||
| public Project getProject() { | public Project getProject() { | ||||
| return project; | return project; | ||||
| } | } | ||||
| @@ -90,7 +92,7 @@ public class ParseProperties implements ParseNextProperty { | |||||
| * <code>null</code> if the original string is <code>null</code>. | * <code>null</code> if the original string is <code>null</code>. | ||||
| */ | */ | ||||
| public Object parseProperties(String value) { | public Object parseProperties(String value) { | ||||
| if (value == null || "".equals(value)) { | |||||
| if (value == null || value.isEmpty()) { | |||||
| return value; | return value; | ||||
| } | } | ||||
| final int len = value.length(); | final int len = value.length(); | ||||
| @@ -99,7 +101,7 @@ public class ParseProperties implements ParseNextProperty { | |||||
| if (o != null && pos.getIndex() >= len) { | if (o != null && pos.getIndex() >= len) { | ||||
| return o; | return o; | ||||
| } | } | ||||
| StringBuffer sb = new StringBuffer(len * 2); | |||||
| StringBuilder sb = new StringBuilder(len * 2); | |||||
| if (o == null) { | if (o == null) { | ||||
| sb.append(value.charAt(pos.getIndex())); | sb.append(value.charAt(pos.getIndex())); | ||||
| pos.setIndex(pos.getIndex() + 1); | pos.setIndex(pos.getIndex() + 1); | ||||
| @@ -157,6 +159,7 @@ public class ParseProperties implements ParseNextProperty { | |||||
| * property doesn't expand to a value, the property's name is | * property doesn't expand to a value, the property's name is | ||||
| * returned. | * returned. | ||||
| */ | */ | ||||
| @Override | |||||
| public Object parseNextProperty(String value, ParsePosition pos) { | public Object parseNextProperty(String value, ParsePosition pos) { | ||||
| final int start = pos.getIndex(); | final int start = pos.getIndex(); | ||||
| @@ -183,14 +186,9 @@ public class ParseProperties implements ParseNextProperty { | |||||
| } | } | ||||
| private String parsePropertyName(String value, ParsePosition pos) { | private String parsePropertyName(String value, ParsePosition pos) { | ||||
| for (PropertyExpander propertyExpander : expanders) { | |||||
| String propertyName = propertyExpander.parsePropertyName(value, pos, this); | |||||
| if (propertyName == null) { | |||||
| continue; | |||||
| } | |||||
| return propertyName; | |||||
| } | |||||
| return null; | |||||
| return expanders.stream() | |||||
| .map(xp -> xp.parsePropertyName(value, pos, this)) | |||||
| .filter(Objects::nonNull).findFirst().orElse(null); | |||||
| } | } | ||||
| private Object getProperty(String propertyName) { | private Object getProperty(String propertyName) { | ||||
| @@ -30,7 +30,7 @@ import org.apache.tools.ant.Project; | |||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| public class ResolvePropertyMap implements GetProperty { | public class ResolvePropertyMap implements GetProperty { | ||||
| private final Set<String> seen = new HashSet<String>(); | |||||
| private final Set<String> seen = new HashSet<>(); | |||||
| private final ParseProperties parseProperties; | private final ParseProperties parseProperties; | ||||
| private final GetProperty master; | private final GetProperty master; | ||||
| private Map<String, Object> map; | private Map<String, Object> map; | ||||
| @@ -58,10 +58,11 @@ public class ResolvePropertyMap implements GetProperty { | |||||
| * @param name name of the property. | * @param name name of the property. | ||||
| * @return the property value, or null for no match or for name being null. | * @return the property value, or null for no match or for name being null. | ||||
| */ | */ | ||||
| @Override | |||||
| public Object getProperty(String name) { | public Object getProperty(String name) { | ||||
| if (seen.contains(name)) { | if (seen.contains(name)) { | ||||
| throw new BuildException( | |||||
| "Property " + name + " was circularly " + "defined."); | |||||
| throw new BuildException("Property %s was circularly defined.", | |||||
| name); | |||||
| } | } | ||||
| try { | try { | ||||
| @@ -110,6 +111,7 @@ public class ResolvePropertyMap implements GetProperty { | |||||
| * @param map the map to resolve properties in. | * @param map the map to resolve properties in. | ||||
| * @deprecated since Ant 1.8.2, use the three-arg method instead. | * @deprecated since Ant 1.8.2, use the three-arg method instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void resolveAllProperties(Map<String, Object> map) { | public void resolveAllProperties(Map<String, Object> map) { | ||||
| resolveAllProperties(map, null, false); | resolveAllProperties(map, null, false); | ||||
| } | } | ||||
| @@ -121,6 +123,7 @@ public class ResolvePropertyMap implements GetProperty { | |||||
| * will finally receive - may be null. | * will finally receive - may be null. | ||||
| * @deprecated since Ant 1.8.2, use the three-arg method instead. | * @deprecated since Ant 1.8.2, use the three-arg method instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void resolveAllProperties(Map<String, Object> map, String prefix) { | public void resolveAllProperties(Map<String, Object> map, String prefix) { | ||||
| resolveAllProperties(map, null, false); | resolveAllProperties(map, null, false); | ||||
| } | } | ||||
| @@ -55,10 +55,10 @@ public abstract class AbstractCvsTask extends Task { | |||||
| private Commandline cmd = new Commandline(); | private Commandline cmd = new Commandline(); | ||||
| private ArrayList<Module> modules = new ArrayList<Module>(); | |||||
| private List<Module> modules = new ArrayList<>(); | |||||
| /** list of Commandline children */ | /** list of Commandline children */ | ||||
| private Vector<Commandline> vecCommandlines = new Vector<Commandline>(); | |||||
| private List<Commandline> commandlines = new Vector<>(); | |||||
| /** | /** | ||||
| * the CVSROOT variable. | * the CVSROOT variable. | ||||
| @@ -149,11 +149,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| private OutputStream outputStream; | private OutputStream outputStream; | ||||
| private OutputStream errorStream; | private OutputStream errorStream; | ||||
| /** empty no-arg constructor*/ | |||||
| public AbstractCvsTask() { | |||||
| super(); | |||||
| } | |||||
| /** | /** | ||||
| * sets the handler | * sets the handler | ||||
| * @param handler a handler able of processing the output and error streams from the cvs exe | * @param handler a handler able of processing the output and error streams from the cvs exe | ||||
| @@ -385,11 +380,12 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @throws BuildException if failonerror is set to true and the | * @throws BuildException if failonerror is set to true and the | ||||
| * cvs command fails. | * cvs command fails. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| String savedCommand = getCommand(); | String savedCommand = getCommand(); | ||||
| if (this.getCommand() == null && vecCommandlines.size() == 0) { | |||||
| if (this.getCommand() == null && commandlines.isEmpty()) { | |||||
| // re-implement legacy behaviour: | // re-implement legacy behaviour: | ||||
| this.setCommand(AbstractCvsTask.DEFAULT_COMMAND); | this.setCommand(AbstractCvsTask.DEFAULT_COMMAND); | ||||
| } | } | ||||
| @@ -397,16 +393,13 @@ public abstract class AbstractCvsTask extends Task { | |||||
| String c = this.getCommand(); | String c = this.getCommand(); | ||||
| Commandline cloned = null; | Commandline cloned = null; | ||||
| if (c != null) { | if (c != null) { | ||||
| cloned = (Commandline) cmd.clone(); | |||||
| cloned = cmd.clone(); | |||||
| cloned.createArgument(true).setLine(c); | cloned.createArgument(true).setLine(c); | ||||
| this.addConfiguredCommandline(cloned, true); | this.addConfiguredCommandline(cloned, true); | ||||
| } | } | ||||
| try { | try { | ||||
| final int size = vecCommandlines.size(); | |||||
| for (int i = 0; i < size; i++) { | |||||
| this.runCommand((Commandline) vecCommandlines.elementAt(i)); | |||||
| } | |||||
| commandlines.forEach(this::runCommand); | |||||
| } finally { | } finally { | ||||
| if (cloned != null) { | if (cloned != null) { | ||||
| removeCommandline(cloned); | removeCommandline(cloned); | ||||
| @@ -421,24 +414,24 @@ public abstract class AbstractCvsTask extends Task { | |||||
| String cmdLine = Commandline.describeCommand(execute | String cmdLine = Commandline.describeCommand(execute | ||||
| .getCommandline()); | .getCommandline()); | ||||
| StringBuffer stringBuffer = removeCvsPassword(cmdLine); | |||||
| StringBuilder buf = removeCvsPassword(cmdLine); | |||||
| String newLine = StringUtils.LINE_SEP; | String newLine = StringUtils.LINE_SEP; | ||||
| String[] variableArray = execute.getEnvironment(); | String[] variableArray = execute.getEnvironment(); | ||||
| if (variableArray != null) { | if (variableArray != null) { | ||||
| stringBuffer.append(newLine); | |||||
| stringBuffer.append(newLine); | |||||
| stringBuffer.append("environment:"); | |||||
| stringBuffer.append(newLine); | |||||
| buf.append(newLine); | |||||
| buf.append(newLine); | |||||
| buf.append("environment:"); | |||||
| buf.append(newLine); | |||||
| for (int z = 0; z < variableArray.length; z++) { | for (int z = 0; z < variableArray.length; z++) { | ||||
| stringBuffer.append(newLine); | |||||
| stringBuffer.append("\t"); | |||||
| stringBuffer.append(variableArray[z]); | |||||
| buf.append(newLine); | |||||
| buf.append("\t"); | |||||
| buf.append(variableArray[z]); | |||||
| } | } | ||||
| } | } | ||||
| return stringBuffer.toString(); | |||||
| return buf.toString(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -449,24 +442,24 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @param cmdLine the CVS command line | * @param cmdLine the CVS command line | ||||
| * @return a StringBuffer where the password has been removed (if available) | * @return a StringBuffer where the password has been removed (if available) | ||||
| */ | */ | ||||
| private StringBuffer removeCvsPassword(String cmdLine) { | |||||
| StringBuffer stringBuffer = new StringBuffer(cmdLine); | |||||
| private StringBuilder removeCvsPassword(String cmdLine) { | |||||
| StringBuilder buf = new StringBuilder(cmdLine); | |||||
| int start = cmdLine.indexOf("-d:"); | int start = cmdLine.indexOf("-d:"); | ||||
| if (start >= 0) { | if (start >= 0) { | ||||
| int stop = cmdLine.indexOf("@", start); | |||||
| int startproto = cmdLine.indexOf(":", start); | |||||
| int startuser = cmdLine.indexOf(":", startproto + 1); | |||||
| int startpass = cmdLine.indexOf(":", startuser + 1); | |||||
| stop = cmdLine.indexOf("@", start); | |||||
| int stop = cmdLine.indexOf('@', start); | |||||
| int startproto = cmdLine.indexOf(':', start); | |||||
| int startuser = cmdLine.indexOf(':', startproto + 1); | |||||
| int startpass = cmdLine.indexOf(':', startuser + 1); | |||||
| stop = cmdLine.indexOf('@', start); | |||||
| if (stop >= 0 && startpass > startproto && startpass < stop) { | if (stop >= 0 && startpass > startproto && startpass < stop) { | ||||
| for (int i = startpass + 1; i < stop; i++) { | for (int i = startpass + 1; i < stop; i++) { | ||||
| stringBuffer.replace(i, i + 1, "*"); | |||||
| buf.replace(i, i + 1, "*"); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| return stringBuffer; | |||||
| return buf; | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -478,10 +471,8 @@ public abstract class AbstractCvsTask extends Task { | |||||
| public void setCvsRoot(String root) { | public void setCvsRoot(String root) { | ||||
| // Check if not real cvsroot => set it to null | // Check if not real cvsroot => set it to null | ||||
| if (root != null) { | |||||
| if (root.trim().equals("")) { | |||||
| root = null; | |||||
| } | |||||
| if (root != null && root.trim().isEmpty()) { | |||||
| root = null; | |||||
| } | } | ||||
| this.cvsRoot = root; | this.cvsRoot = root; | ||||
| @@ -502,11 +493,8 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @param rsh the CVS_RSH variable | * @param rsh the CVS_RSH variable | ||||
| */ | */ | ||||
| public void setCvsRsh(String rsh) { | public void setCvsRsh(String rsh) { | ||||
| // Check if not real cvsrsh => set it to null | |||||
| if (rsh != null) { | |||||
| if (rsh.trim().equals("")) { | |||||
| rsh = null; | |||||
| } | |||||
| if (rsh != null && rsh.trim().isEmpty()) { | |||||
| rsh = null; | |||||
| } | } | ||||
| this.cvsRsh = rsh; | this.cvsRsh = rsh; | ||||
| @@ -535,7 +523,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @return the port of CVS | * @return the port of CVS | ||||
| */ | */ | ||||
| public int getPort() { | public int getPort() { | ||||
| return this.port; | return this.port; | ||||
| } | } | ||||
| @@ -553,7 +540,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @return password file | * @return password file | ||||
| */ | */ | ||||
| public File getPassFile() { | public File getPassFile() { | ||||
| return this.passFile; | return this.passFile; | ||||
| } | } | ||||
| @@ -576,7 +562,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @return directory where the checked out files should be placed | * @return directory where the checked out files should be placed | ||||
| */ | */ | ||||
| public File getDest() { | public File getDest() { | ||||
| return this.dest; | return this.dest; | ||||
| } | } | ||||
| @@ -595,7 +580,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @return package/module | * @return package/module | ||||
| */ | */ | ||||
| public String getPackage() { | public String getPackage() { | ||||
| return this.cvsPackage; | return this.cvsPackage; | ||||
| } | } | ||||
| /** | /** | ||||
| @@ -613,7 +597,7 @@ public abstract class AbstractCvsTask extends Task { | |||||
| */ | */ | ||||
| public void setTag(String p) { | public void setTag(String p) { | ||||
| // Check if not real tag => set it to null | // Check if not real tag => set it to null | ||||
| if (p != null && p.trim().length() > 0) { | |||||
| if (!(p == null || p.trim().isEmpty())) { | |||||
| tag = p; | tag = p; | ||||
| addCommandArgument("-r" + p); | addCommandArgument("-r" + p); | ||||
| } | } | ||||
| @@ -649,7 +633,7 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * can understand see man cvs | * can understand see man cvs | ||||
| */ | */ | ||||
| public void setDate(String p) { | public void setDate(String p) { | ||||
| if (p != null && p.trim().length() > 0) { | |||||
| if (!(p == null || p.trim().isEmpty())) { | |||||
| addCommandArgument("-D"); | addCommandArgument("-D"); | ||||
| addCommandArgument(p); | addCommandArgument(p); | ||||
| } | } | ||||
| @@ -695,7 +679,6 @@ public abstract class AbstractCvsTask extends Task { | |||||
| reallyquiet = q; | reallyquiet = q; | ||||
| } | } | ||||
| /** | /** | ||||
| * If true, report only and don't change any files. | * If true, report only and don't change any files. | ||||
| * | * | ||||
| @@ -794,7 +777,7 @@ public abstract class AbstractCvsTask extends Task { | |||||
| * @param c command line which should be removed | * @param c command line which should be removed | ||||
| */ | */ | ||||
| protected void removeCommandline(Commandline c) { | protected void removeCommandline(Commandline c) { | ||||
| vecCommandlines.removeElement(c); | |||||
| commandlines.remove(c); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -818,9 +801,9 @@ public abstract class AbstractCvsTask extends Task { | |||||
| } | } | ||||
| this.configureCommandline(c); | this.configureCommandline(c); | ||||
| if (insertAtStart) { | if (insertAtStart) { | ||||
| vecCommandlines.insertElementAt(c, 0); | |||||
| commandlines.add(0, c); | |||||
| } else { | } else { | ||||
| vecCommandlines.addElement(c); | |||||
| commandlines.add(c); | |||||
| } | } | ||||
| } | } | ||||
| @@ -854,13 +837,12 @@ public abstract class AbstractCvsTask extends Task { | |||||
| } | } | ||||
| protected List<Module> getModules() { | protected List<Module> getModules() { | ||||
| @SuppressWarnings("unchecked") | |||||
| final List<Module> clone = (List<Module>) modules.clone(); | |||||
| return clone; | |||||
| return new ArrayList<>(modules); | |||||
| } | } | ||||
| public static final class Module { | public static final class Module { | ||||
| private String name; | private String name; | ||||
| public void setName(String s) { | public void setName(String s) { | ||||
| name = s; | name = s; | ||||
| } | } | ||||
| @@ -37,6 +37,17 @@ import org.apache.tools.ant.util.JavaEnvUtils; | |||||
| */ | */ | ||||
| public abstract class AbstractJarSignerTask extends Task { | public abstract class AbstractJarSignerTask extends Task { | ||||
| /** | |||||
| * error string for unit test verification: {@value} | |||||
| */ | |||||
| public static final String ERROR_NO_SOURCE = | |||||
| "jar must be set through jar attribute or nested filesets"; | |||||
| /** | |||||
| * name of JDK program we are looking for | |||||
| */ | |||||
| protected static final String JARSIGNER_COMMAND = "jarsigner"; | |||||
| // CheckStyle:VisibilityModifier OFF - bc | // CheckStyle:VisibilityModifier OFF - bc | ||||
| /** | /** | ||||
| * The name of the jar file. | * The name of the jar file. | ||||
| @@ -78,12 +89,7 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| /** | /** | ||||
| * the filesets of the jars to sign | * the filesets of the jars to sign | ||||
| */ | */ | ||||
| protected Vector<FileSet> filesets = new Vector<FileSet>(); | |||||
| /** | |||||
| * name of JDK program we are looking for | |||||
| */ | |||||
| protected static final String JARSIGNER_COMMAND = "jarsigner"; | |||||
| protected Vector<FileSet> filesets = new Vector<>(); | |||||
| // CheckStyle:VisibilityModifier ON | // CheckStyle:VisibilityModifier ON | ||||
| /** | /** | ||||
| @@ -96,12 +102,6 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| */ | */ | ||||
| private Environment sysProperties = new Environment(); | private Environment sysProperties = new Environment(); | ||||
| /** | |||||
| * error string for unit test verification: {@value} | |||||
| */ | |||||
| public static final String ERROR_NO_SOURCE = "jar must be set through jar attribute " | |||||
| + "or nested filesets"; | |||||
| /** | /** | ||||
| * Path holding all non-filesets of filesystem resources we want to sign. | * Path holding all non-filesets of filesystem resources we want to sign. | ||||
| * | * | ||||
| @@ -253,7 +253,7 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| private RedirectorElement createRedirector() { | private RedirectorElement createRedirector() { | ||||
| RedirectorElement result = new RedirectorElement(); | RedirectorElement result = new RedirectorElement(); | ||||
| if (storepass != null) { | if (storepass != null) { | ||||
| StringBuffer input = new StringBuffer(storepass).append('\n'); | |||||
| StringBuilder input = new StringBuilder(storepass).append('\n'); | |||||
| if (keypass != null) { | if (keypass != null) { | ||||
| input.append(keypass).append('\n'); | input.append(keypass).append('\n'); | ||||
| } | } | ||||
| @@ -324,7 +324,6 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| addValue(cmd, "-J-D" + property.getContent()); | addValue(cmd, "-J-D" + property.getContent()); | ||||
| } | } | ||||
| /** | /** | ||||
| * bind to a keystore if the attributes are there | * bind to a keystore if the attributes are there | ||||
| * @param cmd command to configure | * @param cmd command to configure | ||||
| @@ -373,8 +372,7 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| * @return a vector of FileSet instances | * @return a vector of FileSet instances | ||||
| */ | */ | ||||
| protected Vector<FileSet> createUnifiedSources() { | protected Vector<FileSet> createUnifiedSources() { | ||||
| @SuppressWarnings("unchecked") | |||||
| Vector<FileSet> sources = (Vector<FileSet>) filesets.clone(); | |||||
| Vector<FileSet> sources = new Vector<>(filesets); | |||||
| if (jar != null) { | if (jar != null) { | ||||
| //we create a fileset with the source file. | //we create a fileset with the source file. | ||||
| //this lets us combine our logic for handling output directories, | //this lets us combine our logic for handling output directories, | ||||
| @@ -408,7 +406,7 @@ public abstract class AbstractJarSignerTask extends Task { | |||||
| * @since Ant 1.7 | * @since Ant 1.7 | ||||
| */ | */ | ||||
| protected boolean hasResources() { | protected boolean hasResources() { | ||||
| return path != null || filesets.size() > 0; | |||||
| return !(path == null && filesets.isEmpty()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -22,11 +22,13 @@ import java.io.File; | |||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.PrintStream; | import java.io.PrintStream; | ||||
| import java.lang.reflect.Method; | import java.lang.reflect.Method; | ||||
| import java.util.HashMap; | |||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.util.Enumeration; | |||||
| import java.util.HashSet; | import java.util.HashSet; | ||||
| import java.util.Hashtable; | |||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| import java.util.List; | |||||
| import java.util.Map; | |||||
| import java.util.Objects; | |||||
| import java.util.Set; | import java.util.Set; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| @@ -88,10 +90,10 @@ public class Ant extends Task { | |||||
| private boolean inheritRefs = false; | private boolean inheritRefs = false; | ||||
| /** the properties to pass to the new project */ | /** the properties to pass to the new project */ | ||||
| private Vector<Property> properties = new Vector<Property>(); | |||||
| private List<Property> properties = new Vector<>(); | |||||
| /** the references to pass to the new project */ | /** the references to pass to the new project */ | ||||
| private Vector<Reference> references = new Vector<Reference>(); | |||||
| private List<Reference> references = new Vector<>(); | |||||
| /** the temporary project created to run the build file */ | /** the temporary project created to run the build file */ | ||||
| private Project newProject; | private Project newProject; | ||||
| @@ -100,10 +102,10 @@ public class Ant extends Task { | |||||
| private PrintStream out = null; | private PrintStream out = null; | ||||
| /** the sets of properties to pass to the new project */ | /** the sets of properties to pass to the new project */ | ||||
| private Vector<PropertySet> propertySets = new Vector<PropertySet>(); | |||||
| private List<PropertySet> propertySets = new Vector<>(); | |||||
| /** the targets to call on the new project */ | /** the targets to call on the new project */ | ||||
| private Vector<String> targets = new Vector<String>(); | |||||
| private List<String> targets = new Vector<>(); | |||||
| /** whether the target attribute was specified **/ | /** whether the target attribute was specified **/ | ||||
| private boolean targetAttributeSet = false; | private boolean targetAttributeSet = false; | ||||
| @@ -164,6 +166,7 @@ public class Ant extends Task { | |||||
| /** | /** | ||||
| * Creates a Project instance for the project to call. | * Creates a Project instance for the project to call. | ||||
| */ | */ | ||||
| @Override | |||||
| public void init() { | public void init() { | ||||
| newProject = getProject().createSubProject(); | newProject = getProject().createSubProject(); | ||||
| newProject.setJavaVersionProperty(); | newProject.setJavaVersionProperty(); | ||||
| @@ -195,11 +198,11 @@ public class Ant extends Task { | |||||
| Iterator<BuildListener> iter = getBuildListeners(); | Iterator<BuildListener> iter = getBuildListeners(); | ||||
| while (iter.hasNext()) { | while (iter.hasNext()) { | ||||
| newProject.addBuildListener((BuildListener) iter.next()); | |||||
| newProject.addBuildListener(iter.next()); | |||||
| } | } | ||||
| if (output != null) { | if (output != null) { | ||||
| File outfile = null; | |||||
| File outfile; | |||||
| if (dir != null) { | if (dir != null) { | ||||
| outfile = FILE_UTILS.resolveFile(dir, output); | outfile = FILE_UTILS.resolveFile(dir, output); | ||||
| } else { | } else { | ||||
| @@ -246,6 +249,7 @@ public class Ant extends Task { | |||||
| * @see Task#handleOutput(String) | * @see Task#handleOutput(String) | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| public void handleOutput(String outputToHandle) { | public void handleOutput(String outputToHandle) { | ||||
| if (newProject != null) { | if (newProject != null) { | ||||
| newProject.demuxOutput(outputToHandle, false); | newProject.demuxOutput(outputToHandle, false); | ||||
| @@ -268,6 +272,7 @@ public class Ant extends Task { | |||||
| * @see Task#handleInput(byte[], int, int) | * @see Task#handleInput(byte[], int, int) | ||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| @Override | |||||
| public int handleInput(byte[] buffer, int offset, int length) | public int handleInput(byte[] buffer, int offset, int length) | ||||
| throws IOException { | throws IOException { | ||||
| if (newProject != null) { | if (newProject != null) { | ||||
| @@ -284,6 +289,7 @@ public class Ant extends Task { | |||||
| * @see Task#handleFlush(String) | * @see Task#handleFlush(String) | ||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| @Override | |||||
| public void handleFlush(String toFlush) { | public void handleFlush(String toFlush) { | ||||
| if (newProject != null) { | if (newProject != null) { | ||||
| newProject.demuxFlush(toFlush, false); | newProject.demuxFlush(toFlush, false); | ||||
| @@ -301,6 +307,7 @@ public class Ant extends Task { | |||||
| * @see Task#handleErrorOutput(String) | * @see Task#handleErrorOutput(String) | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| public void handleErrorOutput(String errorOutputToHandle) { | public void handleErrorOutput(String errorOutputToHandle) { | ||||
| if (newProject != null) { | if (newProject != null) { | ||||
| newProject.demuxOutput(errorOutputToHandle, true); | newProject.demuxOutput(errorOutputToHandle, true); | ||||
| @@ -317,6 +324,7 @@ public class Ant extends Task { | |||||
| * @see Task#handleErrorFlush(String) | * @see Task#handleErrorFlush(String) | ||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| @Override | |||||
| public void handleErrorFlush(String errorOutputToFlush) { | public void handleErrorFlush(String errorOutputToFlush) { | ||||
| if (newProject != null) { | if (newProject != null) { | ||||
| newProject.demuxFlush(errorOutputToFlush, true); | newProject.demuxFlush(errorOutputToFlush, true); | ||||
| @@ -330,10 +338,11 @@ public class Ant extends Task { | |||||
| * @throws BuildException if a target tries to call itself; | * @throws BuildException if a target tries to call itself; | ||||
| * probably also if a BuildException is thrown by the new project. | * probably also if a BuildException is thrown by the new project. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| File savedDir = dir; | File savedDir = dir; | ||||
| String savedAntFile = antFile; | String savedAntFile = antFile; | ||||
| Vector<String> locals = new VectorSet<String>(targets); | |||||
| Vector<String> locals = new VectorSet<>(targets); | |||||
| try { | try { | ||||
| getNewProject(); | getNewProject(); | ||||
| @@ -366,7 +375,7 @@ public class Ant extends Task { | |||||
| antFile = file.getAbsolutePath(); | antFile = file.getAbsolutePath(); | ||||
| log("calling target(s) " | log("calling target(s) " | ||||
| + ((locals.size() > 0) ? locals.toString() : "[default]") | |||||
| + (!locals.isEmpty() ? locals.toString() : "[default]") | |||||
| + " in build file " + antFile, Project.MSG_VERBOSE); | + " in build file " + antFile, Project.MSG_VERBOSE); | ||||
| newProject.setUserProperty(MagicNames.ANT_FILE , antFile); | newProject.setUserProperty(MagicNames.ANT_FILE , antFile); | ||||
| @@ -377,14 +386,14 @@ public class Ant extends Task { | |||||
| && file.equals(getProject().resolveFile(thisAntFile)) | && file.equals(getProject().resolveFile(thisAntFile)) | ||||
| && getOwningTarget() != null) { | && getOwningTarget() != null) { | ||||
| if (getOwningTarget().getName().equals("")) { | |||||
| if (getTaskName().equals("antcall")) { | |||||
| throw new BuildException("antcall must not be used at" | |||||
| + " the top level."); | |||||
| if ("".equals(getOwningTarget().getName())) { | |||||
| if ("antcall".equals(getTaskName())) { | |||||
| throw new BuildException( | |||||
| "antcall must not be used at the top level."); | |||||
| } | } | ||||
| throw new BuildException(getTaskName() + " task at the" | |||||
| + " top level must not invoke" | |||||
| + " its own build file."); | |||||
| throw new BuildException( | |||||
| "%s task at the top level must not invoke its own build file.", | |||||
| getTaskName()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -395,7 +404,7 @@ public class Ant extends Task { | |||||
| ex, getLocation()); | ex, getLocation()); | ||||
| } | } | ||||
| if (locals.size() == 0) { | |||||
| if (locals.isEmpty()) { | |||||
| String defaultTarget = newProject.getDefaultTarget(); | String defaultTarget = newProject.getDefaultTarget(); | ||||
| if (defaultTarget != null) { | if (defaultTarget != null) { | ||||
| locals.add(defaultTarget); | locals.add(defaultTarget); | ||||
| @@ -409,30 +418,25 @@ public class Ant extends Task { | |||||
| String owningTargetName = getOwningTarget().getName(); | String owningTargetName = getOwningTarget().getName(); | ||||
| if (locals.contains(owningTargetName)) { | if (locals.contains(owningTargetName)) { | ||||
| throw new BuildException(getTaskName() + " task calling " | |||||
| + "its own parent target."); | |||||
| throw new BuildException( | |||||
| "%s task calling its own parent target.", | |||||
| getTaskName()); | |||||
| } | } | ||||
| boolean circular = false; | |||||
| for (Iterator<String> it = locals.iterator(); | |||||
| !circular && it.hasNext();) { | |||||
| Target other = | |||||
| getProject().getTargets().get(it.next()); | |||||
| circular |= (other != null | |||||
| && other.dependsOn(owningTargetName)); | |||||
| } | |||||
| if (circular) { | |||||
| throw new BuildException(getTaskName() | |||||
| + " task calling a target" | |||||
| + " that depends on" | |||||
| + " its parent target \'" | |||||
| + owningTargetName | |||||
| + "\'."); | |||||
| final Map<String, Target> targetsMap = getProject().getTargets(); | |||||
| if (locals.stream().map(targetsMap::get) | |||||
| .filter(Objects::nonNull) | |||||
| .anyMatch(other -> other.dependsOn(owningTargetName))) { | |||||
| throw new BuildException( | |||||
| "%s task calling a target that depends on its parent target '%s'.", | |||||
| getTaskName(), owningTargetName); | |||||
| } | } | ||||
| } | } | ||||
| addReferences(); | addReferences(); | ||||
| if (locals.size() > 0 && !(locals.size() == 1 | |||||
| if (!locals.isEmpty() && !(locals.size() == 1 | |||||
| && "".equals(locals.get(0)))) { | && "".equals(locals.get(0)))) { | ||||
| BuildException be = null; | BuildException be = null; | ||||
| try { | try { | ||||
| @@ -484,10 +488,10 @@ public class Ant extends Task { | |||||
| private void overrideProperties() throws BuildException { | private void overrideProperties() throws BuildException { | ||||
| // remove duplicate properties - last property wins | // remove duplicate properties - last property wins | ||||
| // Needed for backward compatibility | // Needed for backward compatibility | ||||
| Set<String> set = new HashSet<String>(); | |||||
| Set<String> set = new HashSet<>(); | |||||
| for (int i = properties.size() - 1; i >= 0; --i) { | for (int i = properties.size() - 1; i >= 0; --i) { | ||||
| Property p = properties.get(i); | Property p = properties.get(i); | ||||
| if (p.getName() != null && !p.getName().equals("")) { | |||||
| if (p.getName() != null && !"".equals(p.getName())) { | |||||
| if (set.contains(p.getName())) { | if (set.contains(p.getName())) { | ||||
| properties.remove(i); | properties.remove(i); | ||||
| } else { | } else { | ||||
| @@ -495,12 +499,9 @@ public class Ant extends Task { | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| Enumeration<Property> e = properties.elements(); | |||||
| while (e.hasMoreElements()) { | |||||
| Property p = e.nextElement(); | |||||
| p.setProject(newProject); | |||||
| p.execute(); | |||||
| } | |||||
| properties.stream().peek(p -> p.setProject(newProject)) | |||||
| .forEach(Property::execute); | |||||
| if (useNativeBasedir) { | if (useNativeBasedir) { | ||||
| addAlmostAll(getProject().getInheritedProperties(), | addAlmostAll(getProject().getInheritedProperties(), | ||||
| PropertyType.INHERITED); | PropertyType.INHERITED); | ||||
| @@ -517,14 +518,13 @@ public class Ant extends Task { | |||||
| * @throws BuildException if a reference does not have a refid. | * @throws BuildException if a reference does not have a refid. | ||||
| */ | */ | ||||
| private void addReferences() throws BuildException { | private void addReferences() throws BuildException { | ||||
| @SuppressWarnings("unchecked") | |||||
| Hashtable<String, Object> thisReferences | |||||
| = (Hashtable<String, Object>) getProject().getReferences().clone(); | |||||
| Map<String, Object> thisReferences = | |||||
| new HashMap<>(getProject().getReferences()); | |||||
| for (Reference ref : references) { | for (Reference ref : references) { | ||||
| String refid = ref.getRefId(); | String refid = ref.getRefId(); | ||||
| if (refid == null) { | if (refid == null) { | ||||
| throw new BuildException("the refid attribute is required" | |||||
| + " for reference elements"); | |||||
| throw new BuildException( | |||||
| "the refid attribute is required for reference elements"); | |||||
| } | } | ||||
| if (!thisReferences.containsKey(refid)) { | if (!thisReferences.containsKey(refid)) { | ||||
| log("Parent project doesn't contain any reference '" | log("Parent project doesn't contain any reference '" | ||||
| @@ -544,7 +544,7 @@ public class Ant extends Task { | |||||
| // Now add all references that are not defined in the | // Now add all references that are not defined in the | ||||
| // subproject, if inheritRefs is true | // subproject, if inheritRefs is true | ||||
| if (inheritRefs) { | if (inheritRefs) { | ||||
| Hashtable<String, Object> newReferences = newProject.getReferences(); | |||||
| Map<String, Object> newReferences = newProject.getReferences(); | |||||
| for (String key : thisReferences.keySet()) { | for (String key : thisReferences.keySet()) { | ||||
| if (newReferences.containsKey(key)) { | if (newReferences.containsKey(key)) { | ||||
| continue; | continue; | ||||
| @@ -576,32 +576,32 @@ public class Ant extends Task { | |||||
| Class<?> c = orig.getClass(); | Class<?> c = orig.getClass(); | ||||
| Object copy = orig; | Object copy = orig; | ||||
| try { | try { | ||||
| Method cloneM = c.getMethod("clone", new Class[0]); | |||||
| Method cloneM = c.getMethod("clone"); | |||||
| if (cloneM != null) { | if (cloneM != null) { | ||||
| copy = cloneM.invoke(orig, new Object[0]); | |||||
| copy = cloneM.invoke(orig); | |||||
| log("Adding clone of reference " + oldKey, Project.MSG_DEBUG); | log("Adding clone of reference " + oldKey, Project.MSG_DEBUG); | ||||
| } | } | ||||
| } catch (Exception e) { | } catch (Exception e) { | ||||
| // not Clonable | // not Clonable | ||||
| } | } | ||||
| if (copy instanceof ProjectComponent) { | if (copy instanceof ProjectComponent) { | ||||
| ((ProjectComponent) copy).setProject(newProject); | ((ProjectComponent) copy).setProject(newProject); | ||||
| } else { | } else { | ||||
| try { | try { | ||||
| Method setProjectM = | Method setProjectM = | ||||
| c.getMethod("setProject", new Class[] {Project.class}); | |||||
| c.getMethod("setProject", Project.class); | |||||
| if (setProjectM != null) { | if (setProjectM != null) { | ||||
| setProjectM.invoke(copy, new Object[] {newProject}); | |||||
| setProjectM.invoke(copy, newProject); | |||||
| } | } | ||||
| } catch (NoSuchMethodException e) { | } catch (NoSuchMethodException e) { | ||||
| // ignore this if the class being referenced does not have | // ignore this if the class being referenced does not have | ||||
| // a set project method. | // a set project method. | ||||
| } catch (Exception e2) { | } catch (Exception e2) { | ||||
| String msg = "Error setting new project instance for " | |||||
| + "reference with id " + oldKey; | |||||
| throw new BuildException(msg, e2, getLocation()); | |||||
| throw new BuildException( | |||||
| "Error setting new project instance for " | |||||
| + "reference with id " + oldKey, | |||||
| e2, getLocation()); | |||||
| } | } | ||||
| } | } | ||||
| newProject.addReference(newKey, copy); | newProject.addReference(newKey, copy); | ||||
| @@ -617,29 +617,31 @@ public class Ant extends Task { | |||||
| * user property or an inherited property). | * user property or an inherited property). | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private void addAlmostAll(Hashtable<?, ?> props, PropertyType type) { | |||||
| Enumeration<?> e = props.keys(); | |||||
| while (e.hasMoreElements()) { | |||||
| String key = e.nextElement().toString(); | |||||
| private void addAlmostAll(Map<?, ?> props, PropertyType type) { | |||||
| props.forEach((k, v) -> { | |||||
| String key = k.toString(); | |||||
| if (MagicNames.PROJECT_BASEDIR.equals(key) | if (MagicNames.PROJECT_BASEDIR.equals(key) | ||||
| || MagicNames.ANT_FILE.equals(key)) { | |||||
| || MagicNames.ANT_FILE.equals(key)) { | |||||
| // basedir and ant.file get special treatment in execute() | // basedir and ant.file get special treatment in execute() | ||||
| continue; | |||||
| return; | |||||
| } | } | ||||
| String value = props.get(key).toString(); | |||||
| if (type == PropertyType.PLAIN) { | |||||
| String value = v.toString(); | |||||
| switch (type) { | |||||
| case PLAIN: | |||||
| // don't re-set user properties, avoid the warning message | // don't re-set user properties, avoid the warning message | ||||
| if (newProject.getProperty(key) == null) { | if (newProject.getProperty(key) == null) { | ||||
| // no user property | // no user property | ||||
| newProject.setNewProperty(key, value); | newProject.setNewProperty(key, value); | ||||
| } | } | ||||
| } else if (type == PropertyType.USER) { | |||||
| break; | |||||
| case USER: | |||||
| newProject.setUserProperty(key, value); | newProject.setUserProperty(key, value); | ||||
| } else if (type == PropertyType.INHERITED) { | |||||
| break; | |||||
| case INHERITED: | |||||
| newProject.setInheritedProperty(key, value); | newProject.setInheritedProperty(key, value); | ||||
| break; | |||||
| } | } | ||||
| } | |||||
| }); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -671,7 +673,7 @@ public class Ant extends Task { | |||||
| * @param targetToAdd the name of the target to invoke. | * @param targetToAdd the name of the target to invoke. | ||||
| */ | */ | ||||
| public void setTarget(String targetToAdd) { | public void setTarget(String targetToAdd) { | ||||
| if (targetToAdd.equals("")) { | |||||
| if ("".equals(targetToAdd)) { | |||||
| throw new BuildException("target attribute must not be empty"); | throw new BuildException("target attribute must not be empty"); | ||||
| } | } | ||||
| targets.add(targetToAdd); | targets.add(targetToAdd); | ||||
| @@ -697,7 +699,7 @@ public class Ant extends Task { | |||||
| Property p = new Property(true, getProject()); | Property p = new Property(true, getProject()); | ||||
| p.setProject(getNewProject()); | p.setProject(getNewProject()); | ||||
| p.setTaskName("property"); | p.setTaskName("property"); | ||||
| properties.addElement(p); | |||||
| properties.add(p); | |||||
| return p; | return p; | ||||
| } | } | ||||
| @@ -707,7 +709,7 @@ public class Ant extends Task { | |||||
| * @param ref <code>Reference</code> to add. | * @param ref <code>Reference</code> to add. | ||||
| */ | */ | ||||
| public void addReference(Reference ref) { | public void addReference(Reference ref) { | ||||
| references.addElement(ref); | |||||
| references.add(ref); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -721,7 +723,7 @@ public class Ant extends Task { | |||||
| "nested target is incompatible with the target attribute"); | "nested target is incompatible with the target attribute"); | ||||
| } | } | ||||
| String name = t.getName(); | String name = t.getName(); | ||||
| if (name.equals("")) { | |||||
| if ("".equals(name)) { | |||||
| throw new BuildException("target name must not be empty"); | throw new BuildException("target name must not be empty"); | ||||
| } | } | ||||
| targets.add(name); | targets.add(name); | ||||
| @@ -734,7 +736,7 @@ public class Ant extends Task { | |||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| public void addPropertyset(PropertySet ps) { | public void addPropertyset(PropertySet ps) { | ||||
| propertySets.addElement(ps); | |||||
| propertySets.add(ps); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -760,14 +762,10 @@ public class Ant extends Task { | |||||
| * Helper class that implements the nested <reference> | * Helper class that implements the nested <reference> | ||||
| * element of <ant> and <antcall>. | * element of <ant> and <antcall>. | ||||
| */ | */ | ||||
| @SuppressWarnings("deprecation") | |||||
| public static class Reference | public static class Reference | ||||
| extends org.apache.tools.ant.types.Reference { | extends org.apache.tools.ant.types.Reference { | ||||
| /** Creates a reference to be configured by Ant. */ | |||||
| public Reference() { | |||||
| super(); | |||||
| } | |||||
| private String targetid = null; | private String targetid = null; | ||||
| /** | /** | ||||
| @@ -823,10 +821,7 @@ public class Ant extends Task { | |||||
| } | } | ||||
| } | } | ||||
| private static final class PropertyType { | |||||
| private PropertyType() {} | |||||
| private static final PropertyType PLAIN = new PropertyType(); | |||||
| private static final PropertyType INHERITED = new PropertyType(); | |||||
| private static final PropertyType USER = new PropertyType(); | |||||
| private enum PropertyType { | |||||
| PLAIN, INHERITED, USER; | |||||
| } | } | ||||
| } | } | ||||
| @@ -25,10 +25,15 @@ import java.io.OutputStream; | |||||
| import java.io.OutputStreamWriter; | import java.io.OutputStreamWriter; | ||||
| import java.io.PrintWriter; | import java.io.PrintWriter; | ||||
| import java.io.UnsupportedEncodingException; | import java.io.UnsupportedEncodingException; | ||||
| import java.util.ArrayList; | |||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.Hashtable; | import java.util.Hashtable; | ||||
| import java.util.Vector; | |||||
| import java.util.List; | |||||
| import java.util.Set; | |||||
| import java.util.stream.Collector; | |||||
| import java.util.stream.Collectors; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.IntrospectionHelper; | import org.apache.tools.ant.IntrospectionHelper; | ||||
| @@ -122,8 +127,8 @@ public class AntStructure extends Task { | |||||
| printer.printTail(out); | printer.printTail(out); | ||||
| if (out.checkError()) { | if (out.checkError()) { | ||||
| throw new IOException("Encountered an error writing Ant" | |||||
| + " structure"); | |||||
| throw new IOException( | |||||
| "Encountered an error writing Ant structure"); | |||||
| } | } | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| throw new BuildException("Error writing " | throw new BuildException("Error writing " | ||||
| @@ -187,13 +192,15 @@ public class AntStructure extends Task { | |||||
| private final Hashtable<String, String> visited = new Hashtable<String, String>(); | private final Hashtable<String, String> visited = new Hashtable<String, String>(); | ||||
| @Override | |||||
| public void printTail(final PrintWriter out) { | public void printTail(final PrintWriter out) { | ||||
| visited.clear(); | visited.clear(); | ||||
| } | } | ||||
| @Override | |||||
| public void printHead(final PrintWriter out, final Project p, final Hashtable<String, Class<?>> tasks, | public void printHead(final PrintWriter out, final Project p, final Hashtable<String, Class<?>> tasks, | ||||
| final Hashtable<String, Class<?>> types) { | final Hashtable<String, Class<?>> types) { | ||||
| printHead(out, tasks.keys(), types.keys()); | |||||
| printHead(out, tasks.keySet(), types.keySet()); | |||||
| } | } | ||||
| @@ -203,36 +210,18 @@ public class AntStructure extends Task { | |||||
| * <p>Basically this prints the XML declaration, defines some | * <p>Basically this prints the XML declaration, defines some | ||||
| * entities and the project element.</p> | * entities and the project element.</p> | ||||
| */ | */ | ||||
| private void printHead(final PrintWriter out, final Enumeration<String> tasks, | |||||
| final Enumeration<String> types) { | |||||
| private void printHead(final PrintWriter out, final Set<String> tasks, | |||||
| final Set<String> types) { | |||||
| out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); | out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); | ||||
| out.println("<!ENTITY % boolean \"(true|false|on|off|yes|no)\">"); | out.println("<!ENTITY % boolean \"(true|false|on|off|yes|no)\">"); | ||||
| out.print("<!ENTITY % tasks \""); | |||||
| boolean first = true; | |||||
| while (tasks.hasMoreElements()) { | |||||
| final String tName = tasks.nextElement(); | |||||
| if (!first) { | |||||
| out.print(" | "); | |||||
| } else { | |||||
| first = false; | |||||
| } | |||||
| out.print(tName); | |||||
| } | |||||
| out.println("\">"); | |||||
| out.print("<!ENTITY % types \""); | |||||
| first = true; | |||||
| while (types.hasMoreElements()) { | |||||
| final String typeName = types.nextElement(); | |||||
| if (!first) { | |||||
| out.print(" | "); | |||||
| } else { | |||||
| first = false; | |||||
| } | |||||
| out.print(typeName); | |||||
| } | |||||
| out.println("\">"); | |||||
| out.println(tasks.stream().collect( | |||||
| Collectors.joining(" | ", "<!ENTITY % tasks \"", "\">"))); | |||||
| out.println(""); | |||||
| out.println(types.stream().collect( | |||||
| Collectors.joining(" | ", "<!ENTITY % types \"", "\">"))); | |||||
| out.println(); | |||||
| out.print("<!ELEMENT project (target | extension-point | "); | out.print("<!ELEMENT project (target | extension-point | "); | ||||
| out.print(TASKS); | out.print(TASKS); | ||||
| @@ -249,6 +238,7 @@ public class AntStructure extends Task { | |||||
| /** | /** | ||||
| * Prints the definition for the target element. | * Prints the definition for the target element. | ||||
| */ | */ | ||||
| @Override | |||||
| public void printTargetDecl(final PrintWriter out) { | public void printTargetDecl(final PrintWriter out) { | ||||
| out.print("<!ELEMENT target ("); | out.print("<!ELEMENT target ("); | ||||
| out.print(TASKS); | out.print(TASKS); | ||||
| @@ -282,6 +272,7 @@ public class AntStructure extends Task { | |||||
| /** | /** | ||||
| * Print the definition for a given element. | * Print the definition for a given element. | ||||
| */ | */ | ||||
| @Override | |||||
| public void printElementDecl(final PrintWriter out, final Project p, | public void printElementDecl(final PrintWriter out, final Project p, | ||||
| final String name, final Class<?> element) { | final String name, final Class<?> element) { | ||||
| @@ -290,7 +281,7 @@ public class AntStructure extends Task { | |||||
| } | } | ||||
| visited.put(name, ""); | visited.put(name, ""); | ||||
| IntrospectionHelper ih = null; | |||||
| IntrospectionHelper ih; | |||||
| try { | try { | ||||
| ih = IntrospectionHelper.getHelper(p, element); | ih = IntrospectionHelper.getHelper(p, element); | ||||
| } catch (final Throwable t) { | } catch (final Throwable t) { | ||||
| @@ -302,10 +293,10 @@ public class AntStructure extends Task { | |||||
| return; | return; | ||||
| } | } | ||||
| StringBuffer sb = new StringBuffer("<!ELEMENT "); | |||||
| sb.append(name).append(" "); | |||||
| StringBuilder sb = | |||||
| new StringBuilder("<!ELEMENT ").append(name).append(" "); | |||||
| if (org.apache.tools.ant.types.Reference.class.equals(element)) { | |||||
| if (Reference.class.equals(element)) { | |||||
| sb.append("EMPTY>").append(LINE_SEP); | sb.append("EMPTY>").append(LINE_SEP); | ||||
| sb.append("<!ATTLIST ").append(name); | sb.append("<!ATTLIST ").append(name); | ||||
| sb.append(LINE_SEP).append(" id ID #IMPLIED"); | sb.append(LINE_SEP).append(" id ID #IMPLIED"); | ||||
| @@ -315,40 +306,35 @@ public class AntStructure extends Task { | |||||
| return; | return; | ||||
| } | } | ||||
| final Vector<String> v = new Vector<String>(); | |||||
| final List<String> v = new ArrayList<>(); | |||||
| if (ih.supportsCharacters()) { | if (ih.supportsCharacters()) { | ||||
| v.addElement("#PCDATA"); | |||||
| v.add("#PCDATA"); | |||||
| } | } | ||||
| if (TaskContainer.class.isAssignableFrom(element)) { | if (TaskContainer.class.isAssignableFrom(element)) { | ||||
| v.addElement(TASKS); | |||||
| v.add(TASKS); | |||||
| } | } | ||||
| Enumeration<String> e = ih.getNestedElements(); | Enumeration<String> e = ih.getNestedElements(); | ||||
| while (e.hasMoreElements()) { | while (e.hasMoreElements()) { | ||||
| v.addElement(e.nextElement()); | |||||
| v.add(e.nextElement()); | |||||
| } | } | ||||
| final Collector<CharSequence, ?, String> joinAlts = | |||||
| Collectors.joining(" | ", "(", ")"); | |||||
| if (v.isEmpty()) { | if (v.isEmpty()) { | ||||
| sb.append("EMPTY"); | sb.append("EMPTY"); | ||||
| } else { | } else { | ||||
| sb.append("("); | |||||
| final int count = v.size(); | |||||
| for (int i = 0; i < count; i++) { | |||||
| if (i != 0) { | |||||
| sb.append(" | "); | |||||
| } | |||||
| sb.append(v.elementAt(i)); | |||||
| } | |||||
| sb.append(")"); | |||||
| if (count > 1 || !v.elementAt(0).equals("#PCDATA")) { | |||||
| sb.append(v.stream().collect(joinAlts)); | |||||
| if (v.size() > 1 || !"#PCDATA".equals(v.get(0))) { | |||||
| sb.append("*"); | sb.append("*"); | ||||
| } | } | ||||
| } | } | ||||
| sb.append(">"); | sb.append(">"); | ||||
| out.println(sb); | out.println(sb); | ||||
| sb = new StringBuffer("<!ATTLIST "); | |||||
| sb = new StringBuilder("<!ATTLIST "); | |||||
| sb.append(name); | sb.append(name); | ||||
| sb.append(LINE_SEP).append(" id ID #IMPLIED"); | sb.append(LINE_SEP).append(" id ID #IMPLIED"); | ||||
| @@ -362,29 +348,23 @@ public class AntStructure extends Task { | |||||
| sb.append(LINE_SEP).append(" ") | sb.append(LINE_SEP).append(" ") | ||||
| .append(attrName).append(" "); | .append(attrName).append(" "); | ||||
| final Class<?> type = ih.getAttributeType(attrName); | final Class<?> type = ih.getAttributeType(attrName); | ||||
| if (type.equals(java.lang.Boolean.class) | |||||
| || type.equals(java.lang.Boolean.TYPE)) { | |||||
| if (type.equals(Boolean.class) | |||||
| || type.equals(Boolean.TYPE)) { | |||||
| sb.append(BOOLEAN).append(" "); | sb.append(BOOLEAN).append(" "); | ||||
| } else if (Reference.class.isAssignableFrom(type)) { | } else if (Reference.class.isAssignableFrom(type)) { | ||||
| sb.append("IDREF "); | sb.append("IDREF "); | ||||
| } else if (EnumeratedAttribute.class.isAssignableFrom(type)) { | } else if (EnumeratedAttribute.class.isAssignableFrom(type)) { | ||||
| try { | try { | ||||
| final EnumeratedAttribute ea = | final EnumeratedAttribute ea = | ||||
| (EnumeratedAttribute) type.newInstance(); | |||||
| type.asSubclass(EnumeratedAttribute.class) | |||||
| .newInstance(); | |||||
| final String[] values = ea.getValues(); | final String[] values = ea.getValues(); | ||||
| if (values == null | if (values == null | ||||
| || values.length == 0 | || values.length == 0 | ||||
| || !areNmtokens(values)) { | || !areNmtokens(values)) { | ||||
| sb.append("CDATA "); | sb.append("CDATA "); | ||||
| } else { | } else { | ||||
| sb.append("("); | |||||
| for (int i = 0; i < values.length; i++) { | |||||
| if (i != 0) { | |||||
| sb.append(" | "); | |||||
| } | |||||
| sb.append(values[i]); | |||||
| } | |||||
| sb.append(") "); | |||||
| sb.append(Stream.of(values).collect(joinAlts)); | |||||
| } | } | ||||
| } catch (final InstantiationException ie) { | } catch (final InstantiationException ie) { | ||||
| sb.append("CDATA "); | sb.append("CDATA "); | ||||
| @@ -393,20 +373,13 @@ public class AntStructure extends Task { | |||||
| } | } | ||||
| } else if (Enum.class.isAssignableFrom(type)) { | } else if (Enum.class.isAssignableFrom(type)) { | ||||
| try { | try { | ||||
| final Object[] values = (Object[]) type.getMethod("values", (Class[]) null) | |||||
| .invoke(null, (Object[]) null); | |||||
| final Enum<?>[] values = | |||||
| (Enum<?>[]) type.getMethod("values").invoke(null); | |||||
| if (values.length == 0) { | if (values.length == 0) { | ||||
| sb.append("CDATA "); | sb.append("CDATA "); | ||||
| } else { | } else { | ||||
| sb.append('('); | |||||
| for (int i = 0; i < values.length; i++) { | |||||
| if (i != 0) { | |||||
| sb.append(" | "); | |||||
| } | |||||
| sb.append(type.getMethod("name", (Class[]) null) | |||||
| .invoke(values[i], (Object[]) null)); | |||||
| } | |||||
| sb.append(") "); | |||||
| sb.append(Stream.of(values).map(Enum::name) | |||||
| .collect(joinAlts)); | |||||
| } | } | ||||
| } catch (final Exception x) { | } catch (final Exception x) { | ||||
| sb.append("CDATA "); | sb.append("CDATA "); | ||||
| @@ -419,9 +392,7 @@ public class AntStructure extends Task { | |||||
| sb.append(">").append(LINE_SEP); | sb.append(">").append(LINE_SEP); | ||||
| out.println(sb); | out.println(sb); | ||||
| final int count = v.size(); | |||||
| for (int i = 0; i < count; i++) { | |||||
| final String nestedName = v.elementAt(i); | |||||
| for (String nestedName : v) { | |||||
| if (!"#PCDATA".equals(nestedName) | if (!"#PCDATA".equals(nestedName) | ||||
| && !TASKS.equals(nestedName) | && !TASKS.equals(nestedName) | ||||
| && !TYPES.equals(nestedName)) { | && !TYPES.equals(nestedName)) { | ||||
| @@ -22,9 +22,7 @@ import java.io.IOException; | |||||
| import java.net.URL; | import java.net.URL; | ||||
| import java.net.URLConnection; | import java.net.URLConnection; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Iterator; | |||||
| import java.util.List; | import java.util.List; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.ComponentHelper; | import org.apache.tools.ant.ComponentHelper; | ||||
| import org.apache.tools.ant.Project; | import org.apache.tools.ant.Project; | ||||
| @@ -94,7 +92,7 @@ public class Antlib extends Task implements TaskContainer { | |||||
| UnknownElement ue = | UnknownElement ue = | ||||
| parser.parseAntlibDescriptor(project, antlibResource); | parser.parseAntlibDescriptor(project, antlibResource); | ||||
| // Check name is "antlib" | // Check name is "antlib" | ||||
| if (!(ue.getTag().equals(TAG))) { | |||||
| if (!(TAG.equals(ue.getTag()))) { | |||||
| throw new BuildException( | throw new BuildException( | ||||
| "Unexpected tag " + ue.getTag() + " expecting " | "Unexpected tag " + ue.getTag() + " expecting " | ||||
| + TAG, ue.getLocation()); | + TAG, ue.getLocation()); | ||||
| @@ -116,7 +114,7 @@ public class Antlib extends Task implements TaskContainer { | |||||
| // | // | ||||
| private ClassLoader classLoader; | private ClassLoader classLoader; | ||||
| private String uri = ""; | private String uri = ""; | ||||
| private List<Object> tasks = new ArrayList<Object>(); | |||||
| private List<Task> tasks = new ArrayList<>(); | |||||
| /** | /** | ||||
| * Set the class loader for this antlib. | * Set the class loader for this antlib. | ||||
| @@ -149,6 +147,7 @@ public class Antlib extends Task implements TaskContainer { | |||||
| * | * | ||||
| * @param nestedTask Nested task to execute in antlib | * @param nestedTask Nested task to execute in antlib | ||||
| */ | */ | ||||
| @Override | |||||
| public void addTask(Task nestedTask) { | public void addTask(Task nestedTask) { | ||||
| tasks.add(nestedTask); | tasks.add(nestedTask); | ||||
| } | } | ||||
| @@ -157,10 +156,12 @@ public class Antlib extends Task implements TaskContainer { | |||||
| * Execute the nested tasks, setting the classloader for | * Execute the nested tasks, setting the classloader for | ||||
| * any tasks that derive from Definer. | * any tasks that derive from Definer. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() { | public void execute() { | ||||
| //TODO handle tasks added via #addTask() | //TODO handle tasks added via #addTask() | ||||
| for (Iterator<Object> i = tasks.iterator(); i.hasNext();) { | |||||
| UnknownElement ue = (UnknownElement) i.next(); | |||||
| for (Task task : tasks) { | |||||
| UnknownElement ue = (UnknownElement) task; | |||||
| setLocation(ue.getLocation()); | setLocation(ue.getLocation()); | ||||
| ue.maybeConfigure(); | ue.maybeConfigure(); | ||||
| Object configuredObject = ue.getRealThing(); | Object configuredObject = ue.getRealThing(); | ||||
| @@ -169,9 +170,9 @@ public class Antlib extends Task implements TaskContainer { | |||||
| } | } | ||||
| if (!(configuredObject instanceof AntlibDefinition)) { | if (!(configuredObject instanceof AntlibDefinition)) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Invalid task in antlib " + ue.getTag() | |||||
| + " " + configuredObject.getClass() + " does not " | |||||
| + "extend org.apache.tools.ant.taskdefs.AntlibDefinition"); | |||||
| "Invalid task in antlib %s %s does not extend %s", | |||||
| ue.getTag(), configuredObject.getClass(), | |||||
| AntlibDefinition.class.getName()); | |||||
| } | } | ||||
| AntlibDefinition def = (AntlibDefinition) configuredObject; | AntlibDefinition def = (AntlibDefinition) configuredObject; | ||||
| def.setURI(uri); | def.setURI(uri); | ||||
| @@ -44,11 +44,11 @@ public class AntlibDefinition extends Task { | |||||
| * @throws BuildException if a reserved URI is used | * @throws BuildException if a reserved URI is used | ||||
| */ | */ | ||||
| public void setURI(String uri) throws BuildException { | public void setURI(String uri) throws BuildException { | ||||
| if (uri.equals(ProjectHelper.ANT_CORE_URI)) { | |||||
| if (ProjectHelper.ANT_CORE_URI.equals(uri)) { | |||||
| uri = ""; | uri = ""; | ||||
| } | } | ||||
| if (uri.startsWith("ant:")) { | if (uri.startsWith("ant:")) { | ||||
| throw new BuildException("Attempt to use a reserved URI " + uri); | |||||
| throw new BuildException("Attempt to use a reserved URI %s", uri); | |||||
| } | } | ||||
| this.uri = uri; | this.uri = uri; | ||||
| } | } | ||||
| @@ -193,9 +193,9 @@ public class Available extends Task implements Condition { | |||||
| * the type in its own class. | * the type in its own class. | ||||
| * @param type the type of resource | * @param type the type of resource | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setType(String type) { | public void setType(String type) { | ||||
| log("DEPRECATED - The setType(String) method has been deprecated." | |||||
| + " Use setType(Available.FileDir) instead.", | |||||
| log("DEPRECATED - The setType(String) method has been deprecated. Use setType(Available.FileDir) instead.", | |||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| this.type = new FileDir(); | this.type = new FileDir(); | ||||
| this.type.setValue(type); | this.type.setValue(type); | ||||
| @@ -227,6 +227,7 @@ public class Available extends Task implements Condition { | |||||
| * | * | ||||
| * @exception BuildException if the task is not configured correctly. | * @exception BuildException if the task is not configured correctly. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (property == null) { | if (property == null) { | ||||
| throw new BuildException("property attribute is required", | throw new BuildException("property attribute is required", | ||||
| @@ -261,17 +262,19 @@ public class Available extends Task implements Condition { | |||||
| * @return boolean is the resource is available. | * @return boolean is the resource is available. | ||||
| * @exception BuildException if the condition is not configured correctly | * @exception BuildException if the condition is not configured correctly | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean eval() throws BuildException { | public boolean eval() throws BuildException { | ||||
| try { | try { | ||||
| if (classname == null && file == null && resource == null) { | if (classname == null && file == null && resource == null) { | ||||
| throw new BuildException("At least one of (classname|file|" | |||||
| + "resource) is required", getLocation()); | |||||
| throw new BuildException( | |||||
| "At least one of (classname|file|resource) is required", | |||||
| getLocation()); | |||||
| } | } | ||||
| if (type != null) { | if (type != null) { | ||||
| if (file == null) { | if (file == null) { | ||||
| throw new BuildException("The type attribute is only valid " | |||||
| + "when specifying the file " | |||||
| + "attribute.", getLocation()); | |||||
| throw new BuildException( | |||||
| "The type attribute is only valid when specifying the file attribute.", | |||||
| getLocation()); | |||||
| } | } | ||||
| } | } | ||||
| if (classpath != null) { | if (classpath != null) { | ||||
| @@ -284,13 +287,13 @@ public class Available extends Task implements Condition { | |||||
| } else { | } else { | ||||
| setTaskName("available"); | setTaskName("available"); | ||||
| } | } | ||||
| if ((classname != null) && !checkClass(classname)) { | |||||
| if (!(classname == null || checkClass(classname))) { | |||||
| log("Unable to load class " + classname + appendix, | log("Unable to load class " + classname + appendix, | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| return false; | return false; | ||||
| } | } | ||||
| if ((file != null) && !checkFile()) { | if ((file != null) && !checkFile()) { | ||||
| StringBuffer buf = new StringBuffer("Unable to find "); | |||||
| StringBuilder buf = new StringBuilder("Unable to find "); | |||||
| if (type != null) { | if (type != null) { | ||||
| buf.append(type).append(' '); | buf.append(type).append(' '); | ||||
| } | } | ||||
| @@ -334,62 +337,64 @@ public class Available extends Task implements Condition { | |||||
| private boolean checkFile() { | private boolean checkFile() { | ||||
| if (filepath == null) { | if (filepath == null) { | ||||
| return checkFile(file, filename); | return checkFile(file, filename); | ||||
| } else { | |||||
| String[] paths = filepath.list(); | |||||
| for (int i = 0; i < paths.length; ++i) { | |||||
| log("Searching " + paths[i], Project.MSG_VERBOSE); | |||||
| File path = new File(paths[i]); | |||||
| // ** full-pathname specified == path in list | |||||
| // ** simple name specified == path in list | |||||
| if (path.exists() | |||||
| && (filename.equals(paths[i]) | |||||
| || filename.equals(path.getName()))) { | |||||
| if (type == null) { | |||||
| log("Found: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } else if (type.isDir() | |||||
| && path.isDirectory()) { | |||||
| log("Found directory: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } else if (type.isFile() | |||||
| && path.isFile()) { | |||||
| log("Found file: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | |||||
| // not the requested type | |||||
| return false; | |||||
| } | |||||
| String[] paths = filepath.list(); | |||||
| for (String p : paths) { | |||||
| log("Searching " + p, Project.MSG_VERBOSE); | |||||
| File path = new File(p); | |||||
| // ** full-pathname specified == path in list | |||||
| // ** simple name specified == path in list | |||||
| if (path.exists() | |||||
| && (filename.equals(p) | |||||
| || filename.equals(path.getName()))) { | |||||
| if (type == null) { | |||||
| log("Found: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | } | ||||
| File parent = path.getParentFile(); | |||||
| // ** full-pathname specified == parent dir of path in list | |||||
| if (parent != null && parent.exists() | |||||
| && filename.equals(parent.getAbsolutePath())) { | |||||
| if (type == null) { | |||||
| log("Found: " + parent, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } else if (type.isDir()) { | |||||
| log("Found directory: " + parent, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | |||||
| // not the requested type | |||||
| return false; | |||||
| if (type.isDir() | |||||
| && path.isDirectory()) { | |||||
| log("Found directory: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | } | ||||
| // ** simple name specified == path in list + name | |||||
| if (path.exists() && path.isDirectory()) { | |||||
| if (checkFile(new File(path, filename), | |||||
| filename + " in " + path)) { | |||||
| return true; | |||||
| } | |||||
| if (type.isFile() | |||||
| && path.isFile()) { | |||||
| log("Found file: " + path, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | } | ||||
| // not the requested type | |||||
| return false; | |||||
| } | |||||
| File parent = path.getParentFile(); | |||||
| // ** full-pathname specified == parent dir of path in list | |||||
| if (parent != null && parent.exists() | |||||
| && filename.equals(parent.getAbsolutePath())) { | |||||
| if (type == null) { | |||||
| log("Found: " + parent, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | |||||
| if (type.isDir()) { | |||||
| log("Found directory: " + parent, Project.MSG_VERBOSE); | |||||
| return true; | |||||
| } | |||||
| // not the requested type | |||||
| return false; | |||||
| } | |||||
| // ** simple name specified == path in list + name | |||||
| if (path.exists() && path.isDirectory()) { | |||||
| if (checkFile(new File(path, filename), | |||||
| filename + " in " + path)) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| // ** simple name specified == parent dir + name | |||||
| while (searchParents && parent != null && parent.exists()) { | |||||
| if (checkFile(new File(parent, filename), | |||||
| filename + " in " + parent)) { | |||||
| return true; | |||||
| } | |||||
| parent = parent.getParentFile(); | |||||
| // ** simple name specified == parent dir + name | |||||
| while (searchParents && parent != null && parent.exists()) { | |||||
| if (checkFile(new File(parent, filename), | |||||
| filename + " in " + parent)) { | |||||
| return true; | |||||
| } | } | ||||
| parent = parent.getParentFile(); | |||||
| } | } | ||||
| } | } | ||||
| return false; | return false; | ||||
| @@ -405,7 +410,8 @@ public class Available extends Task implements Condition { | |||||
| log("Found directory: " + text, Project.MSG_VERBOSE); | log("Found directory: " + text, Project.MSG_VERBOSE); | ||||
| } | } | ||||
| return f.isDirectory(); | return f.isDirectory(); | ||||
| } else if (type.isFile()) { | |||||
| } | |||||
| if (type.isFile()) { | |||||
| if (f.isFile()) { | if (f.isFile()) { | ||||
| log("Found file: " + text, Project.MSG_VERBOSE); | log("Found file: " + text, Project.MSG_VERBOSE); | ||||
| } | } | ||||
| @@ -488,12 +494,13 @@ public class Available extends Task implements Condition { | |||||
| */ | */ | ||||
| public static class FileDir extends EnumeratedAttribute { | public static class FileDir extends EnumeratedAttribute { | ||||
| private static final String[] VALUES = {"file", "dir"}; | |||||
| private static final String[] VALUES = { "file", "dir" }; | |||||
| /** | /** | ||||
| * @see EnumeratedAttribute#getValues | * @see EnumeratedAttribute#getValues | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return VALUES; | return VALUES; | ||||
| } | } | ||||
| @@ -85,6 +85,7 @@ public class Basename extends Task { | |||||
| * @throws BuildException if required attributes are not supplied | * @throws BuildException if required attributes are not supplied | ||||
| * property and attribute are required attributes | * property and attribute are required attributes | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (property == null) { | if (property == null) { | ||||
| throw new BuildException("property attribute required", getLocation()); | throw new BuildException("property attribute required", getLocation()); | ||||
| @@ -92,19 +93,21 @@ public class Basename extends Task { | |||||
| if (file == null) { | if (file == null) { | ||||
| throw new BuildException("file attribute required", getLocation()); | throw new BuildException("file attribute required", getLocation()); | ||||
| } | } | ||||
| String value = file.getName(); | |||||
| if (suffix != null && value.endsWith(suffix)) { | |||||
| // if the suffix does not starts with a '.' and the | |||||
| // char preceding the suffix is a '.', we assume the user | |||||
| // wants to remove the '.' as well (see docs) | |||||
| int pos = value.length() - suffix.length(); | |||||
| if (pos > 0 && suffix.charAt(0) != '.' | |||||
| && value.charAt(pos - 1) == '.') { | |||||
| pos--; | |||||
| } | |||||
| value = value.substring(0, pos); | |||||
| getProject().setNewProperty(property, | |||||
| removeExtension(file.getName(), suffix)); | |||||
| } | |||||
| private String removeExtension(String s, String ext) { | |||||
| if (ext == null || !s.endsWith(ext)) { | |||||
| return s; | |||||
| } | } | ||||
| getProject().setNewProperty(property, value); | |||||
| int clipFrom = s.length() - ext.length(); | |||||
| // if the suffix does not starts with a '.' and the | |||||
| // char preceding the suffix is a '.', we assume the user | |||||
| // wants to remove the '.' as well (see docs) | |||||
| if (ext.charAt(0) != '.' && clipFrom > 0 && s.charAt(clipFrom - 1) == '.') { | |||||
| clipFrom -= 1; | |||||
| } | |||||
| return s.substring(0, clipFrom); | |||||
| } | } | ||||
| } | } | ||||
| @@ -18,8 +18,8 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Iterator; | |||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.ProjectHelper; | import org.apache.tools.ant.ProjectHelper; | ||||
| @@ -54,13 +54,8 @@ public class BindTargets extends Task { | |||||
| } | } | ||||
| public void setTargets(final String target) { | public void setTargets(final String target) { | ||||
| final String[] inputs = target.split(","); | |||||
| for (int i = 0; i < inputs.length; i++) { | |||||
| final String input = inputs[i].trim(); | |||||
| if (input.length() > 0) { | |||||
| targets.add(input); | |||||
| } | |||||
| } | |||||
| Stream.of(target.split(",")).map(String::trim).filter(s -> !s.isEmpty()) | |||||
| .forEach(targets::add); | |||||
| } | } | ||||
| @Override | @Override | ||||
| @@ -81,11 +76,9 @@ public class BindTargets extends Task { | |||||
| final ProjectHelper helper = (ProjectHelper) getProject().getReference( | final ProjectHelper helper = (ProjectHelper) getProject().getReference( | ||||
| ProjectHelper.PROJECTHELPER_REFERENCE); | ProjectHelper.PROJECTHELPER_REFERENCE); | ||||
| for (final Iterator<String> itTarget = targets.iterator(); itTarget.hasNext();) { | |||||
| helper.getExtensionStack().add( | |||||
| new String[] {extensionPoint, itTarget.next(), | |||||
| onMissingExtensionPoint.name()}); | |||||
| for (String target : targets) { | |||||
| helper.getExtensionStack().add(new String[] { extensionPoint, | |||||
| target, onMissingExtensionPoint.name() }); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -25,7 +25,6 @@ import java.nio.file.Files; | |||||
| import java.util.Properties; | import java.util.Properties; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.Project; | |||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| import org.apache.tools.ant.util.FileUtils; | import org.apache.tools.ant.util.FileUtils; | ||||
| @@ -40,8 +39,7 @@ import org.apache.tools.ant.util.FileUtils; | |||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| * @ant.task name="buildnumber" | * @ant.task name="buildnumber" | ||||
| */ | */ | ||||
| public class BuildNumber | |||||
| extends Task { | |||||
| public class BuildNumber extends Task { | |||||
| /** | /** | ||||
| * The name of the property in which the build number is stored. | * The name of the property in which the build number is stored. | ||||
| */ | */ | ||||
| @@ -55,7 +53,6 @@ public class BuildNumber | |||||
| /** The File in which the build number is stored. */ | /** The File in which the build number is stored. */ | ||||
| private File myFile; | private File myFile; | ||||
| /** | /** | ||||
| * The file in which the build number is stored. Defaults to | * The file in which the build number is stored. Defaults to | ||||
| * "build.number" if not specified. | * "build.number" if not specified. | ||||
| @@ -66,14 +63,13 @@ public class BuildNumber | |||||
| myFile = file; | myFile = file; | ||||
| } | } | ||||
| /** | /** | ||||
| * Run task. | * Run task. | ||||
| * | * | ||||
| * @exception BuildException if an error occurs | * @exception BuildException if an error occurs | ||||
| */ | */ | ||||
| public void execute() | |||||
| throws BuildException { | |||||
| @Override | |||||
| public void execute() throws BuildException { | |||||
| File savedFile = myFile; // may be altered in validate | File savedFile = myFile; // may be altered in validate | ||||
| validate(); | validate(); | ||||
| @@ -85,26 +81,12 @@ public class BuildNumber | |||||
| String.valueOf(buildNumber + 1)); | String.valueOf(buildNumber + 1)); | ||||
| // Write the properties file back out | // Write the properties file back out | ||||
| OutputStream output = null; | |||||
| try { | |||||
| output = Files.newOutputStream(myFile.toPath()); | |||||
| final String header = "Build Number for ANT. Do not edit!"; | |||||
| properties.store(output, header); | |||||
| try (OutputStream output = Files.newOutputStream(myFile.toPath())) { | |||||
| properties.store(output, "Build Number for ANT. Do not edit!"); | |||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| final String message = "Error while writing " + myFile; | |||||
| throw new BuildException(message, ioe); | |||||
| throw new BuildException("Error while writing " + myFile, ioe); | |||||
| } finally { | } finally { | ||||
| if (null != output) { | |||||
| try { | |||||
| output.close(); | |||||
| } catch (final IOException ioe) { | |||||
| log("error closing output stream " + ioe, Project.MSG_ERR); | |||||
| } | |||||
| } | |||||
| myFile = savedFile; | myFile = savedFile; | ||||
| } | } | ||||
| @@ -113,7 +95,6 @@ public class BuildNumber | |||||
| String.valueOf(buildNumber)); | String.valueOf(buildNumber)); | ||||
| } | } | ||||
| /** | /** | ||||
| * Utility method to retrieve build number from properties object. | * Utility method to retrieve build number from properties object. | ||||
| * | * | ||||
| @@ -130,43 +111,28 @@ public class BuildNumber | |||||
| try { | try { | ||||
| return Integer.parseInt(buildNumber); | return Integer.parseInt(buildNumber); | ||||
| } catch (final NumberFormatException nfe) { | } catch (final NumberFormatException nfe) { | ||||
| final String message = | |||||
| myFile + " contains a non integer build number: " + buildNumber; | |||||
| throw new BuildException(message, nfe); | |||||
| throw new BuildException( | |||||
| myFile + " contains a non integer build number: " + buildNumber, | |||||
| nfe); | |||||
| } | } | ||||
| } | } | ||||
| /** | /** | ||||
| * Utility method to load properties from file. | * Utility method to load properties from file. | ||||
| * | * | ||||
| * @return the loaded properties | * @return the loaded properties | ||||
| * @throws BuildException | * @throws BuildException | ||||
| */ | */ | ||||
| private Properties loadProperties() | |||||
| throws BuildException { | |||||
| InputStream input = null; | |||||
| try { | |||||
| private Properties loadProperties() throws BuildException { | |||||
| try (InputStream input = Files.newInputStream(myFile.toPath())) { | |||||
| final Properties properties = new Properties(); | final Properties properties = new Properties(); | ||||
| input = Files.newInputStream(myFile.toPath()); | |||||
| properties.load(input); | properties.load(input); | ||||
| return properties; | return properties; | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| throw new BuildException(ioe); | throw new BuildException(ioe); | ||||
| } finally { | |||||
| if (null != input) { | |||||
| try { | |||||
| input.close(); | |||||
| } catch (final IOException ioe) { | |||||
| log("error closing input stream " + ioe, Project.MSG_ERR); | |||||
| } | |||||
| } | |||||
| } | } | ||||
| } | } | ||||
| /** | /** | ||||
| * Validate that the task parameters are valid. | * Validate that the task parameters are valid. | ||||
| * | * | ||||
| @@ -182,21 +148,18 @@ public class BuildNumber | |||||
| try { | try { | ||||
| FILE_UTILS.createNewFile(myFile); | FILE_UTILS.createNewFile(myFile); | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| final String message = | |||||
| myFile + " doesn't exist and new file can't be created."; | |||||
| throw new BuildException(message, ioe); | |||||
| throw new BuildException( | |||||
| myFile + " doesn't exist and new file can't be created.", | |||||
| ioe); | |||||
| } | } | ||||
| } | } | ||||
| if (!myFile.canRead()) { | if (!myFile.canRead()) { | ||||
| final String message = "Unable to read from " + myFile + "."; | |||||
| throw new BuildException(message); | |||||
| throw new BuildException("Unable to read from " + myFile + "."); | |||||
| } | } | ||||
| if (!myFile.canWrite()) { | if (!myFile.canWrite()) { | ||||
| final String message = "Unable to write to " + myFile + "."; | |||||
| throw new BuildException(message); | |||||
| throw new BuildException("Unable to write to " + myFile + "."); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -82,6 +82,7 @@ public class CVSPass extends Task { | |||||
| * | * | ||||
| * @exception BuildException if something goes wrong with the build | * @exception BuildException if something goes wrong with the build | ||||
| */ | */ | ||||
| @Override | |||||
| public final void execute() throws BuildException { | public final void execute() throws BuildException { | ||||
| if (cvsRoot == null) { | if (cvsRoot == null) { | ||||
| throw new BuildException("cvsroot is required"); | throw new BuildException("cvsroot is required"); | ||||
| @@ -97,7 +98,7 @@ public class CVSPass extends Task { | |||||
| BufferedReader reader = null; | BufferedReader reader = null; | ||||
| BufferedWriter writer = null; | BufferedWriter writer = null; | ||||
| try { | try { | ||||
| StringBuffer buf = new StringBuffer(); | |||||
| StringBuilder buf = new StringBuilder(); | |||||
| if (passFile.exists()) { | if (passFile.exists()) { | ||||
| reader = new BufferedReader(new FileReader(passFile)); | reader = new BufferedReader(new FileReader(passFile)); | ||||
| @@ -129,7 +130,7 @@ public class CVSPass extends Task { | |||||
| } | } | ||||
| private final String mangle(String password) { | private final String mangle(String password) { | ||||
| StringBuffer buf = new StringBuffer(); | |||||
| StringBuilder buf = new StringBuilder(); | |||||
| for (int i = 0; i < password.length(); i++) { | for (int i = 0; i < password.length(); i++) { | ||||
| buf.append(shifts[password.charAt(i)]); | buf.append(shifts[password.charAt(i)]); | ||||
| } | } | ||||
| @@ -71,6 +71,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| super.add(u); | super.add(u); | ||||
| super.add(Type.FILE); | super.add(Type.FILE); | ||||
| } | } | ||||
| @Override | |||||
| public void add(ResourceCollection rc) { | public void add(ResourceCollection rc) { | ||||
| u.add(rc); | u.add(rc); | ||||
| } | } | ||||
| @@ -110,14 +111,14 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * Key: java.util.File (source file) | * Key: java.util.File (source file) | ||||
| * Value: java.lang.String (digest) | * Value: java.lang.String (digest) | ||||
| */ | */ | ||||
| private Map<File, byte[]> allDigests = new HashMap<File, byte[]>(); | |||||
| private Map<File, byte[]> allDigests = new HashMap<>(); | |||||
| /** | /** | ||||
| * Holds relative file names for all files (always with a forward slash). | * Holds relative file names for all files (always with a forward slash). | ||||
| * This is used to calculate the total hash. | * This is used to calculate the total hash. | ||||
| * Key: java.util.File (source file) | * Key: java.util.File (source file) | ||||
| * Value: java.lang.String (relative file name) | * Value: java.lang.String (relative file name) | ||||
| */ | */ | ||||
| private Map<File, String> relativeFilePaths = new HashMap<File, String>(); | |||||
| private Map<File, String> relativeFilePaths = new HashMap<>(); | |||||
| /** | /** | ||||
| * Property where totalChecksum gets set. | * Property where totalChecksum gets set. | ||||
| */ | */ | ||||
| @@ -138,7 +139,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| /** | /** | ||||
| * Stores SourceFile, DestFile pairs and SourceFile, Property String pairs. | * Stores SourceFile, DestFile pairs and SourceFile, Property String pairs. | ||||
| */ | */ | ||||
| private Hashtable<File, Object> includeFileMap = new Hashtable<File, Object>(); | |||||
| private Hashtable<File, Object> includeFileMap = new Hashtable<>(); | |||||
| /** | /** | ||||
| * Message Digest instance | * Message Digest instance | ||||
| */ | */ | ||||
| @@ -294,13 +295,13 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * Calculate the checksum(s). | * Calculate the checksum(s). | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| isCondition = false; | isCondition = false; | ||||
| boolean value = validateAndExecute(); | boolean value = validateAndExecute(); | ||||
| if (verifyProperty != null) { | if (verifyProperty != null) { | ||||
| getProject().setNewProperty( | |||||
| verifyProperty, | |||||
| (value ? Boolean.TRUE.toString() : Boolean.FALSE.toString())); | |||||
| getProject().setNewProperty(verifyProperty, | |||||
| Boolean.toString(value)); | |||||
| } | } | ||||
| } | } | ||||
| @@ -311,6 +312,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * false otherwise. | * false otherwise. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean eval() throws BuildException { | public boolean eval() throws BuildException { | ||||
| isCondition = true; | isCondition = true; | ||||
| return validateAndExecute(); | return validateAndExecute(); | ||||
| @@ -386,7 +388,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| } | } | ||||
| if (fileext == null) { | if (fileext == null) { | ||||
| fileext = "." + algorithm; | fileext = "." + algorithm; | ||||
| } else if (fileext.trim().length() == 0) { | |||||
| } else if (fileext.trim().isEmpty()) { | |||||
| throw new BuildException("File extension when specified must not be an empty string"); | throw new BuildException("File extension when specified must not be an empty string"); | ||||
| } | } | ||||
| try { | try { | ||||
| @@ -463,8 +465,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| // This directory will exist | // This directory will exist | ||||
| directory = file.getParentFile(); | directory = file.getParentFile(); | ||||
| } | } | ||||
| File checksumFile = new File(directory, file.getName() + fileext); | |||||
| return checksumFile; | |||||
| return new File(directory, file.getName() + fileext); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -498,7 +499,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| String checksum = createDigestString(fileDigest); | String checksum = createDigestString(fileDigest); | ||||
| //can either be a property name string or a file | //can either be a property name string or a file | ||||
| Object destination = e.getValue(); | Object destination = e.getValue(); | ||||
| if (destination instanceof java.lang.String) { | |||||
| if (destination instanceof String) { | |||||
| String prop = (String) destination; | String prop = (String) destination; | ||||
| if (isCondition) { | if (isCondition) { | ||||
| checksumMatches | checksumMatches | ||||
| @@ -506,7 +507,7 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| } else { | } else { | ||||
| getProject().setNewProperty(prop, checksum); | getProject().setNewProperty(prop, checksum); | ||||
| } | } | ||||
| } else if (destination instanceof java.io.File) { | |||||
| } else if (destination instanceof File) { | |||||
| if (isCondition) { | if (isCondition) { | ||||
| File existingFile = (File) destination; | File existingFile = (File) destination; | ||||
| if (existingFile.exists()) { | if (existingFile.exists()) { | ||||
| @@ -550,14 +551,9 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| File[] keyArray = allDigests.keySet().toArray(new File[allDigests.size()]); | File[] keyArray = allDigests.keySet().toArray(new File[allDigests.size()]); | ||||
| // File is Comparable, but sort-order is platform | // File is Comparable, but sort-order is platform | ||||
| // dependent (case-insensitive on Windows) | // dependent (case-insensitive on Windows) | ||||
| Arrays.sort(keyArray, new Comparator<File>() { | |||||
| public int compare(File f1, File f2) { | |||||
| return f1 == null ? (f2 == null ? 0 : -1) | |||||
| : (f2 == null ? 1 | |||||
| : getRelativeFilePath(f1) | |||||
| .compareTo(getRelativeFilePath(f2))); | |||||
| } | |||||
| }); | |||||
| Arrays.sort(keyArray, Comparator.nullsFirst( | |||||
| Comparator.comparing(this::getRelativeFilePath))); | |||||
| // Loop over the checksums and generate a total hash. | // Loop over the checksums and generate a total hash. | ||||
| messageDigest.reset(); | messageDigest.reset(); | ||||
| for (File src : keyArray) { | for (File src : keyArray) { | ||||
| @@ -582,11 +578,11 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| } | } | ||||
| private String createDigestString(byte[] fileDigest) { | private String createDigestString(byte[] fileDigest) { | ||||
| StringBuffer checksumSb = new StringBuffer(); | |||||
| StringBuilder checksumSb = new StringBuilder(); | |||||
| for (int i = 0; i < fileDigest.length; i++) { | for (int i = 0; i < fileDigest.length; i++) { | ||||
| String hexStr = Integer.toHexString(BYTE_MASK & fileDigest[i]); | String hexStr = Integer.toHexString(BYTE_MASK & fileDigest[i]); | ||||
| if (hexStr.length() < 2) { | if (hexStr.length() < 2) { | ||||
| checksumSb.append("0"); | |||||
| checksumSb.append('0'); | |||||
| } | } | ||||
| checksumSb.append(hexStr); | checksumSb.append(hexStr); | ||||
| } | } | ||||
| @@ -630,20 +626,15 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * @since 1.7 | * @since 1.7 | ||||
| */ | */ | ||||
| private String readChecksum(File f) { | private String readChecksum(File f) { | ||||
| BufferedReader diskChecksumReader = null; | |||||
| try { | |||||
| diskChecksumReader = new BufferedReader(new FileReader(f)); | |||||
| try (BufferedReader diskChecksumReader = | |||||
| new BufferedReader(new FileReader(f))) { | |||||
| Object[] result = format.parse(diskChecksumReader.readLine()); | Object[] result = format.parse(diskChecksumReader.readLine()); | ||||
| if (result == null || result.length == 0 || result[0] == null) { | if (result == null || result.length == 0 || result[0] == null) { | ||||
| throw new BuildException("failed to find a checksum"); | throw new BuildException("failed to find a checksum"); | ||||
| } | } | ||||
| return (String) result[0]; | return (String) result[0]; | ||||
| } catch (IOException e) { | |||||
| throw new BuildException("Couldn't read checksum file " + f, e); | |||||
| } catch (ParseException e) { | |||||
| } catch (IOException | ParseException e) { | |||||
| throw new BuildException("Couldn't read checksum file " + f, e); | throw new BuildException("Couldn't read checksum file " + f, e); | ||||
| } finally { | |||||
| FileUtils.close(diskChecksumReader); | |||||
| } | } | ||||
| } | } | ||||
| @@ -651,13 +642,12 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * @since Ant 1.8.2 | * @since Ant 1.8.2 | ||||
| */ | */ | ||||
| private String getRelativeFilePath(File f) { | private String getRelativeFilePath(File f) { | ||||
| String path = (String) relativeFilePaths.get(f); | |||||
| String path = relativeFilePaths.get(f); | |||||
| if (path == null) { | if (path == null) { | ||||
| //bug 37386. this should not occur, but it has, once. | //bug 37386. this should not occur, but it has, once. | ||||
| throw new BuildException("Internal error: " | |||||
| + "relativeFilePaths could not match file " | |||||
| + f + "\n" | |||||
| + "please file a bug report on this"); | |||||
| throw new BuildException( | |||||
| "Internal error: relativeFilePaths could not match file %s\nplease file a bug report on this", | |||||
| f); | |||||
| } | } | ||||
| return path; | return path; | ||||
| } | } | ||||
| @@ -679,11 +669,6 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| formatMap.put(SVF, new MessageFormat("MD5 ({1}) = {0}")); | formatMap.put(SVF, new MessageFormat("MD5 ({1}) = {0}")); | ||||
| } | } | ||||
| /** Constructor for FormatElement */ | |||||
| public FormatElement() { | |||||
| super(); | |||||
| } | |||||
| /** | /** | ||||
| * Get the default value - CHECKSUM. | * Get the default value - CHECKSUM. | ||||
| * @return the defaul value. | * @return the defaul value. | ||||
| @@ -699,15 +684,16 @@ public class Checksum extends MatchingTask implements Condition { | |||||
| * @return a <code>MessageFormat</code> object. | * @return a <code>MessageFormat</code> object. | ||||
| */ | */ | ||||
| public MessageFormat getFormat() { | public MessageFormat getFormat() { | ||||
| return (MessageFormat) formatMap.get(getValue()); | |||||
| return formatMap.get(getValue()); | |||||
| } | } | ||||
| /** | /** | ||||
| * Get the valid values. | * Get the valid values. | ||||
| * @return an array of values. | * @return an array of values. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {CHECKSUM, MD5SUM, SVF}; | |||||
| return new String[] { CHECKSUM, MD5SUM, SVF }; | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -58,6 +58,7 @@ public class Chmod extends ExecuteOn { | |||||
| * @param project the project for this task. | * @param project the project for this task. | ||||
| * @see org.apache.tools.ant.ProjectComponent#setProject | * @see org.apache.tools.ant.ProjectComponent#setProject | ||||
| */ | */ | ||||
| @Override | |||||
| public void setProject(Project project) { | public void setProject(Project project) { | ||||
| super.setProject(project); | super.setProject(project); | ||||
| defaultSet.setProject(project); | defaultSet.setProject(project); | ||||
| @@ -77,6 +78,7 @@ public class Chmod extends ExecuteOn { | |||||
| * The directory which holds the files whose permissions must be changed. | * The directory which holds the files whose permissions must be changed. | ||||
| * @param src the directory. | * @param src the directory. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setDir(File src) { | public void setDir(File src) { | ||||
| defaultSet.setDir(src); | defaultSet.setDir(src); | ||||
| } | } | ||||
| @@ -154,6 +156,7 @@ public class Chmod extends ExecuteOn { | |||||
| /** | /** | ||||
| * Check the attributes and nested elements. | * Check the attributes and nested elements. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void checkConfiguration() { | protected void checkConfiguration() { | ||||
| if (!havePerm) { | if (!havePerm) { | ||||
| throw new BuildException("Required attribute perm not set in chmod", | throw new BuildException("Required attribute perm not set in chmod", | ||||
| @@ -170,6 +173,7 @@ public class Chmod extends ExecuteOn { | |||||
| * Carry out the chmoding. | * Carry out the chmoding. | ||||
| * @throws BuildException on error. | * @throws BuildException on error. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| /* | /* | ||||
| * In Ant 1.1, <chmod dir="foo" /> means, change the permissions | * In Ant 1.1, <chmod dir="foo" /> means, change the permissions | ||||
| @@ -188,7 +192,7 @@ public class Chmod extends ExecuteOn { | |||||
| } else if (isValidOs()) { | } else if (isValidOs()) { | ||||
| // we are chmodding the given directory | // we are chmodding the given directory | ||||
| Execute execute = prepareExec(); | Execute execute = prepareExec(); | ||||
| Commandline cloned = (Commandline) cmdl.clone(); | |||||
| Commandline cloned = cmdl.clone(); | |||||
| cloned.createArgument().setValue(defaultSet.getDir(getProject()) | cloned.createArgument().setValue(defaultSet.getDir(getProject()) | ||||
| .getPath()); | .getPath()); | ||||
| try { | try { | ||||
| @@ -210,6 +214,7 @@ public class Chmod extends ExecuteOn { | |||||
| * @throws BuildException always. | * @throws BuildException always. | ||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| @Override | |||||
| public void setExecutable(String e) { | public void setExecutable(String e) { | ||||
| throw new BuildException(getTaskType() | throw new BuildException(getTaskType() | ||||
| + " doesn\'t support the executable attribute", getLocation()); | + " doesn\'t support the executable attribute", getLocation()); | ||||
| @@ -222,6 +227,7 @@ public class Chmod extends ExecuteOn { | |||||
| * @throws BuildException always. | * @throws BuildException always. | ||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| @Override | |||||
| public void setCommand(Commandline cmdl) { | public void setCommand(Commandline cmdl) { | ||||
| throw new BuildException(getTaskType() | throw new BuildException(getTaskType() | ||||
| + " doesn\'t support the command attribute", getLocation()); | + " doesn\'t support the command attribute", getLocation()); | ||||
| @@ -233,6 +239,7 @@ public class Chmod extends ExecuteOn { | |||||
| * @throws BuildException always. | * @throws BuildException always. | ||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| @Override | |||||
| public void setSkipEmptyFilesets(boolean skip) { | public void setSkipEmptyFilesets(boolean skip) { | ||||
| throw new BuildException(getTaskType() | throw new BuildException(getTaskType() | ||||
| + " doesn\'t support the skipemptyfileset attribute", getLocation()); | + " doesn\'t support the skipemptyfileset attribute", getLocation()); | ||||
| @@ -244,6 +251,7 @@ public class Chmod extends ExecuteOn { | |||||
| * @throws BuildException always. | * @throws BuildException always. | ||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| @Override | |||||
| public void setAddsourcefile(boolean b) { | public void setAddsourcefile(boolean b) { | ||||
| throw new BuildException(getTaskType() | throw new BuildException(getTaskType() | ||||
| + " doesn\'t support the addsourcefile attribute", getLocation()); | + " doesn\'t support the addsourcefile attribute", getLocation()); | ||||
| @@ -254,6 +262,7 @@ public class Chmod extends ExecuteOn { | |||||
| * Always include unix. | * Always include unix. | ||||
| * @return true if the os is valid. | * @return true if the os is valid. | ||||
| */ | */ | ||||
| @Override | |||||
| protected boolean isValidOs() { | protected boolean isValidOs() { | ||||
| return getOs() == null && getOsFamily() == null | return getOs() == null && getOsFamily() == null | ||||
| ? Os.isFamily(Os.FAMILY_UNIX) : super.isValidOs(); | ? Os.isFamily(Os.FAMILY_UNIX) : super.isValidOs(); | ||||
| @@ -70,12 +70,6 @@ public class Classloader extends Task { | |||||
| private boolean parentFirst = true; | private boolean parentFirst = true; | ||||
| private String parentName = null; | private String parentName = null; | ||||
| /** | |||||
| * Default constructor | |||||
| */ | |||||
| public Classloader() { | |||||
| } | |||||
| /** Name of the loader. If none, the default loader will be modified | /** Name of the loader. If none, the default loader will be modified | ||||
| * | * | ||||
| * @param name the name of this loader | * @param name the name of this loader | ||||
| @@ -101,6 +95,7 @@ public class Classloader extends Task { | |||||
| * @param b if true reverse the normal classloader lookup. | * @param b if true reverse the normal classloader lookup. | ||||
| * @deprecated use setParentFirst with a negated argument instead | * @deprecated use setParentFirst with a negated argument instead | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setReverse(boolean b) { | public void setReverse(boolean b) { | ||||
| this.parentFirst = !b; | this.parentFirst = !b; | ||||
| } | } | ||||
| @@ -156,17 +151,17 @@ public class Classloader extends Task { | |||||
| return this.classpath.createPath(); | return this.classpath.createPath(); | ||||
| } | } | ||||
| /** | /** | ||||
| * do the classloader manipulation. | * do the classloader manipulation. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() { | public void execute() { | ||||
| try { | try { | ||||
| // Gump friendly - don't mess with the core loader if only classpath | // Gump friendly - don't mess with the core loader if only classpath | ||||
| if ("only".equals(getProject().getProperty("build.sysclasspath")) | if ("only".equals(getProject().getProperty("build.sysclasspath")) | ||||
| && (name == null || SYSTEM_LOADER_REF.equals(name))) { | && (name == null || SYSTEM_LOADER_REF.equals(name))) { | ||||
| log("Changing the system loader is disabled " | |||||
| + "by build.sysclasspath=only", Project.MSG_WARN); | |||||
| log("Changing the system loader is disabled by build.sysclasspath=only", | |||||
| Project.MSG_WARN); | |||||
| return; | return; | ||||
| } | } | ||||
| @@ -186,6 +181,7 @@ public class Classloader extends Task { | |||||
| return; | return; | ||||
| } | } | ||||
| @SuppressWarnings("resource") | |||||
| AntClassLoader acl = (AntClassLoader) obj; | AntClassLoader acl = (AntClassLoader) obj; | ||||
| boolean existingLoader = acl != null; | boolean existingLoader = acl != null; | ||||
| @@ -130,7 +130,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| public void setFile(File file) throws BuildException { | public void setFile(File file) throws BuildException { | ||||
| // non-existing files are not allowed | // non-existing files are not allowed | ||||
| if (!file.exists()) { | if (!file.exists()) { | ||||
| throw new BuildException("File " + file + " does not exist."); | |||||
| throw new BuildException("File %s does not exist.", file); | |||||
| } | } | ||||
| BufferedReader reader = null; | BufferedReader reader = null; | ||||
| @@ -181,12 +181,12 @@ public class Concat extends Task implements ResourceCollection { | |||||
| if (value == null) { | if (value == null) { | ||||
| value = ""; | value = ""; | ||||
| } | } | ||||
| if (value.trim().length() == 0) { | |||||
| if (value.trim().isEmpty()) { | |||||
| value = ""; | value = ""; | ||||
| } | } | ||||
| if (trimLeading) { | if (trimLeading) { | ||||
| char[] current = value.toCharArray(); | char[] current = value.toCharArray(); | ||||
| StringBuffer b = new StringBuffer(current.length); | |||||
| StringBuilder b = new StringBuilder(current.length); | |||||
| boolean startOfLine = true; | boolean startOfLine = true; | ||||
| int pos = 0; | int pos = 0; | ||||
| while (pos < current.length) { | while (pos < current.length) { | ||||
| @@ -253,6 +253,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * @exception IOException - possibly thrown by the read for a reader | * @exception IOException - possibly thrown by the read for a reader | ||||
| * object. | * object. | ||||
| */ | */ | ||||
| @Override | |||||
| public int read() throws IOException { | public int read() throws IOException { | ||||
| if (needAddSeparator) { | if (needAddSeparator) { | ||||
| if (lastPos >= eolString.length()) { | if (lastPos >= eolString.length()) { | ||||
| @@ -287,6 +288,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * @exception IOException - possibly thrown by the reads to the | * @exception IOException - possibly thrown by the reads to the | ||||
| * reader objects. | * reader objects. | ||||
| */ | */ | ||||
| @Override | |||||
| public int read(char[] cbuf, int off, int len) | public int read(char[] cbuf, int off, int len) | ||||
| throws IOException { | throws IOException { | ||||
| @@ -334,14 +336,14 @@ public class Concat extends Task implements ResourceCollection { | |||||
| } | } | ||||
| if (amountRead == 0) { | if (amountRead == 0) { | ||||
| return -1; | return -1; | ||||
| } else { | |||||
| return amountRead; | |||||
| } | } | ||||
| return amountRead; | |||||
| } | } | ||||
| /** | /** | ||||
| * Close the current reader | * Close the current reader | ||||
| */ | */ | ||||
| @Override | |||||
| public void close() throws IOException { | public void close() throws IOException { | ||||
| if (reader != null) { | if (reader != null) { | ||||
| reader.close(); | reader.close(); | ||||
| @@ -383,6 +385,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| private ConcatResource(ResourceCollection c) { | private ConcatResource(ResourceCollection c) { | ||||
| this.c = c; | this.c = c; | ||||
| } | } | ||||
| @Override | |||||
| public InputStream getInputStream() { | public InputStream getInputStream() { | ||||
| if (binary) { | if (binary) { | ||||
| ConcatResourceInputStream result = new ConcatResourceInputStream(c); | ConcatResourceInputStream result = new ConcatResourceInputStream(c); | ||||
| @@ -424,6 +427,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| return outputEncoding == null ? new ReaderInputStream(rdr) | return outputEncoding == null ? new ReaderInputStream(rdr) | ||||
| : new ReaderInputStream(rdr, outputEncoding); | : new ReaderInputStream(rdr, outputEncoding); | ||||
| } | } | ||||
| @Override | |||||
| public String getName() { | public String getName() { | ||||
| return resourceName == null | return resourceName == null | ||||
| ? "concat (" + String.valueOf(c) + ")" : resourceName; | ? "concat (" + String.valueOf(c) + ")" : resourceName; | ||||
| @@ -492,6 +496,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| private String resourceName; | private String resourceName; | ||||
| private ReaderFactory<Resource> resourceReaderFactory = new ReaderFactory<Resource>() { | private ReaderFactory<Resource> resourceReaderFactory = new ReaderFactory<Resource>() { | ||||
| @Override | |||||
| public Reader getReader(Resource o) throws IOException { | public Reader getReader(Resource o) throws IOException { | ||||
| InputStream is = o.getInputStream(); | InputStream is = o.getInputStream(); | ||||
| return new BufferedReader(encoding == null | return new BufferedReader(encoding == null | ||||
| @@ -501,6 +506,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| }; | }; | ||||
| private ReaderFactory<Reader> identityReaderFactory = new ReaderFactory<Reader>() { | private ReaderFactory<Reader> identityReaderFactory = new ReaderFactory<Reader>() { | ||||
| @Override | |||||
| public Reader getReader(Reader o) { | public Reader getReader(Reader o) { | ||||
| return o; | return o; | ||||
| } | } | ||||
| @@ -594,6 +600,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| * @deprecated use #setOverwrite instead | * @deprecated use #setOverwrite instead | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setForce(boolean forceOverwrite) { | public void setForce(boolean forceOverwrite) { | ||||
| this.forceOverwrite = forceOverwrite; | this.forceOverwrite = forceOverwrite; | ||||
| } | } | ||||
| @@ -752,11 +759,11 @@ public class Concat extends Task implements ResourceCollection { | |||||
| */ | */ | ||||
| public void setEol(FixCRLF.CrLf crlf) { | public void setEol(FixCRLF.CrLf crlf) { | ||||
| String s = crlf.getValue(); | String s = crlf.getValue(); | ||||
| if (s.equals("cr") || s.equals("mac")) { | |||||
| if ("cr".equals(s) || "mac".equals(s)) { | |||||
| eolString = "\r"; | eolString = "\r"; | ||||
| } else if (s.equals("lf") || s.equals("unix")) { | |||||
| } else if ("lf".equals(s) || "unix".equals(s)) { | |||||
| eolString = "\n"; | eolString = "\n"; | ||||
| } else if (s.equals("crlf") || s.equals("dos")) { | |||||
| } else if ("crlf".equals(s) || "dos".equals(s)) { | |||||
| eolString = "\r\n"; | eolString = "\r\n"; | ||||
| } | } | ||||
| } | } | ||||
| @@ -785,6 +792,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| /** | /** | ||||
| * Execute the concat task. | * Execute the concat task. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() { | public void execute() { | ||||
| validate(); | validate(); | ||||
| if (binary && dest == null) { | if (binary && dest == null) { | ||||
| @@ -796,7 +804,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| log(dest + " is up-to-date.", Project.MSG_VERBOSE); | log(dest + " is up-to-date.", Project.MSG_VERBOSE); | ||||
| return; | return; | ||||
| } | } | ||||
| if (c.size() == 0 && ignoreEmpty) { | |||||
| if (c.isEmpty() && ignoreEmpty) { | |||||
| return; | return; | ||||
| } | } | ||||
| try { | try { | ||||
| @@ -815,15 +823,19 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * Implement ResourceCollection. | * Implement ResourceCollection. | ||||
| * @return Iterator<Resource>. | * @return Iterator<Resource>. | ||||
| */ | */ | ||||
| @Override | |||||
| public Iterator<Resource> iterator() { | public Iterator<Resource> iterator() { | ||||
| validate(); | validate(); | ||||
| return Collections.<Resource>singletonList(new ConcatResource(getResources())).iterator(); | |||||
| return Collections | |||||
| .<Resource> singletonList(new ConcatResource(getResources())) | |||||
| .iterator(); | |||||
| } | } | ||||
| /** | /** | ||||
| * Implement ResourceCollection. | * Implement ResourceCollection. | ||||
| * @return 1. | * @return 1. | ||||
| */ | */ | ||||
| @Override | |||||
| public int size() { | public int size() { | ||||
| return 1; | return 1; | ||||
| } | } | ||||
| @@ -832,6 +844,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * Implement ResourceCollection. | * Implement ResourceCollection. | ||||
| * @return false. | * @return false. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean isFilesystemOnly() { | public boolean isFilesystemOnly() { | ||||
| return false; | return false; | ||||
| } | } | ||||
| @@ -852,8 +865,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| } | } | ||||
| if (encoding != null || outputEncoding != null) { | if (encoding != null || outputEncoding != null) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Setting input or output encoding is incompatible with binary" | |||||
| + " concatenation"); | |||||
| "Setting input or output encoding is incompatible with binary concatenation"); | |||||
| } | } | ||||
| if (filterChains != null) { | if (filterChains != null) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| @@ -899,8 +911,9 @@ public class Concat extends Task implements ResourceCollection { | |||||
| checkDestNotInSources.add(rc); | checkDestNotInSources.add(rc); | ||||
| checkDestNotInSources.add(dest); | checkDestNotInSources.add(dest); | ||||
| if (checkDestNotInSources.size() > 0) { | if (checkDestNotInSources.size() > 0) { | ||||
| throw new BuildException("Destination resource " + dest | |||||
| + " was specified as an input resource."); | |||||
| throw new BuildException( | |||||
| "Destination resource %s was specified as an input resource.", | |||||
| dest); | |||||
| } | } | ||||
| } | } | ||||
| Restrict noexistRc = new Restrict(); | Restrict noexistRc = new Restrict(); | ||||
| @@ -919,12 +932,8 @@ public class Concat extends Task implements ResourceCollection { | |||||
| if (dest == null || forceOverwrite) { | if (dest == null || forceOverwrite) { | ||||
| return false; | return false; | ||||
| } | } | ||||
| for (Resource r : c) { | |||||
| if (SelectorUtils.isOutOfDate(r, dest, FILE_UTILS.getFileTimestampGranularity())) { | |||||
| return false; | |||||
| } | |||||
| } | |||||
| return true; | |||||
| return c.stream().noneMatch(r -> SelectorUtils.isOutOfDate(r, dest, | |||||
| FILE_UTILS.getFileTimestampGranularity())); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -934,7 +943,7 @@ public class Concat extends Task implements ResourceCollection { | |||||
| * for "ignorable whitespace" as well.</p> | * for "ignorable whitespace" as well.</p> | ||||
| */ | */ | ||||
| private void sanitizeText() { | private void sanitizeText() { | ||||
| if (textBuffer != null && "".equals(textBuffer.toString().trim())) { | |||||
| if (textBuffer != null && textBuffer.toString().trim().isEmpty()) { | |||||
| textBuffer = null; | textBuffer = null; | ||||
| } | } | ||||
| } | } | ||||
| @@ -107,16 +107,18 @@ public class ConditionTask extends ConditionBase { | |||||
| */ | */ | ||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (countConditions() > 1) { | if (countConditions() > 1) { | ||||
| throw new BuildException("You must not nest more than one condition into <" | |||||
| + getTaskName() + ">"); | |||||
| throw new BuildException( | |||||
| "You must not nest more than one condition into <%s>", | |||||
| getTaskName()); | |||||
| } | } | ||||
| if (countConditions() < 1) { | if (countConditions() < 1) { | ||||
| throw new BuildException("You must nest a condition into <" + getTaskName() + ">"); | |||||
| throw new BuildException("You must nest a condition into <%s>", | |||||
| getTaskName()); | |||||
| } | } | ||||
| if (property == null) { | if (property == null) { | ||||
| throw new BuildException("The property attribute is required."); | throw new BuildException("The property attribute is required."); | ||||
| } | } | ||||
| Condition c = (Condition) getConditions().nextElement(); | |||||
| Condition c = getConditions().nextElement(); | |||||
| if (c.eval()) { | if (c.eval()) { | ||||
| log("Condition true; setting " + property + " to " + value, Project.MSG_DEBUG); | log("Condition true; setting " + property + " to " + value, Project.MSG_DEBUG); | ||||
| PropertyHelper.getPropertyHelper(getProject()).setNewProperty(property, value); | PropertyHelper.getPropertyHelper(getProject()).setNewProperty(property, value); | ||||
| @@ -26,6 +26,7 @@ import java.util.HashSet; | |||||
| import java.util.Hashtable; | import java.util.Hashtable; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| import java.util.Set; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -75,7 +76,7 @@ public class Copy extends Task { | |||||
| protected File file = null; // the source file | protected File file = null; // the source file | ||||
| protected File destFile = null; // the destination file | protected File destFile = null; // the destination file | ||||
| protected File destDir = null; // the destination directory | protected File destDir = null; // the destination directory | ||||
| protected Vector<ResourceCollection> rcs = new Vector<ResourceCollection>(); | |||||
| protected Vector<ResourceCollection> rcs = new Vector<>(); | |||||
| // here to provide API backwards compatibility | // here to provide API backwards compatibility | ||||
| protected Vector<ResourceCollection> filesets = rcs; | protected Vector<ResourceCollection> filesets = rcs; | ||||
| @@ -88,15 +89,15 @@ public class Copy extends Task { | |||||
| protected boolean includeEmpty = true; | protected boolean includeEmpty = true; | ||||
| protected boolean failonerror = true; | protected boolean failonerror = true; | ||||
| protected Hashtable<String, String[]> fileCopyMap = new LinkedHashtable<String, String[]>(); | |||||
| protected Hashtable<String, String[]> dirCopyMap = new LinkedHashtable<String, String[]>(); | |||||
| protected Hashtable<File, File> completeDirMap = new LinkedHashtable<File, File>(); | |||||
| protected Hashtable<String, String[]> fileCopyMap = new LinkedHashtable<>(); | |||||
| protected Hashtable<String, String[]> dirCopyMap = new LinkedHashtable<>(); | |||||
| protected Hashtable<File, File> completeDirMap = new LinkedHashtable<>(); | |||||
| protected Mapper mapperElement = null; | protected Mapper mapperElement = null; | ||||
| protected FileUtils fileUtils; | protected FileUtils fileUtils; | ||||
| //CheckStyle:VisibilityModifier ON | //CheckStyle:VisibilityModifier ON | ||||
| private final Vector<FilterChain> filterChains = new Vector<FilterChain>(); | |||||
| private final Vector<FilterSet> filterSets = new Vector<FilterSet>(); | |||||
| private final Vector<FilterChain> filterChains = new Vector<>(); | |||||
| private final Vector<FilterSet> filterSets = new Vector<>(); | |||||
| private String inputEncoding = null; | private String inputEncoding = null; | ||||
| private String outputEncoding = null; | private String outputEncoding = null; | ||||
| private long granularity = 0; | private long granularity = 0; | ||||
| @@ -474,18 +475,17 @@ public class Copy extends Task { | |||||
| separate lists and then each list is handled in one go. | separate lists and then each list is handled in one go. | ||||
| */ | */ | ||||
| final HashMap<File, List<String>> filesByBasedir = new HashMap<File, List<String>>(); | |||||
| final HashMap<File, List<String>> dirsByBasedir = new HashMap<File, List<String>>(); | |||||
| final HashSet<File> baseDirs = new HashSet<File>(); | |||||
| final ArrayList<Resource> nonFileResources = new ArrayList<Resource>(); | |||||
| final int size = rcs.size(); | |||||
| for (int i = 0; i < size; i++) { | |||||
| final ResourceCollection rc = rcs.elementAt(i); | |||||
| final Map<File, List<String>> filesByBasedir = new HashMap<>(); | |||||
| final Map<File, List<String>> dirsByBasedir = new HashMap<>(); | |||||
| final Set<File> baseDirs = new HashSet<>(); | |||||
| final List<Resource> nonFileResources = new ArrayList<>(); | |||||
| for (ResourceCollection rc : rcs) { | |||||
| // Step (1) - beware of the ZipFileSet | // Step (1) - beware of the ZipFileSet | ||||
| if (rc instanceof FileSet && rc.isFilesystemOnly()) { | if (rc instanceof FileSet && rc.isFilesystemOnly()) { | ||||
| final FileSet fs = (FileSet) rc; | final FileSet fs = (FileSet) rc; | ||||
| DirectoryScanner ds = null; | |||||
| DirectoryScanner ds; | |||||
| try { | try { | ||||
| ds = fs.getDirectoryScanner(getProject()); | ds = fs.getDirectoryScanner(getProject()); | ||||
| } catch (final BuildException e) { | } catch (final BuildException e) { | ||||
| @@ -493,12 +493,11 @@ public class Copy extends Task { | |||||
| || !getMessage(e).endsWith(DirectoryScanner | || !getMessage(e).endsWith(DirectoryScanner | ||||
| .DOES_NOT_EXIST_POSTFIX)) { | .DOES_NOT_EXIST_POSTFIX)) { | ||||
| throw e; | throw e; | ||||
| } else { | |||||
| if (!quiet) { | |||||
| log("Warning: " + getMessage(e), Project.MSG_ERR); | |||||
| } | |||||
| continue; | |||||
| } | } | ||||
| if (!quiet) { | |||||
| log("Warning: " + getMessage(e), Project.MSG_ERR); | |||||
| } | |||||
| continue; | |||||
| } | } | ||||
| final File fromDir = fs.getDir(getProject()); | final File fromDir = fs.getDir(getProject()); | ||||
| @@ -574,7 +573,7 @@ public class Copy extends Task { | |||||
| } | } | ||||
| } | } | ||||
| if (nonFileResources.size() > 0 || singleResource != null) { | |||||
| if (!nonFileResources.isEmpty() || singleResource != null) { | |||||
| final Resource[] nonFiles = | final Resource[] nonFiles = | ||||
| nonFileResources.toArray(new Resource[nonFileResources.size()]); | nonFileResources.toArray(new Resource[nonFileResources.size()]); | ||||
| // restrict to out-of-date resources | // restrict to out-of-date resources | ||||
| @@ -645,8 +644,9 @@ public class Copy extends Task { | |||||
| } | } | ||||
| } | } | ||||
| private void iterateOverBaseDirs( | |||||
| final HashSet<File> baseDirs, final HashMap<File, List<String>> dirsByBasedir, final HashMap<File, List<String>> filesByBasedir) { | |||||
| private void iterateOverBaseDirs(final Set<File> baseDirs, | |||||
| final Map<File, List<String>> dirsByBasedir, | |||||
| final Map<File, List<String>> filesByBasedir) { | |||||
| for (final File f : baseDirs) { | for (final File f : baseDirs) { | ||||
| final List<String> files = filesByBasedir.get(f); | final List<String> files = filesByBasedir.get(f); | ||||
| @@ -672,7 +672,7 @@ public class Copy extends Task { | |||||
| * @exception BuildException if an error occurs. | * @exception BuildException if an error occurs. | ||||
| */ | */ | ||||
| protected void validateAttributes() throws BuildException { | protected void validateAttributes() throws BuildException { | ||||
| if (file == null && rcs.size() == 0) { | |||||
| if (file == null && rcs.isEmpty()) { | |||||
| throw new BuildException( | throw new BuildException( | ||||
| "Specify at least one source--a file or a resource collection."); | "Specify at least one source--a file or a resource collection."); | ||||
| } | } | ||||
| @@ -686,36 +686,36 @@ public class Copy extends Task { | |||||
| if (file != null && file.isDirectory()) { | if (file != null && file.isDirectory()) { | ||||
| throw new BuildException("Use a resource collection to copy directories."); | throw new BuildException("Use a resource collection to copy directories."); | ||||
| } | } | ||||
| if (destFile != null && rcs.size() > 0) { | |||||
| if (destFile != null && !rcs.isEmpty()) { | |||||
| if (rcs.size() > 1) { | if (rcs.size() > 1) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Cannot concatenate multiple files into a single file."); | "Cannot concatenate multiple files into a single file."); | ||||
| } else { | |||||
| final ResourceCollection rc = rcs.elementAt(0); | |||||
| if (!rc.isFilesystemOnly() && !supportsNonFileResources()) { | |||||
| throw new BuildException("Only FileSystem resources are" | |||||
| + " supported."); | |||||
| } | |||||
| if (rc.size() == 0) { | |||||
| throw new BuildException(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE); | |||||
| } else if (rc.size() == 1) { | |||||
| final Resource res = rc.iterator().next(); | |||||
| final FileProvider r = res.as(FileProvider.class); | |||||
| if (file == null) { | |||||
| if (r != null) { | |||||
| file = r.getFile(); | |||||
| } else { | |||||
| singleResource = res; | |||||
| } | |||||
| rcs.removeElementAt(0); | |||||
| } | |||||
| final ResourceCollection rc = rcs.elementAt(0); | |||||
| if (!rc.isFilesystemOnly() && !supportsNonFileResources()) { | |||||
| throw new BuildException( | |||||
| "Only FileSystem resources are supported."); | |||||
| } | |||||
| if (rc.isEmpty()) { | |||||
| throw new BuildException(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE); | |||||
| } | |||||
| if (rc.size() == 1) { | |||||
| final Resource res = rc.iterator().next(); | |||||
| final FileProvider r = res.as(FileProvider.class); | |||||
| if (file == null) { | |||||
| if (r != null) { | |||||
| file = r.getFile(); | |||||
| } else { | } else { | ||||
| throw new BuildException( | |||||
| "Cannot concatenate multiple files into a single file."); | |||||
| singleResource = res; | |||||
| } | } | ||||
| rcs.removeElementAt(0); | |||||
| } else { | } else { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Cannot concatenate multiple files into a single file."); | "Cannot concatenate multiple files into a single file."); | ||||
| } | } | ||||
| } else { | |||||
| throw new BuildException( | |||||
| "Cannot concatenate multiple files into a single file."); | |||||
| } | } | ||||
| } | } | ||||
| if (destFile != null) { | if (destFile != null) { | ||||
| @@ -811,34 +811,28 @@ public class Copy extends Task { | |||||
| */ | */ | ||||
| protected Map<Resource, String[]> buildMap(final Resource[] fromResources, final File toDir, | protected Map<Resource, String[]> buildMap(final Resource[] fromResources, final File toDir, | ||||
| final FileNameMapper mapper) { | final FileNameMapper mapper) { | ||||
| final HashMap<Resource, String[]> map = new HashMap<Resource, String[]>(); | |||||
| Resource[] toCopy = null; | |||||
| final Map<Resource, String[]> map = new HashMap<>(); | |||||
| Resource[] toCopy; | |||||
| if (forceOverwrite) { | if (forceOverwrite) { | ||||
| final Vector<Resource> v = new Vector<Resource>(); | |||||
| final List<Resource> v = new ArrayList<>(); | |||||
| for (int i = 0; i < fromResources.length; i++) { | for (int i = 0; i < fromResources.length; i++) { | ||||
| if (mapper.mapFileName(fromResources[i].getName()) != null) { | if (mapper.mapFileName(fromResources[i].getName()) != null) { | ||||
| v.addElement(fromResources[i]); | |||||
| v.add(fromResources[i]); | |||||
| } | } | ||||
| } | } | ||||
| toCopy = new Resource[v.size()]; | |||||
| v.copyInto(toCopy); | |||||
| toCopy = v.toArray(new Resource[v.size()]); | |||||
| } else { | } else { | ||||
| toCopy = ResourceUtils.selectOutOfDateSources(this, fromResources, | toCopy = ResourceUtils.selectOutOfDateSources(this, fromResources, | ||||
| mapper, | mapper, | ||||
| new ResourceFactory() { | |||||
| public Resource getResource(final String name) { | |||||
| return new FileResource(toDir, name); | |||||
| } | |||||
| }, | |||||
| (ResourceFactory) name -> new FileResource(toDir, name), | |||||
| granularity); | granularity); | ||||
| } | } | ||||
| for (int i = 0; i < toCopy.length; i++) { | for (int i = 0; i < toCopy.length; i++) { | ||||
| final String[] mappedFiles = mapper.mapFileName(toCopy[i].getName()); | final String[] mappedFiles = mapper.mapFileName(toCopy[i].getName()); | ||||
| for (int j = 0; j < mappedFiles.length; j++) { | |||||
| if (mappedFiles[j] == null) { | |||||
| throw new BuildException("Can't copy a resource without a" | |||||
| + " name if the mapper doesn't" | |||||
| + " provide one."); | |||||
| for (String mappedFile : mappedFiles) { | |||||
| if (mappedFile == null) { | |||||
| throw new BuildException( | |||||
| "Can't copy a resource without a name if the mapper doesn't provide one."); | |||||
| } | } | ||||
| } | } | ||||
| @@ -861,7 +855,7 @@ public class Copy extends Task { | |||||
| * This is a good method for subclasses to override. | * This is a good method for subclasses to override. | ||||
| */ | */ | ||||
| protected void doFileOperations() { | protected void doFileOperations() { | ||||
| if (fileCopyMap.size() > 0) { | |||||
| if (!fileCopyMap.isEmpty()) { | |||||
| log("Copying " + fileCopyMap.size() | log("Copying " + fileCopyMap.size() | ||||
| + " file" + (fileCopyMap.size() == 1 ? "" : "s") | + " file" + (fileCopyMap.size() == 1 ? "" : "s") | ||||
| + " to " + destDir.getAbsolutePath()); | + " to " + destDir.getAbsolutePath()); | ||||
| @@ -870,9 +864,7 @@ public class Copy extends Task { | |||||
| final String fromFile = e.getKey(); | final String fromFile = e.getKey(); | ||||
| final String[] toFiles = e.getValue(); | final String[] toFiles = e.getValue(); | ||||
| for (int i = 0; i < toFiles.length; i++) { | |||||
| final String toFile = toFiles[i]; | |||||
| for (final String toFile : toFiles) { | |||||
| if (fromFile.equals(toFile)) { | if (fromFile.equals(toFile)) { | ||||
| log("Skipping self-copy of " + fromFile, verbosity); | log("Skipping self-copy of " + fromFile, verbosity); | ||||
| continue; | continue; | ||||
| @@ -916,8 +908,8 @@ public class Copy extends Task { | |||||
| if (includeEmpty) { | if (includeEmpty) { | ||||
| int createCount = 0; | int createCount = 0; | ||||
| for (final String[] dirs : dirCopyMap.values()) { | for (final String[] dirs : dirCopyMap.values()) { | ||||
| for (int i = 0; i < dirs.length; i++) { | |||||
| final File d = new File(dirs[i]); | |||||
| for (String dir : dirs) { | |||||
| final File d = new File(dir); | |||||
| if (!d.exists()) { | if (!d.exists()) { | ||||
| if (!(d.mkdirs() || d.isDirectory())) { | if (!(d.mkdirs() || d.isDirectory())) { | ||||
| log("Unable to create directory " | log("Unable to create directory " | ||||
| @@ -947,7 +939,7 @@ public class Copy extends Task { | |||||
| * @since Ant 1.7 | * @since Ant 1.7 | ||||
| */ | */ | ||||
| protected void doResourceOperations(final Map<Resource, String[]> map) { | protected void doResourceOperations(final Map<Resource, String[]> map) { | ||||
| if (map.size() > 0) { | |||||
| if (!map.isEmpty()) { | |||||
| log("Copying " + map.size() | log("Copying " + map.size() | ||||
| + " resource" + (map.size() == 1 ? "" : "s") | + " resource" + (map.size() == 1 ? "" : "s") | ||||
| + " to " + destDir.getAbsolutePath()); | + " to " + destDir.getAbsolutePath()); | ||||
| @@ -1026,7 +1018,7 @@ public class Copy extends Task { | |||||
| baseDir = getKeyFile(baseDir); | baseDir = getKeyFile(baseDir); | ||||
| List<String> l = m.get(baseDir); | List<String> l = m.get(baseDir); | ||||
| if (l == null) { | if (l == null) { | ||||
| l = new ArrayList<String>(names.length); | |||||
| l = new ArrayList<>(names.length); | |||||
| m.put(baseDir, l); | m.put(baseDir, l); | ||||
| } | } | ||||
| l.addAll(java.util.Arrays.asList(names)); | l.addAll(java.util.Arrays.asList(names)); | ||||
| @@ -1085,7 +1077,7 @@ public class Copy extends Task { | |||||
| */ | */ | ||||
| private String getDueTo(final Exception ex) { | private String getDueTo(final Exception ex) { | ||||
| final boolean baseIOException = ex.getClass() == IOException.class; | final boolean baseIOException = ex.getClass() == IOException.class; | ||||
| final StringBuffer message = new StringBuffer(); | |||||
| final StringBuilder message = new StringBuilder(); | |||||
| if (!baseIOException || ex.getMessage() == null) { | if (!baseIOException || ex.getMessage() == null) { | ||||
| message.append(ex.getClass().getName()); | message.append(ex.getClass().getName()); | ||||
| } | } | ||||
| @@ -35,6 +35,7 @@ import org.apache.tools.ant.Project; | |||||
| * @deprecated The copydir task is deprecated since Ant 1.2. Use copy instead. | * @deprecated The copydir task is deprecated since Ant 1.2. Use copy instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public class Copydir extends MatchingTask { | public class Copydir extends MatchingTask { | ||||
| private File srcDir; | private File srcDir; | ||||
| @@ -42,7 +43,7 @@ public class Copydir extends MatchingTask { | |||||
| private boolean filtering = false; | private boolean filtering = false; | ||||
| private boolean flatten = false; | private boolean flatten = false; | ||||
| private boolean forceOverwrite = false; | private boolean forceOverwrite = false; | ||||
| private Hashtable<String, String> filecopyList = new Hashtable<String, String>(); | |||||
| private Map<String, String> filecopyList = new Hashtable<>(); | |||||
| /** | /** | ||||
| * The src attribute | * The src attribute | ||||
| @@ -94,6 +95,7 @@ public class Copydir extends MatchingTask { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| log("DEPRECATED - The copydir task is deprecated. Use copy instead."); | log("DEPRECATED - The copydir task is deprecated. Use copy instead."); | ||||
| @@ -34,6 +34,7 @@ import org.apache.tools.ant.Task; | |||||
| * copy instead. | * copy instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public class Copyfile extends Task { | public class Copyfile extends Task { | ||||
| private File srcFile; | private File srcFile; | ||||
| @@ -80,6 +81,7 @@ public class Copyfile extends Task { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| log("DEPRECATED - The copyfile task is deprecated. Use copy instead."); | log("DEPRECATED - The copyfile task is deprecated. Use copy instead."); | ||||
| @@ -107,9 +109,9 @@ public class Copyfile extends Task { | |||||
| try { | try { | ||||
| getProject().copyFile(srcFile, destFile, filtering, forceOverwrite); | getProject().copyFile(srcFile, destFile, filtering, forceOverwrite); | ||||
| } catch (IOException ioe) { | } catch (IOException ioe) { | ||||
| String msg = "Error copying file: " + srcFile.getAbsolutePath() | |||||
| + " due to " + ioe.getMessage(); | |||||
| throw new BuildException(msg); | |||||
| throw new BuildException( | |||||
| "Error copying file: " + srcFile.getAbsolutePath() | |||||
| + " due to " + ioe.getMessage()); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -45,29 +45,28 @@ public class DefaultExcludes extends Task { | |||||
| * | * | ||||
| * @exception BuildException if something goes wrong with the build | * @exception BuildException if something goes wrong with the build | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (!defaultrequested && add.equals("") && remove.equals("") && !echo) { | |||||
| throw new BuildException("<defaultexcludes> task must set " | |||||
| + "at least one attribute (echo=\"false\"" | |||||
| + " doesn't count since that is the default"); | |||||
| if (!defaultrequested && "".equals(add) && "".equals(remove) && !echo) { | |||||
| throw new BuildException( | |||||
| "<defaultexcludes> task must set at least one attribute (echo=\"false\" doesn't count since that is the default"); | |||||
| } | } | ||||
| if (defaultrequested) { | if (defaultrequested) { | ||||
| DirectoryScanner.resetDefaultExcludes(); | DirectoryScanner.resetDefaultExcludes(); | ||||
| } | } | ||||
| if (!add.equals("")) { | |||||
| if (!"".equals(add)) { | |||||
| DirectoryScanner.addDefaultExclude(add); | DirectoryScanner.addDefaultExclude(add); | ||||
| } | } | ||||
| if (!remove.equals("")) { | |||||
| if (!"".equals(remove)) { | |||||
| DirectoryScanner.removeDefaultExclude(remove); | DirectoryScanner.removeDefaultExclude(remove); | ||||
| } | } | ||||
| if (echo) { | if (echo) { | ||||
| StringBuffer message | |||||
| = new StringBuffer("Current Default Excludes:"); | |||||
| StringBuilder message | |||||
| = new StringBuilder("Current Default Excludes:"); | |||||
| message.append(StringUtils.LINE_SEP); | message.append(StringUtils.LINE_SEP); | ||||
| String[] excludes = DirectoryScanner.getDefaultExcludes(); | |||||
| for (int i = 0; i < excludes.length; i++) { | |||||
| for (String exclude : DirectoryScanner.getDefaultExcludes()) { | |||||
| message.append(" "); | message.append(" "); | ||||
| message.append(excludes[i]); | |||||
| message.append(exclude); | |||||
| message.append(StringUtils.LINE_SEP); | message.append(StringUtils.LINE_SEP); | ||||
| } | } | ||||
| log(message.toString(), logLevel); | log(message.toString(), logLevel); | ||||
| @@ -111,5 +110,4 @@ public class DefaultExcludes extends Task { | |||||
| this.echo = echo; | this.echo = echo; | ||||
| } | } | ||||
| } | } | ||||
| @@ -50,13 +50,14 @@ public abstract class Definer extends DefBase { | |||||
| /** | /** | ||||
| * the extension of an antlib file for autoloading. | * the extension of an antlib file for autoloading. | ||||
| * {@value[ | |||||
| * {@value /antlib.xml} | |||||
| */ | */ | ||||
| private static final String ANTLIB_XML = "/antlib.xml"; | private static final String ANTLIB_XML = "/antlib.xml"; | ||||
| private static final ThreadLocal<Map<URL, Location>> RESOURCE_STACK = new ThreadLocal<Map<URL, Location>>() { | private static final ThreadLocal<Map<URL, Location>> RESOURCE_STACK = new ThreadLocal<Map<URL, Location>>() { | ||||
| @Override | |||||
| protected Map<URL, Location> initialValue() { | protected Map<URL, Location> initialValue() { | ||||
| return new HashMap<URL, Location>(); | |||||
| return new HashMap<>(); | |||||
| } | } | ||||
| }; | }; | ||||
| @@ -120,8 +121,10 @@ public abstract class Definer extends DefBase { | |||||
| * get the values | * get the values | ||||
| * @return an array of the allowed values for this attribute. | * @return an array of the allowed values for this attribute. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {POLICY_FAIL, POLICY_REPORT, POLICY_IGNORE, POLICY_FAILALL}; | |||||
| return new String[] { POLICY_FAIL, POLICY_REPORT, POLICY_IGNORE, | |||||
| POLICY_FAILALL }; | |||||
| } | } | ||||
| } | } | ||||
| @@ -138,8 +141,9 @@ public abstract class Definer extends DefBase { | |||||
| * get the values | * get the values | ||||
| * @return an array of the allowed values for this attribute. | * @return an array of the allowed values for this attribute. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {"properties", "xml"}; | |||||
| return new String[] { "properties", "xml" }; | |||||
| } | } | ||||
| } | } | ||||
| @@ -202,6 +206,7 @@ public abstract class Definer extends DefBase { | |||||
| * | * | ||||
| * @exception BuildException if an error occurs | * @exception BuildException if an error occurs | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| ClassLoader al = createLoader(); | ClassLoader al = createLoader(); | ||||
| @@ -223,23 +228,22 @@ public abstract class Definer extends DefBase { | |||||
| setResource(makeResourceFromURI(uri1)); | setResource(makeResourceFromURI(uri1)); | ||||
| } else { | } else { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Only antlib URIs can be located from the URI alone," | |||||
| + " not the URI '" + getURI() + "'"); | |||||
| "Only antlib URIs can be located from the URI alone, not the URI '" | |||||
| + getURI() + "'"); | |||||
| } | } | ||||
| } | } | ||||
| if (name != null) { | if (name != null) { | ||||
| if (classname == null) { | if (classname == null) { | ||||
| throw new BuildException( | |||||
| "classname attribute of " + getTaskName() + " element " | |||||
| + "is undefined", getLocation()); | |||||
| throw new BuildException("classname attribute of " | |||||
| + getTaskName() + " element is undefined", getLocation()); | |||||
| } | } | ||||
| addDefinition(al, name, classname); | addDefinition(al, name, classname); | ||||
| } else { | } else { | ||||
| if (classname != null) { | if (classname != null) { | ||||
| String msg = "You must not specify classname " | |||||
| + "together with file or resource."; | |||||
| throw new BuildException(msg, getLocation()); | |||||
| throw new BuildException( | |||||
| "You must not specify classname together with file or resource.", | |||||
| getLocation()); | |||||
| } | } | ||||
| final Enumeration<URL> urls; | final Enumeration<URL> urls; | ||||
| if (file == null) { | if (file == null) { | ||||
| @@ -263,21 +267,19 @@ public abstract class Definer extends DefBase { | |||||
| if (fmt == Format.PROPERTIES) { | if (fmt == Format.PROPERTIES) { | ||||
| loadProperties(al, url); | loadProperties(al, url); | ||||
| break; | break; | ||||
| } else if (RESOURCE_STACK.get().get(url) != null) { | |||||
| log("Warning: Recursive loading of " + url | |||||
| + " ignored" | |||||
| + " at " + getLocation() | |||||
| + " originally loaded at " | |||||
| + RESOURCE_STACK.get().get(url), | |||||
| Project.MSG_WARN); | |||||
| } else { | } else { | ||||
| if (RESOURCE_STACK.get().get(url) != null) { | |||||
| log("Warning: Recursive loading of " + url | |||||
| + " ignored" | |||||
| + " at " + getLocation() | |||||
| + " originally loaded at " | |||||
| + RESOURCE_STACK.get().get(url), | |||||
| Project.MSG_WARN); | |||||
| } else { | |||||
| try { | |||||
| RESOURCE_STACK.get().put(url, getLocation()); | |||||
| loadAntlib(al, url); | |||||
| } finally { | |||||
| RESOURCE_STACK.get().remove(url); | |||||
| } | |||||
| try { | |||||
| RESOURCE_STACK.get().put(url, getLocation()); | |||||
| loadAntlib(al, url); | |||||
| } finally { | |||||
| RESOURCE_STACK.get().remove(url); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -290,7 +292,6 @@ public abstract class Definer extends DefBase { | |||||
| * @param uri the xml namespace uri that to convert. | * @param uri the xml namespace uri that to convert. | ||||
| * @return the name of a resource. It may not exist | * @return the name of a resource. It may not exist | ||||
| */ | */ | ||||
| public static String makeResourceFromURI(String uri) { | public static String makeResourceFromURI(String uri) { | ||||
| String path = uri.substring(MagicNames.ANTLIB_PREFIX.length()); | String path = uri.substring(MagicNames.ANTLIB_PREFIX.length()); | ||||
| String resource; | String resource; | ||||
| @@ -391,9 +392,7 @@ public abstract class Definer extends DefBase { | |||||
| * @param url the url to get the definitions from | * @param url the url to get the definitions from | ||||
| */ | */ | ||||
| protected void loadProperties(ClassLoader al, URL url) { | protected void loadProperties(ClassLoader al, URL url) { | ||||
| InputStream is = null; | |||||
| try { | |||||
| is = url.openStream(); | |||||
| try (InputStream is = url.openStream()) { | |||||
| if (is == null) { | if (is == null) { | ||||
| log("Could not load definitions from " + url, | log("Could not load definitions from " + url, | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| @@ -401,16 +400,13 @@ public abstract class Definer extends DefBase { | |||||
| } | } | ||||
| Properties props = new Properties(); | Properties props = new Properties(); | ||||
| props.load(is); | props.load(is); | ||||
| Enumeration<?> keys = props.keys(); | |||||
| while (keys.hasMoreElements()) { | |||||
| name = ((String) keys.nextElement()); | |||||
| for (String key : props.stringPropertyNames()) { | |||||
| name = key; | |||||
| classname = props.getProperty(name); | classname = props.getProperty(name); | ||||
| addDefinition(al, name, classname); | addDefinition(al, name, classname); | ||||
| } | } | ||||
| } catch (IOException ex) { | } catch (IOException ex) { | ||||
| throw new BuildException(ex, getLocation()); | throw new BuildException(ex, getLocation()); | ||||
| } finally { | |||||
| FileUtils.close(is); | |||||
| } | } | ||||
| } | } | ||||
| @@ -559,7 +555,6 @@ public abstract class Definer extends DefBase { | |||||
| this.adaptToClass = adaptToClass; | this.adaptToClass = adaptToClass; | ||||
| } | } | ||||
| /** | /** | ||||
| * Add a definition using the attributes of Definer | * Add a definition using the attributes of Definer | ||||
| * | * | ||||
| @@ -601,15 +596,16 @@ public abstract class Definer extends DefBase { | |||||
| ComponentHelper.getComponentHelper(getProject()) | ComponentHelper.getComponentHelper(getProject()) | ||||
| .addDataTypeDefinition(def); | .addDataTypeDefinition(def); | ||||
| } catch (ClassNotFoundException cnfe) { | } catch (ClassNotFoundException cnfe) { | ||||
| String msg = getTaskName() + " class " + classname | |||||
| + " cannot be found" | |||||
| + "\n using the classloader " + al; | |||||
| throw new BuildException(msg, cnfe, getLocation()); | |||||
| throw new BuildException( | |||||
| getTaskName() + " class " + classname | |||||
| + " cannot be found\n using the classloader " + al, | |||||
| cnfe, getLocation()); | |||||
| } catch (NoClassDefFoundError ncdfe) { | } catch (NoClassDefFoundError ncdfe) { | ||||
| String msg = getTaskName() + " A class needed by class " | |||||
| + classname + " cannot be found: " + ncdfe.getMessage() | |||||
| + "\n using the classloader " + al; | |||||
| throw new BuildException(msg, ncdfe, getLocation()); | |||||
| throw new BuildException( | |||||
| getTaskName() + " A class needed by class " + classname | |||||
| + " cannot be found: " + ncdfe.getMessage() | |||||
| + "\n using the classloader " + al, | |||||
| ncdfe, getLocation()); | |||||
| } | } | ||||
| } catch (BuildException ex) { | } catch (BuildException ex) { | ||||
| switch (onError) { | switch (onError) { | ||||
| @@ -633,7 +629,7 @@ public abstract class Definer extends DefBase { | |||||
| */ | */ | ||||
| private void tooManyDefinitions() { | private void tooManyDefinitions() { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Only one of the attributes name, file and resource" | |||||
| + " can be set", getLocation()); | |||||
| "Only one of the attributes name, file and resource can be set", | |||||
| getLocation()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -19,6 +19,7 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.IOException; | |||||
| import java.util.Arrays; | import java.util.Arrays; | ||||
| import java.util.Comparator; | import java.util.Comparator; | ||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| @@ -79,33 +80,43 @@ import org.apache.tools.ant.util.SymbolicLinkUtils; | |||||
| public class Delete extends MatchingTask { | public class Delete extends MatchingTask { | ||||
| private static final ResourceComparator REVERSE_FILESYSTEM = new Reverse(new FileSystem()); | private static final ResourceComparator REVERSE_FILESYSTEM = new Reverse(new FileSystem()); | ||||
| private static final ResourceSelector EXISTS = new Exists(); | private static final ResourceSelector EXISTS = new Exists(); | ||||
| private static FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| private static SymbolicLinkUtils SYMLINK_UTILS = | |||||
| SymbolicLinkUtils.getSymbolicLinkUtils(); | |||||
| private static class ReverseDirs implements ResourceCollection { | private static class ReverseDirs implements ResourceCollection { | ||||
| static final Comparator<Comparable<?>> REVERSE = new Comparator<Comparable<?>>() { | |||||
| public int compare(Comparable<?> foo, Comparable<?> bar) { | |||||
| return ((Comparable) foo).compareTo(bar) * -1; | |||||
| } | |||||
| }; | |||||
| private Project project; | private Project project; | ||||
| private File basedir; | private File basedir; | ||||
| private String[] dirs; | private String[] dirs; | ||||
| ReverseDirs(Project project, File basedir, String[] dirs) { | ReverseDirs(Project project, File basedir, String[] dirs) { | ||||
| this.project = project; | this.project = project; | ||||
| this.basedir = basedir; | this.basedir = basedir; | ||||
| this.dirs = dirs; | this.dirs = dirs; | ||||
| Arrays.sort(this.dirs, REVERSE); | |||||
| Arrays.sort(this.dirs, Comparator.reverseOrder()); | |||||
| } | } | ||||
| @Override | |||||
| public Iterator<Resource> iterator() { | public Iterator<Resource> iterator() { | ||||
| return new FileResourceIterator(project, basedir, dirs); | return new FileResourceIterator(project, basedir, dirs); | ||||
| } | } | ||||
| public boolean isFilesystemOnly() { return true; } | |||||
| public int size() { return dirs.length; } | |||||
| @Override | |||||
| public boolean isFilesystemOnly() { | |||||
| return true; | |||||
| } | |||||
| @Override | |||||
| public int size() { | |||||
| return dirs.length; | |||||
| } | |||||
| } | } | ||||
| // CheckStyle:VisibilityModifier OFF - bc | // CheckStyle:VisibilityModifier OFF - bc | ||||
| protected File file = null; | protected File file = null; | ||||
| protected File dir = null; | protected File dir = null; | ||||
| protected Vector<FileSet> filesets = new Vector<FileSet>(); | |||||
| protected Vector<FileSet> filesets = new Vector<>(); | |||||
| protected boolean usedMatchingTask = false; | protected boolean usedMatchingTask = false; | ||||
| // by default, remove matching empty dirs | // by default, remove matching empty dirs | ||||
| protected boolean includeEmpty = false; | protected boolean includeEmpty = false; | ||||
| @@ -117,9 +128,6 @@ public class Delete extends MatchingTask { | |||||
| private boolean deleteOnExit = false; | private boolean deleteOnExit = false; | ||||
| private boolean removeNotFollowedSymlinks = false; | private boolean removeNotFollowedSymlinks = false; | ||||
| private Resources rcs = null; | private Resources rcs = null; | ||||
| private static FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| private static SymbolicLinkUtils SYMLINK_UTILS = | |||||
| SymbolicLinkUtils.getSymbolicLinkUtils(); | |||||
| private boolean performGc = Os.isFamily("windows"); | private boolean performGc = Os.isFamily("windows"); | ||||
| /** | /** | ||||
| @@ -175,9 +183,9 @@ public class Delete extends MatchingTask { | |||||
| * | * | ||||
| * @param failonerror true or false | * @param failonerror true or false | ||||
| */ | */ | ||||
| public void setFailOnError(boolean failonerror) { | |||||
| this.failonerror = failonerror; | |||||
| } | |||||
| public void setFailOnError(boolean failonerror) { | |||||
| this.failonerror = failonerror; | |||||
| } | |||||
| /** | /** | ||||
| * If true, on failure to delete, note the error and set | * If true, on failure to delete, note the error and set | ||||
| @@ -185,10 +193,9 @@ public class Delete extends MatchingTask { | |||||
| * | * | ||||
| * @param deleteOnExit true or false | * @param deleteOnExit true or false | ||||
| */ | */ | ||||
| public void setDeleteOnExit(boolean deleteOnExit) { | |||||
| this.deleteOnExit = deleteOnExit; | |||||
| } | |||||
| public void setDeleteOnExit(boolean deleteOnExit) { | |||||
| this.deleteOnExit = deleteOnExit; | |||||
| } | |||||
| /** | /** | ||||
| * If true, delete empty directories. | * If true, delete empty directories. | ||||
| @@ -212,10 +219,10 @@ public class Delete extends MatchingTask { | |||||
| performGc = b; | performGc = b; | ||||
| } | } | ||||
| /** | |||||
| * Adds a set of files to be deleted. | |||||
| * @param set the set of files to be deleted | |||||
| */ | |||||
| /** | |||||
| * Adds a set of files to be deleted. | |||||
| * @param set the set of files to be deleted | |||||
| */ | |||||
| public void addFileset(FileSet set) { | public void addFileset(FileSet set) { | ||||
| filesets.addElement(set); | filesets.addElement(set); | ||||
| } | } | ||||
| @@ -239,6 +246,7 @@ public class Delete extends MatchingTask { | |||||
| * add a name entry on the include list | * add a name entry on the include list | ||||
| * @return a NameEntry object to be configured | * @return a NameEntry object to be configured | ||||
| */ | */ | ||||
| @Override | |||||
| public PatternSet.NameEntry createInclude() { | public PatternSet.NameEntry createInclude() { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| return super.createInclude(); | return super.createInclude(); | ||||
| @@ -248,6 +256,7 @@ public class Delete extends MatchingTask { | |||||
| * add a name entry on the include files list | * add a name entry on the include files list | ||||
| * @return an NameEntry object to be configured | * @return an NameEntry object to be configured | ||||
| */ | */ | ||||
| @Override | |||||
| public PatternSet.NameEntry createIncludesFile() { | public PatternSet.NameEntry createIncludesFile() { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| return super.createIncludesFile(); | return super.createIncludesFile(); | ||||
| @@ -257,6 +266,7 @@ public class Delete extends MatchingTask { | |||||
| * add a name entry on the exclude list | * add a name entry on the exclude list | ||||
| * @return an NameEntry object to be configured | * @return an NameEntry object to be configured | ||||
| */ | */ | ||||
| @Override | |||||
| public PatternSet.NameEntry createExclude() { | public PatternSet.NameEntry createExclude() { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| return super.createExclude(); | return super.createExclude(); | ||||
| @@ -266,6 +276,7 @@ public class Delete extends MatchingTask { | |||||
| * add a name entry on the include files list | * add a name entry on the include files list | ||||
| * @return an NameEntry object to be configured | * @return an NameEntry object to be configured | ||||
| */ | */ | ||||
| @Override | |||||
| public PatternSet.NameEntry createExcludesFile() { | public PatternSet.NameEntry createExcludesFile() { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| return super.createExcludesFile(); | return super.createExcludesFile(); | ||||
| @@ -275,6 +286,7 @@ public class Delete extends MatchingTask { | |||||
| * add a set of patterns | * add a set of patterns | ||||
| * @return PatternSet object to be configured | * @return PatternSet object to be configured | ||||
| */ | */ | ||||
| @Override | |||||
| public PatternSet createPatternSet() { | public PatternSet createPatternSet() { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| return super.createPatternSet(); | return super.createPatternSet(); | ||||
| @@ -286,6 +298,7 @@ public class Delete extends MatchingTask { | |||||
| * | * | ||||
| * @param includes the string containing the include patterns | * @param includes the string containing the include patterns | ||||
| */ | */ | ||||
| @Override | |||||
| public void setIncludes(String includes) { | public void setIncludes(String includes) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setIncludes(includes); | super.setIncludes(includes); | ||||
| @@ -297,6 +310,7 @@ public class Delete extends MatchingTask { | |||||
| * | * | ||||
| * @param excludes the string containing the exclude patterns | * @param excludes the string containing the exclude patterns | ||||
| */ | */ | ||||
| @Override | |||||
| public void setExcludes(String excludes) { | public void setExcludes(String excludes) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setExcludes(excludes); | super.setExcludes(excludes); | ||||
| @@ -309,6 +323,7 @@ public class Delete extends MatchingTask { | |||||
| * should be used, "false"|"off"|"no" when they | * should be used, "false"|"off"|"no" when they | ||||
| * shouldn't be used. | * shouldn't be used. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setDefaultexcludes(boolean useDefaultExcludes) { | public void setDefaultexcludes(boolean useDefaultExcludes) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setDefaultexcludes(useDefaultExcludes); | super.setDefaultexcludes(useDefaultExcludes); | ||||
| @@ -320,6 +335,7 @@ public class Delete extends MatchingTask { | |||||
| * @param includesfile A string containing the filename to fetch | * @param includesfile A string containing the filename to fetch | ||||
| * the include patterns from. | * the include patterns from. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setIncludesfile(File includesfile) { | public void setIncludesfile(File includesfile) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setIncludesfile(includesfile); | super.setIncludesfile(includesfile); | ||||
| @@ -331,6 +347,7 @@ public class Delete extends MatchingTask { | |||||
| * @param excludesfile A string containing the filename to fetch | * @param excludesfile A string containing the filename to fetch | ||||
| * the include patterns from. | * the include patterns from. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setExcludesfile(File excludesfile) { | public void setExcludesfile(File excludesfile) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setExcludesfile(excludesfile); | super.setExcludesfile(excludesfile); | ||||
| @@ -342,6 +359,7 @@ public class Delete extends MatchingTask { | |||||
| * @param isCaseSensitive "true"|"on"|"yes" if file system is case | * @param isCaseSensitive "true"|"on"|"yes" if file system is case | ||||
| * sensitive, "false"|"off"|"no" when not. | * sensitive, "false"|"off"|"no" when not. | ||||
| */ | */ | ||||
| @Override | |||||
| public void setCaseSensitive(boolean isCaseSensitive) { | public void setCaseSensitive(boolean isCaseSensitive) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setCaseSensitive(isCaseSensitive); | super.setCaseSensitive(isCaseSensitive); | ||||
| @@ -352,6 +370,7 @@ public class Delete extends MatchingTask { | |||||
| * | * | ||||
| * @param followSymlinks whether or not symbolic links should be followed | * @param followSymlinks whether or not symbolic links should be followed | ||||
| */ | */ | ||||
| @Override | |||||
| public void setFollowSymlinks(boolean followSymlinks) { | public void setFollowSymlinks(boolean followSymlinks) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.setFollowSymlinks(followSymlinks); | super.setFollowSymlinks(followSymlinks); | ||||
| @@ -371,6 +390,7 @@ public class Delete extends MatchingTask { | |||||
| * add a "Select" selector entry on the selector list | * add a "Select" selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addSelector(SelectSelector selector) { | public void addSelector(SelectSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addSelector(selector); | super.addSelector(selector); | ||||
| @@ -380,6 +400,7 @@ public class Delete extends MatchingTask { | |||||
| * add an "And" selector entry on the selector list | * add an "And" selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addAnd(AndSelector selector) { | public void addAnd(AndSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addAnd(selector); | super.addAnd(selector); | ||||
| @@ -389,6 +410,7 @@ public class Delete extends MatchingTask { | |||||
| * add an "Or" selector entry on the selector list | * add an "Or" selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addOr(OrSelector selector) { | public void addOr(OrSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addOr(selector); | super.addOr(selector); | ||||
| @@ -398,6 +420,7 @@ public class Delete extends MatchingTask { | |||||
| * add a "Not" selector entry on the selector list | * add a "Not" selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addNot(NotSelector selector) { | public void addNot(NotSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addNot(selector); | super.addNot(selector); | ||||
| @@ -407,6 +430,7 @@ public class Delete extends MatchingTask { | |||||
| * add a "None" selector entry on the selector list | * add a "None" selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addNone(NoneSelector selector) { | public void addNone(NoneSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addNone(selector); | super.addNone(selector); | ||||
| @@ -416,6 +440,7 @@ public class Delete extends MatchingTask { | |||||
| * add a majority selector entry on the selector list | * add a majority selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addMajority(MajoritySelector selector) { | public void addMajority(MajoritySelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addMajority(selector); | super.addMajority(selector); | ||||
| @@ -425,6 +450,7 @@ public class Delete extends MatchingTask { | |||||
| * add a selector date entry on the selector list | * add a selector date entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addDate(DateSelector selector) { | public void addDate(DateSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addDate(selector); | super.addDate(selector); | ||||
| @@ -434,6 +460,7 @@ public class Delete extends MatchingTask { | |||||
| * add a selector size entry on the selector list | * add a selector size entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addSize(SizeSelector selector) { | public void addSize(SizeSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addSize(selector); | super.addSize(selector); | ||||
| @@ -443,6 +470,7 @@ public class Delete extends MatchingTask { | |||||
| * add a selector filename entry on the selector list | * add a selector filename entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addFilename(FilenameSelector selector) { | public void addFilename(FilenameSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addFilename(selector); | super.addFilename(selector); | ||||
| @@ -452,6 +480,7 @@ public class Delete extends MatchingTask { | |||||
| * add an extended selector entry on the selector list | * add an extended selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addCustom(ExtendSelector selector) { | public void addCustom(ExtendSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addCustom(selector); | super.addCustom(selector); | ||||
| @@ -461,6 +490,7 @@ public class Delete extends MatchingTask { | |||||
| * add a contains selector entry on the selector list | * add a contains selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addContains(ContainsSelector selector) { | public void addContains(ContainsSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addContains(selector); | super.addContains(selector); | ||||
| @@ -470,6 +500,7 @@ public class Delete extends MatchingTask { | |||||
| * add a present selector entry on the selector list | * add a present selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addPresent(PresentSelector selector) { | public void addPresent(PresentSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addPresent(selector); | super.addPresent(selector); | ||||
| @@ -479,6 +510,7 @@ public class Delete extends MatchingTask { | |||||
| * add a depth selector entry on the selector list | * add a depth selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addDepth(DepthSelector selector) { | public void addDepth(DepthSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addDepth(selector); | super.addDepth(selector); | ||||
| @@ -488,6 +520,7 @@ public class Delete extends MatchingTask { | |||||
| * add a depends selector entry on the selector list | * add a depends selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addDepend(DependSelector selector) { | public void addDepend(DependSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addDepend(selector); | super.addDepend(selector); | ||||
| @@ -497,6 +530,7 @@ public class Delete extends MatchingTask { | |||||
| * add a regular expression selector entry on the selector list | * add a regular expression selector entry on the selector list | ||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| */ | */ | ||||
| @Override | |||||
| public void addContainsRegexp(ContainsRegexpSelector selector) { | public void addContainsRegexp(ContainsRegexpSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addContainsRegexp(selector); | super.addContainsRegexp(selector); | ||||
| @@ -507,6 +541,7 @@ public class Delete extends MatchingTask { | |||||
| * @param selector the selector to add | * @param selector the selector to add | ||||
| * @since ant 1.6 | * @since ant 1.6 | ||||
| */ | */ | ||||
| @Override | |||||
| public void addModified(ModifiedSelector selector) { | public void addModified(ModifiedSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.addModified(selector); | super.addModified(selector); | ||||
| @@ -517,6 +552,7 @@ public class Delete extends MatchingTask { | |||||
| * @param selector the selector to be added | * @param selector the selector to be added | ||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| @Override | |||||
| public void add(FileSelector selector) { | public void add(FileSelector selector) { | ||||
| usedMatchingTask = true; | usedMatchingTask = true; | ||||
| super.add(selector); | super.add(selector); | ||||
| @@ -526,21 +562,22 @@ public class Delete extends MatchingTask { | |||||
| * Delete the file(s). | * Delete the file(s). | ||||
| * @exception BuildException if an error occurs | * @exception BuildException if an error occurs | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (usedMatchingTask) { | if (usedMatchingTask) { | ||||
| log("DEPRECATED - Use of the implicit FileSet is deprecated. " | |||||
| + "Use a nested fileset element instead.", quiet ? Project.MSG_VERBOSE : verbosity); | |||||
| log("DEPRECATED - Use of the implicit FileSet is deprecated. Use a nested fileset element instead.", | |||||
| quiet ? Project.MSG_VERBOSE : verbosity); | |||||
| } | } | ||||
| if (file == null && dir == null && filesets.size() == 0 && rcs == null) { | |||||
| throw new BuildException("At least one of the file or dir " | |||||
| + "attributes, or a nested resource collection, " | |||||
| + "must be set."); | |||||
| if (file == null && dir == null && filesets.isEmpty() && rcs == null) { | |||||
| throw new BuildException( | |||||
| "At least one of the file or dir attributes, or a nested resource collection, must be set."); | |||||
| } | } | ||||
| if (quiet && failonerror) { | if (quiet && failonerror) { | ||||
| throw new BuildException("quiet and failonerror cannot both be " | |||||
| + "set to true", getLocation()); | |||||
| throw new BuildException( | |||||
| "quiet and failonerror cannot both be set to true", | |||||
| getLocation()); | |||||
| } | } | ||||
| // delete the single file | // delete the single file | ||||
| @@ -548,8 +585,8 @@ public class Delete extends MatchingTask { | |||||
| if (file.exists()) { | if (file.exists()) { | ||||
| if (file.isDirectory()) { | if (file.isDirectory()) { | ||||
| log("Directory " + file.getAbsolutePath() | log("Directory " + file.getAbsolutePath() | ||||
| + " cannot be removed using the file attribute. " | |||||
| + "Use dir instead.", quiet ? Project.MSG_VERBOSE : verbosity); | |||||
| + " cannot be removed using the file attribute. Use dir instead.", | |||||
| quiet ? Project.MSG_VERBOSE : verbosity); | |||||
| } else { | } else { | ||||
| log("Deleting: " + file.getAbsolutePath()); | log("Deleting: " + file.getAbsolutePath()); | ||||
| @@ -610,11 +647,11 @@ public class Delete extends MatchingTask { | |||||
| final int size = filesets.size(); | final int size = filesets.size(); | ||||
| for (int i = 0; i < size; i++) { | for (int i = 0; i < size; i++) { | ||||
| FileSet fs = (FileSet) filesets.get(i); | |||||
| FileSet fs = filesets.get(i); | |||||
| if (fs.getProject() == null) { | if (fs.getProject() == null) { | ||||
| log("Deleting fileset with no project specified;" | |||||
| + " assuming executing project", Project.MSG_VERBOSE); | |||||
| fs = (FileSet) fs.clone(); | |||||
| log("Deleting fileset with no project specified; assuming executing project", | |||||
| Project.MSG_VERBOSE); | |||||
| fs = fs.clone(); | |||||
| fs.setProject(getProject()); | fs.setProject(getProject()); | ||||
| } | } | ||||
| final File fsDir = fs.getDir(); | final File fsDir = fs.getDir(); | ||||
| @@ -634,12 +671,15 @@ public class Delete extends MatchingTask { | |||||
| // iterating, capture the results now and store them | // iterating, capture the results now and store them | ||||
| final String[] files = ds.getIncludedFiles(); | final String[] files = ds.getIncludedFiles(); | ||||
| resourcesToDelete.add(new ResourceCollection() { | resourcesToDelete.add(new ResourceCollection() { | ||||
| @Override | |||||
| public boolean isFilesystemOnly() { | public boolean isFilesystemOnly() { | ||||
| return true; | return true; | ||||
| } | } | ||||
| @Override | |||||
| public int size() { | public int size() { | ||||
| return files.length; | return files.length; | ||||
| } | } | ||||
| @Override | |||||
| public Iterator<Resource> iterator() { | public Iterator<Resource> iterator() { | ||||
| return new FileResourceIterator(getProject(), | return new FileResourceIterator(getProject(), | ||||
| fsDir, files); | fsDir, files); | ||||
| @@ -656,7 +696,7 @@ public class Delete extends MatchingTask { | |||||
| if (n.length > 0) { | if (n.length > 0) { | ||||
| String[] links = new String[n.length]; | String[] links = new String[n.length]; | ||||
| System.arraycopy(n, 0, links, 0, n.length); | System.arraycopy(n, 0, links, 0, n.length); | ||||
| Arrays.sort(links, ReverseDirs.REVERSE); | |||||
| Arrays.sort(links, Comparator.reverseOrder()); | |||||
| for (int l = 0; l < links.length; l++) { | for (int l = 0; l < links.length; l++) { | ||||
| try { | try { | ||||
| SYMLINK_UTILS | SYMLINK_UTILS | ||||
| @@ -826,7 +866,7 @@ public class Delete extends MatchingTask { | |||||
| private boolean isDanglingSymlink(File f) { | private boolean isDanglingSymlink(File f) { | ||||
| try { | try { | ||||
| return SYMLINK_UTILS.isDanglingSymbolicLink(f); | return SYMLINK_UTILS.isDanglingSymbolicLink(f); | ||||
| } catch (java.io.IOException e) { | |||||
| } catch (IOException e) { | |||||
| log("Error while trying to detect " + f.getAbsolutePath() | log("Error while trying to detect " + f.getAbsolutePath() | ||||
| + " as broken symbolic link. " + e.getMessage(), | + " as broken symbolic link. " + e.getMessage(), | ||||
| quiet ? Project.MSG_VERBOSE : verbosity); | quiet ? Project.MSG_VERBOSE : verbosity); | ||||
| @@ -102,12 +102,15 @@ public class DependSet extends MatchingTask { | |||||
| private HideMissingBasedir(FileSet fs) { | private HideMissingBasedir(FileSet fs) { | ||||
| this.fs = fs; | this.fs = fs; | ||||
| } | } | ||||
| @Override | |||||
| public Iterator<Resource> iterator() { | public Iterator<Resource> iterator() { | ||||
| return basedirExists() ? fs.iterator() : Resources.EMPTY_ITERATOR; | return basedirExists() ? fs.iterator() : Resources.EMPTY_ITERATOR; | ||||
| } | } | ||||
| @Override | |||||
| public int size() { | public int size() { | ||||
| return basedirExists() ? fs.size() : 0; | return basedirExists() ? fs.size() : 0; | ||||
| } | } | ||||
| @Override | |||||
| public boolean isFilesystemOnly() { | public boolean isFilesystemOnly() { | ||||
| return true; | return true; | ||||
| } | } | ||||
| @@ -190,6 +193,7 @@ public class DependSet extends MatchingTask { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException if errors occur. | * @throws BuildException if errors occur. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (sources == null) { | if (sources == null) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| @@ -200,12 +204,11 @@ public class DependSet extends MatchingTask { | |||||
| "At least one set of target files must be specified"); | "At least one set of target files must be specified"); | ||||
| } | } | ||||
| //no sources = nothing to compare; no targets = nothing to delete: | //no sources = nothing to compare; no targets = nothing to delete: | ||||
| if (sources.size() > 0 && targets.size() > 0 && !uptodate(sources, targets)) { | |||||
| if (!(sources.isEmpty() || targets.isEmpty() || uptodate(sources, targets))) { | |||||
| log("Deleting all target files.", Project.MSG_VERBOSE); | log("Deleting all target files.", Project.MSG_VERBOSE); | ||||
| if (verbose) { | if (verbose) { | ||||
| String[] t = targets.list(); | |||||
| for (int i = 0; i < t.length; i++) { | |||||
| log("Deleting " + t[i]); | |||||
| for (String t : targets.list()) { | |||||
| log("Deleting " + t); | |||||
| } | } | ||||
| } | } | ||||
| Delete delete = new Delete(); | Delete delete = new Delete(); | ||||
| @@ -244,7 +247,7 @@ public class DependSet extends MatchingTask { | |||||
| logMissing(missingSources, "source"); | logMissing(missingSources, "source"); | ||||
| return false; | return false; | ||||
| } | } | ||||
| Resource newestSource = (Resource) getNewest(sources); | |||||
| Resource newestSource = getNewest(sources); | |||||
| logWithModificationTime(newestSource, "newest source"); | logWithModificationTime(newestSource, "newest source"); | ||||
| return oldestTarget.getLastModified() >= newestSource.getLastModified(); | return oldestTarget.getLastModified() >= newestSource.getLastModified(); | ||||
| } | } | ||||
| @@ -262,7 +265,6 @@ public class DependSet extends MatchingTask { | |||||
| Iterator<Resource> i = rc.iterator(); | Iterator<Resource> i = rc.iterator(); | ||||
| if (!i.hasNext()) { | if (!i.hasNext()) { | ||||
| return null; | return null; | ||||
| } | } | ||||
| Resource xest = i.next(); | Resource xest = i.next(); | ||||
| while (i.hasNext()) { | while (i.hasNext()) { | ||||
| @@ -68,15 +68,14 @@ public class Dirname extends Task { | |||||
| * Execute this task. | * Execute this task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (property == null) { | if (property == null) { | ||||
| throw new BuildException("property attribute required", getLocation()); | throw new BuildException("property attribute required", getLocation()); | ||||
| } | } | ||||
| if (file == null) { | if (file == null) { | ||||
| throw new BuildException("file attribute required", getLocation()); | throw new BuildException("file attribute required", getLocation()); | ||||
| } else { | |||||
| String value = file.getParent(); | |||||
| getProject().setNewProperty(property, value); | |||||
| } | } | ||||
| getProject().setNewProperty(property, file.getParent()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -55,6 +55,7 @@ public class Ear extends Jar { | |||||
| * @deprecated since 1.5.x. | * @deprecated since 1.5.x. | ||||
| * Use setDestFile(destfile) instead. | * Use setDestFile(destfile) instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setEarfile(File earFile) { | public void setEarfile(File earFile) { | ||||
| setDestFile(earFile); | setDestFile(earFile); | ||||
| } | } | ||||
| @@ -66,9 +67,9 @@ public class Ear extends Jar { | |||||
| public void setAppxml(File descr) { | public void setAppxml(File descr) { | ||||
| deploymentDescriptor = descr; | deploymentDescriptor = descr; | ||||
| if (!deploymentDescriptor.exists()) { | if (!deploymentDescriptor.exists()) { | ||||
| throw new BuildException("Deployment descriptor: " | |||||
| + deploymentDescriptor | |||||
| + " does not exist."); | |||||
| throw new BuildException( | |||||
| "Deployment descriptor: %s does not exist.", | |||||
| deploymentDescriptor); | |||||
| } | } | ||||
| // Create a ZipFileSet for this file, and pass it up. | // Create a ZipFileSet for this file, and pass it up. | ||||
| @@ -78,7 +79,6 @@ public class Ear extends Jar { | |||||
| super.addFileset(fs); | super.addFileset(fs); | ||||
| } | } | ||||
| /** | /** | ||||
| * Adds zipfileset. | * Adds zipfileset. | ||||
| * | * | ||||
| @@ -91,13 +91,13 @@ public class Ear extends Jar { | |||||
| super.addFileset(fs); | super.addFileset(fs); | ||||
| } | } | ||||
| /** | /** | ||||
| * Initialize the output stream. | * Initialize the output stream. | ||||
| * @param zOut the zip output stream. | * @param zOut the zip output stream. | ||||
| * @throws IOException on I/O errors | * @throws IOException on I/O errors | ||||
| * @throws BuildException on other errors | * @throws BuildException on other errors | ||||
| */ | */ | ||||
| @Override | |||||
| protected void initZipOutputStream(ZipOutputStream zOut) | protected void initZipOutputStream(ZipOutputStream zOut) | ||||
| throws IOException, BuildException { | throws IOException, BuildException { | ||||
| // If no webxml file is specified, it's an error. | // If no webxml file is specified, it's an error. | ||||
| @@ -116,6 +116,7 @@ public class Ear extends Jar { | |||||
| * @param mode the Unix permissions to set. | * @param mode the Unix permissions to set. | ||||
| * @throws IOException on error | * @throws IOException on error | ||||
| */ | */ | ||||
| @Override | |||||
| protected void zipFile(File file, ZipOutputStream zOut, String vPath, | protected void zipFile(File file, ZipOutputStream zOut, String vPath, | ||||
| int mode) | int mode) | ||||
| throws IOException { | throws IOException { | ||||
| @@ -147,6 +148,7 @@ public class Ear extends Jar { | |||||
| * Make sure we don't think we already have a application.xml next | * Make sure we don't think we already have a application.xml next | ||||
| * time this task gets executed. | * time this task gets executed. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void cleanUp() { | protected void cleanUp() { | ||||
| descriptorAdded = false; | descriptorAdded = false; | ||||
| super.cleanUp(); | super.cleanUp(); | ||||
| @@ -113,24 +113,26 @@ public class EchoXML extends XMLFragment { | |||||
| public NamespacePolicy(String s) { | public NamespacePolicy(String s) { | ||||
| setValue(s); | setValue(s); | ||||
| } | } | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | @Override | ||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {IGNORE, ELEMENTS, ALL}; | |||||
| return new String[] { IGNORE, ELEMENTS, ALL }; | |||||
| } | } | ||||
| public DOMElementWriter.XmlNamespacePolicy getPolicy() { | public DOMElementWriter.XmlNamespacePolicy getPolicy() { | ||||
| String s = getValue(); | String s = getValue(); | ||||
| if (IGNORE.equalsIgnoreCase(s)) { | if (IGNORE.equalsIgnoreCase(s)) { | ||||
| return DOMElementWriter.XmlNamespacePolicy.IGNORE; | return DOMElementWriter.XmlNamespacePolicy.IGNORE; | ||||
| } else if (ELEMENTS.equalsIgnoreCase(s)) { | |||||
| } | |||||
| if (ELEMENTS.equalsIgnoreCase(s)) { | |||||
| return | return | ||||
| DOMElementWriter.XmlNamespacePolicy.ONLY_QUALIFY_ELEMENTS; | DOMElementWriter.XmlNamespacePolicy.ONLY_QUALIFY_ELEMENTS; | ||||
| } else if (ALL.equalsIgnoreCase(s)) { | |||||
| } | |||||
| if (ALL.equalsIgnoreCase(s)) { | |||||
| return DOMElementWriter.XmlNamespacePolicy.QUALIFY_ALL; | return DOMElementWriter.XmlNamespacePolicy.QUALIFY_ALL; | ||||
| } else { | |||||
| throw new BuildException("Invalid namespace policy: " + s); | |||||
| } | } | ||||
| throw new BuildException("Invalid namespace policy: " + s); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -44,6 +44,7 @@ import org.apache.tools.ant.Task; | |||||
| * delegate to {@link org.apache.tools.ant.taskdefs.Execute Execute} | * delegate to {@link org.apache.tools.ant.taskdefs.Execute Execute} | ||||
| * instead. | * instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public class Exec extends Task { | public class Exec extends Task { | ||||
| private String os; | private String os; | ||||
| private String out; | private String out; | ||||
| @@ -70,6 +71,7 @@ public class Exec extends Task { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| run(command); | run(command); | ||||
| } | } | ||||
| @@ -160,9 +162,8 @@ public class Exec extends Task { | |||||
| if (err != 0) { | if (err != 0) { | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException("Exec returned: " + err, getLocation()); | throw new BuildException("Exec returned: " + err, getLocation()); | ||||
| } else { | |||||
| log("Result: " + err, Project.MSG_ERR); | |||||
| } | } | ||||
| log("Result: " + err, Project.MSG_ERR); | |||||
| } | } | ||||
| } catch (IOException ioe) { | } catch (IOException ioe) { | ||||
| throw new BuildException("Error exec: " + command, ioe, getLocation()); | throw new BuildException("Error exec: " + command, ioe, getLocation()); | ||||
| @@ -262,6 +263,7 @@ public class Exec extends Task { | |||||
| } | } | ||||
| } | } | ||||
| @Override | |||||
| public void run() { | public void run() { | ||||
| try { | try { | ||||
| try { | try { | ||||
| @@ -125,7 +125,7 @@ public class ExecTask extends Task { | |||||
| */ | */ | ||||
| public void setTimeout(Integer value) { | public void setTimeout(Integer value) { | ||||
| setTimeout( | setTimeout( | ||||
| (Long) ((value == null) ? null : new Long(value.intValue()))); | |||||
| (value == null) ? null : Long.valueOf(value.intValue())); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -167,8 +167,7 @@ public class ExecTask extends Task { | |||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| public void setCommand(Commandline cmdl) { | public void setCommand(Commandline cmdl) { | ||||
| log("The command attribute is deprecated.\n" | |||||
| + "Please use the executable attribute and nested arg elements.", | |||||
| log("The command attribute is deprecated.\nPlease use the executable attribute and nested arg elements.", | |||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| this.cmdl = cmdl; | this.cmdl = cmdl; | ||||
| } | } | ||||
| @@ -191,8 +190,8 @@ public class ExecTask extends Task { | |||||
| */ | */ | ||||
| public void setInput(File input) { | public void setInput(File input) { | ||||
| if (inputString != null) { | if (inputString != null) { | ||||
| throw new BuildException("The \"input\" and \"inputstring\" " | |||||
| + "attributes cannot both be specified"); | |||||
| throw new BuildException( | |||||
| "The \"input\" and \"inputstring\" attributes cannot both be specified"); | |||||
| } | } | ||||
| this.input = input; | this.input = input; | ||||
| incompatibleWithSpawn = true; | incompatibleWithSpawn = true; | ||||
| @@ -205,8 +204,8 @@ public class ExecTask extends Task { | |||||
| */ | */ | ||||
| public void setInputString(String inputString) { | public void setInputString(String inputString) { | ||||
| if (input != null) { | if (input != null) { | ||||
| throw new BuildException("The \"input\" and \"inputstring\" " | |||||
| + "attributes cannot both be specified"); | |||||
| throw new BuildException( | |||||
| "The \"input\" and \"inputstring\" attributes cannot both be specified"); | |||||
| } | } | ||||
| this.inputString = inputString; | this.inputString = inputString; | ||||
| incompatibleWithSpawn = true; | incompatibleWithSpawn = true; | ||||
| @@ -484,6 +483,7 @@ public class ExecTask extends Task { | |||||
| * <li>this list is not exhaustive or limitative</li> | * <li>this list is not exhaustive or limitative</li> | ||||
| * </ul> | * </ul> | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| // Quick fail if this is not a valid OS for the command | // Quick fail if this is not a valid OS for the command | ||||
| if (!isValidOs()) { | if (!isValidOs()) { | ||||
| @@ -633,9 +633,8 @@ public class ExecTask extends Task { | |||||
| String msg = "Timeout: killed the sub-process"; | String msg = "Timeout: killed the sub-process"; | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(msg); | throw new BuildException(msg); | ||||
| } else { | |||||
| log(msg, Project.MSG_WARN); | |||||
| } | } | ||||
| log(msg, Project.MSG_WARN); | |||||
| } | } | ||||
| maybeSetResultPropertyValue(returnCode); | maybeSetResultPropertyValue(returnCode); | ||||
| redirector.complete(); | redirector.complete(); | ||||
| @@ -643,9 +642,8 @@ public class ExecTask extends Task { | |||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(getTaskType() + " returned: " | throw new BuildException(getTaskType() + " returned: " | ||||
| + returnCode, getLocation()); | + returnCode, getLocation()); | ||||
| } else { | |||||
| log("Result: " + returnCode, Project.MSG_ERR); | |||||
| } | } | ||||
| log("Result: " + returnCode, Project.MSG_ERR); | |||||
| } | } | ||||
| } else { | } else { | ||||
| exe.spawn(); | exe.spawn(); | ||||
| @@ -672,9 +670,8 @@ public class ExecTask extends Task { | |||||
| if (failIfExecFails) { | if (failIfExecFails) { | ||||
| throw new BuildException("Execute failed: " + e.toString(), e, | throw new BuildException("Execute failed: " + e.toString(), e, | ||||
| getLocation()); | getLocation()); | ||||
| } else { | |||||
| log("Execute failed: " + e.toString(), Project.MSG_ERR); | |||||
| } | } | ||||
| log("Execute failed: " + e.toString(), Project.MSG_ERR); | |||||
| } finally { | } finally { | ||||
| // close the output file if required | // close the output file if required | ||||
| logFlush(); | logFlush(); | ||||
| @@ -24,7 +24,7 @@ import java.io.File; | |||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.OutputStream; | import java.io.OutputStream; | ||||
| import java.io.StringReader; | import java.io.StringReader; | ||||
| import java.util.ArrayList; | |||||
| import java.io.UnsupportedEncodingException; | |||||
| import java.util.HashMap; | import java.util.HashMap; | ||||
| import java.util.LinkedHashMap; | import java.util.LinkedHashMap; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| @@ -54,18 +54,6 @@ public class Execute { | |||||
| */ | */ | ||||
| public static final int INVALID = Integer.MAX_VALUE; | public static final int INVALID = Integer.MAX_VALUE; | ||||
| private String[] cmdl = null; | |||||
| private String[] env = null; | |||||
| private int exitValue = INVALID; | |||||
| private ExecuteStreamHandler streamHandler; | |||||
| private final ExecuteWatchdog watchdog; | |||||
| private File workingDirectory = null; | |||||
| private Project project = null; | |||||
| private boolean newEnvironment = false; | |||||
| /** Controls whether the VM is used to launch commands, where possible. */ | |||||
| private boolean useVMLauncher = true; | |||||
| private static String antWorkingDirectory = System.getProperty("user.dir"); | private static String antWorkingDirectory = System.getProperty("user.dir"); | ||||
| private static Map<String, String> procEnvironment = null; | private static Map<String, String> procEnvironment = null; | ||||
| @@ -81,6 +69,18 @@ public class Execute { | |||||
| } | } | ||||
| } | } | ||||
| private String[] cmdl = null; | |||||
| private String[] env = null; | |||||
| private int exitValue = INVALID; | |||||
| private ExecuteStreamHandler streamHandler; | |||||
| private final ExecuteWatchdog watchdog; | |||||
| private File workingDirectory = null; | |||||
| private Project project = null; | |||||
| private boolean newEnvironment = false; | |||||
| /** Controls whether the VM is used to launch commands, where possible. */ | |||||
| private boolean useVMLauncher = true; | |||||
| /** | /** | ||||
| * Set whether or not you want the process to be spawned. | * Set whether or not you want the process to be spawned. | ||||
| * Default is not spawned. | * Default is not spawned. | ||||
| @@ -104,7 +104,7 @@ public class Execute { | |||||
| * @return a map containing the environment variables. | * @return a map containing the environment variables. | ||||
| * @since Ant 1.8.2 | * @since Ant 1.8.2 | ||||
| */ | */ | ||||
| public static synchronized Map<String,String> getEnvironmentVariables() { | |||||
| public static synchronized Map<String, String> getEnvironmentVariables() { | |||||
| if (procEnvironment != null) { | if (procEnvironment != null) { | ||||
| return procEnvironment; | return procEnvironment; | ||||
| } | } | ||||
| @@ -117,7 +117,7 @@ public class Execute { | |||||
| } | } | ||||
| } | } | ||||
| procEnvironment = new LinkedHashMap<String, String>(); | |||||
| procEnvironment = new LinkedHashMap<>(); | |||||
| try { | try { | ||||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||||
| Execute exe = new Execute(new PumpStreamHandler(out)); | Execute exe = new Execute(new PumpStreamHandler(out)); | ||||
| @@ -149,7 +149,7 @@ public class Execute { | |||||
| } else { | } else { | ||||
| // New env var...append the previous one if we have it. | // New env var...append the previous one if we have it. | ||||
| if (var != null) { | if (var != null) { | ||||
| int eq = var.indexOf("="); | |||||
| int eq = var.indexOf('='); | |||||
| procEnvironment.put(var.substring(0, eq), | procEnvironment.put(var.substring(0, eq), | ||||
| var.substring(eq + 1)); | var.substring(eq + 1)); | ||||
| } | } | ||||
| @@ -158,10 +158,10 @@ public class Execute { | |||||
| } | } | ||||
| // Since we "look ahead" before adding, there's one last env var. | // Since we "look ahead" before adding, there's one last env var. | ||||
| if (var != null) { | if (var != null) { | ||||
| int eq = var.indexOf("="); | |||||
| int eq = var.indexOf('='); | |||||
| procEnvironment.put(var.substring(0, eq), var.substring(eq + 1)); | procEnvironment.put(var.substring(0, eq), var.substring(eq + 1)); | ||||
| } | } | ||||
| } catch (java.io.IOException exc) { | |||||
| } catch (IOException exc) { | |||||
| exc.printStackTrace(); //NOSONAR | exc.printStackTrace(); //NOSONAR | ||||
| // Just try to see how much we got | // Just try to see how much we got | ||||
| } | } | ||||
| @@ -177,7 +177,7 @@ public class Execute { | |||||
| */ | */ | ||||
| @Deprecated | @Deprecated | ||||
| public static synchronized Vector<String> getProcEnvironment() { | public static synchronized Vector<String> getProcEnvironment() { | ||||
| Vector<String> v = new Vector<String>(); | |||||
| Vector<String> v = new Vector<>(); | |||||
| for (Entry<String, String> entry : getEnvironmentVariables().entrySet()) { | for (Entry<String, String> entry : getEnvironmentVariables().entrySet()) { | ||||
| v.add(entry.getKey() + "=" + entry.getValue()); | v.add(entry.getKey() + "=" + entry.getValue()); | ||||
| } | } | ||||
| @@ -194,17 +194,18 @@ public class Execute { | |||||
| private static String[] getProcEnvCommand() { | private static String[] getProcEnvCommand() { | ||||
| if (Os.isFamily("os/2")) { | if (Os.isFamily("os/2")) { | ||||
| // OS/2 - use same mechanism as Windows 2000 | // OS/2 - use same mechanism as Windows 2000 | ||||
| return new String[] {"cmd", "/c", "set"}; | |||||
| } else if (Os.isFamily("windows")) { | |||||
| return new String[] { "cmd", "/c", "set" }; | |||||
| } | |||||
| if (Os.isFamily("windows")) { | |||||
| // Determine if we're running under XP/2000/NT or 98/95 | // Determine if we're running under XP/2000/NT or 98/95 | ||||
| if (Os.isFamily("win9x")) { | if (Os.isFamily("win9x")) { | ||||
| // Windows 98/95 | // Windows 98/95 | ||||
| return new String[] {"command.com", "/c", "set"}; | |||||
| } else { | |||||
| // Windows XP/2000/NT/2003 | |||||
| return new String[] {"cmd", "/c", "set"}; | |||||
| return new String[] { "command.com", "/c", "set" }; | |||||
| } | } | ||||
| } else if (Os.isFamily("z/os") || Os.isFamily("unix")) { | |||||
| // Windows XP/2000/NT/2003 | |||||
| return new String[] { "cmd", "/c", "set" }; | |||||
| } | |||||
| if (Os.isFamily("z/os") || Os.isFamily("unix")) { | |||||
| // On most systems one could use: /bin/sh -c env | // On most systems one could use: /bin/sh -c env | ||||
| // Some systems have /bin/env, others /usr/bin/env, just try | // Some systems have /bin/env, others /usr/bin/env, just try | ||||
| @@ -218,16 +219,17 @@ public class Execute { | |||||
| cmd[0] = "env"; | cmd[0] = "env"; | ||||
| } | } | ||||
| return cmd; | return cmd; | ||||
| } else if (Os.isFamily("netware") || Os.isFamily("os/400")) { | |||||
| } | |||||
| if (Os.isFamily("netware") || Os.isFamily("os/400")) { | |||||
| // rely on PATH | // rely on PATH | ||||
| return new String[] {"env"}; | |||||
| } else if (Os.isFamily("openvms")) { | |||||
| return new String[] {"show", "logical"}; | |||||
| } else { | |||||
| // MAC OS 9 and previous | |||||
| // TODO: I have no idea how to get it, someone must fix it | |||||
| return null; | |||||
| return new String[] { "env" }; | |||||
| } | |||||
| if (Os.isFamily("openvms")) { | |||||
| return new String[] { "show", "logical" }; | |||||
| } | } | ||||
| // MAC OS 9 and previous | |||||
| // TODO: I have no idea how to get it, someone must fix it | |||||
| return null; | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -244,13 +246,13 @@ public class Execute { | |||||
| if (Os.isFamily("z/os")) { | if (Os.isFamily("z/os")) { | ||||
| try { | try { | ||||
| return bos.toString("Cp1047"); | return bos.toString("Cp1047"); | ||||
| } catch (java.io.UnsupportedEncodingException e) { | |||||
| } catch (UnsupportedEncodingException e) { | |||||
| // noop default encoding used | // noop default encoding used | ||||
| } | } | ||||
| } else if (Os.isFamily("os/400")) { | } else if (Os.isFamily("os/400")) { | ||||
| try { | try { | ||||
| return bos.toString("Cp500"); | return bos.toString("Cp500"); | ||||
| } catch (java.io.UnsupportedEncodingException e) { | |||||
| } catch (UnsupportedEncodingException e) { | |||||
| // noop default encoding used | // noop default encoding used | ||||
| } | } | ||||
| } | } | ||||
| @@ -417,7 +419,7 @@ public class Execute { | |||||
| String[] env, File dir, boolean useVM) | String[] env, File dir, boolean useVM) | ||||
| throws IOException { | throws IOException { | ||||
| if (dir != null && !dir.exists()) { | if (dir != null && !dir.exists()) { | ||||
| throw new BuildException(dir + " doesn't exist."); | |||||
| throw new BuildException("%s doesn't exist.", dir); | |||||
| } | } | ||||
| CommandLauncher vmLauncher = CommandLauncher.getVMLauncher(project); | CommandLauncher vmLauncher = CommandLauncher.getVMLauncher(project); | ||||
| @@ -435,7 +437,7 @@ public class Execute { | |||||
| */ | */ | ||||
| public int execute() throws IOException { | public int execute() throws IOException { | ||||
| if (workingDirectory != null && !workingDirectory.exists()) { | if (workingDirectory != null && !workingDirectory.exists()) { | ||||
| throw new BuildException(workingDirectory + " doesn't exist."); | |||||
| throw new BuildException("%s doesn't exist.", workingDirectory); | |||||
| } | } | ||||
| final Process process = launch(project, getCommandline(), | final Process process = launch(project, getCommandline(), | ||||
| getEnvironment(), workingDirectory, | getEnvironment(), workingDirectory, | ||||
| @@ -492,7 +494,7 @@ public class Execute { | |||||
| */ | */ | ||||
| public void spawn() throws IOException { | public void spawn() throws IOException { | ||||
| if (workingDirectory != null && !workingDirectory.exists()) { | if (workingDirectory != null && !workingDirectory.exists()) { | ||||
| throw new BuildException(workingDirectory + " doesn't exist."); | |||||
| throw new BuildException("%s doesn't exist.", workingDirectory); | |||||
| } | } | ||||
| final Process process = launch(project, getCommandline(), | final Process process = launch(project, getCommandline(), | ||||
| getEnvironment(), workingDirectory, | getEnvironment(), workingDirectory, | ||||
| @@ -611,7 +613,7 @@ public class Execute { | |||||
| return env; | return env; | ||||
| } | } | ||||
| Map<String, String> osEnv = | Map<String, String> osEnv = | ||||
| new LinkedHashMap<String, String>(getEnvironmentVariables()); | |||||
| new LinkedHashMap<>(getEnvironmentVariables()); | |||||
| for (int i = 0; i < env.length; i++) { | for (int i = 0; i < env.length; i++) { | ||||
| String keyValue = env[i]; | String keyValue = env[i]; | ||||
| String key = keyValue.substring(0, keyValue.indexOf('=')); | String key = keyValue.substring(0, keyValue.indexOf('=')); | ||||
| @@ -624,7 +626,7 @@ public class Execute { | |||||
| for (String osEnvItem : osEnv.keySet()) { | for (String osEnvItem : osEnv.keySet()) { | ||||
| // Nb: using default locale as key is a env name | // Nb: using default locale as key is a env name | ||||
| if (osEnvItem.toLowerCase().equals(key.toLowerCase())) { | |||||
| if (osEnvItem.equalsIgnoreCase(key)) { | |||||
| // Use the original casiness of the key | // Use the original casiness of the key | ||||
| key = osEnvItem; | key = osEnvItem; | ||||
| break; | break; | ||||
| @@ -636,11 +638,8 @@ public class Execute { | |||||
| osEnv.put(key, keyValue.substring(key.length() + 1)); | osEnv.put(key, keyValue.substring(key.length() + 1)); | ||||
| } | } | ||||
| ArrayList<String> l = new ArrayList<String>(); | |||||
| for (Entry<String, String> entry : osEnv.entrySet()) { | |||||
| l.add(entry.getKey() + "=" + entry.getValue()); | |||||
| } | |||||
| return l.toArray(new String[osEnv.size()]); | |||||
| return osEnv.entrySet().stream() | |||||
| .map(e -> e.getKey() + "=" + e.getValue()).toArray(String[]::new); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -651,7 +650,7 @@ public class Execute { | |||||
| * @param cmdline The command to execute. | * @param cmdline The command to execute. | ||||
| * @throws BuildException if the command does not exit successfully. | * @throws BuildException if the command does not exit successfully. | ||||
| */ | */ | ||||
| public static void runCommand(Task task, String[] cmdline) | |||||
| public static void runCommand(Task task, String... cmdline) | |||||
| throws BuildException { | throws BuildException { | ||||
| try { | try { | ||||
| task.log(Commandline.describeCommand(cmdline), | task.log(Commandline.describeCommand(cmdline), | ||||
| @@ -665,7 +664,7 @@ public class Execute { | |||||
| throw new BuildException(cmdline[0] | throw new BuildException(cmdline[0] | ||||
| + " failed with return code " + retval, task.getLocation()); | + " failed with return code " + retval, task.getLocation()); | ||||
| } | } | ||||
| } catch (java.io.IOException exc) { | |||||
| } catch (IOException exc) { | |||||
| throw new BuildException("Could not launch " + cmdline[0] + ": " | throw new BuildException("Could not launch " + cmdline[0] + ": " | ||||
| + exc, task.getLocation()); | + exc, task.getLocation()); | ||||
| } | } | ||||
| @@ -695,9 +694,9 @@ public class Execute { | |||||
| */ | */ | ||||
| private static Map<String, String> getVMSLogicals(BufferedReader in) | private static Map<String, String> getVMSLogicals(BufferedReader in) | ||||
| throws IOException { | throws IOException { | ||||
| HashMap<String, String> logicals = new HashMap<String, String>(); | |||||
| Map<String, String> logicals = new HashMap<>(); | |||||
| String logName = null, logValue = null, newLogName; | String logName = null, logValue = null, newLogName; | ||||
| String line = null; | |||||
| String line; | |||||
| // CheckStyle:MagicNumber OFF | // CheckStyle:MagicNumber OFF | ||||
| while ((line = in.readLine()) != null) { | while ((line = in.readLine()) != null) { | ||||
| // parse the VMS logicals into required format ("VAR=VAL[,VAL2]") | // parse the VMS logicals into required format ("VAR=VAL[,VAL2]") | ||||
| @@ -97,6 +97,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| * @deprecated since 1.4.x. | * @deprecated since 1.4.x. | ||||
| * manage output at the task level. | * manage output at the task level. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setOutput(PrintStream out) { | public void setOutput(PrintStream out) { | ||||
| } | } | ||||
| @@ -122,7 +123,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| if (sysProperties != null) { | if (sysProperties != null) { | ||||
| sysProperties.setSystem(); | sysProperties.setSystem(); | ||||
| } | } | ||||
| Class<?> target = null; | |||||
| Class<?> target; | |||||
| try { | try { | ||||
| if (classpath == null) { | if (classpath == null) { | ||||
| target = Class.forName(classname); | target = Class.forName(classname); | ||||
| @@ -137,18 +138,18 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| target = Class.forName(classname, true, loader); | target = Class.forName(classname, true, loader); | ||||
| } | } | ||||
| } catch (ClassNotFoundException e) { | } catch (ClassNotFoundException e) { | ||||
| throw new BuildException("Could not find " + classname + "." | |||||
| + " Make sure you have it in your" | |||||
| + " classpath"); | |||||
| throw new BuildException( | |||||
| "Could not find %s. Make sure you have it in your classpath", | |||||
| classname); | |||||
| } | } | ||||
| main = target.getMethod("main", new Class[] {String[].class}); | main = target.getMethod("main", new Class[] {String[].class}); | ||||
| if (main == null) { | if (main == null) { | ||||
| throw new BuildException("Could not find main() method in " | |||||
| + classname); | |||||
| throw new BuildException("Could not find main() method in %s", | |||||
| classname); | |||||
| } | } | ||||
| if ((main.getModifiers() & Modifier.STATIC) == 0) { | if ((main.getModifiers() & Modifier.STATIC) == 0) { | ||||
| throw new BuildException("main() method in " + classname | |||||
| + " is not declared static"); | |||||
| throw new BuildException( | |||||
| "main() method in %s is not declared static", classname); | |||||
| } | } | ||||
| if (timeout == null) { | if (timeout == null) { | ||||
| run(); //NOSONAR | run(); //NOSONAR | ||||
| @@ -212,6 +213,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| * Run this ExecuteJava in a Thread. | * Run this ExecuteJava in a Thread. | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| public void run() { | public void run() { | ||||
| final Object[] argument = {javaCommand.getArguments()}; | final Object[] argument = {javaCommand.getArguments()}; | ||||
| try { | try { | ||||
| @@ -242,6 +244,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| * @param w the responsible Watchdog. | * @param w the responsible Watchdog. | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void timeoutOccured(Watchdog w) { | public synchronized void timeoutOccured(Watchdog w) { | ||||
| if (thread != null) { | if (thread != null) { | ||||
| timedOut = true; | timedOut = true; | ||||
| @@ -318,7 +321,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| exe.setVMLauncher(true); | exe.setVMLauncher(true); | ||||
| File vmsJavaOptionFile = null; | File vmsJavaOptionFile = null; | ||||
| try { | try { | ||||
| String [] args = new String[command.length - 1]; | |||||
| String[] args = new String[command.length - 1]; | |||||
| System.arraycopy(command, 1, args, 0, command.length - 1); | System.arraycopy(command, 1, args, 0, command.length - 1); | ||||
| vmsJavaOptionFile = JavaEnvUtils.createVmsJavaOptionFile(args); | vmsJavaOptionFile = JavaEnvUtils.createVmsJavaOptionFile(args); | ||||
| //we mark the file to be deleted on exit. | //we mark the file to be deleted on exit. | ||||
| @@ -326,7 +329,7 @@ public class ExecuteJava implements Runnable, TimeoutObserver { | |||||
| //after execution finished, which is much better for long-lived runtimes | //after execution finished, which is much better for long-lived runtimes | ||||
| //though spawning complicates things... | //though spawning complicates things... | ||||
| vmsJavaOptionFile.deleteOnExit(); | vmsJavaOptionFile.deleteOnExit(); | ||||
| String [] vmsCmd = {command[0], "-V", vmsJavaOptionFile.getPath()}; | |||||
| String[] vmsCmd = { command[0], "-V", vmsJavaOptionFile.getPath() }; | |||||
| exe.setCommandline(vmsCmd); | exe.setCommandline(vmsCmd); | ||||
| } catch (IOException e) { | } catch (IOException e) { | ||||
| throw new BuildException("Failed to create a temporary file for \"-V\" switch"); | throw new BuildException("Failed to create a temporary file for \"-V\" switch"); | ||||
| @@ -20,7 +20,10 @@ package org.apache.tools.ant.taskdefs; | |||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.util.ArrayList; | |||||
| import java.util.HashSet; | import java.util.HashSet; | ||||
| import java.util.List; | |||||
| import java.util.Set; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -60,8 +63,9 @@ public class ExecuteOn extends ExecTask { | |||||
| // switching type to "dir" when we encounter a DirSet that would | // switching type to "dir" when we encounter a DirSet that would | ||||
| // be more difficult to achieve otherwise. | // be more difficult to achieve otherwise. | ||||
| protected Vector<AbstractFileSet> filesets = new Vector<AbstractFileSet>(); // contains AbstractFileSet | |||||
| // (both DirSet and FileSet) | |||||
| // (both DirSet and FileSet) | |||||
| protected Vector<AbstractFileSet> filesets = new Vector<>(); | |||||
| private Union resources = null; | private Union resources = null; | ||||
| private boolean relative = false; | private boolean relative = false; | ||||
| private boolean parallel = false; | private boolean parallel = false; | ||||
| @@ -296,6 +300,7 @@ public class ExecuteOn extends ExecTask { | |||||
| /** | /** | ||||
| * Check the configuration of this ExecuteOn instance. | * Check the configuration of this ExecuteOn instance. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void checkConfiguration() { | protected void checkConfiguration() { | ||||
| // * @TODO using taskName here is brittle, as a user could override it. | // * @TODO using taskName here is brittle, as a user could override it. | ||||
| // * this should probably be modified to use the classname instead. | // * this should probably be modified to use the classname instead. | ||||
| @@ -303,7 +308,7 @@ public class ExecuteOn extends ExecTask { | |||||
| log("!! execon is deprecated. Use apply instead. !!"); | log("!! execon is deprecated. Use apply instead. !!"); | ||||
| } | } | ||||
| super.checkConfiguration(); | super.checkConfiguration(); | ||||
| if (filesets.size() == 0 && resources == null) { | |||||
| if (filesets.isEmpty() && resources == null) { | |||||
| throw new BuildException("no resources specified", | throw new BuildException("no resources specified", | ||||
| getLocation()); | getLocation()); | ||||
| } | } | ||||
| @@ -326,6 +331,7 @@ public class ExecuteOn extends ExecTask { | |||||
| * @return <code>ExecuteStreamHandler</code>. | * @return <code>ExecuteStreamHandler</code>. | ||||
| * @throws BuildException on error. | * @throws BuildException on error. | ||||
| */ | */ | ||||
| @Override | |||||
| protected ExecuteStreamHandler createHandler() throws BuildException { | protected ExecuteStreamHandler createHandler() throws BuildException { | ||||
| //if we have a RedirectorElement, return a decoy | //if we have a RedirectorElement, return a decoy | ||||
| return (redirectorElement == null) | return (redirectorElement == null) | ||||
| @@ -335,6 +341,7 @@ public class ExecuteOn extends ExecTask { | |||||
| /** | /** | ||||
| * Set up the I/O Redirector. | * Set up the I/O Redirector. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void setupRedirector() { | protected void setupRedirector() { | ||||
| super.setupRedirector(); | super.setupRedirector(); | ||||
| redirector.setAppendProperties(true); | redirector.setAppendProperties(true); | ||||
| @@ -345,23 +352,21 @@ public class ExecuteOn extends ExecTask { | |||||
| * @param exe the Execute instance representing the external process. | * @param exe the Execute instance representing the external process. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| protected void runExec(Execute exe) throws BuildException { | protected void runExec(Execute exe) throws BuildException { | ||||
| int totalFiles = 0; | int totalFiles = 0; | ||||
| int totalDirs = 0; | int totalDirs = 0; | ||||
| boolean haveExecuted = false; | boolean haveExecuted = false; | ||||
| try { | try { | ||||
| Vector<String> fileNames = new Vector<String>(); | |||||
| Vector<File> baseDirs = new Vector<File>(); | |||||
| final int size = filesets.size(); | |||||
| for (int i = 0; i < size; i++) { | |||||
| Vector<String> fileNames = new Vector<>(); | |||||
| Vector<File> baseDirs = new Vector<>(); | |||||
| for (AbstractFileSet fs : filesets) { | |||||
| String currentType = type; | String currentType = type; | ||||
| AbstractFileSet fs = filesets.elementAt(i); | |||||
| if (fs instanceof DirSet) { | if (fs instanceof DirSet) { | ||||
| if (!FileDirBoth.DIR.equals(type)) { | if (!FileDirBoth.DIR.equals(type)) { | ||||
| log("Found a nested dirset but type is " + type + ". " | log("Found a nested dirset but type is " + type + ". " | ||||
| + "Temporarily switching to type=\"dir\" on the" | |||||
| + " assumption that you really did mean" | |||||
| + " <dirset> not <fileset>.", Project.MSG_DEBUG); | |||||
| + "Temporarily switching to type=\"dir\" on the assumption that you really did mean <dirset> not <fileset>.", | |||||
| Project.MSG_DEBUG); | |||||
| currentType = FileDirBoth.DIR; | currentType = FileDirBoth.DIR; | ||||
| } | } | ||||
| } | } | ||||
| @@ -373,34 +378,32 @@ public class ExecuteOn extends ExecTask { | |||||
| String[] s = getFiles(base, ds); | String[] s = getFiles(base, ds); | ||||
| for (int j = 0; j < s.length; j++) { | for (int j = 0; j < s.length; j++) { | ||||
| totalFiles++; | totalFiles++; | ||||
| fileNames.addElement(s[j]); | |||||
| baseDirs.addElement(base); | |||||
| fileNames.add(s[j]); | |||||
| baseDirs.add(base); | |||||
| } | } | ||||
| } | } | ||||
| if (!FileDirBoth.FILE.equals(currentType)) { | if (!FileDirBoth.FILE.equals(currentType)) { | ||||
| String[] s = getDirs(base, ds); | String[] s = getDirs(base, ds); | ||||
| for (int j = 0; j < s.length; j++) { | for (int j = 0; j < s.length; j++) { | ||||
| totalDirs++; | totalDirs++; | ||||
| fileNames.addElement(s[j]); | |||||
| baseDirs.addElement(base); | |||||
| fileNames.add(s[j]); | |||||
| baseDirs.add(base); | |||||
| } | } | ||||
| } | } | ||||
| if (fileNames.size() == 0 && skipEmpty) { | |||||
| if (fileNames.isEmpty() && skipEmpty) { | |||||
| logSkippingFileset(currentType, ds, base); | logSkippingFileset(currentType, ds, base); | ||||
| continue; | continue; | ||||
| } | } | ||||
| if (!parallel) { | if (!parallel) { | ||||
| String[] s = new String[fileNames.size()]; | |||||
| fileNames.copyInto(s); | |||||
| for (int j = 0; j < s.length; j++) { | |||||
| String[] command = getCommandline(s[j], base); | |||||
| for (String srcFile : fileNames) { | |||||
| String[] command = getCommandline(srcFile, base); | |||||
| log(Commandline.describeCommand(command), | log(Commandline.describeCommand(command), | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| exe.setCommandline(command); | exe.setCommandline(command); | ||||
| if (redirectorElement != null) { | if (redirectorElement != null) { | ||||
| setupRedirector(); | setupRedirector(); | ||||
| redirectorElement.configure(redirector, s[j]); | |||||
| redirectorElement.configure(redirector, srcFile); | |||||
| } | } | ||||
| if (redirectorElement != null || haveExecuted) { | if (redirectorElement != null || haveExecuted) { | ||||
| // need to reset the stream handler to restart | // need to reset the stream handler to restart | ||||
| @@ -411,8 +414,8 @@ public class ExecuteOn extends ExecTask { | |||||
| runExecute(exe); | runExecute(exe); | ||||
| haveExecuted = true; | haveExecuted = true; | ||||
| } | } | ||||
| fileNames.removeAllElements(); | |||||
| baseDirs.removeAllElements(); | |||||
| fileNames.clear(); | |||||
| baseDirs.clear(); | |||||
| } | } | ||||
| } | } | ||||
| @@ -469,12 +472,12 @@ public class ExecuteOn extends ExecTask { | |||||
| } | } | ||||
| runExecute(exe); | runExecute(exe); | ||||
| haveExecuted = true; | haveExecuted = true; | ||||
| fileNames.removeAllElements(); | |||||
| baseDirs.removeAllElements(); | |||||
| fileNames.clear(); | |||||
| baseDirs.clear(); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| if (parallel && (fileNames.size() > 0 || !skipEmpty)) { | |||||
| if (parallel && (!fileNames.isEmpty() || !skipEmpty)) { | |||||
| runParallel(exe, fileNames, baseDirs); | runParallel(exe, fileNames, baseDirs); | ||||
| haveExecuted = true; | haveExecuted = true; | ||||
| } | } | ||||
| @@ -524,31 +527,31 @@ public class ExecuteOn extends ExecTask { | |||||
| */ | */ | ||||
| protected String[] getCommandline(String[] srcFiles, File[] baseDirs) { | protected String[] getCommandline(String[] srcFiles, File[] baseDirs) { | ||||
| final char fileSeparator = File.separatorChar; | final char fileSeparator = File.separatorChar; | ||||
| Vector<String> targets = new Vector<String>(); | |||||
| List<String> targets = new ArrayList<>(); | |||||
| if (targetFilePos != null) { | if (targetFilePos != null) { | ||||
| HashSet<String> addedFiles = new HashSet<String>(); | |||||
| Set<String> addedFiles = new HashSet<>(); | |||||
| for (int i = 0; i < srcFiles.length; i++) { | for (int i = 0; i < srcFiles.length; i++) { | ||||
| String[] subTargets = mapper.mapFileName(srcFiles[i]); | String[] subTargets = mapper.mapFileName(srcFiles[i]); | ||||
| if (subTargets != null) { | if (subTargets != null) { | ||||
| for (int j = 0; j < subTargets.length; j++) { | |||||
| String name = null; | |||||
| if (!relative) { | |||||
| name = new File(destDir, subTargets[j]).getAbsolutePath(); | |||||
| for (String subTarget : subTargets) { | |||||
| String name; | |||||
| if (relative) { | |||||
| name = subTarget; | |||||
| } else { | } else { | ||||
| name = subTargets[j]; | |||||
| name = new File(destDir, subTarget).getAbsolutePath(); | |||||
| } | } | ||||
| if (forwardSlash && fileSeparator != '/') { | if (forwardSlash && fileSeparator != '/') { | ||||
| name = name.replace(fileSeparator, '/'); | name = name.replace(fileSeparator, '/'); | ||||
| } | } | ||||
| if (!addedFiles.contains(name)) { | if (!addedFiles.contains(name)) { | ||||
| targets.addElement(name); | |||||
| targets.add(name); | |||||
| addedFiles.add(name); | addedFiles.add(name); | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| String[] targetFiles = (String[]) targets.toArray(new String[targets.size()]); | |||||
| String[] targetFiles = targets.toArray(new String[targets.size()]); | |||||
| if (!addSourceFile) { | if (!addSourceFile) { | ||||
| srcFiles = new String[0]; | srcFiles = new String[0]; | ||||
| @@ -642,7 +645,7 @@ public class ExecuteOn extends ExecTask { | |||||
| * @return the command line in the form of a String[]. | * @return the command line in the form of a String[]. | ||||
| */ | */ | ||||
| protected String[] getCommandline(String srcFile, File baseDir) { | protected String[] getCommandline(String srcFile, File baseDir) { | ||||
| return getCommandline(new String[] {srcFile}, new File[] {baseDir}); | |||||
| return getCommandline(new String[] { srcFile }, new File[] { baseDir }); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -697,10 +700,8 @@ public class ExecuteOn extends ExecTask { | |||||
| protected void runParallel(Execute exe, Vector<String> fileNames, | protected void runParallel(Execute exe, Vector<String> fileNames, | ||||
| Vector<File> baseDirs) | Vector<File> baseDirs) | ||||
| throws IOException, BuildException { | throws IOException, BuildException { | ||||
| String[] s = new String[fileNames.size()]; | |||||
| fileNames.copyInto(s); | |||||
| File[] b = new File[baseDirs.size()]; | |||||
| baseDirs.copyInto(b); | |||||
| String[] s = fileNames.toArray(new String[fileNames.size()]); | |||||
| File[] b = baseDirs.toArray(new File[baseDirs.size()]); | |||||
| if (maxParallel <= 0 | if (maxParallel <= 0 | ||||
| || s.length == 0 /* this is skipEmpty == false */) { | || s.length == 0 /* this is skipEmpty == false */) { | ||||
| @@ -752,7 +753,7 @@ public class ExecuteOn extends ExecTask { | |||||
| String[] arguments, | String[] arguments, | ||||
| int insertPosition, | int insertPosition, | ||||
| String prefix, String suffix) { | String prefix, String suffix) { | ||||
| if (prefix.length() == 0 && suffix.length() == 0) { | |||||
| if (prefix.isEmpty() && suffix.isEmpty()) { | |||||
| System.arraycopy(targetFiles, 0, arguments, insertPosition, | System.arraycopy(targetFiles, 0, arguments, insertPosition, | ||||
| targetFiles.length); | targetFiles.length); | ||||
| } else { | } else { | ||||
| @@ -772,12 +773,14 @@ public class ExecuteOn extends ExecTask { | |||||
| public static final String FILE = "file"; | public static final String FILE = "file"; | ||||
| /** Dir value */ | /** Dir value */ | ||||
| public static final String DIR = "dir"; | public static final String DIR = "dir"; | ||||
| /** | /** | ||||
| * {@inheritDoc} | |||||
| * @see EnumeratedAttribute#getValues | * @see EnumeratedAttribute#getValues | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | |||||
| public String[] getValues() { | |||||
| return new String[] {FILE, DIR, "both"}; | |||||
| @Override | |||||
| public String[] getValues() { | |||||
| return new String[] { FILE, DIR, "both" }; | |||||
| } | } | ||||
| } | } | ||||
| @@ -74,6 +74,7 @@ public class ExecuteWatchdog implements TimeoutObserver { | |||||
| * Use constructor with a long type instead. | * Use constructor with a long type instead. | ||||
| * (1.4.x compatibility) | * (1.4.x compatibility) | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public ExecuteWatchdog(int timeout) { | public ExecuteWatchdog(int timeout) { | ||||
| this((long) timeout); | this((long) timeout); | ||||
| } | } | ||||
| @@ -112,6 +113,7 @@ public class ExecuteWatchdog implements TimeoutObserver { | |||||
| * This can be called in the watchdog thread | * This can be called in the watchdog thread | ||||
| * @param w the watchdog | * @param w the watchdog | ||||
| */ | */ | ||||
| @Override | |||||
| public synchronized void timeoutOccured(Watchdog w) { | public synchronized void timeoutOccured(Watchdog w) { | ||||
| try { | try { | ||||
| try { | try { | ||||
| @@ -174,4 +176,3 @@ public class ExecuteWatchdog implements TimeoutObserver { | |||||
| return killedProcess; | return killedProcess; | ||||
| } | } | ||||
| } | } | ||||
| @@ -50,12 +50,13 @@ import org.apache.tools.ant.taskdefs.condition.ConditionBase; | |||||
| public class Exit extends Task { | public class Exit extends Task { | ||||
| private static class NestedCondition extends ConditionBase implements Condition { | private static class NestedCondition extends ConditionBase implements Condition { | ||||
| @Override | |||||
| public boolean eval() { | public boolean eval() { | ||||
| if (countConditions() != 1) { | if (countConditions() != 1) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "A single nested condition is required."); | "A single nested condition is required."); | ||||
| } | } | ||||
| return ((Condition) (getConditions().nextElement())).eval(); | |||||
| return getConditions().nextElement().eval(); | |||||
| } | } | ||||
| } | } | ||||
| @@ -131,12 +132,13 @@ public class Exit extends Task { | |||||
| * the if and unless parameters (if present). | * the if and unless parameters (if present). | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| boolean fail = (nestedConditionPresent()) ? testNestedCondition() | boolean fail = (nestedConditionPresent()) ? testNestedCondition() | ||||
| : (testIfCondition() && testUnlessCondition()); | : (testIfCondition() && testUnlessCondition()); | ||||
| if (fail) { | if (fail) { | ||||
| String text = null; | String text = null; | ||||
| if (message != null && message.trim().length() > 0) { | |||||
| if (!(message == null || message.trim().isEmpty())) { | |||||
| text = message.trim(); | text = message.trim(); | ||||
| } else { | } else { | ||||
| if (ifCondition != null && !"".equals(ifCondition) | if (ifCondition != null && !"".equals(ifCondition) | ||||
| @@ -154,15 +156,13 @@ public class Exit extends Task { | |||||
| } | } | ||||
| if (nestedConditionPresent()) { | if (nestedConditionPresent()) { | ||||
| text = "condition satisfied"; | text = "condition satisfied"; | ||||
| } else { | |||||
| if (text == null) { | |||||
| text = "No message"; | |||||
| } | |||||
| } else if (text == null) { | |||||
| text = "No message"; | |||||
| } | } | ||||
| } | } | ||||
| log("failing due to " + text, Project.MSG_DEBUG); | log("failing due to " + text, Project.MSG_DEBUG); | ||||
| throw ((status == null) ? new BuildException(text) | |||||
| : new ExitStatusException(text, status.intValue())); | |||||
| throw status == null ? new BuildException(text) | |||||
| : new ExitStatusException(text, status.intValue()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -217,8 +217,8 @@ public class Exit extends Task { | |||||
| boolean result = nestedConditionPresent(); | boolean result = nestedConditionPresent(); | ||||
| if (result && ifCondition != null || unlessCondition != null) { | if (result && ifCondition != null || unlessCondition != null) { | ||||
| throw new BuildException("Nested conditions " | |||||
| + "not permitted in conjunction with if/unless attributes"); | |||||
| throw new BuildException( | |||||
| "Nested conditions not permitted in conjunction with if/unless attributes"); | |||||
| } | } | ||||
| return result && nestedCondition.eval(); | return result && nestedCondition.eval(); | ||||
| @@ -28,6 +28,7 @@ import java.util.Date; | |||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.HashSet; | import java.util.HashSet; | ||||
| import java.util.Iterator; | import java.util.Iterator; | ||||
| import java.util.List; | |||||
| import java.util.Set; | import java.util.Set; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| @@ -59,25 +60,26 @@ import org.apache.tools.zip.ZipFile; | |||||
| * name="unwar" | * name="unwar" | ||||
| */ | */ | ||||
| public class Expand extends Task { | public class Expand extends Task { | ||||
| public static final String NATIVE_ENCODING = "native-encoding"; | |||||
| /** Error message when more that one mapper is defined */ | |||||
| public static final String ERROR_MULTIPLE_MAPPERS = "Cannot define more than one mapper"; | |||||
| private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| private static final int BUFFER_SIZE = 1024; | private static final int BUFFER_SIZE = 1024; | ||||
| private File dest; //req | private File dest; //req | ||||
| private File source; // req | private File source; // req | ||||
| private boolean overwrite = true; | private boolean overwrite = true; | ||||
| private Mapper mapperElement = null; | private Mapper mapperElement = null; | ||||
| private Vector<PatternSet> patternsets = new Vector<PatternSet>(); | |||||
| private List<PatternSet> patternsets = new Vector<>(); | |||||
| private Union resources = new Union(); | private Union resources = new Union(); | ||||
| private boolean resourcesSpecified = false; | private boolean resourcesSpecified = false; | ||||
| private boolean failOnEmptyArchive = false; | private boolean failOnEmptyArchive = false; | ||||
| private boolean stripAbsolutePathSpec = false; | private boolean stripAbsolutePathSpec = false; | ||||
| private boolean scanForUnicodeExtraFields = true; | private boolean scanForUnicodeExtraFields = true; | ||||
| public static final String NATIVE_ENCODING = "native-encoding"; | |||||
| private String encoding; | private String encoding; | ||||
| /** Error message when more that one mapper is defined */ | |||||
| public static final String ERROR_MULTIPLE_MAPPERS = "Cannot define more than one mapper"; | |||||
| private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| /** | /** | ||||
| * Creates an Expand instance and sets encoding to UTF-8. | * Creates an Expand instance and sets encoding to UTF-8. | ||||
| @@ -118,14 +120,15 @@ public class Expand extends Task { | |||||
| * | * | ||||
| * @exception BuildException Thrown in unrecoverable error. | * @exception BuildException Thrown in unrecoverable error. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if ("expand".equals(getTaskType())) { | if ("expand".equals(getTaskType())) { | ||||
| log("!! expand is deprecated. Use unzip instead. !!"); | log("!! expand is deprecated. Use unzip instead. !!"); | ||||
| } | } | ||||
| if (source == null && !resourcesSpecified) { | if (source == null && !resourcesSpecified) { | ||||
| throw new BuildException("src attribute and/or resources must be " | |||||
| + "specified"); | |||||
| throw new BuildException( | |||||
| "src attribute and/or resources must be specified"); | |||||
| } | } | ||||
| if (dest == null) { | if (dest == null) { | ||||
| @@ -141,13 +144,14 @@ public class Expand extends Task { | |||||
| if (source.isDirectory()) { | if (source.isDirectory()) { | ||||
| throw new BuildException("Src must not be a directory." | throw new BuildException("Src must not be a directory." | ||||
| + " Use nested filesets instead.", getLocation()); | + " Use nested filesets instead.", getLocation()); | ||||
| } else if (!source.exists()) { | |||||
| } | |||||
| if (!source.exists()) { | |||||
| throw new BuildException("src '" + source + "' doesn't exist."); | throw new BuildException("src '" + source + "' doesn't exist."); | ||||
| } else if (!source.canRead()) { | |||||
| } | |||||
| if (!source.canRead()) { | |||||
| throw new BuildException("src '" + source + "' cannot be read."); | throw new BuildException("src '" + source + "' cannot be read."); | ||||
| } else { | |||||
| expandFile(FILE_UTILS, source, dest); | |||||
| } | } | ||||
| expandFile(FILE_UTILS, source, dest); | |||||
| } | } | ||||
| for (Resource r : resources) { | for (Resource r : resources) { | ||||
| if (!r.isExists()) { | if (!r.isExists()) { | ||||
| @@ -173,7 +177,6 @@ public class Expand extends Task { | |||||
| */ | */ | ||||
| protected void expandFile(FileUtils fileUtils, File srcF, File dir) { | protected void expandFile(FileUtils fileUtils, File srcF, File dir) { | ||||
| log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO); | log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO); | ||||
| ZipFile zf = null; | |||||
| FileNameMapper mapper = getMapper(); | FileNameMapper mapper = getMapper(); | ||||
| if (!srcF.exists()) { | if (!srcF.exists()) { | ||||
| throw new BuildException("Unable to expand " | throw new BuildException("Unable to expand " | ||||
| @@ -181,8 +184,9 @@ public class Expand extends Task { | |||||
| + " as the file does not exist", | + " as the file does not exist", | ||||
| getLocation()); | getLocation()); | ||||
| } | } | ||||
| try { | |||||
| zf = new ZipFile(srcF, encoding, scanForUnicodeExtraFields); | |||||
| try ( | |||||
| ZipFile | |||||
| zf = new ZipFile(srcF, encoding, scanForUnicodeExtraFields)){ | |||||
| boolean empty = true; | boolean empty = true; | ||||
| Enumeration<ZipEntry> e = zf.getEntries(); | Enumeration<ZipEntry> e = zf.getEntries(); | ||||
| while (e.hasMoreElements()) { | while (e.hasMoreElements()) { | ||||
| @@ -200,7 +204,7 @@ public class Expand extends Task { | |||||
| } | } | ||||
| } | } | ||||
| if (empty && getFailOnEmptyArchive()) { | if (empty && getFailOnEmptyArchive()) { | ||||
| throw new BuildException("archive '" + srcF + "' is empty"); | |||||
| throw new BuildException("archive '%s' is empty", srcF); | |||||
| } | } | ||||
| log("expand complete", Project.MSG_VERBOSE); | log("expand complete", Project.MSG_VERBOSE); | ||||
| } catch (IOException ioe) { | } catch (IOException ioe) { | ||||
| @@ -208,8 +212,6 @@ public class Expand extends Task { | |||||
| "Error while expanding " + srcF.getPath() | "Error while expanding " + srcF.getPath() | ||||
| + "\n" + ioe.toString(), | + "\n" + ioe.toString(), | ||||
| ioe); | ioe); | ||||
| } finally { | |||||
| ZipFile.closeQuietly(zf); | |||||
| } | } | ||||
| } | } | ||||
| @@ -220,8 +222,8 @@ public class Expand extends Task { | |||||
| * @param dir the destination directory | * @param dir the destination directory | ||||
| */ | */ | ||||
| protected void expandResource(Resource srcR, File dir) { | protected void expandResource(Resource srcR, File dir) { | ||||
| throw new BuildException("only filesystem based resources are" | |||||
| + " supported by this task."); | |||||
| throw new BuildException( | |||||
| "only filesystem based resources are supported by this task."); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -229,13 +231,10 @@ public class Expand extends Task { | |||||
| * @return a filenamemapper for a file | * @return a filenamemapper for a file | ||||
| */ | */ | ||||
| protected FileNameMapper getMapper() { | protected FileNameMapper getMapper() { | ||||
| FileNameMapper mapper = null; | |||||
| if (mapperElement != null) { | if (mapperElement != null) { | ||||
| mapper = mapperElement.getImplementation(); | |||||
| } else { | |||||
| mapper = new IdentityMapper(); | |||||
| return mapperElement.getImplementation(); | |||||
| } | } | ||||
| return mapper; | |||||
| return new IdentityMapper(); | |||||
| } | } | ||||
| // CheckStyle:ParameterNumberCheck OFF - bc | // CheckStyle:ParameterNumberCheck OFF - bc | ||||
| @@ -257,7 +256,7 @@ public class Expand extends Task { | |||||
| boolean isDirectory, FileNameMapper mapper) | boolean isDirectory, FileNameMapper mapper) | ||||
| throws IOException { | throws IOException { | ||||
| if (stripAbsolutePathSpec && entryName.length() > 0 | |||||
| if (stripAbsolutePathSpec && !entryName.isEmpty() | |||||
| && (entryName.charAt(0) == File.separatorChar | && (entryName.charAt(0) == File.separatorChar | ||||
| || entryName.charAt(0) == '/' | || entryName.charAt(0) == '/' | ||||
| || entryName.charAt(0) == '\\')) { | || entryName.charAt(0) == '\\')) { | ||||
| @@ -266,16 +265,16 @@ public class Expand extends Task { | |||||
| entryName = entryName.substring(1); | entryName = entryName.substring(1); | ||||
| } | } | ||||
| if (patternsets != null && patternsets.size() > 0) { | |||||
| if (!(patternsets == null || patternsets.isEmpty())) { | |||||
| String name = entryName.replace('/', File.separatorChar) | String name = entryName.replace('/', File.separatorChar) | ||||
| .replace('\\', File.separatorChar); | .replace('\\', File.separatorChar); | ||||
| boolean included = false; | boolean included = false; | ||||
| Set<String> includePatterns = new HashSet<String>(); | |||||
| Set<String> excludePatterns = new HashSet<String>(); | |||||
| Set<String> includePatterns = new HashSet<>(); | |||||
| Set<String> excludePatterns = new HashSet<>(); | |||||
| final int size = patternsets.size(); | final int size = patternsets.size(); | ||||
| for (int v = 0; v < size; v++) { | for (int v = 0; v < size; v++) { | ||||
| PatternSet p = patternsets.elementAt(v); | |||||
| PatternSet p = patternsets.get(v); | |||||
| String[] incls = p.getIncludePatterns(getProject()); | String[] incls = p.getIncludePatterns(getProject()); | ||||
| if (incls == null || incls.length == 0) { | if (incls == null || incls.length == 0) { | ||||
| // no include pattern implicitly means includes="**" | // no include pattern implicitly means includes="**" | ||||
| @@ -350,20 +349,11 @@ public class Expand extends Task { | |||||
| f.mkdirs(); | f.mkdirs(); | ||||
| } else { | } else { | ||||
| byte[] buffer = new byte[BUFFER_SIZE]; | byte[] buffer = new byte[BUFFER_SIZE]; | ||||
| int length = 0; | |||||
| OutputStream fos = null; | |||||
| try { | |||||
| fos = Files.newOutputStream(f.toPath()); | |||||
| while ((length = | |||||
| compressedInputStream.read(buffer)) >= 0) { | |||||
| try (OutputStream fos = Files.newOutputStream(f.toPath())) { | |||||
| int length; | |||||
| while ((length = compressedInputStream.read(buffer)) >= 0) { | |||||
| fos.write(buffer, 0, length); | fos.write(buffer, 0, length); | ||||
| } | } | ||||
| fos.close(); | |||||
| fos = null; | |||||
| } finally { | |||||
| FileUtils.close(fos); | |||||
| } | } | ||||
| } | } | ||||
| @@ -410,7 +400,7 @@ public class Expand extends Task { | |||||
| * @param set a pattern set | * @param set a pattern set | ||||
| */ | */ | ||||
| public void addPatternset(PatternSet set) { | public void addPatternset(PatternSet set) { | ||||
| patternsets.addElement(set); | |||||
| patternsets.add(set); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -69,6 +69,7 @@ public class Filter extends Task { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| boolean isFiltersFromFile = | boolean isFiltersFromFile = | ||||
| filtersFile != null && token == null && value == null; | filtersFile != null && token == null && value == null; | ||||
| @@ -76,9 +77,9 @@ public class Filter extends Task { | |||||
| filtersFile == null && token != null && value != null; | filtersFile == null && token != null && value != null; | ||||
| if (!isFiltersFromFile && !isSingleFilter) { | if (!isFiltersFromFile && !isSingleFilter) { | ||||
| throw new BuildException("both token and value parameters, or " | |||||
| + "only a filtersFile parameter is " | |||||
| + "required", getLocation()); | |||||
| throw new BuildException( | |||||
| "both token and value parameters, or only a filtersFile parameter is required", | |||||
| getLocation()); | |||||
| } | } | ||||
| if (isSingleFilter) { | if (isSingleFilter) { | ||||
| @@ -115,6 +115,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| * @return a Reader. | * @return a Reader. | ||||
| * @since Ant 1.7? | * @since Ant 1.7? | ||||
| */ | */ | ||||
| @Override | |||||
| public final Reader chain(final Reader rdr) { | public final Reader chain(final Reader rdr) { | ||||
| return filter.chain(rdr); | return filter.chain(rdr); | ||||
| } | } | ||||
| @@ -181,15 +182,16 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| * @deprecated since 1.4.x. | * @deprecated since 1.4.x. | ||||
| * Use {@link #setEol setEol} instead. | * Use {@link #setEol setEol} instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setCr(AddAsisRemove attr) { | public void setCr(AddAsisRemove attr) { | ||||
| log("DEPRECATED: The cr attribute has been deprecated,", | log("DEPRECATED: The cr attribute has been deprecated,", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| log("Please use the eol attribute instead", Project.MSG_WARN); | log("Please use the eol attribute instead", Project.MSG_WARN); | ||||
| String option = attr.getValue(); | String option = attr.getValue(); | ||||
| CrLf c = new CrLf(); | CrLf c = new CrLf(); | ||||
| if (option.equals("remove")) { | |||||
| if ("remove".equals(option)) { | |||||
| c.setValue("lf"); | c.setValue("lf"); | ||||
| } else if (option.equals("asis")) { | |||||
| } else if ("asis".equals(option)) { | |||||
| c.setValue("asis"); | c.setValue("asis"); | ||||
| } else { | } else { | ||||
| // must be "add" | // must be "add" | ||||
| @@ -282,6 +284,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| * Executes the task. | * Executes the task. | ||||
| * @throws BuildException on error. | * @throws BuildException on error. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| // first off, make sure that we've got a srcdir and destdir | // first off, make sure that we've got a srcdir and destdir | ||||
| validate(); | validate(); | ||||
| @@ -322,22 +325,21 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| } | } | ||||
| if (!srcDir.exists()) { | if (!srcDir.exists()) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| FIXCRLF_ERROR + "srcdir does not exist: '" + srcDir + "'"); | |||||
| FIXCRLF_ERROR + "srcdir does not exist: '%s'", srcDir); | |||||
| } | } | ||||
| if (!srcDir.isDirectory()) { | if (!srcDir.isDirectory()) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| FIXCRLF_ERROR + "srcdir is not a directory: '" + srcDir + "'"); | |||||
| FIXCRLF_ERROR + "srcdir is not a directory: '%s'", srcDir); | |||||
| } | } | ||||
| if (destDir != null) { | if (destDir != null) { | ||||
| if (!destDir.exists()) { | if (!destDir.exists()) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| FIXCRLF_ERROR + "destdir does not exist: '" | |||||
| + destDir + "'"); | |||||
| FIXCRLF_ERROR + "destdir does not exist: '%s'", destDir); | |||||
| } | } | ||||
| if (!destDir.isDirectory()) { | if (!destDir.isDirectory()) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| FIXCRLF_ERROR + "destdir is not a directory: '" | |||||
| + destDir + "'"); | |||||
| FIXCRLF_ERROR + "destdir is not a directory: '%s'", | |||||
| destDir); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -350,7 +352,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| if (fcv == null) { | if (fcv == null) { | ||||
| FilterChain fc = new FilterChain(); | FilterChain fc = new FilterChain(); | ||||
| fc.add(filter); | fc.add(filter); | ||||
| fcv = new Vector<FilterChain>(1); | |||||
| fcv = new Vector<>(1); | |||||
| fcv.add(fc); | fcv.add(fc); | ||||
| } | } | ||||
| File tmpFile = FILE_UTILS.createTempFile("fixcrlf", "", null, true, true); | File tmpFile = FILE_UTILS.createTempFile("fixcrlf", "", null, true, true); | ||||
| @@ -391,6 +393,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| * Deprecated, the functionality has been moved to filters.FixCrLfFilter. | * Deprecated, the functionality has been moved to filters.FixCrLfFilter. | ||||
| * @deprecated since 1.7.0. | * @deprecated since 1.7.0. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| protected class OneLiner implements Enumeration<Object> { | protected class OneLiner implements Enumeration<Object> { | ||||
| private static final int UNDEF = -1; | private static final int UNDEF = -1; | ||||
| private static final int NOTJAVA = 0; | private static final int NOTJAVA = 0; | ||||
| @@ -549,6 +552,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| /** | /** | ||||
| * @return true if there is more elements. | * @return true if there is more elements. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean hasMoreElements() { | public boolean hasMoreElements() { | ||||
| return !reachedEof; | return !reachedEof; | ||||
| } | } | ||||
| @@ -558,6 +562,7 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| * @return the next element. | * @return the next element. | ||||
| * @throws NoSuchElementException if there is no more. | * @throws NoSuchElementException if there is no more. | ||||
| */ | */ | ||||
| @Override | |||||
| public Object nextElement() | public Object nextElement() | ||||
| throws NoSuchElementException { | throws NoSuchElementException { | ||||
| if (!hasMoreElements()) { | if (!hasMoreElements()) { | ||||
| @@ -673,22 +678,24 @@ public class FixCRLF extends MatchingTask implements ChainableReader { | |||||
| */ | */ | ||||
| public static class AddAsisRemove extends EnumeratedAttribute { | public static class AddAsisRemove extends EnumeratedAttribute { | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {"add", "asis", "remove"}; | |||||
| return new String[] { "add", "asis", "remove" }; | |||||
| } | } | ||||
| } | } | ||||
| /** | /** | ||||
| * Enumerated attribute with the values "asis", "cr", "lf" and "crlf". | |||||
| * Enumerated attribute with the values "asis", "cr", "lf", "crlf", "mac", "unix" and "dos. | |||||
| */ | */ | ||||
| public static class CrLf extends EnumeratedAttribute { | public static class CrLf extends EnumeratedAttribute { | ||||
| /** | /** | ||||
| * @see EnumeratedAttribute#getValues | * @see EnumeratedAttribute#getValues | ||||
| */ | */ | ||||
| /** {@inheritDoc}. */ | /** {@inheritDoc}. */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {"asis", "cr", "lf", "crlf", | |||||
| "mac", "unix", "dos"}; | |||||
| return new String[] { "asis", "cr", "lf", "crlf", "mac", "unix", | |||||
| "dos" }; | |||||
| } | } | ||||
| } | } | ||||
| @@ -19,13 +19,11 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.InputStream; | |||||
| import java.io.OutputStream; | import java.io.OutputStream; | ||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.util.zip.GZIPInputStream; | import java.util.zip.GZIPInputStream; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| /** | /** | ||||
| * Expands a file that has been compressed with the GZIP | * Expands a file that has been compressed with the GZIP | ||||
| @@ -45,6 +43,7 @@ public class GUnzip extends Unpack { | |||||
| * Get the default extension. | * Get the default extension. | ||||
| * @return the value ".gz" | * @return the value ".gz" | ||||
| */ | */ | ||||
| @Override | |||||
| protected String getDefaultExtension() { | protected String getDefaultExtension() { | ||||
| return DEFAULT_EXTENSION; | return DEFAULT_EXTENSION; | ||||
| } | } | ||||
| @@ -52,18 +51,14 @@ public class GUnzip extends Unpack { | |||||
| /** | /** | ||||
| * Implement the gunzipping. | * Implement the gunzipping. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void extract() { | protected void extract() { | ||||
| if (srcResource.getLastModified() > dest.lastModified()) { | if (srcResource.getLastModified() > dest.lastModified()) { | ||||
| log("Expanding " + srcResource.getName() + " to " | log("Expanding " + srcResource.getName() + " to " | ||||
| + dest.getAbsolutePath()); | + dest.getAbsolutePath()); | ||||
| OutputStream out = null; | |||||
| GZIPInputStream zIn = null; | |||||
| InputStream fis = null; | |||||
| try { | |||||
| out = Files.newOutputStream(dest.toPath()); | |||||
| fis = srcResource.getInputStream(); | |||||
| zIn = new GZIPInputStream(fis); | |||||
| try (OutputStream out = Files.newOutputStream(dest.toPath()); | |||||
| GZIPInputStream zIn = | |||||
| new GZIPInputStream(srcResource.getInputStream())) { | |||||
| byte[] buffer = new byte[BUFFER_SIZE]; | byte[] buffer = new byte[BUFFER_SIZE]; | ||||
| int count = 0; | int count = 0; | ||||
| do { | do { | ||||
| @@ -73,10 +68,6 @@ public class GUnzip extends Unpack { | |||||
| } catch (IOException ioe) { | } catch (IOException ioe) { | ||||
| String msg = "Problem expanding gzip " + ioe.getMessage(); | String msg = "Problem expanding gzip " + ioe.getMessage(); | ||||
| throw new BuildException(msg, ioe, getLocation()); | throw new BuildException(msg, ioe, getLocation()); | ||||
| } finally { | |||||
| FileUtils.close(fis); | |||||
| FileUtils.close(out); | |||||
| FileUtils.close(zIn); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -92,6 +83,7 @@ public class GUnzip extends Unpack { | |||||
| * @return true if this task supports non file resources. | * @return true if this task supports non file resources. | ||||
| * @since Ant 1.7 | * @since Ant 1.7 | ||||
| */ | */ | ||||
| @Override | |||||
| protected boolean supportsNonFileResources() { | protected boolean supportsNonFileResources() { | ||||
| return getClass().equals(GUnzip.class); | return getClass().equals(GUnzip.class); | ||||
| } | } | ||||
| @@ -19,12 +19,10 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.OutputStream; | |||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.util.zip.GZIPOutputStream; | import java.util.zip.GZIPOutputStream; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| /** | /** | ||||
| * Compresses a file with the GZIP algorithm. Normally used to compress | * Compresses a file with the GZIP algorithm. Normally used to compress | ||||
| @@ -39,16 +37,14 @@ public class GZip extends Pack { | |||||
| /** | /** | ||||
| * perform the GZip compression operation. | * perform the GZip compression operation. | ||||
| */ | */ | ||||
| @Override | |||||
| protected void pack() { | protected void pack() { | ||||
| GZIPOutputStream zOut = null; | |||||
| try { | |||||
| zOut = new GZIPOutputStream(Files.newOutputStream(zipFile.toPath())); | |||||
| try (GZIPOutputStream zOut = | |||||
| new GZIPOutputStream(Files.newOutputStream(zipFile.toPath()))) { | |||||
| zipResource(getSrcResource(), zOut); | zipResource(getSrcResource(), zOut); | ||||
| } catch (IOException ioe) { | } catch (IOException ioe) { | ||||
| String msg = "Problem creating gzip " + ioe.getMessage(); | String msg = "Problem creating gzip " + ioe.getMessage(); | ||||
| throw new BuildException(msg, ioe, getLocation()); | throw new BuildException(msg, ioe, getLocation()); | ||||
| } finally { | |||||
| FileUtils.close(zOut); | |||||
| } | } | ||||
| } | } | ||||
| @@ -63,6 +59,7 @@ public class GZip extends Pack { | |||||
| * @return true if this case supports non file resources. | * @return true if this case supports non file resources. | ||||
| * @since Ant 1.7 | * @since Ant 1.7 | ||||
| */ | */ | ||||
| @Override | |||||
| protected boolean supportsNonFileResources() { | protected boolean supportsNonFileResources() { | ||||
| return getClass().equals(GZip.class); | return getClass().equals(GZip.class); | ||||
| } | } | ||||
| @@ -17,8 +17,12 @@ | |||||
| */ | */ | ||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.util.Collections; | |||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.List; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import java.util.stream.Collectors; | |||||
| import java.util.stream.Stream; | |||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| @@ -83,7 +87,7 @@ public class GenerateKey extends Task { | |||||
| * A class corresponding to the dname nested element. | * A class corresponding to the dname nested element. | ||||
| */ | */ | ||||
| public static class DistinguishedName { | public static class DistinguishedName { | ||||
| private Vector<DnameParam> params = new Vector<DnameParam>(); | |||||
| private List<DnameParam> params = new Vector<>(); | |||||
| /** | /** | ||||
| * Create a param nested element. | * Create a param nested element. | ||||
| @@ -91,8 +95,7 @@ public class GenerateKey extends Task { | |||||
| */ | */ | ||||
| public Object createParam() { | public Object createParam() { | ||||
| DnameParam param = new DnameParam(); | DnameParam param = new DnameParam(); | ||||
| params.addElement(param); | |||||
| params.add(param); | |||||
| return param; | return param; | ||||
| } | } | ||||
| @@ -101,7 +104,7 @@ public class GenerateKey extends Task { | |||||
| * @return an enumeration of the nested parameters. | * @return an enumeration of the nested parameters. | ||||
| */ | */ | ||||
| public Enumeration<DnameParam> getParams() { | public Enumeration<DnameParam> getParams() { | ||||
| return params.elements(); | |||||
| return Collections.enumeration(params); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -111,26 +114,10 @@ public class GenerateKey extends Task { | |||||
| * This is used on the command line. | * This is used on the command line. | ||||
| * @return a string rep of this name | * @return a string rep of this name | ||||
| */ | */ | ||||
| @Override | |||||
| public String toString() { | public String toString() { | ||||
| final int size = params.size(); | |||||
| final StringBuffer sb = new StringBuffer(); | |||||
| boolean firstPass = true; | |||||
| for (int i = 0; i < size; i++) { | |||||
| if (!firstPass) { | |||||
| sb.append(" ,"); | |||||
| } | |||||
| firstPass = false; | |||||
| final DnameParam param = (DnameParam) params.elementAt(i); | |||||
| if (param.isComplete()) { | |||||
| sb.append(encode(param.getName())); | |||||
| sb.append('='); | |||||
| sb.append(encode(param.getValue())); | |||||
| } | |||||
| } | |||||
| return sb.toString(); | |||||
| return params.stream().map(p -> p.getName() + "=" + p.getValue()) | |||||
| .collect(Collectors.joining(", ")); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -141,26 +128,8 @@ public class GenerateKey extends Task { | |||||
| * @return the encoded value. | * @return the encoded value. | ||||
| */ | */ | ||||
| public String encode(final String string) { | public String encode(final String string) { | ||||
| int end = string.indexOf(','); | |||||
| if (-1 == end) { | |||||
| return string; | |||||
| } | |||||
| final StringBuffer sb = new StringBuffer(); | |||||
| int start = 0; | |||||
| while (-1 != end) { | |||||
| sb.append(string.substring(start, end)); | |||||
| sb.append("\\,"); | |||||
| start = end + 1; | |||||
| end = string.indexOf(',', start); | |||||
| } | |||||
| sb.append(string.substring(start)); | |||||
| return sb.toString(); | |||||
| return Stream.of(string.split(",")) | |||||
| .collect(Collectors.joining("\\,")); | |||||
| } | } | ||||
| } | } | ||||
| @@ -197,12 +166,11 @@ public class GenerateKey extends Task { | |||||
| */ | */ | ||||
| public DistinguishedName createDname() throws BuildException { | public DistinguishedName createDname() throws BuildException { | ||||
| if (null != expandedDname) { | if (null != expandedDname) { | ||||
| throw new BuildException("DName sub-element can only be " | |||||
| + "specified once."); | |||||
| throw new BuildException("DName sub-element can only be specified once."); | |||||
| } | } | ||||
| if (null != dname) { | if (null != dname) { | ||||
| throw new BuildException("It is not possible to specify dname " | |||||
| + " both as attribute and element."); | |||||
| throw new BuildException( | |||||
| "It is not possible to specify dname both as attribute and element."); | |||||
| } | } | ||||
| expandedDname = new DistinguishedName(); | expandedDname = new DistinguishedName(); | ||||
| return expandedDname; | return expandedDname; | ||||
| @@ -215,8 +183,8 @@ public class GenerateKey extends Task { | |||||
| */ | */ | ||||
| public void setDname(final String dname) { | public void setDname(final String dname) { | ||||
| if (null != expandedDname) { | if (null != expandedDname) { | ||||
| throw new BuildException("It is not possible to specify dname " | |||||
| + " both as attribute and element."); | |||||
| throw new BuildException( | |||||
| "It is not possible to specify dname both as attribute and element."); | |||||
| } | } | ||||
| this.dname = dname; | this.dname = dname; | ||||
| } | } | ||||
| @@ -324,6 +292,7 @@ public class GenerateKey extends Task { | |||||
| * Execute the task. | * Execute the task. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (null == alias) { | if (null == alias) { | ||||
| @@ -338,7 +307,7 @@ public class GenerateKey extends Task { | |||||
| throw new BuildException("dname must be set"); | throw new BuildException("dname must be set"); | ||||
| } | } | ||||
| final StringBuffer sb = new StringBuffer(); | |||||
| final StringBuilder sb = new StringBuilder(); | |||||
| sb.append("-genkey "); | sb.append("-genkey "); | ||||
| @@ -400,7 +369,6 @@ public class GenerateKey extends Task { | |||||
| sb.append("\" "); | sb.append("\" "); | ||||
| } | } | ||||
| if (0 < keysize) { | if (0 < keysize) { | ||||
| sb.append("-keysize \""); | sb.append("-keysize \""); | ||||
| sb.append(keysize); | sb.append(keysize); | ||||
| @@ -96,7 +96,7 @@ public class Get extends Task { | |||||
| + Main.getShortAntVersion()); | + Main.getShortAntVersion()); | ||||
| // Store headers as key/value pair without duplicate in keyz | // Store headers as key/value pair without duplicate in keyz | ||||
| private Map<String, String> headers = new LinkedHashMap<String, String>(); | |||||
| private Map<String, String> headers = new LinkedHashMap<>(); | |||||
| /** | /** | ||||
| * Does the work. | * Does the work. | ||||
| @@ -118,7 +118,7 @@ public class Get extends Task { | |||||
| if (path.endsWith("/")) { | if (path.endsWith("/")) { | ||||
| path = path.substring(0, path.length() - 1); | path = path.substring(0, path.length() - 1); | ||||
| } | } | ||||
| final int slash = path.lastIndexOf("/"); | |||||
| final int slash = path.lastIndexOf('/'); | |||||
| if (slash > -1) { | if (slash > -1) { | ||||
| path = path.substring(slash + 1); | path = path.substring(slash + 1); | ||||
| } | } | ||||
| @@ -130,11 +130,13 @@ public class Get extends Task { | |||||
| log("skipping " + r + " - mapper can't handle it", | log("skipping " + r + " - mapper can't handle it", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| continue; | continue; | ||||
| } else if (d.length == 0) { | |||||
| } | |||||
| if (d.length == 0) { | |||||
| log("skipping " + r + " - mapper returns no file name", | log("skipping " + r + " - mapper returns no file name", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| continue; | continue; | ||||
| } else if (d.length > 1) { | |||||
| } | |||||
| if (d.length > 1) { | |||||
| log("skipping " + r + " - mapper returns multiple file" | log("skipping " + r + " - mapper returns multiple file" | ||||
| + " names", Project.MSG_WARN); | + " names", Project.MSG_WARN); | ||||
| continue; | continue; | ||||
| @@ -288,8 +290,8 @@ public class Get extends Task { | |||||
| for (final Resource r : sources) { | for (final Resource r : sources) { | ||||
| final URLProvider up = r.as(URLProvider.class); | final URLProvider up = r.as(URLProvider.class); | ||||
| if (up == null) { | if (up == null) { | ||||
| throw new BuildException("Only URLProvider resources are" | |||||
| + " supported", getLocation()); | |||||
| throw new BuildException( | |||||
| "Only URLProvider resources are supported", getLocation()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -299,9 +301,8 @@ public class Get extends Task { | |||||
| if (destination.exists() && sources.size() > 1 | if (destination.exists() && sources.size() > 1 | ||||
| && !destination.isDirectory()) { | && !destination.isDirectory()) { | ||||
| throw new BuildException("The specified destination is not a" | |||||
| + " directory", | |||||
| getLocation()); | |||||
| throw new BuildException( | |||||
| "The specified destination is not a directory", getLocation()); | |||||
| } | } | ||||
| if (destination.exists() && !destination.canWrite()) { | if (destination.exists() && !destination.canWrite()) { | ||||
| @@ -391,7 +392,6 @@ public class Get extends Task { | |||||
| useTimestamp = v; | useTimestamp = v; | ||||
| } | } | ||||
| /** | /** | ||||
| * Username for basic auth. | * Username for basic auth. | ||||
| * | * | ||||
| @@ -566,6 +566,7 @@ public class Get extends Task { | |||||
| /** | /** | ||||
| * begin a download | * begin a download | ||||
| */ | */ | ||||
| @Override | |||||
| public void beginDownload() { | public void beginDownload() { | ||||
| } | } | ||||
| @@ -573,12 +574,14 @@ public class Get extends Task { | |||||
| * tick handler | * tick handler | ||||
| * | * | ||||
| */ | */ | ||||
| @Override | |||||
| public void onTick() { | public void onTick() { | ||||
| } | } | ||||
| /** | /** | ||||
| * end a download | * end a download | ||||
| */ | */ | ||||
| @Override | |||||
| public void endDownload() { | public void endDownload() { | ||||
| } | } | ||||
| } | } | ||||
| @@ -603,6 +606,7 @@ public class Get extends Task { | |||||
| /** | /** | ||||
| * begin a download | * begin a download | ||||
| */ | */ | ||||
| @Override | |||||
| public void beginDownload() { | public void beginDownload() { | ||||
| dots = 0; | dots = 0; | ||||
| } | } | ||||
| @@ -611,6 +615,7 @@ public class Get extends Task { | |||||
| * tick handler | * tick handler | ||||
| * | * | ||||
| */ | */ | ||||
| @Override | |||||
| public void onTick() { | public void onTick() { | ||||
| out.print("."); | out.print("."); | ||||
| if (dots++ > DOTS_PER_LINE) { | if (dots++ > DOTS_PER_LINE) { | ||||
| @@ -622,6 +627,7 @@ public class Get extends Task { | |||||
| /** | /** | ||||
| * end a download | * end a download | ||||
| */ | */ | ||||
| @Override | |||||
| public void endDownload() { | public void endDownload() { | ||||
| out.println(); | out.println(); | ||||
| out.flush(); | out.flush(); | ||||
| @@ -699,9 +705,8 @@ public class Get extends Task { | |||||
| if (ignoreErrors) { | if (ignoreErrors) { | ||||
| log(message, logLevel); | log(message, logLevel); | ||||
| return false; | return false; | ||||
| } else { | |||||
| throw new BuildException(message); | |||||
| } | } | ||||
| throw new BuildException(message); | |||||
| } | } | ||||
| redirections++; | redirections++; | ||||
| @@ -711,12 +716,9 @@ public class Get extends Task { | |||||
| if (ignoreErrors) { | if (ignoreErrors) { | ||||
| log(message, logLevel); | log(message, logLevel); | ||||
| return false; | return false; | ||||
| } else { | |||||
| throw new BuildException(message); | |||||
| } | } | ||||
| throw new BuildException(message); | |||||
| } | } | ||||
| return true; | return true; | ||||
| } | } | ||||
| @@ -749,14 +751,12 @@ public class Get extends Task { | |||||
| connection.setRequestProperty("Accept-Encoding", GZIP_CONTENT_ENCODING); | connection.setRequestProperty("Accept-Encoding", GZIP_CONTENT_ENCODING); | ||||
| } | } | ||||
| for (final Map.Entry<String, String> header : headers.entrySet()) { | for (final Map.Entry<String, String> header : headers.entrySet()) { | ||||
| //we do not log the header value as it may contain sensitive data like passwords | //we do not log the header value as it may contain sensitive data like passwords | ||||
| log(String.format("Adding header '%s' ", header.getKey())); | log(String.format("Adding header '%s' ", header.getKey())); | ||||
| connection.setRequestProperty(header.getKey(), header.getValue()); | connection.setRequestProperty(header.getKey(), header.getValue()); | ||||
| } | } | ||||
| if (connection instanceof HttpURLConnection) { | if (connection instanceof HttpURLConnection) { | ||||
| ((HttpURLConnection) connection) | ((HttpURLConnection) connection) | ||||
| .setInstanceFollowRedirects(false); | .setInstanceFollowRedirects(false); | ||||
| @@ -804,9 +804,8 @@ public class Get extends Task { | |||||
| if (ignoreErrors) { | if (ignoreErrors) { | ||||
| log(message, logLevel); | log(message, logLevel); | ||||
| return null; | return null; | ||||
| } else { | |||||
| throw new BuildException(message); | |||||
| } | } | ||||
| throw new BuildException(message); | |||||
| } | } | ||||
| } | } | ||||
| @@ -105,8 +105,9 @@ public class HostInfo extends Task { | |||||
| * @throws BuildException | * @throws BuildException | ||||
| * on error. | * on error. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| if (host == null || "".equals(host)) { | |||||
| if (host == null || host.isEmpty()) { | |||||
| executeLocal(); | executeLocal(); | ||||
| } else { | } else { | ||||
| executeRemote(); | executeRemote(); | ||||
| @@ -115,7 +116,7 @@ public class HostInfo extends Task { | |||||
| private void executeLocal() { | private void executeLocal() { | ||||
| try { | try { | ||||
| inetAddrs = new LinkedList<InetAddress>(); | |||||
| inetAddrs = new LinkedList<>(); | |||||
| Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); | Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); | ||||
| while (interfaces.hasMoreElements()) { | while (interfaces.hasMoreElements()) { | ||||
| NetworkInterface currentif = interfaces.nextElement(); | NetworkInterface currentif = interfaces.nextElement(); | ||||
| @@ -175,34 +176,32 @@ public class HostInfo extends Task { | |||||
| if (best == null) { | if (best == null) { | ||||
| // none selected so far, so this one is better. | // none selected so far, so this one is better. | ||||
| best = current; | best = current; | ||||
| } else if (current == null || current.isLoopbackAddress()) { | |||||
| // definitely not better than the previously selected address. | |||||
| } else if (current.isLinkLocalAddress()) { | |||||
| // link local considered better than loopback | |||||
| if (best.isLoopbackAddress()) { | |||||
| best = current; | |||||
| } | |||||
| } else if (current.isSiteLocalAddress()) { | |||||
| // site local considered better than link local (and loopback) | |||||
| // address with hostname resolved considered better than | |||||
| // address without hostname | |||||
| if (best.isLoopbackAddress() | |||||
| || best.isLinkLocalAddress() | |||||
| || (best.isSiteLocalAddress() && !hasHostName(best))) { | |||||
| best = current; | |||||
| } | |||||
| } else { | } else { | ||||
| if (current == null || current.isLoopbackAddress()) { | |||||
| // definitely not better than the previously selected address. | |||||
| } else if (current.isLinkLocalAddress()) { | |||||
| // link local considered better than loopback | |||||
| if (best.isLoopbackAddress()) { | |||||
| best = current; | |||||
| } | |||||
| } else if (current.isSiteLocalAddress()) { | |||||
| // site local considered better than link local (and loopback) | |||||
| // address with hostname resolved considered better than | |||||
| // address without hostname | |||||
| if (best.isLoopbackAddress() | |||||
| || best.isLinkLocalAddress() | |||||
| || (best.isSiteLocalAddress() && !hasHostName(best))) { | |||||
| best = current; | |||||
| } | |||||
| } else { | |||||
| // current is a "Global address", considered better than | |||||
| // site local (and better than link local, loopback) | |||||
| // address with hostname resolved considered better than | |||||
| // address without hostname | |||||
| if (best.isLoopbackAddress() | |||||
| || best.isLinkLocalAddress() | |||||
| || best.isSiteLocalAddress() | |||||
| || !hasHostName(best)) { | |||||
| best = current; | |||||
| } | |||||
| // current is a "Global address", considered better than | |||||
| // site local (and better than link local, loopback) | |||||
| // address with hostname resolved considered better than | |||||
| // address without hostname | |||||
| if (best.isLoopbackAddress() | |||||
| || best.isLinkLocalAddress() | |||||
| || best.isSiteLocalAddress() | |||||
| || !hasHostName(best)) { | |||||
| best = current; | |||||
| } | } | ||||
| } | } | ||||
| return best; | return best; | ||||
| @@ -63,12 +63,13 @@ import org.apache.tools.ant.util.FileUtils; | |||||
| * @ant.task category="control" | * @ant.task category="control" | ||||
| */ | */ | ||||
| public class ImportTask extends Task { | public class ImportTask extends Task { | ||||
| private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| private String file; | private String file; | ||||
| private boolean optional; | private boolean optional; | ||||
| private String targetPrefix = ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX; | private String targetPrefix = ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX; | ||||
| private String prefixSeparator = "."; | private String prefixSeparator = "."; | ||||
| private final Union resources = new Union(); | private final Union resources = new Union(); | ||||
| private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); | |||||
| public ImportTask() { | public ImportTask() { | ||||
| resources.setCache(true); | resources.setCache(true); | ||||
| @@ -123,18 +124,18 @@ public class ImportTask extends Task { | |||||
| resources.add(r); | resources.add(r); | ||||
| } | } | ||||
| @Override | |||||
| public void execute() { | public void execute() { | ||||
| if (file == null && resources.size() == 0) { | |||||
| throw new BuildException("import requires file attribute or" | |||||
| + " at least one nested resource"); | |||||
| if (file == null && resources.isEmpty()) { | |||||
| throw new BuildException( | |||||
| "import requires file attribute or at least one nested resource"); | |||||
| } | } | ||||
| if (getOwningTarget() == null | if (getOwningTarget() == null | ||||
| || !"".equals(getOwningTarget().getName())) { | |||||
| || !getOwningTarget().getName().isEmpty()) { | |||||
| throw new BuildException("import only allowed as a top-level task"); | throw new BuildException("import only allowed as a top-level task"); | ||||
| } | } | ||||
| ProjectHelper helper = | |||||
| (ProjectHelper) getProject(). | |||||
| ProjectHelper helper = getProject(). | |||||
| getReference(ProjectHelper.PROJECTHELPER_REFERENCE); | getReference(ProjectHelper.PROJECTHELPER_REFERENCE); | ||||
| if (helper == null) { | if (helper == null) { | ||||
| @@ -142,9 +143,7 @@ public class ImportTask extends Task { | |||||
| throw new BuildException("import requires support in ProjectHelper"); | throw new BuildException("import requires support in ProjectHelper"); | ||||
| } | } | ||||
| Vector<Object> importStack = helper.getImportStack(); | |||||
| if (importStack.size() == 0) { | |||||
| if (helper.getImportStack().isEmpty()) { | |||||
| // this happens if ant is used with a project | // this happens if ant is used with a project | ||||
| // helper that doesn't set the import. | // helper that doesn't set the import. | ||||
| throw new BuildException("import requires support in ProjectHelper"); | throw new BuildException("import requires support in ProjectHelper"); | ||||
| @@ -166,8 +165,6 @@ public class ImportTask extends Task { | |||||
| private void importResource(ProjectHelper helper, | private void importResource(ProjectHelper helper, | ||||
| Resource importedResource) { | Resource importedResource) { | ||||
| Vector<Object> importStack = helper.getImportStack(); | |||||
| getProject().log("Importing file " + importedResource + " from " | getProject().log("Importing file " + importedResource + " from " | ||||
| + getLocation().getFileName(), Project.MSG_VERBOSE); | + getLocation().getFileName(), Project.MSG_VERBOSE); | ||||
| @@ -178,13 +175,12 @@ public class ImportTask extends Task { | |||||
| if (optional) { | if (optional) { | ||||
| getProject().log(message, Project.MSG_VERBOSE); | getProject().log(message, Project.MSG_VERBOSE); | ||||
| return; | return; | ||||
| } else { | |||||
| throw new BuildException(message); | |||||
| } | } | ||||
| throw new BuildException(message); | |||||
| } | } | ||||
| if (!isInIncludeMode() && | |||||
| hasAlreadyBeenImported(importedResource, importStack)) { | |||||
| if (!isInIncludeMode() && hasAlreadyBeenImported(importedResource, | |||||
| helper.getImportStack())) { | |||||
| getProject().log( | getProject().log( | ||||
| "Skipped already imported file:\n " | "Skipped already imported file:\n " | ||||
| + importedResource + "\n", Project.MSG_VERBOSE); | + importedResource + "\n", Project.MSG_VERBOSE); | ||||
| @@ -203,10 +199,10 @@ public class ImportTask extends Task { | |||||
| prefix = oldPrefix + oldSep + targetPrefix; | prefix = oldPrefix + oldSep + targetPrefix; | ||||
| } else if (isInIncludeMode()) { | } else if (isInIncludeMode()) { | ||||
| prefix = targetPrefix; | prefix = targetPrefix; | ||||
| } else if (!ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX.equals(targetPrefix)) { | |||||
| prefix = targetPrefix; | |||||
| } else { | |||||
| } else if (ProjectHelper.USE_PROJECT_NAME_AS_TARGET_PREFIX.equals(targetPrefix)) { | |||||
| prefix = oldPrefix; | prefix = oldPrefix; | ||||
| } else { | |||||
| prefix = targetPrefix; | |||||
| } | } | ||||
| setProjectHelperProps(prefix, prefixSeparator, | setProjectHelperProps(prefix, prefixSeparator, | ||||
| isInIncludeMode()); | isInIncludeMode()); | ||||
| @@ -260,9 +256,8 @@ public class ImportTask extends Task { | |||||
| } catch (MalformedURLException ex) { | } catch (MalformedURLException ex) { | ||||
| log(ex.toString(), Project.MSG_VERBOSE); | log(ex.toString(), Project.MSG_VERBOSE); | ||||
| } | } | ||||
| throw new BuildException("failed to resolve " + file | |||||
| + " relative to " | |||||
| + getLocation().getFileName()); | |||||
| throw new BuildException("failed to resolve %s relative to %s", | |||||
| file, getLocation().getFileName()); | |||||
| } | } | ||||
| return null; | return null; | ||||
| } | } | ||||
| @@ -274,22 +269,14 @@ public class ImportTask extends Task { | |||||
| private boolean hasAlreadyBeenImported(Resource importedResource, | private boolean hasAlreadyBeenImported(Resource importedResource, | ||||
| Vector<Object> importStack) { | Vector<Object> importStack) { | ||||
| File importedFile = null; | |||||
| FileProvider fp = importedResource.as(FileProvider.class); | |||||
| if (fp != null) { | |||||
| importedFile = fp.getFile(); | |||||
| } | |||||
| URL importedURL = null; | |||||
| URLProvider up = importedResource.as(URLProvider.class); | |||||
| if (up != null) { | |||||
| importedURL = up.getURL(); | |||||
| } | |||||
| for (Object o : importStack) { | |||||
| if (isOneOf(o, importedResource, importedFile, importedURL)) { | |||||
| return true; | |||||
| } | |||||
| } | |||||
| return false; | |||||
| File importedFile = importedResource.asOptional(FileProvider.class) | |||||
| .map(FileProvider::getFile).orElse(null); | |||||
| URL importedURL = importedResource.asOptional(URLProvider.class) | |||||
| .map(URLProvider::getURL).orElse(null); | |||||
| return importStack.stream().anyMatch( | |||||
| o -> isOneOf(o, importedResource, importedFile, importedURL)); | |||||
| } | } | ||||
| private boolean isOneOf(Object o, Resource importedResource, | private boolean isOneOf(Object o, Resource importedResource, | ||||
| @@ -18,8 +18,7 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.util.Vector; | |||||
| import java.util.List; | |||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| import org.apache.tools.ant.input.DefaultInputHandler; | import org.apache.tools.ant.input.DefaultInputHandler; | ||||
| @@ -59,6 +58,7 @@ public class Input extends Task { | |||||
| public void setRefid(final String refid) { | public void setRefid(final String refid) { | ||||
| this.refid = refid; | this.refid = refid; | ||||
| } | } | ||||
| /** | /** | ||||
| * Get the refid of this Handler. | * Get the refid of this Handler. | ||||
| * @return String refid. | * @return String refid. | ||||
| @@ -66,6 +66,7 @@ public class Input extends Task { | |||||
| public String getRefid() { | public String getRefid() { | ||||
| return refid; | return refid; | ||||
| } | } | ||||
| /** | /** | ||||
| * Set the InputHandler classname. | * Set the InputHandler classname. | ||||
| * @param classname the String classname. | * @param classname the String classname. | ||||
| @@ -73,6 +74,7 @@ public class Input extends Task { | |||||
| public void setClassname(final String classname) { | public void setClassname(final String classname) { | ||||
| this.classname = classname; | this.classname = classname; | ||||
| } | } | ||||
| /** | /** | ||||
| * Get the classname of the InputHandler. | * Get the classname of the InputHandler. | ||||
| * @return String classname. | * @return String classname. | ||||
| @@ -80,6 +82,7 @@ public class Input extends Task { | |||||
| public String getClassname() { | public String getClassname() { | ||||
| return classname; | return classname; | ||||
| } | } | ||||
| /** | /** | ||||
| * Set the handler type. | * Set the handler type. | ||||
| * @param type a HandlerType. | * @param type a HandlerType. | ||||
| @@ -87,6 +90,7 @@ public class Input extends Task { | |||||
| public void setType(final HandlerType type) { | public void setType(final HandlerType type) { | ||||
| this.type = type; | this.type = type; | ||||
| } | } | ||||
| /** | /** | ||||
| * Get the handler type. | * Get the handler type. | ||||
| * @return a HandlerType object. | * @return a HandlerType object. | ||||
| @@ -94,6 +98,7 @@ public class Input extends Task { | |||||
| public HandlerType getType() { | public HandlerType getType() { | ||||
| return type; | return type; | ||||
| } | } | ||||
| private InputHandler getInputHandler() { | private InputHandler getInputHandler() { | ||||
| if (type != null) { | if (type != null) { | ||||
| return type.getInputHandler(); | return type.getInputHandler(); | ||||
| @@ -107,8 +112,8 @@ public class Input extends Task { | |||||
| } | } | ||||
| } | } | ||||
| if (classname != null) { | if (classname != null) { | ||||
| return (InputHandler) (ClasspathUtils.newInstance(classname, | |||||
| createLoader(), InputHandler.class)); | |||||
| return ClasspathUtils.newInstance(classname, | |||||
| createLoader(), InputHandler.class); | |||||
| } | } | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Must specify refid, classname or type"); | "Must specify refid, classname or type"); | ||||
| @@ -120,19 +125,21 @@ public class Input extends Task { | |||||
| * "default", "propertyfile", "greedy", "secure" (since Ant 1.8). | * "default", "propertyfile", "greedy", "secure" (since Ant 1.8). | ||||
| */ | */ | ||||
| public static class HandlerType extends EnumeratedAttribute { | public static class HandlerType extends EnumeratedAttribute { | ||||
| private static final String[] VALUES = {"default", "propertyfile", "greedy", "secure"}; | |||||
| private static final String[] VALUES = | |||||
| { "default", "propertyfile", "greedy", "secure" }; | |||||
| private static final InputHandler[] HANDLERS | private static final InputHandler[] HANDLERS | ||||
| = {new DefaultInputHandler(), | |||||
| new PropertyFileInputHandler(), | |||||
| new GreedyInputHandler(), | |||||
| new SecureInputHandler()}; | |||||
| = { new DefaultInputHandler(), | |||||
| new PropertyFileInputHandler(), | |||||
| new GreedyInputHandler(), | |||||
| new SecureInputHandler() }; | |||||
| /** {@inheritDoc} */ | /** {@inheritDoc} */ | ||||
| @Override | @Override | ||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return VALUES; | return VALUES; | ||||
| } | } | ||||
| private InputHandler getInputHandler() { | private InputHandler getInputHandler() { | ||||
| return HANDLERS[getIndex()]; | return HANDLERS[getIndex()]; | ||||
| } | } | ||||
| @@ -193,18 +200,12 @@ public class Input extends Task { | |||||
| * @param msg The message to be displayed. | * @param msg The message to be displayed. | ||||
| */ | */ | ||||
| public void addText(final String msg) { | public void addText(final String msg) { | ||||
| if (messageAttribute && "".equals(msg.trim())) { | |||||
| if (messageAttribute && msg.trim().isEmpty()) { | |||||
| return; | return; | ||||
| } | } | ||||
| message += getProject().replaceProperties(msg); | message += getProject().replaceProperties(msg); | ||||
| } | } | ||||
| /** | |||||
| * No arg constructor. | |||||
| */ | |||||
| public Input () { | |||||
| } | |||||
| /** | /** | ||||
| * Actual method executed by ant. | * Actual method executed by ant. | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| @@ -220,7 +221,7 @@ public class Input extends Task { | |||||
| InputRequest request = null; | InputRequest request = null; | ||||
| if (validargs != null) { | if (validargs != null) { | ||||
| final Vector<String> accept = StringUtils.split(validargs, ','); | |||||
| final List<String> accept = StringUtils.split(validargs, ','); | |||||
| request = new MultipleChoiceInputRequest(message, accept); | request = new MultipleChoiceInputRequest(message, accept); | ||||
| } else { | } else { | ||||
| request = new InputRequest(message); | request = new InputRequest(message); | ||||
| @@ -234,7 +235,7 @@ public class Input extends Task { | |||||
| h.handleInput(request); | h.handleInput(request); | ||||
| String value = request.getInput(); | String value = request.getInput(); | ||||
| if ((value == null || value.trim().length() == 0) | |||||
| if ((value == null || value.trim().isEmpty()) | |||||
| && defaultvalue != null) { | && defaultvalue != null) { | ||||
| value = defaultvalue; | value = defaultvalue; | ||||
| } | } | ||||
| @@ -24,7 +24,6 @@ import java.sql.Driver; | |||||
| import java.sql.SQLException; | import java.sql.SQLException; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Hashtable; | import java.util.Hashtable; | ||||
| import java.util.Iterator; | |||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Locale; | import java.util.Locale; | ||||
| import java.util.Properties; | import java.util.Properties; | ||||
| @@ -98,7 +97,7 @@ public abstract class JDBCTask extends Task { | |||||
| * getting an OutOfMemoryError when calling this task | * getting an OutOfMemoryError when calling this task | ||||
| * multiple times in a row. | * multiple times in a row. | ||||
| */ | */ | ||||
| private static Hashtable<String, AntClassLoader> LOADER_MAP = new Hashtable<String, AntClassLoader>(HASH_TABLE_SIZE); | |||||
| private static Hashtable<String, AntClassLoader> LOADER_MAP = new Hashtable<>(HASH_TABLE_SIZE); | |||||
| private boolean caching = true; | private boolean caching = true; | ||||
| @@ -152,7 +151,7 @@ public abstract class JDBCTask extends Task { | |||||
| * | * | ||||
| * @since Ant 1.8.0 | * @since Ant 1.8.0 | ||||
| */ | */ | ||||
| private List<Property> connectionProperties = new ArrayList<Property>(); | |||||
| private List<Property> connectionProperties = new ArrayList<>(); | |||||
| /** | /** | ||||
| * Sets the classpath for loading the driver. | * Sets the classpath for loading the driver. | ||||
| @@ -342,20 +341,17 @@ public abstract class JDBCTask extends Task { | |||||
| throw new BuildException("Url attribute must be set!", getLocation()); | throw new BuildException("Url attribute must be set!", getLocation()); | ||||
| } | } | ||||
| try { | try { | ||||
| log("connecting to " + getUrl(), Project.MSG_VERBOSE); | log("connecting to " + getUrl(), Project.MSG_VERBOSE); | ||||
| Properties info = new Properties(); | Properties info = new Properties(); | ||||
| info.put("user", getUserId()); | info.put("user", getUserId()); | ||||
| info.put("password", getPassword()); | info.put("password", getPassword()); | ||||
| for (Iterator<Property> props = connectionProperties.iterator(); | |||||
| props.hasNext();) { | |||||
| Property p = props.next(); | |||||
| String name = p.getName(); | |||||
| String value = p.getValue(); | |||||
| for (Property p : connectionProperties) { | |||||
| String name = p.getName(); | |||||
| String value = p.getValue(); | |||||
| if (name == null || value == null) { | if (name == null || value == null) { | ||||
| log("Only name/value pairs are supported as connection" | |||||
| + " properties.", Project.MSG_WARN); | |||||
| log("Only name/value pairs are supported as connection properties.", | |||||
| Project.MSG_WARN); | |||||
| } else { | } else { | ||||
| log("Setting connection property " + name + " to " + value, | log("Setting connection property " + name + " to " + value, | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| @@ -374,14 +370,12 @@ public abstract class JDBCTask extends Task { | |||||
| return conn; | return conn; | ||||
| } catch (SQLException e) { | } catch (SQLException e) { | ||||
| // failed to connect | // failed to connect | ||||
| if (!failOnConnectionError) { | |||||
| log("Failed to connect: " + e.getMessage(), Project.MSG_WARN); | |||||
| return null; | |||||
| } else { | |||||
| if (failOnConnectionError) { | |||||
| throw new BuildException(e, getLocation()); | throw new BuildException(e, getLocation()); | ||||
| } | } | ||||
| log("Failed to connect: " + e.getMessage(), Project.MSG_WARN); | |||||
| return null; | |||||
| } | } | ||||
| } | } | ||||
| /** | /** | ||||
| @@ -395,9 +389,9 @@ public abstract class JDBCTask extends Task { | |||||
| throw new BuildException("Driver attribute must be set!", getLocation()); | throw new BuildException("Driver attribute must be set!", getLocation()); | ||||
| } | } | ||||
| Driver driverInstance = null; | |||||
| Driver driverInstance; | |||||
| try { | try { | ||||
| Class<?> dc; | |||||
| Class<? extends Driver> dc; | |||||
| if (classpath != null) { | if (classpath != null) { | ||||
| // check first that it is not already loaded otherwise | // check first that it is not already loaded otherwise | ||||
| // consecutive runs seems to end into an OutOfMemoryError | // consecutive runs seems to end into an OutOfMemoryError | ||||
| @@ -423,13 +417,13 @@ public abstract class JDBCTask extends Task { | |||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| } | } | ||||
| } | } | ||||
| dc = loader.loadClass(driver); | |||||
| dc = loader.loadClass(driver).asSubclass(Driver.class); | |||||
| } else { | } else { | ||||
| log("Loading " + driver + " using system loader.", | log("Loading " + driver + " using system loader.", | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| dc = Class.forName(driver); | |||||
| dc = Class.forName(driver).asSubclass(Driver.class); | |||||
| } | } | ||||
| driverInstance = (Driver) dc.newInstance(); | |||||
| driverInstance = dc.newInstance(); | |||||
| } catch (ClassNotFoundException e) { | } catch (ClassNotFoundException e) { | ||||
| throw new BuildException( | throw new BuildException( | ||||
| "Class Not Found: JDBC driver " + driver + " could not be loaded", | "Class Not Found: JDBC driver " + driver + " could not be loaded", | ||||
| @@ -449,7 +443,6 @@ public abstract class JDBCTask extends Task { | |||||
| return driverInstance; | return driverInstance; | ||||
| } | } | ||||
| /** | /** | ||||
| * Set the caching attribute. | * Set the caching attribute. | ||||
| * @param value a <code>boolean</code> value | * @param value a <code>boolean</code> value | ||||
| @@ -28,6 +28,7 @@ import java.io.OutputStreamWriter; | |||||
| import java.io.PrintWriter; | import java.io.PrintWriter; | ||||
| import java.io.Reader; | import java.io.Reader; | ||||
| import java.io.UnsupportedEncodingException; | import java.io.UnsupportedEncodingException; | ||||
| import java.nio.charset.Charset; | |||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||
| import java.util.Collections; | import java.util.Collections; | ||||
| @@ -35,6 +36,8 @@ import java.util.Comparator; | |||||
| import java.util.Enumeration; | import java.util.Enumeration; | ||||
| import java.util.HashSet; | import java.util.HashSet; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Set; | |||||
| import java.util.SortedMap; | |||||
| import java.util.StringTokenizer; | import java.util.StringTokenizer; | ||||
| import java.util.TreeMap; | import java.util.TreeMap; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| @@ -74,7 +77,7 @@ public class Jar extends Zip { | |||||
| /** | /** | ||||
| * List of all known SPI Services | * List of all known SPI Services | ||||
| */ | */ | ||||
| private List<Service> serviceList = new ArrayList<Service>(); | |||||
| private List<Service> serviceList = new ArrayList<>(); | |||||
| /** merged manifests added through addConfiguredManifest */ | /** merged manifests added through addConfiguredManifest */ | ||||
| private Manifest configuredManifest; | private Manifest configuredManifest; | ||||
| @@ -138,7 +141,7 @@ public class Jar extends Zip { | |||||
| * | * | ||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| private Vector<String> rootEntries; | |||||
| private List<String> rootEntries; | |||||
| /** | /** | ||||
| * Path containing jars that shall be indexed in addition to this archive. | * Path containing jars that shall be indexed in addition to this archive. | ||||
| @@ -182,7 +185,7 @@ public class Jar extends Zip { | |||||
| emptyBehavior = "create"; | emptyBehavior = "create"; | ||||
| setEncoding("UTF8"); | setEncoding("UTF8"); | ||||
| setZip64Mode(Zip64ModeAttribute.NEVER); | setZip64Mode(Zip64ModeAttribute.NEVER); | ||||
| rootEntries = new Vector<String>(); | |||||
| rootEntries = new Vector<>(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -190,6 +193,7 @@ public class Jar extends Zip { | |||||
| * @param we not used | * @param we not used | ||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| @Override | |||||
| public void setWhenempty(WhenEmpty we) { | public void setWhenempty(WhenEmpty we) { | ||||
| log("JARs are never empty, they contain at least a manifest file", | log("JARs are never empty, they contain at least a manifest file", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| @@ -225,6 +229,7 @@ public class Jar extends Zip { | |||||
| * @deprecated since 1.5.x. | * @deprecated since 1.5.x. | ||||
| * Use setDestFile(File) instead. | * Use setDestFile(File) instead. | ||||
| */ | */ | ||||
| @Deprecated | |||||
| public void setJarfile(File jarFile) { | public void setJarfile(File jarFile) { | ||||
| setDestFile(jarFile); | setDestFile(jarFile); | ||||
| } | } | ||||
| @@ -301,29 +306,13 @@ public class Jar extends Zip { | |||||
| } | } | ||||
| private Manifest getManifest(File manifestFile) { | private Manifest getManifest(File manifestFile) { | ||||
| Manifest newManifest = null; | |||||
| InputStream fis = null; | |||||
| InputStreamReader isr = null; | |||||
| try { | |||||
| fis = Files.newInputStream(manifestFile.toPath()); | |||||
| if (manifestEncoding == null) { | |||||
| isr = new InputStreamReader(fis); | |||||
| } else { | |||||
| isr = new InputStreamReader(fis, manifestEncoding); | |||||
| } | |||||
| newManifest = getManifest(isr); | |||||
| } catch (UnsupportedEncodingException e) { | |||||
| throw new BuildException("Unsupported encoding while reading manifest: " | |||||
| + e.getMessage(), e); | |||||
| try (InputStreamReader isr = new InputStreamReader( | |||||
| Files.newInputStream(manifestFile.toPath()), getManifestCharset())) { | |||||
| return getManifest(isr); | |||||
| } catch (IOException e) { | } catch (IOException e) { | ||||
| throw new BuildException("Unable to read manifest file: " | throw new BuildException("Unable to read manifest file: " | ||||
| + manifestFile | |||||
| + " (" + e.getMessage() + ")", e); | |||||
| } finally { | |||||
| FileUtils.close(isr); | |||||
| + manifestFile + " (" + e.getMessage() + ")", e); | |||||
| } | } | ||||
| return newManifest; | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -332,32 +321,27 @@ public class Jar extends Zip { | |||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| private Manifest getManifestFromJar(File jarFile) throws IOException { | private Manifest getManifestFromJar(File jarFile) throws IOException { | ||||
| ZipFile zf = null; | |||||
| try { | |||||
| zf = new ZipFile(jarFile); | |||||
| try (ZipFile zf = new ZipFile(jarFile)) { | |||||
| // must not use getEntry as "well behaving" applications | // must not use getEntry as "well behaving" applications | ||||
| // must accept the manifest in any capitalization | // must accept the manifest in any capitalization | ||||
| Enumeration<? extends ZipEntry> e = zf.entries(); | Enumeration<? extends ZipEntry> e = zf.entries(); | ||||
| while (e.hasMoreElements()) { | while (e.hasMoreElements()) { | ||||
| ZipEntry ze = e.nextElement(); | ZipEntry ze = e.nextElement(); | ||||
| if (ze.getName().equalsIgnoreCase(MANIFEST_NAME)) { | |||||
| InputStreamReader isr = | |||||
| new InputStreamReader(zf.getInputStream(ze), "UTF-8"); | |||||
| return getManifest(isr); | |||||
| if (MANIFEST_NAME.equalsIgnoreCase(ze.getName())) { | |||||
| try (InputStreamReader isr = | |||||
| new InputStreamReader(zf.getInputStream(ze), "UTF-8")) { | |||||
| return getManifest(isr); | |||||
| } | |||||
| } | } | ||||
| } | } | ||||
| return null; | return null; | ||||
| } finally { | |||||
| FileUtils.close(zf); | |||||
| } | } | ||||
| } | } | ||||
| private Manifest getManifest(Reader r) { | private Manifest getManifest(Reader r) { | ||||
| Manifest newManifest = null; | |||||
| try { | try { | ||||
| newManifest = new Manifest(r); | |||||
| return new Manifest(r); | |||||
| } catch (ManifestException e) { | } catch (ManifestException e) { | ||||
| log("Manifest is invalid: " + e.getMessage(), Project.MSG_ERR); | log("Manifest is invalid: " + e.getMessage(), Project.MSG_ERR); | ||||
| throw new BuildException("Invalid Manifest: " + manifestFile, | throw new BuildException("Invalid Manifest: " + manifestFile, | ||||
| @@ -366,23 +350,18 @@ public class Jar extends Zip { | |||||
| throw new BuildException("Unable to read manifest file" | throw new BuildException("Unable to read manifest file" | ||||
| + " (" + e.getMessage() + ")", e); | + " (" + e.getMessage() + ")", e); | ||||
| } | } | ||||
| return newManifest; | |||||
| } | } | ||||
| private boolean jarHasIndex(File jarFile) throws IOException { | private boolean jarHasIndex(File jarFile) throws IOException { | ||||
| ZipFile zf = null; | |||||
| try { | |||||
| zf = new ZipFile(jarFile); | |||||
| try (ZipFile zf = new ZipFile(jarFile)) { | |||||
| Enumeration<? extends ZipEntry> e = zf.entries(); | Enumeration<? extends ZipEntry> e = zf.entries(); | ||||
| while (e.hasMoreElements()) { | while (e.hasMoreElements()) { | ||||
| ZipEntry ze = e.nextElement(); | ZipEntry ze = e.nextElement(); | ||||
| if (ze.getName().equalsIgnoreCase(INDEX_NAME)) { | |||||
| if (INDEX_NAME.equalsIgnoreCase(ze.getName())) { | |||||
| return true; | return true; | ||||
| } | } | ||||
| } | } | ||||
| return false; | return false; | ||||
| } finally { | |||||
| FileUtils.close(zf); | |||||
| } | } | ||||
| } | } | ||||
| @@ -404,7 +383,7 @@ public class Jar extends Zip { | |||||
| mergeManifestsMain = config != null && "merge".equals(config.getValue()); | mergeManifestsMain = config != null && "merge".equals(config.getValue()); | ||||
| if (filesetManifestConfig != null | if (filesetManifestConfig != null | ||||
| && !filesetManifestConfig.getValue().equals("skip")) { | |||||
| && !"skip".equals(filesetManifestConfig.getValue())) { | |||||
| doubleFilePass = true; | doubleFilePass = true; | ||||
| } | } | ||||
| @@ -449,19 +428,12 @@ public class Jar extends Zip { | |||||
| */ | */ | ||||
| private void writeServices(ZipOutputStream zOut) throws IOException { | private void writeServices(ZipOutputStream zOut) throws IOException { | ||||
| for (Service service : serviceList) { | for (Service service : serviceList) { | ||||
| InputStream is = null; | |||||
| try { | |||||
| is = service.getAsStream(); | |||||
| //stolen from writeManifest | |||||
| try (InputStream is = service.getAsStream()) { | |||||
| //stolen from writeManifest | |||||
| super.zipFile(is, zOut, | super.zipFile(is, zOut, | ||||
| "META-INF/services/" + service.getType(), | "META-INF/services/" + service.getType(), | ||||
| System.currentTimeMillis(), null, | System.currentTimeMillis(), null, | ||||
| ZipFileSet.DEFAULT_FILE_MODE); | ZipFileSet.DEFAULT_FILE_MODE); | ||||
| } finally { | |||||
| // technically this is unnecessary since | |||||
| // Service.getAsStream returns a ByteArrayInputStream | |||||
| // and not closing it wouldn't do any harm. | |||||
| FileUtils.close(is); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -491,6 +463,7 @@ public class Jar extends Zip { | |||||
| * @throws IOException on I/O errors | * @throws IOException on I/O errors | ||||
| * @throws BuildException on other errors | * @throws BuildException on other errors | ||||
| */ | */ | ||||
| @Override | |||||
| protected void initZipOutputStream(ZipOutputStream zOut) | protected void initZipOutputStream(ZipOutputStream zOut) | ||||
| throws IOException, BuildException { | throws IOException, BuildException { | ||||
| @@ -504,12 +477,10 @@ public class Jar extends Zip { | |||||
| private Manifest createManifest() | private Manifest createManifest() | ||||
| throws BuildException { | throws BuildException { | ||||
| try { | try { | ||||
| if (manifest == null) { | |||||
| if (manifestFile != null) { | |||||
| // if we haven't got the manifest yet, attempt to | |||||
| // get it now and have manifest be the final merge | |||||
| manifest = getManifest(manifestFile); | |||||
| } | |||||
| if (manifest == null && manifestFile != null) { | |||||
| // if we haven't got the manifest yet, attempt to | |||||
| // get it now and have manifest be the final merge | |||||
| manifest = getManifest(manifestFile); | |||||
| } | } | ||||
| // fileset manifest must come even before the default | // fileset manifest must come even before the default | ||||
| @@ -598,6 +569,7 @@ public class Jar extends Zip { | |||||
| * @throws IOException on I/O errors | * @throws IOException on I/O errors | ||||
| * @throws BuildException on other errors | * @throws BuildException on other errors | ||||
| */ | */ | ||||
| @Override | |||||
| protected void finalizeZipOutputStream(ZipOutputStream zOut) | protected void finalizeZipOutputStream(ZipOutputStream zOut) | ||||
| throws IOException, BuildException { | throws IOException, BuildException { | ||||
| @@ -667,14 +639,10 @@ public class Jar extends Zip { | |||||
| throw new IOException("Encountered an error writing jar index"); | throw new IOException("Encountered an error writing jar index"); | ||||
| } | } | ||||
| writer.close(); | writer.close(); | ||||
| ByteArrayInputStream bais = | |||||
| new ByteArrayInputStream(baos.toByteArray()); | |||||
| try { | |||||
| try (ByteArrayInputStream bais = | |||||
| new ByteArrayInputStream(baos.toByteArray())) { | |||||
| super.zipFile(bais, zOut, INDEX_NAME, System.currentTimeMillis(), | super.zipFile(bais, zOut, INDEX_NAME, System.currentTimeMillis(), | ||||
| null, ZipFileSet.DEFAULT_FILE_MODE); | null, ZipFileSet.DEFAULT_FILE_MODE); | ||||
| } finally { | |||||
| // not really required | |||||
| FileUtils.close(bais); | |||||
| } | } | ||||
| } | } | ||||
| @@ -690,6 +658,7 @@ public class Jar extends Zip { | |||||
| * @param mode the Unix permissions to set. | * @param mode the Unix permissions to set. | ||||
| * @throws IOException on error | * @throws IOException on error | ||||
| */ | */ | ||||
| @Override | |||||
| protected void zipFile(InputStream is, ZipOutputStream zOut, String vPath, | protected void zipFile(InputStream is, ZipOutputStream zOut, String vPath, | ||||
| long lastModified, File fromArchive, int mode) | long lastModified, File fromArchive, int mode) | ||||
| throws IOException { | throws IOException { | ||||
| @@ -703,8 +672,8 @@ public class Jar extends Zip { | |||||
| + " be replaced by a newly generated one.", | + " be replaced by a newly generated one.", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| } else { | } else { | ||||
| if (index && vPath.indexOf("/") == -1) { | |||||
| rootEntries.addElement(vPath); | |||||
| if (index && vPath.indexOf('/') == -1) { | |||||
| rootEntries.add(vPath); | |||||
| } | } | ||||
| super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode); | super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode); | ||||
| } | } | ||||
| @@ -715,40 +684,29 @@ public class Jar extends Zip { | |||||
| // If this is the same name specified in 'manifest', this | // If this is the same name specified in 'manifest', this | ||||
| // is the manifest to use | // is the manifest to use | ||||
| log("Found manifest " + file, Project.MSG_VERBOSE); | log("Found manifest " + file, Project.MSG_VERBOSE); | ||||
| try { | |||||
| if (is != null) { | |||||
| InputStreamReader isr; | |||||
| if (manifestEncoding == null) { | |||||
| isr = new InputStreamReader(is); | |||||
| } else { | |||||
| isr = new InputStreamReader(is, manifestEncoding); | |||||
| } | |||||
| if (is == null) { | |||||
| manifest = getManifest(file); | |||||
| } else { | |||||
| try (InputStreamReader isr = | |||||
| new InputStreamReader(is, getManifestCharset())) { | |||||
| manifest = getManifest(isr); | manifest = getManifest(isr); | ||||
| } else { | |||||
| manifest = getManifest(file); | |||||
| } | } | ||||
| } catch (UnsupportedEncodingException e) { | |||||
| throw new BuildException("Unsupported encoding while reading " | |||||
| + "manifest: " + e.getMessage(), e); | |||||
| } | } | ||||
| } else if (filesetManifestConfig != null | } else if (filesetManifestConfig != null | ||||
| && !filesetManifestConfig.getValue().equals("skip")) { | |||||
| && !"skip".equals(filesetManifestConfig.getValue())) { | |||||
| // we add this to our group of fileset manifests | // we add this to our group of fileset manifests | ||||
| logWhenWriting("Found manifest to merge in file " + file, | logWhenWriting("Found manifest to merge in file " + file, | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| try { | try { | ||||
| Manifest newManifest = null; | |||||
| if (is != null) { | |||||
| InputStreamReader isr; | |||||
| if (manifestEncoding == null) { | |||||
| isr = new InputStreamReader(is); | |||||
| } else { | |||||
| isr = new InputStreamReader(is, manifestEncoding); | |||||
| } | |||||
| newManifest = getManifest(isr); | |||||
| } else { | |||||
| Manifest newManifest; | |||||
| if (is == null) { | |||||
| newManifest = getManifest(file); | newManifest = getManifest(file); | ||||
| } else { | |||||
| try (InputStreamReader isr = | |||||
| new InputStreamReader(is, getManifestCharset())) { | |||||
| newManifest = getManifest(isr); | |||||
| } | |||||
| } | } | ||||
| if (filesetManifest == null) { | if (filesetManifest == null) { | ||||
| @@ -804,6 +762,7 @@ public class Jar extends Zip { | |||||
| * | * | ||||
| * @exception BuildException if it likes | * @exception BuildException if it likes | ||||
| */ | */ | ||||
| @Override | |||||
| protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs, | protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs, | ||||
| File zipFile, | File zipFile, | ||||
| boolean needsUpdate) | boolean needsUpdate) | ||||
| @@ -874,33 +833,32 @@ public class Jar extends Zip { | |||||
| * @return true for historic reasons | * @return true for historic reasons | ||||
| * @throws BuildException on error | * @throws BuildException on error | ||||
| */ | */ | ||||
| @Override | |||||
| protected boolean createEmptyZip(File zipFile) throws BuildException { | protected boolean createEmptyZip(File zipFile) throws BuildException { | ||||
| if (!createEmpty) { | if (!createEmpty) { | ||||
| return true; | return true; | ||||
| } | } | ||||
| if (emptyBehavior.equals("skip")) { | |||||
| if ("skip".equals(emptyBehavior)) { | |||||
| if (!skipWriting) { | if (!skipWriting) { | ||||
| log("Warning: skipping " + archiveType + " archive " | log("Warning: skipping " + archiveType + " archive " | ||||
| + zipFile + " because no files were included.", | + zipFile + " because no files were included.", | ||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| } | } | ||||
| return true; | return true; | ||||
| } else if (emptyBehavior.equals("fail")) { | |||||
| } | |||||
| if ("fail".equals(emptyBehavior)) { | |||||
| throw new BuildException("Cannot create " + archiveType | throw new BuildException("Cannot create " + archiveType | ||||
| + " archive " + zipFile | + " archive " + zipFile | ||||
| + ": no files were included.", | + ": no files were included.", | ||||
| getLocation()); | getLocation()); | ||||
| } | } | ||||
| ZipOutputStream zOut = null; | |||||
| try { | |||||
| if (!skipWriting) { | |||||
| log("Building MANIFEST-only jar: " | |||||
| if (!skipWriting) { | |||||
| log("Building MANIFEST-only jar: " | |||||
| + getDestFile().getAbsolutePath()); | + getDestFile().getAbsolutePath()); | ||||
| } | |||||
| zOut = new ZipOutputStream(getDestFile()); | |||||
| } | |||||
| try (ZipOutputStream zOut = new ZipOutputStream(getDestFile())) { | |||||
| zOut.setEncoding(getEncoding()); | zOut.setEncoding(getEncoding()); | ||||
| zOut.setUseZip64(getZip64Mode().getMode()); | zOut.setUseZip64(getZip64Mode().getMode()); | ||||
| if (isCompress()) { | if (isCompress()) { | ||||
| @@ -915,8 +873,6 @@ public class Jar extends Zip { | |||||
| + " (" + ioe.getMessage() + ")", ioe, | + " (" + ioe.getMessage() + ")", ioe, | ||||
| getLocation()); | getLocation()); | ||||
| } finally { | } finally { | ||||
| // Close the output stream. | |||||
| FileUtils.close(zOut); | |||||
| createEmpty = false; | createEmpty = false; | ||||
| } | } | ||||
| return true; | return true; | ||||
| @@ -928,6 +884,7 @@ public class Jar extends Zip { | |||||
| * | * | ||||
| * @see Zip#cleanUp | * @see Zip#cleanUp | ||||
| */ | */ | ||||
| @Override | |||||
| protected void cleanUp() { | protected void cleanUp() { | ||||
| super.cleanUp(); | super.cleanUp(); | ||||
| checkJarSpec(); | checkJarSpec(); | ||||
| @@ -939,7 +896,7 @@ public class Jar extends Zip { | |||||
| filesetManifest = null; | filesetManifest = null; | ||||
| originalManifest = null; | originalManifest = null; | ||||
| } | } | ||||
| rootEntries.removeAllElements(); | |||||
| rootEntries.clear(); | |||||
| } | } | ||||
| // CheckStyle:LineLength OFF - Link is too long. | // CheckStyle:LineLength OFF - Link is too long. | ||||
| @@ -950,7 +907,7 @@ public class Jar extends Zip { | |||||
| // CheckStyle:LineLength ON | // CheckStyle:LineLength ON | ||||
| private void checkJarSpec() { | private void checkJarSpec() { | ||||
| String br = System.getProperty("line.separator"); | String br = System.getProperty("line.separator"); | ||||
| StringBuffer message = new StringBuffer(); | |||||
| StringBuilder message = new StringBuilder(); | |||||
| Section mainSection = (configuredManifest == null) | Section mainSection = (configuredManifest == null) | ||||
| ? null | ? null | ||||
| : configuredManifest.getMainSection(); | : configuredManifest.getMainSection(); | ||||
| @@ -975,11 +932,10 @@ public class Jar extends Zip { | |||||
| message.append(br); | message.append(br); | ||||
| message.append("Location: ").append(getLocation()); | message.append("Location: ").append(getLocation()); | ||||
| message.append(br); | message.append(br); | ||||
| if (strict.getValue().equalsIgnoreCase("fail")) { | |||||
| if ("fail".equalsIgnoreCase(strict.getValue())) { | |||||
| throw new BuildException(message.toString(), getLocation()); | throw new BuildException(message.toString(), getLocation()); | ||||
| } else { | |||||
| logWhenWriting(message.toString(), strict.getLogLevel()); | |||||
| } | } | ||||
| logWhenWriting(message.toString(), strict.getLogLevel()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -990,6 +946,7 @@ public class Jar extends Zip { | |||||
| * | * | ||||
| * @since 1.44, Ant 1.5 | * @since 1.44, Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| public void reset() { | public void reset() { | ||||
| super.reset(); | super.reset(); | ||||
| emptyBehavior = "create"; | emptyBehavior = "create"; | ||||
| @@ -1008,8 +965,9 @@ public class Jar extends Zip { | |||||
| * Get the list of valid strings. | * Get the list of valid strings. | ||||
| * @return the list of values - "skip", "merge" and "mergewithoutmain" | * @return the list of values - "skip", "merge" and "mergewithoutmain" | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[] {"skip", "merge", "mergewithoutmain"}; | |||||
| return new String[] { "skip", "merge", "mergewithoutmain" }; | |||||
| } | } | ||||
| } | } | ||||
| @@ -1056,9 +1014,7 @@ public class Jar extends Zip { | |||||
| writer.println(dir); | writer.println(dir); | ||||
| } | } | ||||
| for (String file : files) { | |||||
| writer.println(file); | |||||
| } | |||||
| files.forEach(writer::println); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1084,39 +1040,27 @@ public class Jar extends Zip { | |||||
| protected static String findJarName(String fileName, | protected static String findJarName(String fileName, | ||||
| String[] classpath) { | String[] classpath) { | ||||
| if (classpath == null) { | if (classpath == null) { | ||||
| return (new File(fileName)).getName(); | |||||
| return new File(fileName).getName(); | |||||
| } | } | ||||
| fileName = fileName.replace(File.separatorChar, '/'); | fileName = fileName.replace(File.separatorChar, '/'); | ||||
| TreeMap<String, String> matches = new TreeMap<String, String>(new Comparator<Object>() { | |||||
| // longest match comes first | |||||
| public int compare(Object o1, Object o2) { | |||||
| if (o1 instanceof String && o2 instanceof String) { | |||||
| return ((String) o2).length() | |||||
| - ((String) o1).length(); | |||||
| } | |||||
| return 0; | |||||
| SortedMap<String, String> matches = new TreeMap<>(Comparator | |||||
| .<String> comparingInt(s -> s == null ? 0 : s.length()).reversed()); | |||||
| for (String element : classpath) { | |||||
| String candidate = element; | |||||
| while (true) { | |||||
| if (fileName.endsWith(candidate)) { | |||||
| matches.put(candidate, element); | |||||
| break; | |||||
| } | } | ||||
| }); | |||||
| for (int i = 0; i < classpath.length; i++) { | |||||
| if (fileName.endsWith(classpath[i])) { | |||||
| matches.put(classpath[i], classpath[i]); | |||||
| } else { | |||||
| int slash = classpath[i].indexOf("/"); | |||||
| String candidate = classpath[i]; | |||||
| while (slash > -1) { | |||||
| candidate = candidate.substring(slash + 1); | |||||
| if (fileName.endsWith(candidate)) { | |||||
| matches.put(candidate, classpath[i]); | |||||
| break; | |||||
| } | |||||
| slash = candidate.indexOf("/"); | |||||
| int slash = candidate.indexOf('/'); | |||||
| if (slash < 0) { | |||||
| break; | |||||
| } | } | ||||
| candidate = candidate.substring(slash + 1); | |||||
| } | } | ||||
| } | } | ||||
| return matches.size() == 0 | |||||
| ? null : (String) matches.get(matches.firstKey()); | |||||
| return matches.isEmpty() ? null : matches.get(matches.firstKey()); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1133,21 +1077,21 @@ public class Jar extends Zip { | |||||
| throws IOException { | throws IOException { | ||||
| try (org.apache.tools.zip.ZipFile zf = new org.apache.tools.zip.ZipFile(file, "utf-8")) { | try (org.apache.tools.zip.ZipFile zf = new org.apache.tools.zip.ZipFile(file, "utf-8")) { | ||||
| Enumeration<org.apache.tools.zip.ZipEntry> entries = zf.getEntries(); | Enumeration<org.apache.tools.zip.ZipEntry> entries = zf.getEntries(); | ||||
| HashSet<String> dirSet = new HashSet<String>(); | |||||
| Set<String> dirSet = new HashSet<>(); | |||||
| while (entries.hasMoreElements()) { | while (entries.hasMoreElements()) { | ||||
| org.apache.tools.zip.ZipEntry ze = | org.apache.tools.zip.ZipEntry ze = | ||||
| entries.nextElement(); | entries.nextElement(); | ||||
| String name = ze.getName(); | String name = ze.getName(); | ||||
| if (ze.isDirectory()) { | if (ze.isDirectory()) { | ||||
| dirSet.add(name); | dirSet.add(name); | ||||
| } else if (name.indexOf("/") == -1) { | |||||
| } else if (name.indexOf('/') == -1) { | |||||
| files.add(name); | files.add(name); | ||||
| } else { | } else { | ||||
| // a file, not in the root | // a file, not in the root | ||||
| // since the jar may be one without directory | // since the jar may be one without directory | ||||
| // entries, add the parent dir of this file as | // entries, add the parent dir of this file as | ||||
| // well. | // well. | ||||
| dirSet.add(name.substring(0, name.lastIndexOf("/") + 1)); | |||||
| dirSet.add(name.substring(0, name.lastIndexOf('/') + 1)); | |||||
| } | } | ||||
| } | } | ||||
| dirs.addAll(dirSet); | dirs.addAll(dirSet); | ||||
| @@ -1157,13 +1101,12 @@ public class Jar extends Zip { | |||||
| private Resource[][] grabManifests(ResourceCollection[] rcs) { | private Resource[][] grabManifests(ResourceCollection[] rcs) { | ||||
| Resource[][] manifests = new Resource[rcs.length][]; | Resource[][] manifests = new Resource[rcs.length][]; | ||||
| for (int i = 0; i < rcs.length; i++) { | for (int i = 0; i < rcs.length; i++) { | ||||
| Resource[][] resources = null; | |||||
| Resource[][] resources; | |||||
| if (rcs[i] instanceof FileSet) { | if (rcs[i] instanceof FileSet) { | ||||
| resources = grabResources(new FileSet[] {(FileSet) rcs[i]}); | |||||
| resources = grabResources(new FileSet[] { (FileSet) rcs[i] }); | |||||
| } else { | } else { | ||||
| resources = grabNonFileSetResources(new ResourceCollection[] { | |||||
| rcs[i] | |||||
| }); | |||||
| resources = grabNonFileSetResources( | |||||
| new ResourceCollection[] { rcs[i] }); | |||||
| } | } | ||||
| for (int j = 0; j < resources[0].length; j++) { | for (int j = 0; j < resources[0].length; j++) { | ||||
| String name = resources[0][j].getName().replace('\\', '/'); | String name = resources[0][j].getName().replace('\\', '/'); | ||||
| @@ -1179,7 +1122,7 @@ public class Jar extends Zip { | |||||
| name = prefix + name; | name = prefix + name; | ||||
| } | } | ||||
| } | } | ||||
| if (name.equalsIgnoreCase(MANIFEST_NAME)) { | |||||
| if (MANIFEST_NAME.equalsIgnoreCase(name)) { | |||||
| manifests[i] = new Resource[] {resources[0][j]}; | manifests[i] = new Resource[] {resources[0][j]}; | ||||
| break; | break; | ||||
| } | } | ||||
| @@ -1191,11 +1134,26 @@ public class Jar extends Zip { | |||||
| return manifests; | return manifests; | ||||
| } | } | ||||
| private Charset getManifestCharset() { | |||||
| if (manifestEncoding == null) { | |||||
| return Charset.defaultCharset(); | |||||
| } | |||||
| try { | |||||
| return Charset.forName(manifestEncoding); | |||||
| } catch (IllegalArgumentException e) { | |||||
| throw new BuildException( | |||||
| "Unsupported encoding while reading manifest: " | |||||
| + e.getMessage(), | |||||
| e); | |||||
| } | |||||
| } | |||||
| /** The strict enumerated type. */ | /** The strict enumerated type. */ | ||||
| public static class StrictMode extends EnumeratedAttribute { | public static class StrictMode extends EnumeratedAttribute { | ||||
| /** Public no arg constructor. */ | /** Public no arg constructor. */ | ||||
| public StrictMode() { | public StrictMode() { | ||||
| } | } | ||||
| /** | /** | ||||
| * Constructor with an arg. | * Constructor with an arg. | ||||
| * @param value the enumerated value as a string. | * @param value the enumerated value as a string. | ||||
| @@ -1203,18 +1161,21 @@ public class Jar extends Zip { | |||||
| public StrictMode(String value) { | public StrictMode(String value) { | ||||
| setValue(value); | setValue(value); | ||||
| } | } | ||||
| /** | /** | ||||
| * Get List of valid strings. | * Get List of valid strings. | ||||
| * @return the list of values. | * @return the list of values. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return new String[]{"fail", "warn", "ignore"}; | |||||
| return new String[] { "fail", "warn", "ignore" }; | |||||
| } | } | ||||
| /** | /** | ||||
| * @return The log level according to the strict mode. | * @return The log level according to the strict mode. | ||||
| */ | */ | ||||
| public int getLogLevel() { | public int getLogLevel() { | ||||
| return (getValue().equals("ignore")) ? Project.MSG_VERBOSE : Project.MSG_WARN; | |||||
| return "ignore".equals(getValue()) ? Project.MSG_VERBOSE : Project.MSG_WARN; | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -20,8 +20,6 @@ package org.apache.tools.ant.taskdefs; | |||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.PrintWriter; | |||||
| import java.io.StringWriter; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -52,6 +50,8 @@ import org.apache.tools.ant.util.StringUtils; | |||||
| * @ant.task category="java" | * @ant.task category="java" | ||||
| */ | */ | ||||
| public class Java extends Task { | public class Java extends Task { | ||||
| private static final String TIMEOUT_MESSAGE = | |||||
| "Timeout: killed the sub-process"; | |||||
| private CommandlineJava cmdl = new CommandlineJava(); | private CommandlineJava cmdl = new CommandlineJava(); | ||||
| private Environment env = new Environment(); | private Environment env = new Environment(); | ||||
| @@ -78,9 +78,6 @@ public class Java extends Task { | |||||
| private boolean spawn = false; | private boolean spawn = false; | ||||
| private boolean incompatibleWithSpawn = false; | private boolean incompatibleWithSpawn = false; | ||||
| private static final String TIMEOUT_MESSAGE = | |||||
| "Timeout: killed the sub-process"; | |||||
| /** | /** | ||||
| * Normal constructor | * Normal constructor | ||||
| */ | */ | ||||
| @@ -100,6 +97,7 @@ public class Java extends Task { | |||||
| * @throws BuildException if failOnError is set to true and the application | * @throws BuildException if failOnError is set to true and the application | ||||
| * returns a nonzero result code. | * returns a nonzero result code. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() throws BuildException { | public void execute() throws BuildException { | ||||
| File savedDir = dir; | File savedDir = dir; | ||||
| Permissions savedPermissions = perm; | Permissions savedPermissions = perm; | ||||
| @@ -148,30 +146,32 @@ public class Java extends Task { | |||||
| throw new BuildException("Classname must not be null."); | throw new BuildException("Classname must not be null."); | ||||
| } | } | ||||
| if (!fork && getCommandLine().getJar() != null) { | if (!fork && getCommandLine().getJar() != null) { | ||||
| throw new BuildException("Cannot execute a jar in non-forked mode." | |||||
| + " Please set fork='true'. "); | |||||
| throw new BuildException( | |||||
| "Cannot execute a jar in non-forked mode. Please set fork='true'. "); | |||||
| } | } | ||||
| if (!fork && getCommandLine().getModule() != null) { | if (!fork && getCommandLine().getModule() != null) { | ||||
| throw new BuildException("Cannot execute a module in non-forked mode." | |||||
| + " Please set fork='true'. "); | |||||
| throw new BuildException( | |||||
| "Cannot execute a module in non-forked mode. Please set fork='true'. "); | |||||
| } | } | ||||
| if (spawn && !fork) { | if (spawn && !fork) { | ||||
| throw new BuildException("Cannot spawn a java process in non-forked mode." | |||||
| + " Please set fork='true'. "); | |||||
| throw new BuildException( | |||||
| "Cannot spawn a java process in non-forked mode. Please set fork='true'. "); | |||||
| } | } | ||||
| if (getCommandLine().getClasspath() != null | if (getCommandLine().getClasspath() != null | ||||
| && getCommandLine().getJar() != null) { | && getCommandLine().getJar() != null) { | ||||
| log("When using 'jar' attribute classpath-settings are ignored. " | |||||
| + "See the manual for more information.", Project.MSG_VERBOSE); | |||||
| log("When using 'jar' attribute classpath-settings are ignored. See the manual for more information.", | |||||
| Project.MSG_VERBOSE); | |||||
| } | } | ||||
| if (spawn && incompatibleWithSpawn) { | if (spawn && incompatibleWithSpawn) { | ||||
| getProject().log("spawn does not allow attributes related to input, " | |||||
| + "output, error, result", Project.MSG_ERR); | |||||
| getProject().log( | |||||
| "spawn does not allow attributes related to input, output, error, result", | |||||
| Project.MSG_ERR); | |||||
| getProject().log("spawn also does not allow timeout", Project.MSG_ERR); | getProject().log("spawn also does not allow timeout", Project.MSG_ERR); | ||||
| getProject().log("finally, spawn is not compatible " | |||||
| + "with a nested I/O <redirector>", Project.MSG_ERR); | |||||
| throw new BuildException("You have used an attribute " | |||||
| + "or nested element which is not compatible with spawn"); | |||||
| getProject().log( | |||||
| "finally, spawn is not compatible with a nested I/O <redirector>", | |||||
| Project.MSG_ERR); | |||||
| throw new BuildException( | |||||
| "You have used an attribute or nested element which is not compatible with spawn"); | |||||
| } | } | ||||
| if (getCommandLine().getAssertions() != null && !fork) { | if (getCommandLine().getAssertions() != null && !fork) { | ||||
| log("Assertion statements are currently ignored in non-forked mode"); | log("Assertion statements are currently ignored in non-forked mode"); | ||||
| @@ -191,8 +191,8 @@ public class Java extends Task { | |||||
| Project.MSG_WARN); | Project.MSG_WARN); | ||||
| } | } | ||||
| if (newEnvironment || null != env.getVariables()) { | if (newEnvironment || null != env.getVariables()) { | ||||
| log("Changes to environment variables are ignored when same " | |||||
| + "JVM is used.", Project.MSG_WARN); | |||||
| log("Changes to environment variables are ignored when same JVM is used.", | |||||
| Project.MSG_WARN); | |||||
| } | } | ||||
| if (getCommandLine().getBootclasspath() != null) { | if (getCommandLine().getBootclasspath() != null) { | ||||
| log("bootclasspath ignored when same JVM is used.", | log("bootclasspath ignored when same JVM is used.", | ||||
| @@ -217,19 +217,17 @@ public class Java extends Task { | |||||
| protected int executeJava(CommandlineJava commandLine) { | protected int executeJava(CommandlineJava commandLine) { | ||||
| try { | try { | ||||
| if (fork) { | if (fork) { | ||||
| if (!spawn) { | |||||
| return fork(commandLine.getCommandline()); | |||||
| } else { | |||||
| if (spawn) { | |||||
| spawn(commandLine.getCommandline()); | spawn(commandLine.getCommandline()); | ||||
| return 0; | return 0; | ||||
| } | } | ||||
| } else { | |||||
| try { | |||||
| run(commandLine); | |||||
| return 0; | |||||
| } catch (ExitException ex) { | |||||
| return ex.getStatus(); | |||||
| } | |||||
| return fork(commandLine.getCommandline()); | |||||
| } | |||||
| try { | |||||
| run(commandLine); | |||||
| return 0; | |||||
| } catch (ExitException ex) { | |||||
| return ex.getStatus(); | |||||
| } | } | ||||
| } catch (BuildException e) { | } catch (BuildException e) { | ||||
| if (e.getLocation() == null && getLocation() != null) { | if (e.getLocation() == null && getLocation() != null) { | ||||
| @@ -237,23 +235,21 @@ public class Java extends Task { | |||||
| } | } | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw e; | throw e; | ||||
| } | |||||
| if (TIMEOUT_MESSAGE.equals(e.getMessage())) { | |||||
| log(TIMEOUT_MESSAGE); | |||||
| } else { | } else { | ||||
| if (TIMEOUT_MESSAGE.equals(e.getMessage())) { | |||||
| log(TIMEOUT_MESSAGE); | |||||
| } else { | |||||
| log(e); | |||||
| } | |||||
| return -1; | |||||
| log(e); | |||||
| } | } | ||||
| return -1; | |||||
| } catch (ThreadDeath t) { | } catch (ThreadDeath t) { | ||||
| throw t; // cf. NB #47191 | throw t; // cf. NB #47191 | ||||
| } catch (Throwable t) { | } catch (Throwable t) { | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(t, getLocation()); | throw new BuildException(t, getLocation()); | ||||
| } else { | |||||
| log(t); | |||||
| return -1; | |||||
| } | } | ||||
| log(t); | |||||
| return -1; | |||||
| } | } | ||||
| } | } | ||||
| @@ -363,8 +359,8 @@ public class Java extends Task { | |||||
| */ | */ | ||||
| public void setJar(File jarfile) throws BuildException { | public void setJar(File jarfile) throws BuildException { | ||||
| if (getCommandLine().getClassname() != null || getCommandLine().getModule() != null) { | if (getCommandLine().getClassname() != null || getCommandLine().getModule() != null) { | ||||
| throw new BuildException("Cannot use 'jar' with 'classname' or 'module' " | |||||
| + "attributes in same command."); | |||||
| throw new BuildException( | |||||
| "Cannot use 'jar' with 'classname' or 'module' attributes in same command."); | |||||
| } | } | ||||
| getCommandLine().setJar(jarfile.getAbsolutePath()); | getCommandLine().setJar(jarfile.getAbsolutePath()); | ||||
| } | } | ||||
| @@ -378,8 +374,8 @@ public class Java extends Task { | |||||
| */ | */ | ||||
| public void setClassname(String s) throws BuildException { | public void setClassname(String s) throws BuildException { | ||||
| if (getCommandLine().getJar() != null) { | if (getCommandLine().getJar() != null) { | ||||
| throw new BuildException("Cannot use 'jar' and 'classname' " | |||||
| + "attributes in same command"); | |||||
| throw new BuildException( | |||||
| "Cannot use 'jar' and 'classname' attributes in same command"); | |||||
| } | } | ||||
| getCommandLine().setClassname(s); | getCommandLine().setClassname(s); | ||||
| } | } | ||||
| @@ -394,8 +390,8 @@ public class Java extends Task { | |||||
| */ | */ | ||||
| public void setModule(String module) throws BuildException { | public void setModule(String module) throws BuildException { | ||||
| if (getCommandLine().getJar() != null) { | if (getCommandLine().getJar() != null) { | ||||
| throw new BuildException("Cannot use 'jar' and 'module' " | |||||
| + "attributes in same command"); | |||||
| throw new BuildException( | |||||
| "Cannot use 'jar' and 'module' attributes in same command"); | |||||
| } | } | ||||
| getCommandLine().setModule(module); | getCommandLine().setModule(module); | ||||
| } | } | ||||
| @@ -409,8 +405,8 @@ public class Java extends Task { | |||||
| * @ant.attribute ignore="true" | * @ant.attribute ignore="true" | ||||
| */ | */ | ||||
| public void setArgs(String s) { | public void setArgs(String s) { | ||||
| log("The args attribute is deprecated. " | |||||
| + "Please use nested arg elements.", Project.MSG_WARN); | |||||
| log("The args attribute is deprecated. Please use nested arg elements.", | |||||
| Project.MSG_WARN); | |||||
| getCommandLine().createArgument().setLine(s); | getCommandLine().createArgument().setLine(s); | ||||
| } | } | ||||
| @@ -477,8 +473,8 @@ public class Java extends Task { | |||||
| * @param s jvmargs. | * @param s jvmargs. | ||||
| */ | */ | ||||
| public void setJvmargs(String s) { | public void setJvmargs(String s) { | ||||
| log("The jvmargs attribute is deprecated. " | |||||
| + "Please use nested jvmarg elements.", Project.MSG_WARN); | |||||
| log("The jvmargs attribute is deprecated. Please use nested jvmarg elements.", | |||||
| Project.MSG_WARN); | |||||
| getCommandLine().createVmArgument().setLine(s); | getCommandLine().createVmArgument().setLine(s); | ||||
| } | } | ||||
| @@ -559,8 +555,8 @@ public class Java extends Task { | |||||
| */ | */ | ||||
| public void setInput(File input) { | public void setInput(File input) { | ||||
| if (inputString != null) { | if (inputString != null) { | ||||
| throw new BuildException("The \"input\" and \"inputstring\" " | |||||
| + "attributes cannot both be specified"); | |||||
| throw new BuildException( | |||||
| "The \"input\" and \"inputstring\" attributes cannot both be specified"); | |||||
| } | } | ||||
| this.input = input; | this.input = input; | ||||
| incompatibleWithSpawn = true; | incompatibleWithSpawn = true; | ||||
| @@ -573,8 +569,8 @@ public class Java extends Task { | |||||
| */ | */ | ||||
| public void setInputString(String inputString) { | public void setInputString(String inputString) { | ||||
| if (input != null) { | if (input != null) { | ||||
| throw new BuildException("The \"input\" and \"inputstring\" " | |||||
| + "attributes cannot both be specified"); | |||||
| throw new BuildException( | |||||
| "The \"input\" and \"inputstring\" attributes cannot both be specified"); | |||||
| } | } | ||||
| this.inputString = inputString; | this.inputString = inputString; | ||||
| incompatibleWithSpawn = true; | incompatibleWithSpawn = true; | ||||
| @@ -728,6 +724,7 @@ public class Java extends Task { | |||||
| * | * | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| protected void handleOutput(String output) { | protected void handleOutput(String output) { | ||||
| if (redirector.getOutputStream() != null) { | if (redirector.getOutputStream() != null) { | ||||
| redirector.handleOutput(output); | redirector.handleOutput(output); | ||||
| @@ -748,6 +745,7 @@ public class Java extends Task { | |||||
| * @exception IOException if the data cannot be read. | * @exception IOException if the data cannot be read. | ||||
| * @since Ant 1.6 | * @since Ant 1.6 | ||||
| */ | */ | ||||
| @Override | |||||
| public int handleInput(byte[] buffer, int offset, int length) | public int handleInput(byte[] buffer, int offset, int length) | ||||
| throws IOException { | throws IOException { | ||||
| // Should work whether or not redirector.inputStream == null: | // Should work whether or not redirector.inputStream == null: | ||||
| @@ -761,6 +759,7 @@ public class Java extends Task { | |||||
| * | * | ||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| @Override | |||||
| protected void handleFlush(String output) { | protected void handleFlush(String output) { | ||||
| if (redirector.getOutputStream() != null) { | if (redirector.getOutputStream() != null) { | ||||
| redirector.handleFlush(output); | redirector.handleFlush(output); | ||||
| @@ -776,6 +775,7 @@ public class Java extends Task { | |||||
| * | * | ||||
| * @since Ant 1.5 | * @since Ant 1.5 | ||||
| */ | */ | ||||
| @Override | |||||
| protected void handleErrorOutput(String output) { | protected void handleErrorOutput(String output) { | ||||
| if (redirector.getErrorStream() != null) { | if (redirector.getErrorStream() != null) { | ||||
| redirector.handleErrorOutput(output); | redirector.handleErrorOutput(output); | ||||
| @@ -791,6 +791,7 @@ public class Java extends Task { | |||||
| * | * | ||||
| * @since Ant 1.5.2 | * @since Ant 1.5.2 | ||||
| */ | */ | ||||
| @Override | |||||
| protected void handleErrorFlush(String output) { | protected void handleErrorFlush(String output) { | ||||
| if (redirector.getErrorStream() != null) { | if (redirector.getErrorStream() != null) { | ||||
| redirector.handleErrorFlush(output); | redirector.handleErrorFlush(output); | ||||
| @@ -897,8 +898,8 @@ public class Java extends Task { | |||||
| private void setupEnvironment(Execute exe) { | private void setupEnvironment(Execute exe) { | ||||
| String[] environment = env.getVariables(); | String[] environment = env.getVariables(); | ||||
| if (environment != null) { | if (environment != null) { | ||||
| for (int i = 0; i < environment.length; i++) { | |||||
| log("Setting environment variable: " + environment[i], | |||||
| for (String element : environment) { | |||||
| log("Setting environment variable: " + element, | |||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| } | } | ||||
| } | } | ||||
| @@ -914,7 +915,7 @@ public class Java extends Task { | |||||
| private void setupWorkingDir(Execute exe) { | private void setupWorkingDir(Execute exe) { | ||||
| if (dir == null) { | if (dir == null) { | ||||
| dir = getProject().getBaseDir(); | dir = getProject().getBaseDir(); | ||||
| } else if (!dir.exists() || !dir.isDirectory()) { | |||||
| } else if (!dir.isDirectory()) { | |||||
| throw new BuildException(dir.getAbsolutePath() | throw new BuildException(dir.getAbsolutePath() | ||||
| + " is not a valid directory", | + " is not a valid directory", | ||||
| getLocation()); | getLocation()); | ||||
| @@ -962,10 +963,7 @@ public class Java extends Task { | |||||
| protected void run(String classname, Vector<String> args) throws BuildException { | protected void run(String classname, Vector<String> args) throws BuildException { | ||||
| CommandlineJava cmdj = new CommandlineJava(); | CommandlineJava cmdj = new CommandlineJava(); | ||||
| cmdj.setClassname(classname); | cmdj.setClassname(classname); | ||||
| final int size = args.size(); | |||||
| for (int i = 0; i < size; i++) { | |||||
| cmdj.createArgument().setValue(args.elementAt(i)); | |||||
| } | |||||
| args.forEach(arg -> cmdj.createArgument().setValue(arg)); | |||||
| run(cmdj); | run(cmdj); | ||||
| } | } | ||||
| @@ -19,7 +19,6 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.FileFilter; | |||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.OutputStream; | import java.io.OutputStream; | ||||
| import java.nio.file.Files; | import java.nio.file.Files; | ||||
| @@ -28,7 +27,6 @@ import java.util.Collection; | |||||
| import java.util.HashMap; | import java.util.HashMap; | ||||
| import java.util.List; | import java.util.List; | ||||
| import java.util.Map; | import java.util.Map; | ||||
| import java.util.Map.Entry; | |||||
| import java.util.TreeMap; | import java.util.TreeMap; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| @@ -138,7 +136,7 @@ public class Javac extends MatchingTask { | |||||
| protected boolean failOnError = true; | protected boolean failOnError = true; | ||||
| protected boolean listFiles = false; | protected boolean listFiles = false; | ||||
| protected File[] compileList = new File[0]; | protected File[] compileList = new File[0]; | ||||
| private Map<String, Long> packageInfos = new HashMap<String, Long>(); | |||||
| private Map<String, Long> packageInfos = new HashMap<>(); | |||||
| // CheckStyle:VisibilityModifier ON | // CheckStyle:VisibilityModifier ON | ||||
| private String source; | private String source; | ||||
| @@ -162,19 +160,23 @@ public class Javac extends MatchingTask { | |||||
| private String assumedJavaVersion() { | private String assumedJavaVersion() { | ||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_4)) { | if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_4)) { | ||||
| return JAVAC14; | return JAVAC14; | ||||
| } else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_5)) { | |||||
| } | |||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_5)) { | |||||
| return JAVAC15; | return JAVAC15; | ||||
| } else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_6)) { | |||||
| } | |||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_6)) { | |||||
| return JAVAC16; | return JAVAC16; | ||||
| } else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_7)) { | |||||
| } | |||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_7)) { | |||||
| return JAVAC17; | return JAVAC17; | ||||
| } else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_8)) { | |||||
| } | |||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_8)) { | |||||
| return JAVAC18; | return JAVAC18; | ||||
| } else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) { | |||||
| } | |||||
| if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) { | |||||
| return JAVAC9; | return JAVAC9; | ||||
| } else { | |||||
| return CLASSIC; | |||||
| } | } | ||||
| return CLASSIC; | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1083,8 +1085,8 @@ public class Javac extends MatchingTask { | |||||
| */ | */ | ||||
| public void add(final CompilerAdapter adapter) { | public void add(final CompilerAdapter adapter) { | ||||
| if (nestedAdapter != null) { | if (nestedAdapter != null) { | ||||
| throw new BuildException("Can't have more than one compiler" | |||||
| + " adapter"); | |||||
| throw new BuildException( | |||||
| "Can't have more than one compiler adapter"); | |||||
| } | } | ||||
| nestedAdapter = adapter; | nestedAdapter = adapter; | ||||
| } | } | ||||
| @@ -1131,7 +1133,7 @@ public class Javac extends MatchingTask { | |||||
| */ | */ | ||||
| protected void resetFileLists() { | protected void resetFileLists() { | ||||
| compileList = new File[0]; | compileList = new File[0]; | ||||
| packageInfos = new HashMap<String, Long>(); | |||||
| packageInfos = new HashMap<>(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1146,8 +1148,8 @@ public class Javac extends MatchingTask { | |||||
| final GlobPatternMapper m = new GlobPatternMapper(); | final GlobPatternMapper m = new GlobPatternMapper(); | ||||
| final String[] extensions = findSupportedFileExtensions(); | final String[] extensions = findSupportedFileExtensions(); | ||||
| for (int i = 0; i < extensions.length; i++) { | |||||
| m.setFrom(extensions[i]); | |||||
| for (String extension : extensions) { | |||||
| m.setFrom(extension); | |||||
| m.setTo("*.class"); | m.setTo("*.class"); | ||||
| final SourceFileScanner sfs = new SourceFileScanner(this); | final SourceFileScanner sfs = new SourceFileScanner(this); | ||||
| final File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); | final File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); | ||||
| @@ -1186,7 +1188,8 @@ public class Javac extends MatchingTask { | |||||
| final FileUtils fu = FileUtils.getFileUtils(); | final FileUtils fu = FileUtils.getFileUtils(); | ||||
| for (String pathElement : moduleSourcepath.list()) { | for (String pathElement : moduleSourcepath.list()) { | ||||
| boolean valid = false; | boolean valid = false; | ||||
| for (Map.Entry<String,Collection<File>> modules : resolveModuleSourcePathElement(getProject().getBaseDir(), pathElement).entrySet()) { | |||||
| for (Map.Entry<String, Collection<File>> modules : resolveModuleSourcePathElement( | |||||
| getProject().getBaseDir(), pathElement).entrySet()) { | |||||
| final String moduleName = modules.getKey(); | final String moduleName = modules.getKey(); | ||||
| for (File srcDir : modules.getValue()) { | for (File srcDir : modules.getValue()) { | ||||
| if (srcDir.exists()) { | if (srcDir.exists()) { | ||||
| @@ -1218,7 +1221,7 @@ public class Javac extends MatchingTask { | |||||
| } | } | ||||
| if (extensions == null) { | if (extensions == null) { | ||||
| extensions = new String[] {"java"}; | |||||
| extensions = new String[] { "java" }; | |||||
| } | } | ||||
| // now process the extensions to ensure that they are the | // now process the extensions to ensure that they are the | ||||
| @@ -1297,8 +1300,8 @@ public class Javac extends MatchingTask { | |||||
| if (isJdkCompiler(compilerImpl)) { | if (isJdkCompiler(compilerImpl)) { | ||||
| compilerImpl = EXTJAVAC; | compilerImpl = EXTJAVAC; | ||||
| } else { | } else { | ||||
| log("Since compiler setting isn't classic or modern, " | |||||
| + "ignoring fork setting.", Project.MSG_WARN); | |||||
| log("Since compiler setting isn't classic or modern, ignoring fork setting.", | |||||
| Project.MSG_WARN); | |||||
| } | } | ||||
| } | } | ||||
| return compilerImpl; | return compilerImpl; | ||||
| @@ -1353,13 +1356,12 @@ public class Javac extends MatchingTask { | |||||
| if (destDir != null && !destDir.isDirectory()) { | if (destDir != null && !destDir.isDirectory()) { | ||||
| throw new BuildException("destination directory \"" | throw new BuildException("destination directory \"" | ||||
| + destDir | + destDir | ||||
| + "\" does not exist " | |||||
| + "or is not a directory", getLocation()); | |||||
| + "\" does not exist or is not a directory", getLocation()); | |||||
| } | } | ||||
| if (includeAntRuntime == null && getProject().getProperty("build.sysclasspath") == null) { | if (includeAntRuntime == null && getProject().getProperty("build.sysclasspath") == null) { | ||||
| log(getLocation() + "warning: 'includeantruntime' was not set, " + | |||||
| "defaulting to build.sysclasspath=last; set to false for repeatable builds", | |||||
| Project.MSG_WARN); | |||||
| log(getLocation() | |||||
| + "warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds", | |||||
| Project.MSG_WARN); | |||||
| } | } | ||||
| } | } | ||||
| @@ -1377,9 +1379,8 @@ public class Javac extends MatchingTask { | |||||
| + (destDir != null ? " to " + destDir : "")); | + (destDir != null ? " to " + destDir : "")); | ||||
| if (listFiles) { | if (listFiles) { | ||||
| for (int i = 0; i < compileList.length; i++) { | |||||
| final String filename = compileList[i].getAbsolutePath(); | |||||
| log(filename); | |||||
| for (File element : compileList) { | |||||
| log(element.getAbsolutePath()); | |||||
| } | } | ||||
| } | } | ||||
| @@ -1414,9 +1415,8 @@ public class Javac extends MatchingTask { | |||||
| } | } | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(FAIL_MSG, getLocation()); | throw new BuildException(FAIL_MSG, getLocation()); | ||||
| } else { | |||||
| log(FAIL_MSG, Project.MSG_ERR); | |||||
| } | } | ||||
| log(FAIL_MSG, Project.MSG_ERR); | |||||
| } | } | ||||
| } | } | ||||
| } | } | ||||
| @@ -1438,9 +1438,8 @@ public class Javac extends MatchingTask { | |||||
| } | } | ||||
| private void lookForPackageInfos(final File srcDir, final File[] newFiles) { | private void lookForPackageInfos(final File srcDir, final File[] newFiles) { | ||||
| for (int i = 0; i < newFiles.length; i++) { | |||||
| final File f = newFiles[i]; | |||||
| if (!f.getName().equals("package-info.java")) { | |||||
| for (File f : newFiles) { | |||||
| if (!"package-info.java".equals(f.getName())) { | |||||
| continue; | continue; | ||||
| } | } | ||||
| final String path = FILE_UTILS.removeLeadingPath(srcDir, f). | final String path = FILE_UTILS.removeLeadingPath(srcDir, f). | ||||
| @@ -1451,7 +1450,7 @@ public class Javac extends MatchingTask { | |||||
| continue; | continue; | ||||
| } | } | ||||
| final String pkg = path.substring(0, path.length() - suffix.length()); | final String pkg = path.substring(0, path.length() - suffix.length()); | ||||
| packageInfos.put(pkg, new Long(f.lastModified())); | |||||
| packageInfos.put(pkg, Long.valueOf(f.lastModified())); | |||||
| } | } | ||||
| } | } | ||||
| @@ -1461,7 +1460,7 @@ public class Javac extends MatchingTask { | |||||
| * @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=43114">Bug #43114</a> | * @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=43114">Bug #43114</a> | ||||
| */ | */ | ||||
| private void generateMissingPackageInfoClasses(final File dest) throws IOException { | private void generateMissingPackageInfoClasses(final File dest) throws IOException { | ||||
| for (final Entry<String, Long> entry : packageInfos.entrySet()) { | |||||
| for (final Map.Entry<String, Long> entry : packageInfos.entrySet()) { | |||||
| final String pkg = entry.getKey(); | final String pkg = entry.getKey(); | ||||
| final Long sourceLastMod = entry.getValue(); | final Long sourceLastMod = entry.getValue(); | ||||
| final File pkgBinDir = new File(dest, pkg.replace('/', File.separatorChar)); | final File pkgBinDir = new File(dest, pkg.replace('/', File.separatorChar)); | ||||
| @@ -1490,7 +1489,7 @@ public class Javac extends MatchingTask { | |||||
| * @since 1.9.7 | * @since 1.9.7 | ||||
| */ | */ | ||||
| private static boolean hasPath(final Path path) { | private static boolean hasPath(final Path path) { | ||||
| return path != null && path.size() > 0; | |||||
| return path != null && !path.isEmpty(); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1524,7 +1523,7 @@ public class Javac extends MatchingTask { | |||||
| */ | */ | ||||
| private static Collection<? extends CharSequence> expandGroups( | private static Collection<? extends CharSequence> expandGroups( | ||||
| final CharSequence element) { | final CharSequence element) { | ||||
| List<StringBuilder> result = new ArrayList<StringBuilder>(); | |||||
| List<StringBuilder> result = new ArrayList<>(); | |||||
| result.add(new StringBuilder()); | result.add(new StringBuilder()); | ||||
| StringBuilder resolved = new StringBuilder(); | StringBuilder resolved = new StringBuilder(); | ||||
| for (int i = 0; i < element.length(); i++) { | for (int i = 0; i < element.length(); i++) { | ||||
| @@ -1547,7 +1546,7 @@ public class Javac extends MatchingTask { | |||||
| break; | break; | ||||
| default: | default: | ||||
| final List<StringBuilder> oldRes = result; | final List<StringBuilder> oldRes = result; | ||||
| result = new ArrayList<StringBuilder>(oldRes.size() * parts.size()); | |||||
| result = new ArrayList<>(oldRes.size() * parts.size()); | |||||
| for (CharSequence part : parts) { | for (CharSequence part : parts) { | ||||
| for (CharSequence prefix : oldRes) { | for (CharSequence prefix : oldRes) { | ||||
| result.add(new StringBuilder(prefix).append(resolved).append(part)); | result.add(new StringBuilder(prefix).append(resolved).append(part)); | ||||
| @@ -1574,7 +1573,7 @@ public class Javac extends MatchingTask { | |||||
| * @since 1.9.7 | * @since 1.9.7 | ||||
| */ | */ | ||||
| private static Collection<? extends CharSequence> resolveGroup(final CharSequence group) { | private static Collection<? extends CharSequence> resolveGroup(final CharSequence group) { | ||||
| final Collection<CharSequence> result = new ArrayList<CharSequence>(); | |||||
| final Collection<CharSequence> result = new ArrayList<>(); | |||||
| int start = 0; | int start = 0; | ||||
| int depth = 0; | int depth = 0; | ||||
| for (int i = 0; i < group.length(); i++) { | for (int i = 0; i < group.length(); i++) { | ||||
| @@ -1643,26 +1642,26 @@ public class Javac extends MatchingTask { | |||||
| final int startIndex = pattern.indexOf(MODULE_MARKER); | final int startIndex = pattern.indexOf(MODULE_MARKER); | ||||
| if (startIndex == -1) { | if (startIndex == -1) { | ||||
| findModules(root, pattern, null, collector); | findModules(root, pattern, null, collector); | ||||
| } else { | |||||
| if (startIndex == 0) { | |||||
| throw new BuildException("The modulesourcepath entry must be a folder."); | |||||
| } | |||||
| final int endIndex = startIndex + MODULE_MARKER.length(); | |||||
| if (pattern.charAt(startIndex - 1) != File.separatorChar) { | |||||
| throw new BuildException("The module mark must be preceded by separator"); | |||||
| } | |||||
| if (endIndex < pattern.length() && pattern.charAt(endIndex) != File.separatorChar) { | |||||
| throw new BuildException("The module mark must be followed by separator"); | |||||
| } | |||||
| if (pattern.indexOf(MODULE_MARKER, endIndex) != -1) { | |||||
| throw new BuildException("The modulesourcepath entry must contain at most one module mark"); | |||||
| } | |||||
| final String pathToModule = pattern.substring(0, startIndex); | |||||
| final String pathInModule = endIndex == pattern.length() ? | |||||
| null : | |||||
| pattern.substring(endIndex + 1); //+1 the separator | |||||
| findModules(root, pathToModule, pathInModule, collector); | |||||
| return; | |||||
| } | } | ||||
| if (startIndex == 0) { | |||||
| throw new BuildException("The modulesourcepath entry must be a folder."); | |||||
| } | |||||
| final int endIndex = startIndex + MODULE_MARKER.length(); | |||||
| if (pattern.charAt(startIndex - 1) != File.separatorChar) { | |||||
| throw new BuildException("The module mark must be preceded by separator"); | |||||
| } | |||||
| if (endIndex < pattern.length() && pattern.charAt(endIndex) != File.separatorChar) { | |||||
| throw new BuildException("The module mark must be followed by separator"); | |||||
| } | |||||
| if (pattern.indexOf(MODULE_MARKER, endIndex) != -1) { | |||||
| throw new BuildException("The modulesourcepath entry must contain at most one module mark"); | |||||
| } | |||||
| final String pathToModule = pattern.substring(0, startIndex); | |||||
| final String pathInModule = endIndex == pattern.length() ? | |||||
| null : | |||||
| pattern.substring(endIndex + 1); //+1 the separator | |||||
| findModules(root, pathToModule, pathInModule, collector); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -1683,19 +1682,14 @@ public class Javac extends MatchingTask { | |||||
| if (!f.isDirectory()) { | if (!f.isDirectory()) { | ||||
| return; | return; | ||||
| } | } | ||||
| final File[] modules = f.listFiles(new FileFilter() { | |||||
| public boolean accept(File pathname) { | |||||
| return pathname.isDirectory(); | |||||
| } | |||||
| }); | |||||
| for (File module : modules) { | |||||
| for (File module : f.listFiles(File::isDirectory)) { | |||||
| final String moduleName = module.getName(); | final String moduleName = module.getName(); | ||||
| final File moduleSourceRoot = pathInModule == null ? | final File moduleSourceRoot = pathInModule == null ? | ||||
| module : | module : | ||||
| new File(module, pathInModule); | new File(module, pathInModule); | ||||
| Collection<File> moduleRoots = collector.get(moduleName); | Collection<File> moduleRoots = collector.get(moduleName); | ||||
| if (moduleRoots == null) { | if (moduleRoots == null) { | ||||
| moduleRoots = new ArrayList<File>(); | |||||
| moduleRoots = new ArrayList<>(); | |||||
| collector.put(moduleName, moduleRoots); | collector.put(moduleName, moduleRoots); | ||||
| } | } | ||||
| moduleRoots.add(moduleSourceRoot); | moduleRoots.add(moduleSourceRoot); | ||||
| @@ -108,7 +108,7 @@ public class Length extends Task implements Condition { | |||||
| * @param ell the long length to compare with. | * @param ell the long length to compare with. | ||||
| */ | */ | ||||
| public synchronized void setLength(long ell) { | public synchronized void setLength(long ell) { | ||||
| length = new Long(ell); | |||||
| length = Long.valueOf(ell); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -152,7 +152,7 @@ public class Length extends Task implements Condition { | |||||
| * @param trim <code>boolean</code>. | * @param trim <code>boolean</code>. | ||||
| */ | */ | ||||
| public synchronized void setTrim(boolean trim) { | public synchronized void setTrim(boolean trim) { | ||||
| this.trim = trim ? Boolean.TRUE : Boolean.FALSE; | |||||
| this.trim = Boolean.valueOf(trim); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -160,25 +160,31 @@ public class Length extends Task implements Condition { | |||||
| * @return boolean trim setting. | * @return boolean trim setting. | ||||
| */ | */ | ||||
| public boolean getTrim() { | public boolean getTrim() { | ||||
| return trim != null && trim.booleanValue(); | |||||
| return Boolean.TRUE.equals(trim); | |||||
| } | } | ||||
| /** | /** | ||||
| * Execute the length task. | * Execute the length task. | ||||
| */ | */ | ||||
| @Override | |||||
| public void execute() { | public void execute() { | ||||
| validate(); | validate(); | ||||
| PrintStream ps = new PrintStream((property != null) | |||||
| ? (OutputStream) new PropertyOutputStream(getProject(), property) | |||||
| : (OutputStream) new LogOutputStream(this, Project.MSG_INFO)); | |||||
| OutputStream out = | |||||
| property == null ? new LogOutputStream(this, Project.MSG_INFO) | |||||
| : new PropertyOutputStream(getProject(), property); | |||||
| PrintStream ps = new PrintStream(out); | |||||
| if (STRING.equals(mode)) { | |||||
| switch (mode) { | |||||
| case STRING: | |||||
| ps.print(getLength(string, getTrim())); | ps.print(getLength(string, getTrim())); | ||||
| ps.close(); | ps.close(); | ||||
| } else if (EACH.equals(mode)) { | |||||
| break; | |||||
| case EACH: | |||||
| handleResources(new EachHandler(ps)); | handleResources(new EachHandler(ps)); | ||||
| } else if (ALL.equals(mode)) { | |||||
| break; | |||||
| case ALL: | |||||
| handleResources(new AllHandler(ps)); | handleResources(new AllHandler(ps)); | ||||
| break; | |||||
| } | } | ||||
| } | } | ||||
| @@ -187,6 +193,7 @@ public class Length extends Task implements Condition { | |||||
| * @return true if the condition is true. | * @return true if the condition is true. | ||||
| * @throws BuildException if an error occurs. | * @throws BuildException if an error occurs. | ||||
| */ | */ | ||||
| @Override | |||||
| public boolean eval() { | public boolean eval() { | ||||
| validate(); | validate(); | ||||
| if (length == null) { | if (length == null) { | ||||
| @@ -194,11 +201,11 @@ public class Length extends Task implements Condition { | |||||
| } | } | ||||
| Long ell; | Long ell; | ||||
| if (STRING.equals(mode)) { | if (STRING.equals(mode)) { | ||||
| ell = new Long(getLength(string, getTrim())); | |||||
| ell = Long.valueOf(getLength(string, getTrim())); | |||||
| } else { | } else { | ||||
| AccumHandler h = new AccumHandler(); | AccumHandler h = new AccumHandler(); | ||||
| handleResources(h); | handleResources(h); | ||||
| ell = new Long(h.getAccum()); | |||||
| ell = Long.valueOf(h.getAccum()); | |||||
| } | } | ||||
| return when.evaluate(ell.compareTo(length)); | return when.evaluate(ell.compareTo(length)); | ||||
| } | } | ||||
| @@ -206,25 +213,26 @@ public class Length extends Task implements Condition { | |||||
| private void validate() { | private void validate() { | ||||
| if (string != null) { | if (string != null) { | ||||
| if (resources != null) { | if (resources != null) { | ||||
| throw new BuildException("the string length function" | |||||
| + " is incompatible with the file/resource length function"); | |||||
| throw new BuildException( | |||||
| "the string length function is incompatible with the file/resource length function"); | |||||
| } | } | ||||
| if (!(STRING.equals(mode))) { | if (!(STRING.equals(mode))) { | ||||
| throw new BuildException("the mode attribute is for use" | |||||
| + " with the file/resource length function"); | |||||
| throw new BuildException( | |||||
| "the mode attribute is for use with the file/resource length function"); | |||||
| } | } | ||||
| } else if (resources != null) { | } else if (resources != null) { | ||||
| if (!(EACH.equals(mode) || ALL.equals(mode))) { | if (!(EACH.equals(mode) || ALL.equals(mode))) { | ||||
| throw new BuildException("invalid mode setting for" | |||||
| + " file/resource length function: \"" + mode + "\""); | |||||
| } else if (trim != null) { | |||||
| throw new BuildException("the trim attribute is" | |||||
| + " for use with the string length function only"); | |||||
| throw new BuildException( | |||||
| "invalid mode setting for file/resource length function: \"" | |||||
| + mode + "\""); | |||||
| } | |||||
| if (trim != null) { | |||||
| throw new BuildException( | |||||
| "the trim attribute is for use with the string length function only"); | |||||
| } | } | ||||
| } else { | } else { | ||||
| throw new BuildException("you must set either the string attribute" | |||||
| + " or specify one or more files using the file attribute or" | |||||
| + " nested resource collections"); | |||||
| throw new BuildException( | |||||
| "you must set either the string attribute or specify one or more files using the file attribute or nested resource collections"); | |||||
| } | } | ||||
| } | } | ||||
| @@ -247,12 +255,13 @@ public class Length extends Task implements Condition { | |||||
| /** EnumeratedAttribute operation mode */ | /** EnumeratedAttribute operation mode */ | ||||
| public static class FileMode extends EnumeratedAttribute { | public static class FileMode extends EnumeratedAttribute { | ||||
| static final String[] MODES = new String[] {EACH, ALL}; //NOSONAR | |||||
| static final String[] MODES = new String[] { EACH, ALL }; //NOSONAR | |||||
| /** | /** | ||||
| * Return the possible values for FileMode. | * Return the possible values for FileMode. | ||||
| * @return <code>String[]</code>. | * @return <code>String[]</code>. | ||||
| */ | */ | ||||
| @Override | |||||
| public String[] getValues() { | public String[] getValues() { | ||||
| return MODES; | return MODES; | ||||
| } | } | ||||
| @@ -268,6 +277,7 @@ public class Length extends Task implements Condition { | |||||
| private abstract class Handler { | private abstract class Handler { | ||||
| private PrintStream ps; | private PrintStream ps; | ||||
| Handler(PrintStream ps) { | Handler(PrintStream ps) { | ||||
| this.ps = ps; | this.ps = ps; | ||||
| } | } | ||||
| @@ -287,6 +297,8 @@ public class Length extends Task implements Condition { | |||||
| EachHandler(PrintStream ps) { | EachHandler(PrintStream ps) { | ||||
| super(ps); | super(ps); | ||||
| } | } | ||||
| @Override | |||||
| protected void handle(Resource r) { | protected void handle(Resource r) { | ||||
| getPs().print(r.toString()); | getPs().print(r.toString()); | ||||
| getPs().print(" : "); | getPs().print(" : "); | ||||
| @@ -306,12 +318,16 @@ public class Length extends Task implements Condition { | |||||
| AccumHandler() { | AccumHandler() { | ||||
| super(null); | super(null); | ||||
| } | } | ||||
| protected AccumHandler(PrintStream ps) { | protected AccumHandler(PrintStream ps) { | ||||
| super(ps); | super(ps); | ||||
| } | } | ||||
| protected long getAccum() { | protected long getAccum() { | ||||
| return accum; | return accum; | ||||
| } | } | ||||
| @Override | |||||
| protected synchronized void handle(Resource r) { | protected synchronized void handle(Resource r) { | ||||
| long size = r.getSize(); | long size = r.getSize(); | ||||
| if (size == Resource.UNKNOWN_SIZE) { | if (size == Resource.UNKNOWN_SIZE) { | ||||
| @@ -326,6 +342,8 @@ public class Length extends Task implements Condition { | |||||
| AllHandler(PrintStream ps) { | AllHandler(PrintStream ps) { | ||||
| super(ps); | super(ps); | ||||
| } | } | ||||
| @Override | |||||
| void complete() { | void complete() { | ||||
| getPs().print(getAccum()); | getPs().print(getAccum()); | ||||
| super.complete(); | super.complete(); | ||||
| @@ -17,12 +17,12 @@ | |||||
| */ | */ | ||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.BufferedInputStream; | |||||
| import java.io.ByteArrayInputStream; | import java.io.ByteArrayInputStream; | ||||
| import java.io.File; | import java.io.File; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.InputStreamReader; | import java.io.InputStreamReader; | ||||
| import java.io.Reader; | |||||
| import java.nio.charset.Charset; | |||||
| import java.util.List; | |||||
| import java.util.Properties; | import java.util.Properties; | ||||
| import java.util.Vector; | import java.util.Vector; | ||||
| @@ -30,6 +30,7 @@ import org.apache.tools.ant.BuildException; | |||||
| import org.apache.tools.ant.Project; | import org.apache.tools.ant.Project; | ||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| import org.apache.tools.ant.filters.util.ChainReaderHelper; | import org.apache.tools.ant.filters.util.ChainReaderHelper; | ||||
| import org.apache.tools.ant.filters.util.ChainReaderHelper.ChainReader; | |||||
| import org.apache.tools.ant.types.FilterChain; | import org.apache.tools.ant.types.FilterChain; | ||||
| import org.apache.tools.ant.types.Path; | import org.apache.tools.ant.types.Path; | ||||
| import org.apache.tools.ant.types.Reference; | import org.apache.tools.ant.types.Reference; | ||||
| @@ -37,7 +38,6 @@ import org.apache.tools.ant.types.Resource; | |||||
| import org.apache.tools.ant.types.ResourceCollection; | import org.apache.tools.ant.types.ResourceCollection; | ||||
| import org.apache.tools.ant.types.resources.FileResource; | import org.apache.tools.ant.types.resources.FileResource; | ||||
| import org.apache.tools.ant.types.resources.JavaResource; | import org.apache.tools.ant.types.resources.JavaResource; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| import org.apache.tools.ant.util.ResourceUtils; | import org.apache.tools.ant.util.ResourceUtils; | ||||
| /** | /** | ||||
| @@ -56,7 +56,7 @@ public class LoadProperties extends Task { | |||||
| /** | /** | ||||
| * Holds filterchains | * Holds filterchains | ||||
| */ | */ | ||||
| private final Vector<FilterChain> filterChains = new Vector<FilterChain>(); | |||||
| private final List<FilterChain> filterChains = new Vector<>(); | |||||
| /** | /** | ||||
| * Encoding to use for input; defaults to the platform's default encoding. | * Encoding to use for input; defaults to the platform's default encoding. | ||||
| @@ -158,6 +158,7 @@ public class LoadProperties extends Task { | |||||
| * | * | ||||
| * @exception BuildException if something goes wrong with the build | * @exception BuildException if something goes wrong with the build | ||||
| */ | */ | ||||
| @Override | |||||
| public final void execute() throws BuildException { | public final void execute() throws BuildException { | ||||
| //validation | //validation | ||||
| if (src == null) { | if (src == null) { | ||||
| @@ -171,30 +172,21 @@ public class LoadProperties extends Task { | |||||
| } | } | ||||
| throw new BuildException("Source resource does not exist: " + src); | throw new BuildException("Source resource does not exist: " + src); | ||||
| } | } | ||||
| BufferedInputStream bis = null; | |||||
| Reader instream = null; | |||||
| ByteArrayInputStream tis = null; | |||||
| try { | |||||
| bis = new BufferedInputStream(src.getInputStream()); | |||||
| if (encoding == null) { | |||||
| instream = new InputStreamReader(bis); | |||||
| } else { | |||||
| instream = new InputStreamReader(bis, encoding); | |||||
| } | |||||
| ChainReaderHelper crh = new ChainReaderHelper(); | |||||
| crh.setPrimaryReader(instream); | |||||
| crh.setFilterChains(filterChains); | |||||
| crh.setProject(getProject()); | |||||
| instream = crh.getAssembledReader(); | |||||
| String text = crh.readFully(instream); | |||||
| Charset charset = encoding == null ? Charset.defaultCharset() : Charset.forName(encoding); | |||||
| try (ChainReader instream = new ChainReaderHelper(getProject(), | |||||
| new InputStreamReader(src.getInputStream(), charset), filterChains) | |||||
| .getAssembledReader()) { | |||||
| String text = instream.readFully(); | |||||
| if (text != null && text.length() != 0) { | |||||
| if (!(text == null || text.isEmpty())) { | |||||
| if (!text.endsWith("\n")) { | if (!text.endsWith("\n")) { | ||||
| text = text + "\n"; | text = text + "\n"; | ||||
| } | } | ||||
| tis = new ByteArrayInputStream(text.getBytes(ResourceUtils.ISO_8859_1)); | |||||
| ByteArrayInputStream tis = new ByteArrayInputStream( | |||||
| text.getBytes(ResourceUtils.ISO_8859_1)); | |||||
| final Properties props = new Properties(); | final Properties props = new Properties(); | ||||
| props.load(tis); | props.load(tis); | ||||
| @@ -206,9 +198,6 @@ public class LoadProperties extends Task { | |||||
| } | } | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| throw new BuildException("Unable to load file: " + ioe, ioe, getLocation()); | throw new BuildException("Unable to load file: " + ioe, ioe, getLocation()); | ||||
| } finally { | |||||
| FileUtils.close(bis); | |||||
| FileUtils.close(tis); | |||||
| } | } | ||||
| } | } | ||||
| @@ -217,7 +206,7 @@ public class LoadProperties extends Task { | |||||
| * @param filter the filter to add | * @param filter the filter to add | ||||
| */ | */ | ||||
| public final void addFilterChain(FilterChain filter) { | public final void addFilterChain(FilterChain filter) { | ||||
| filterChains.addElement(filter); | |||||
| filterChains.add(filter); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -19,19 +19,18 @@ package org.apache.tools.ant.taskdefs; | |||||
| import java.io.BufferedInputStream; | import java.io.BufferedInputStream; | ||||
| import java.io.IOException; | import java.io.IOException; | ||||
| import java.io.InputStream; | |||||
| import java.io.InputStreamReader; | import java.io.InputStreamReader; | ||||
| import java.io.Reader; | |||||
| import java.nio.charset.Charset; | |||||
| import java.util.List; | |||||
| import java.util.Vector; | import java.util.Vector; | ||||
| import org.apache.tools.ant.BuildException; | import org.apache.tools.ant.BuildException; | ||||
| import org.apache.tools.ant.Project; | import org.apache.tools.ant.Project; | ||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| import org.apache.tools.ant.filters.util.ChainReaderHelper; | import org.apache.tools.ant.filters.util.ChainReaderHelper; | ||||
| import org.apache.tools.ant.filters.util.ChainReaderHelper.ChainReader; | |||||
| import org.apache.tools.ant.types.FilterChain; | import org.apache.tools.ant.types.FilterChain; | ||||
| import org.apache.tools.ant.types.Resource; | import org.apache.tools.ant.types.Resource; | ||||
| import org.apache.tools.ant.types.ResourceCollection; | import org.apache.tools.ant.types.ResourceCollection; | ||||
| import org.apache.tools.ant.util.FileUtils; | |||||
| /** | /** | ||||
| * Load a resource into a property | * Load a resource into a property | ||||
| @@ -70,7 +69,7 @@ public class LoadResource extends Task { | |||||
| /** | /** | ||||
| * Holds FilterChains | * Holds FilterChains | ||||
| */ | */ | ||||
| private final Vector<FilterChain> filterChains = new Vector<FilterChain>(); | |||||
| private final List<FilterChain> filterChains = new Vector<>(); | |||||
| /** | /** | ||||
| * Encoding to use for input, defaults to the platform's default | * Encoding to use for input, defaults to the platform's default | ||||
| @@ -124,6 +123,7 @@ public class LoadResource extends Task { | |||||
| * | * | ||||
| * @exception BuildException if something goes wrong with the build | * @exception BuildException if something goes wrong with the build | ||||
| */ | */ | ||||
| @Override | |||||
| public final void execute() | public final void execute() | ||||
| throws BuildException { | throws BuildException { | ||||
| //validation | //validation | ||||
| @@ -134,82 +134,67 @@ public class LoadResource extends Task { | |||||
| throw new BuildException("output property not defined"); | throw new BuildException("output property not defined"); | ||||
| } | } | ||||
| if (quiet && failOnError) { | if (quiet && failOnError) { | ||||
| throw new BuildException("quiet and failonerror cannot both be " | |||||
| + "set to true"); | |||||
| throw new BuildException("quiet and failonerror cannot both be set to true"); | |||||
| } | } | ||||
| if (!src.isExists()) { | if (!src.isExists()) { | ||||
| String message = src + " doesn't exist"; | String message = src + " doesn't exist"; | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(message); | throw new BuildException(message); | ||||
| } else { | |||||
| log(message, quiet ? Project.MSG_WARN : Project.MSG_ERR); | |||||
| return; | |||||
| } | } | ||||
| log(message, quiet ? Project.MSG_WARN : Project.MSG_ERR); | |||||
| return; | |||||
| } | } | ||||
| InputStream is = null; | |||||
| BufferedInputStream bis = null; | |||||
| Reader instream = null; | |||||
| log("loading " + src + " into property " + property, | log("loading " + src + " into property " + property, | ||||
| Project.MSG_VERBOSE); | Project.MSG_VERBOSE); | ||||
| Charset charset = encoding == null ? Charset.defaultCharset() | |||||
| : Charset.forName(encoding); | |||||
| try { | try { | ||||
| final long len = src.getSize(); | final long len = src.getSize(); | ||||
| log("resource size = " | |||||
| + (len != Resource.UNKNOWN_SIZE ? String.valueOf(len) | |||||
| : "unknown"), Project.MSG_DEBUG); | |||||
| log("resource size = " + (len != Resource.UNKNOWN_SIZE | |||||
| ? String.valueOf(len) : "unknown"), Project.MSG_DEBUG); | |||||
| //discard most of really big resources | //discard most of really big resources | ||||
| final int size = (int) len; | final int size = (int) len; | ||||
| //open up the resource | //open up the resource | ||||
| is = src.getInputStream(); | |||||
| bis = new BufferedInputStream(is); | |||||
| if (encoding == null) { | |||||
| instream = new InputStreamReader(bis); | |||||
| } else { | |||||
| instream = new InputStreamReader(bis, encoding); | |||||
| } | |||||
| String text = ""; | |||||
| String text; | |||||
| if (size != 0) { | if (size != 0) { | ||||
| ChainReaderHelper crh = new ChainReaderHelper(); | |||||
| if (len != Resource.UNKNOWN_SIZE) { | |||||
| crh.setBufferSize(size); | |||||
| try (ChainReader chainReader = new ChainReaderHelper( | |||||
| getProject(), | |||||
| new InputStreamReader( | |||||
| new BufferedInputStream(src.getInputStream()), charset), | |||||
| filterChains).with(crh -> { | |||||
| if (src.getSize() != Resource.UNKNOWN_SIZE) { | |||||
| crh.setBufferSize(size); | |||||
| } | |||||
| }).getAssembledReader()) { | |||||
| text = chainReader.readFully(); | |||||
| } | } | ||||
| crh.setPrimaryReader(instream); | |||||
| crh.setFilterChains(filterChains); | |||||
| crh.setProject(getProject()); | |||||
| instream = crh.getAssembledReader(); | |||||
| text = crh.readFully(instream); | |||||
| } else { | } else { | ||||
| log("Do not set property " + property + " as its length is 0.", | log("Do not set property " + property + " as its length is 0.", | ||||
| quiet ? Project.MSG_VERBOSE : Project.MSG_INFO); | quiet ? Project.MSG_VERBOSE : Project.MSG_INFO); | ||||
| text = null; | |||||
| } | } | ||||
| if (text != null) { | |||||
| if (text.length() > 0) { | |||||
| getProject().setNewProperty(property, text); | |||||
| log("loaded " + text.length() + " characters", | |||||
| Project.MSG_VERBOSE); | |||||
| log(property + " := " + text, Project.MSG_DEBUG); | |||||
| } | |||||
| if (!(text == null || text.isEmpty())) { | |||||
| getProject().setNewProperty(property, text); | |||||
| log("loaded " + text.length() + " characters", | |||||
| Project.MSG_VERBOSE); | |||||
| log(property + " := " + text, Project.MSG_DEBUG); | |||||
| } | } | ||||
| } catch (final IOException ioe) { | } catch (final IOException ioe) { | ||||
| final String message = "Unable to load resource: " | |||||
| + ioe.toString(); | |||||
| final String message = "Unable to load resource: " + ioe; | |||||
| if (failOnError) { | if (failOnError) { | ||||
| throw new BuildException(message, ioe, getLocation()); | throw new BuildException(message, ioe, getLocation()); | ||||
| } else { | |||||
| log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); | |||||
| } | } | ||||
| log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); | |||||
| } catch (final BuildException be) { | } catch (final BuildException be) { | ||||
| if (failOnError) { | if (failOnError) { | ||||
| throw be; | throw be; | ||||
| } else { | |||||
| log(be.getMessage(), | |||||
| quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); | |||||
| } | } | ||||
| } finally { | |||||
| FileUtils.close(is); | |||||
| log(be.getMessage(), quiet ? Project.MSG_VERBOSE : Project.MSG_ERR); | |||||
| } | } | ||||
| } | } | ||||
| @@ -218,7 +203,7 @@ public class LoadResource extends Task { | |||||
| * @param filter the filter to add | * @param filter the filter to add | ||||
| */ | */ | ||||
| public final void addFilterChain(FilterChain filter) { | public final void addFilterChain(FilterChain filter) { | ||||
| filterChains.addElement(filter); | |||||
| filterChains.add(filter); | |||||
| } | } | ||||
| /** | /** | ||||
| @@ -227,8 +212,8 @@ public class LoadResource extends Task { | |||||
| */ | */ | ||||
| public void addConfigured(ResourceCollection a) { | public void addConfigured(ResourceCollection a) { | ||||
| if (a.size() != 1) { | if (a.size() != 1) { | ||||
| throw new BuildException("only single argument resource collections" | |||||
| + " are supported"); | |||||
| throw new BuildException( | |||||
| "only single argument resource collections are supported"); | |||||
| } | } | ||||
| src = a.iterator().next(); | src = a.iterator().next(); | ||||
| } | } | ||||
| @@ -18,9 +18,6 @@ | |||||
| package org.apache.tools.ant.taskdefs; | package org.apache.tools.ant.taskdefs; | ||||
| import java.io.IOException; | |||||
| import org.apache.tools.ant.BuildException; | |||||
| import org.apache.tools.ant.ProjectComponent; | import org.apache.tools.ant.ProjectComponent; | ||||
| import org.apache.tools.ant.Task; | import org.apache.tools.ant.Task; | ||||
| import org.apache.tools.ant.util.FileUtils; | import org.apache.tools.ant.util.FileUtils; | ||||
| @@ -58,6 +55,7 @@ public class LogStreamHandler extends PumpStreamHandler { | |||||
| /** | /** | ||||
| * Stop the log stream handler. | * Stop the log stream handler. | ||||
| */ | */ | ||||
| @Override | |||||
| public void stop() { | public void stop() { | ||||
| super.stop(); | super.stop(); | ||||
| FileUtils.close(getErr()); | FileUtils.close(getErr()); | ||||