http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java index 85a2fc6..8fa6913 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsUser.java @@ -26,10 +26,10 @@ import org.apache.tools.ant.BuildException; public class CvsUser { /** The user's Id */ private String userID; + /** The user's full name */ private String displayName; - /** * Set the user's fullname * @@ -39,7 +39,6 @@ public class CvsUser { this.displayName = displayName; } - /** * Set the user's id * @@ -49,7 +48,6 @@ public class CvsUser { this.userID = userID; } - /** * Get the user's id. * @@ -59,7 +57,6 @@ public class CvsUser { return userID; } - /** * Get the user's full name * @@ -69,7 +66,6 @@ public class CvsUser { return displayName; } - /** * Validate that this object is configured. * @@ -78,16 +74,11 @@ public class CvsUser { */ public void validate() throws BuildException { if (null == userID) { - final String message = "Username attribute must be set."; - - throw new BuildException(message); + throw new BuildException("Username attribute must be set."); } if (null == displayName) { - final String message = - "Displayname attribute must be set for userID " + userID; - - throw new BuildException(message); + throw new BuildException( + "Displayname attribute must be set for userID %s", userID); } } } -
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsVersion.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsVersion.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsVersion.java index 618da4e..0e0fc20 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsVersion.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/CvsVersion.java @@ -43,6 +43,7 @@ import org.apache.tools.ant.taskdefs.AbstractCvsTask; public class CvsVersion extends AbstractCvsTask { static final long VERSION_1_11_2 = 11102; static final long MULTIPLY = 100; + private String clientVersion; private String serverVersion; private String clientVersionProperty; @@ -55,6 +56,7 @@ public class CvsVersion extends AbstractCvsTask { public String getClientVersion() { return clientVersion; } + /** * Get the CVS server version * @return CVS server version @@ -62,6 +64,7 @@ public class CvsVersion extends AbstractCvsTask { public String getServerVersion() { return serverVersion; } + /** * Set a property where to store the CVS client version * @param clientVersionProperty property for CVS client version @@ -77,6 +80,7 @@ public class CvsVersion extends AbstractCvsTask { public void setServerVersionProperty(String serverVersionProperty) { this.serverVersionProperty = serverVersionProperty; } + /** * Find out if the server version supports log with S option * @return boolean indicating if the server version supports log with S option @@ -90,7 +94,7 @@ public class CvsVersion extends AbstractCvsTask { long version = 0; while (tokenizer.hasMoreTokens()) { String s = tokenizer.nextToken(); - int i = 0; + int i; for (i = 0; i < s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { break; @@ -103,11 +107,13 @@ public class CvsVersion extends AbstractCvsTask { } counter = counter / MULTIPLY; } - return (version >= VERSION_1_11_2); + return version >= VERSION_1_11_2; } + /** * the execute method running CvsVersion */ + @Override public void execute() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); this.setOutputStream(bos); @@ -127,9 +133,9 @@ public class CvsVersion extends AbstractCvsTask { while (haveReadAhead || st.hasMoreTokens()) { String currentToken = haveReadAhead ? cachedVersion : st.nextToken(); haveReadAhead = false; - if (currentToken.equals("Client:")) { + if ("Client:".equals(currentToken)) { client = true; - } else if (currentToken.equals("Server:")) { + } else if ("Server:".equals(currentToken)) { server = true; } else if (currentToken.startsWith("(CVS") && currentToken.endsWith(")")) { @@ -151,7 +157,7 @@ public class CvsVersion extends AbstractCvsTask { } server = false; cvs = null; - } else if (currentToken.equals("(client/server)") + } else if ("(client/server)".equals(currentToken) && cvs != null && cachedVersion != null && !client && !server) { client = server = true; http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java index 70a8cf3..6c699aa 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RCSFile.java @@ -26,12 +26,10 @@ class RCSFile { private String revision; private String previousRevision; - RCSFile(final String name, final String rev) { this(name, rev, null); } - RCSFile(final String name, final String revision, final String previousRevision) { @@ -66,4 +64,3 @@ class RCSFile { return previousRevision; } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java index f2b61cf..6e3a28f 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingOutputStream.java @@ -39,8 +39,8 @@ class RedirectingOutputStream extends LineOrientedOutputStream { * * @param line the line to log. */ + @Override protected void processLine(final String line) { parser.stdout(line); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java index e9b755d..b43e645 100644 --- a/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java +++ b/src/main/org/apache/tools/ant/taskdefs/cvslib/RedirectingStreamHandler.java @@ -18,9 +18,7 @@ package org.apache.tools.ant.taskdefs.cvslib; import java.io.ByteArrayOutputStream; -import java.io.IOException; -import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.PumpStreamHandler; import org.apache.tools.ant.util.FileUtils; @@ -35,7 +33,6 @@ class RedirectingStreamHandler new ByteArrayOutputStream()); } - String getErrors() { try { final ByteArrayOutputStream error @@ -47,11 +44,10 @@ class RedirectingStreamHandler } } - + @Override public void stop() { super.stop(); FileUtils.close(getErr()); FileUtils.close(getOut()); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java b/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java index edc9c9d..a515478 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/EmailAddress.java @@ -119,7 +119,7 @@ public class EmailAddress { private String trim(String t, boolean trimAngleBrackets) { int start = 0; int end = t.length(); - boolean trim = false; + boolean trim; do { trim = false; if (t.charAt(end - 1) == ')' @@ -140,7 +140,6 @@ public class EmailAddress { return t.substring(start, end); } - /** * Sets the personal / display name of the address. * @@ -150,7 +149,6 @@ public class EmailAddress { this.name = name; } - /** * Sets the email address. * @@ -160,21 +158,19 @@ public class EmailAddress { this.address = address; } - /** * Constructs a string "name <address>" or "address" * * @return a string representation of the address */ + @Override public String toString() { if (name == null) { return address; - } else { - return name + " <" + address + ">"; } + return name + " <" + address + ">"; } - /** * Returns the address * @@ -184,7 +180,6 @@ public class EmailAddress { return address; } - /** * Returns the display name * @@ -194,4 +189,3 @@ public class EmailAddress { return name; } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java b/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java index 0a5bc68..207a2e3 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java @@ -20,7 +20,6 @@ package org.apache.tools.ant.taskdefs.email; import java.io.File; import java.util.StringTokenizer; import java.util.Vector; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; @@ -60,8 +59,9 @@ public class EmailTask extends Task { * * @return a list of valid entries */ + @Override public String[] getValues() { - return new String[] {AUTO, MIME, UU, PLAIN}; + return new String[] { AUTO, MIME, UU, PLAIN }; } } @@ -82,16 +82,16 @@ public class EmailTask extends Task { /** sender */ private EmailAddress from = null; /** replyto */ - private Vector replyToList = new Vector(); + private Vector<EmailAddress> replyToList = new Vector<>(); /** TO recipients */ - private Vector toList = new Vector(); + private Vector<EmailAddress> toList = new Vector<>(); /** CC (Carbon Copy) recipients */ - private Vector ccList = new Vector(); + private Vector<EmailAddress> ccList = new Vector<>(); /** BCC (Blind Carbon Copy) recipients */ - private Vector bccList = new Vector(); + private Vector<EmailAddress> bccList = new Vector<>(); /** generic headers */ - private Vector headers = new Vector(); + private Vector<Header> headers = new Vector<>(); /** file list */ private Path attachments = null; @@ -189,8 +189,8 @@ public class EmailTask extends Task { */ public void setMessage(String message) { if (this.message != null) { - throw new BuildException("Only one message can be sent in an " - + "email"); + throw new BuildException( + "Only one message can be sent in an email"); } this.message = new Message(message); this.message.setProject(getProject()); @@ -203,8 +203,8 @@ public class EmailTask extends Task { */ public void setMessageFile(File file) { if (this.message != null) { - throw new BuildException("Only one message can be sent in an " - + "email"); + throw new BuildException( + "Only one message can be sent in an email"); } this.message = new Message(file); this.message.setProject(getProject()); @@ -284,7 +284,7 @@ public class EmailTask extends Task { * @param address An email address. */ public void addTo(EmailAddress address) { - toList.addElement(address); + toList.add(address); } /** @@ -296,7 +296,7 @@ public class EmailTask extends Task { StringTokenizer tokens = new StringTokenizer(list, ","); while (tokens.hasMoreTokens()) { - toList.addElement(new EmailAddress(tokens.nextToken())); + toList.add(new EmailAddress(tokens.nextToken())); } } @@ -306,7 +306,7 @@ public class EmailTask extends Task { * @param address The email address. */ public void addCc(EmailAddress address) { - ccList.addElement(address); + ccList.add(address); } /** @@ -318,7 +318,7 @@ public class EmailTask extends Task { StringTokenizer tokens = new StringTokenizer(list, ","); while (tokens.hasMoreTokens()) { - ccList.addElement(new EmailAddress(tokens.nextToken())); + ccList.add(new EmailAddress(tokens.nextToken())); } } @@ -328,7 +328,7 @@ public class EmailTask extends Task { * @param address The email address. */ public void addBcc(EmailAddress address) { - bccList.addElement(address); + bccList.add(address); } /** @@ -340,7 +340,7 @@ public class EmailTask extends Task { StringTokenizer tokens = new StringTokenizer(list, ","); while (tokens.hasMoreTokens()) { - bccList.addElement(new EmailAddress(tokens.nextToken())); + bccList.add(new EmailAddress(tokens.nextToken())); } } @@ -434,6 +434,7 @@ public class EmailTask extends Task { /** * Send an email. */ + @Override public void execute() { Message savedMessage = message; @@ -443,15 +444,15 @@ public class EmailTask extends Task { // prepare for the auto select mechanism boolean autoFound = false; // try MIME format - if (encoding.equals(MIME) - || (encoding.equals(AUTO) && !autoFound)) { + if (MIME.equals(encoding) + || (AUTO.equals(encoding) && !autoFound)) { try { //check to make sure that activation.jar //and mail.jar are available - see bug 31969 Class.forName("javax.activation.DataHandler"); Class.forName("javax.mail.internet.MimeMessage"); - mailer = (Mailer) ClasspathUtils.newInstance( + mailer = ClasspathUtils.newInstance( "org.apache.tools.ant.taskdefs.email.MimeMailer", EmailTask.class.getClassLoader(), Mailer.class); autoFound = true; @@ -463,20 +464,20 @@ public class EmailTask extends Task { } // SMTP auth only allowed with MIME mail if (!autoFound && ((user != null) || (password != null)) - && (encoding.equals(UU) || encoding.equals(PLAIN))) { + && (UU.equals(encoding) || PLAIN.equals(encoding))) { throw new BuildException("SMTP auth only possible with MIME mail"); } // SSL only allowed with MIME mail if (!autoFound && (ssl || starttls) - && (encoding.equals(UU) || encoding.equals(PLAIN))) { - throw new BuildException("SSL and STARTTLS only possible with" - + " MIME mail"); + && (UU.equals(encoding) || PLAIN.equals(encoding))) { + throw new BuildException( + "SSL and STARTTLS only possible with MIME mail"); } // try UU format - if (encoding.equals(UU) - || (encoding.equals(AUTO) && !autoFound)) { + if (UU.equals(encoding) + || (AUTO.equals(encoding) && !autoFound)) { try { - mailer = (Mailer) ClasspathUtils.newInstance( + mailer = ClasspathUtils.newInstance( "org.apache.tools.ant.taskdefs.email.UUMailer", EmailTask.class.getClassLoader(), Mailer.class); autoFound = true; @@ -486,16 +487,16 @@ public class EmailTask extends Task { } } // try plain format - if (encoding.equals(PLAIN) - || (encoding.equals(AUTO) && !autoFound)) { + if (PLAIN.equals(encoding) + || (AUTO.equals(encoding) && !autoFound)) { mailer = new PlainMailer(); autoFound = true; log("Using plain mail", Project.MSG_VERBOSE); } // a valid mailer must be present by now if (mailer == null) { - throw new BuildException("Failed to initialise encoding: " - + encoding); + throw new BuildException("Failed to initialise encoding: %s", + encoding); } // a valid message is required if (message == null) { @@ -508,33 +509,34 @@ public class EmailTask extends Task { } // at least one address to send to/cc/bcc is required if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) { - throw new BuildException("At least one of to, cc or bcc must " - + "be supplied"); + throw new BuildException( + "At least one of to, cc or bcc must be supplied"); } // set the mimetype if not done already (and required) if (messageMimeType != null) { if (message.isMimeTypeSpecified()) { - throw new BuildException("The mime type can only be " - + "specified in one location"); + throw new BuildException( + "The mime type can only be specified in one location"); } message.setMimeType(messageMimeType); } // set the character set if not done already (and required) if (charset != null) { if (message.getCharset() != null) { - throw new BuildException("The charset can only be " - + "specified in one location"); + throw new BuildException( + "The charset can only be specified in one location"); } message.setCharset(charset); } message.setInputEncoding(messageFileInputEncoding); // identify which files should be attached - Vector<File> files = new Vector<File>(); + Vector<File> files = new Vector<>(); + + if (attachments != null) { for (Resource r : attachments) { - files.addElement(r.as(FileProvider.class) - .getFile()); + files.add(r.as(FileProvider.class).getFile()); } } // let the user know what's going to happen @@ -631,4 +633,3 @@ public class EmailTask extends Task { } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java b/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java index 4aaa982..4805177 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/Mailer.java @@ -274,4 +274,3 @@ public abstract class Mailer { return DateUtils.getDateForHeader(); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/Message.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/Message.java b/src/main/org/apache/tools/ant/taskdefs/email/Message.java index a7551bb..2422e44 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/Message.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/Message.java @@ -48,7 +48,6 @@ public class Message extends ProjectComponent { public Message() { } - /** * Creates a new message based on the given string * @@ -58,7 +57,6 @@ public class Message extends ProjectComponent { addText(text); } - /** * Creates a new message using the contents of the given file. * @@ -68,7 +66,6 @@ public class Message extends ProjectComponent { messageSource = file; } - /** * Adds a textual part of the message * @@ -78,7 +75,6 @@ public class Message extends ProjectComponent { buffer.append(text); } - /** * Sets the source file of the message * @@ -88,7 +84,6 @@ public class Message extends ProjectComponent { this.messageSource = src; } - /** * Sets the content type for the message * @@ -99,7 +94,6 @@ public class Message extends ProjectComponent { specified = true; } - /** * Returns the content type * @@ -109,7 +103,6 @@ public class Message extends ProjectComponent { return mimeType; } - /** * Prints the message onto an output stream * @@ -129,7 +122,7 @@ public class Message extends ProjectComponent { // Read message from a file try (Reader freader = getReader(messageSource); BufferedReader in = new BufferedReader(freader)) { - String line = null; + String line; while ((line = in.readLine()) != null) { out.write(getProject().replaceProperties(line)); out.newLine(); @@ -145,7 +138,6 @@ public class Message extends ProjectComponent { } } - /** * Returns true if the mimeType has been set. * @@ -164,6 +156,7 @@ public class Message extends ProjectComponent { public void setCharset(String charset) { this.charset = charset; } + /** * Returns the charset of mail message. * @@ -197,4 +190,3 @@ public class Message extends ProjectComponent { return new FileReader(f); } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java index 186d71e..e80d8d1 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java @@ -27,8 +27,6 @@ import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.security.Provider; import java.security.Security; -import java.util.Enumeration; -import java.util.Iterator; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; @@ -81,6 +79,7 @@ public class MimeMailer extends Mailer { private String charset = null; private ByteArrayOutputStream out; + @Override public InputStream getInputStream() throws IOException { if (data == null && out == null) { throw new IOException("No data"); @@ -93,6 +92,7 @@ public class MimeMailer extends Mailer { return new ByteArrayInputStream(data.getBytes(charset)); } + @Override public OutputStream getOutputStream() throws IOException { out = (out == null) ? new ByteArrayOutputStream() : out; return out; @@ -102,16 +102,18 @@ public class MimeMailer extends Mailer { this.type = type.toLowerCase(Locale.ENGLISH); } + @Override public String getContentType() { if (type != null && type.indexOf("charset") > 0 && type.startsWith("text/")) { return type; } // Must be like "text/plain; charset=windows-1251" - return new StringBuffer(type != null ? type : "text/plain").append( + return new StringBuilder(type != null ? type : "text/plain").append( "; charset=").append(charset).toString(); } + @Override public String getName() { return "StringDataSource"; } @@ -130,6 +132,7 @@ public class MimeMailer extends Mailer { * * @throws BuildException if the email can't be sent. */ + @Override public void send() { try { final Properties props = new Properties(); @@ -144,13 +147,13 @@ public class MimeMailer extends Mailer { Authenticator auth = null; if (SSL) { try { - final Provider p = (Provider) Class.forName( - "com.sun.net.ssl.internal.ssl.Provider").newInstance(); + final Provider p = + Class.forName("com.sun.net.ssl.internal.ssl.Provider") + .asSubclass(Provider.class).newInstance(); Security.addProvider(p); } catch (final Exception e) { - throw new BuildException("could not instantiate ssl " - + "security provider, check that you have JSSE in " - + "your classpath"); + throw new BuildException( + "could not instantiate ssl security provider, check that you have JSSE in your classpath"); } // SMTP provider props.put("mail.smtp.socketFactory.class", SSL_FACTORY); @@ -217,8 +220,7 @@ public class MimeMailer extends Mailer { msg.addHeader("Date", getDate()); if (headers != null) { - for (final Iterator iter = headers.iterator(); iter.hasNext();) { - final Header h = (Header) iter.next(); + for (Header h : headers) { msg.addHeader(h.getName(), h.getValue()); } } @@ -230,18 +232,12 @@ public class MimeMailer extends Mailer { textbody.setDataHandler(new DataHandler(sds)); attachments.addBodyPart(textbody); - final Enumeration e = files.elements(); - - while (e.hasMoreElements()) { - final File file = (File) e.nextElement(); - - MimeBodyPart body; - - body = new MimeBodyPart(); + for (File file : files) { + MimeBodyPart body = new MimeBodyPart(); if (!file.exists() || !file.canRead()) { - throw new BuildException("File \"" + file.getAbsolutePath() - + "\" does not exist or is not " - + "readable."); + throw new BuildException( + "File \"%s\" does not exist or is not readable.", + file.getAbsolutePath()); } final FileDataSource fileData = new FileDataSource(file); final DataHandler fileDataHandler = new DataHandler(fileData); @@ -259,41 +255,40 @@ public class MimeMailer extends Mailer { } catch (final SendFailedException sfe) { if (!shouldIgnoreInvalidRecipients()) { throw new BuildException(GENERIC_ERROR, sfe); - } else if (sfe.getValidSentAddresses() == null + } + if (sfe.getValidSentAddresses() == null || sfe.getValidSentAddresses().length == 0) { throw new BuildException("Couldn't reach any recipient", sfe); - } else { - Address[] invalid = sfe.getInvalidAddresses(); - if (invalid == null) { - invalid = new Address[0]; - } - for (int i = 0; i < invalid.length; i++) { - didntReach(invalid[i], "invalid", sfe); - } - Address[] validUnsent = sfe.getValidUnsentAddresses(); - if (validUnsent == null) { - validUnsent = new Address[0]; - } - for (int i = 0; i < validUnsent.length; i++) { - didntReach(validUnsent[i], "valid", sfe); - } + } + Address[] invalid = sfe.getInvalidAddresses(); + if (invalid == null) { + invalid = new Address[0]; + } + for (int i = 0; i < invalid.length; i++) { + didntReach(invalid[i], "invalid", sfe); + } + Address[] validUnsent = sfe.getValidUnsentAddresses(); + if (validUnsent == null) { + validUnsent = new Address[0]; + } + for (int i = 0; i < validUnsent.length; i++) { + didntReach(validUnsent[i], "valid", sfe); } } - } catch (final MessagingException e) { - throw new BuildException(GENERIC_ERROR, e); - } catch (final IOException e) { + } catch (MessagingException | IOException e) { throw new BuildException(GENERIC_ERROR, e); } } - private static InternetAddress[] internetAddresses(final Vector list) + private static InternetAddress[] internetAddresses(final Vector<EmailAddress> list) throws AddressException, UnsupportedEncodingException { + final int size = list.size(); final InternetAddress[] addrs = new InternetAddress[size]; for (int i = 0; i < size; ++i) { - final EmailAddress addr = (EmailAddress) list.elementAt(i); + final EmailAddress addr = list.get(i); final String name = addr.getName(); addrs[i] = (name == null) @@ -309,7 +304,7 @@ public class MimeMailer extends Mailer { } final int pos = type.indexOf("charset"); if (pos < 0) { - return null; + return null; } // Assuming mime type in form "text/XXXX; charset=XXXXXX" final StringTokenizer token = new StringTokenizer(type.substring(pos), "=; "); @@ -331,10 +326,13 @@ public class MimeMailer extends Mailer { static class SimpleAuthenticator extends Authenticator { private String user = null; private String password = null; + public SimpleAuthenticator(final String user, final String password) { this.user = user; this.password = password; } + + @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java index 0ad57c6..1d0c378 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java @@ -23,8 +23,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.file.Files; -import java.util.Enumeration; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.mail.MailMessage; @@ -40,49 +38,44 @@ class PlainMailer extends Mailer { * * @see org.apache.tools.mail.MailMessage */ + @Override public void send() { try { MailMessage mailMessage = new MailMessage(host, port); mailMessage.from(from.toString()); - Enumeration e; boolean atLeastOneRcptReached = false; - e = replyToList.elements(); - while (e.hasMoreElements()) { - mailMessage.replyto(e.nextElement().toString()); - } - e = toList.elements(); - while (e.hasMoreElements()) { - String to = e.nextElement().toString(); + replyToList.stream().map(Object::toString).forEach(mailMessage::replyto); + + for (EmailAddress to : toList) { try { - mailMessage.to(to); + mailMessage.to(to.toString()); atLeastOneRcptReached = true; } catch (IOException ex) { badRecipient(to, ex); } } - e = ccList.elements(); - while (e.hasMoreElements()) { - String to = e.nextElement().toString(); + + for (EmailAddress cc : ccList) { try { - mailMessage.cc(to); + mailMessage.cc(cc.toString()); atLeastOneRcptReached = true; } catch (IOException ex) { - badRecipient(to, ex); + badRecipient(cc, ex); } } - e = bccList.elements(); - while (e.hasMoreElements()) { - String to = e.nextElement().toString(); + + for (EmailAddress bcc : bccList) { try { - mailMessage.bcc(to); + mailMessage.bcc(bcc.toString()); atLeastOneRcptReached = true; } catch (IOException ex) { - badRecipient(to, ex); + badRecipient(bcc, ex); } } + if (!atLeastOneRcptReached) { throw new BuildException("Couldn't reach any recipient"); } @@ -97,18 +90,17 @@ class PlainMailer extends Mailer { mailMessage.setHeader("Content-Type", message.getMimeType()); } if (headers != null) { - e = headers.elements(); - while (e.hasMoreElements()) { - Header h = (Header) e.nextElement(); + for (Header h : headers) { mailMessage.setHeader(h.getName(), h.getValue()); } } PrintStream out = mailMessage.getPrintStream(); message.print(out); - e = files.elements(); - while (e.hasMoreElements()) { - attach((File) e.nextElement(), out); + if (files != null) { + for (File f : files) { + attach(f, out); + } } mailMessage.sendAndClose(); } catch (IOException ioe) { @@ -127,9 +119,9 @@ class PlainMailer extends Mailer { protected void attach(File file, PrintStream out) throws IOException { if (!file.exists() || !file.canRead()) { - throw new BuildException("File \"" + file.getName() - + "\" does not exist or is not " - + "readable."); + throw new BuildException( + "File \"%s\" does not exist or is not readable.", + file.getAbsolutePath()); } if (includeFileNames) { @@ -145,20 +137,20 @@ class PlainMailer extends Mailer { out.println(); } - int length; final int maxBuf = 1024; byte[] buf = new byte[maxBuf]; try (InputStream finstr = Files.newInputStream(file.toPath()); BufferedInputStream in = new BufferedInputStream(finstr, buf.length)) { + int length; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } } } - private void badRecipient(String rcpt, IOException reason) { + private void badRecipient(EmailAddress rcpt, IOException reason) { String msg = "Failed to send mail to " + rcpt; if (shouldIgnoreInvalidRecipients()) { msg += " because of :" + reason.getMessage(); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java b/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java index 0b61ecd..9759601 100644 --- a/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java +++ b/src/main/org/apache/tools/ant/taskdefs/email/UUMailer.java @@ -33,19 +33,18 @@ import org.apache.tools.ant.util.UUEncoder; * @since Ant 1.5 */ class UUMailer extends PlainMailer { + @Override protected void attach(File file, PrintStream out) throws IOException { if (!file.exists() || !file.canRead()) { - throw new BuildException("File \"" + file.getName() - + "\" does not exist or is not " - + "readable."); + throw new BuildException( + "File \"%s" + "\" does not exist or is not " + "readable.", + file.getAbsolutePath()); } - try (InputStream finstr = Files.newInputStream(file.toPath()); - BufferedInputStream in = new BufferedInputStream(finstr)) { - UUEncoder encoder = new UUEncoder(file.getName()); - - encoder.encode(in, out); + try (InputStream in = + new BufferedInputStream(Files.newInputStream(file.toPath()))) { + new UUEncoder(file.getName()).encode(in, out); } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java index f39fff0..5139ce9 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/CommandLauncher.java @@ -22,6 +22,7 @@ import static org.apache.tools.ant.MagicNames.ANT_VM_LAUNCHER_REF_ID; import java.io.File; import java.io.IOException; +import java.util.Optional; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.condition.Os; @@ -41,7 +42,7 @@ public class CommandLauncher { private static CommandLauncher shellLauncher = null; static { - if(!Os.isFamily("os/2")) { + if (!Os.isFamily("os/2")) { vmLauncher = new Java13CommandLauncher(); } @@ -94,7 +95,7 @@ public class CommandLauncher { */ public Process exec(Project project, String[] cmd, String[] env) throws IOException { - if(project != null) { + if (project != null) { project.log("Execute:CommandLauncher: " + Commandline.describeCommand(cmd), Project.MSG_DEBUG); } @@ -124,8 +125,8 @@ public class CommandLauncher { if (workingDir == null) { return exec(project, cmd, env); } - throw new IOException("Cannot execute a process in different " - + "directory under this JVM"); + throw new IOException( + "Cannot execute a process in different directory under this JVM"); } /** @@ -157,37 +158,24 @@ public class CommandLauncher { private static CommandLauncher extractLauncher(String referenceName, Project project) { - CommandLauncher launcher = null; - if (project != null) { - launcher = (CommandLauncher) project.getReference(referenceName); - } - - if (launcher == null) { - launcher = getSystemLauncher(referenceName); - } - return launcher; + return Optional.ofNullable(project) + .map(p -> p.<CommandLauncher> getReference(referenceName)) + .orElseGet(() -> getSystemLauncher(referenceName)); } private static CommandLauncher getSystemLauncher(String launcherRefId) { - CommandLauncher launcher = null; String launcherClass = System.getProperty(launcherRefId); if (launcherClass != null) { try { - launcher = (CommandLauncher) Class.forName(launcherClass) - .newInstance(); - } catch(InstantiationException e) { - System.err.println("Could not instantiate launcher class " - + launcherClass + ": " + e.getMessage()); - } catch(IllegalAccessException e) { - System.err.println("Could not instantiate launcher class " - + launcherClass + ": " + e.getMessage()); - } catch(ClassNotFoundException e) { + return Class.forName(launcherClass) + .asSubclass(CommandLauncher.class).newInstance(); + } catch (InstantiationException | IllegalAccessException + | ClassNotFoundException e) { System.err.println("Could not instantiate launcher class " - + launcherClass + ": " + e.getMessage()); + + launcherClass + ": " + e.getMessage()); } } - - return launcher; + return null; } /** http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java index d5b06f7..77d1cc8 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/PerlScriptCommandLauncher.java @@ -58,15 +58,14 @@ public class PerlScriptCommandLauncher extends CommandLauncherProxy { if (workingDir == null) { return exec(project, cmd, env); } - throw new IOException("Cannot locate antRun script: " - + "No project provided"); + throw new IOException( + "Cannot locate antRun script: No project provided"); } // Locate the auxiliary script String antHome = project.getProperty(MagicNames.ANT_HOME); if (antHome == null) { - throw new IOException("Cannot locate antRun script: " - + "Property '" + MagicNames.ANT_HOME - + "' not found"); + throw new IOException("Cannot locate antRun script: Property '" + + MagicNames.ANT_HOME + "' not found"); } String antRun = FILE_UTILS.resolveFile(project.getBaseDir(), antHome + File.separator http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java index 936f948..bee01d6 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/ScriptCommandLauncher.java @@ -58,15 +58,14 @@ public class ScriptCommandLauncher extends CommandLauncherProxy { if (workingDir == null) { return exec(project, cmd, env); } - throw new IOException("Cannot locate antRun script: " - + "No project provided"); + throw new IOException( + "Cannot locate antRun script: No project provided"); } // Locate the auxiliary script String antHome = project.getProperty(MagicNames.ANT_HOME); if (antHome == null) { - throw new IOException("Cannot locate antRun script: " - + "Property '" + MagicNames.ANT_HOME - + "' not found"); + throw new IOException("Cannot locate antRun script: Property '" + + MagicNames.ANT_HOME + "' not found"); } String antRun = FILE_UTILS.resolveFile(project.getBaseDir(), antHome + File.separator http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java b/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java index 4c1b3f0..16b8042 100644 --- a/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java +++ b/src/main/org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.java @@ -32,10 +32,6 @@ import org.apache.tools.ant.util.FileUtils; */ public class VmsCommandLauncher extends Java13CommandLauncher { - public VmsCommandLauncher() { - super(); - } - /** * Launches the given command in a new process. * @@ -53,7 +49,8 @@ public class VmsCommandLauncher extends Java13CommandLauncher { public Process exec(Project project, String[] cmd, String[] env) throws IOException { File cmdFile = createCommandFile(cmd, env); - Process p = super.exec(project, new String[] {cmdFile.getPath()}, env); + Process p = + super.exec(project, new String[] { cmdFile.getPath() }, env); deleteAfter(cmdFile, p); return p; } @@ -80,9 +77,8 @@ public class VmsCommandLauncher extends Java13CommandLauncher { public Process exec(Project project, String[] cmd, String[] env, File workingDir) throws IOException { File cmdFile = createCommandFile(cmd, env); - Process p = super.exec(project, new String[] { - cmdFile.getPath() - }, env, workingDir); + Process p = super.exec(project, new String[] { cmdFile.getPath() }, env, + workingDir); deleteAfter(cmdFile, p); return p; } @@ -98,9 +94,7 @@ public class VmsCommandLauncher extends Java13CommandLauncher { private File createCommandFile(String[] cmd, String[] env) throws IOException { File script = FILE_UTILS.createTempFile("ANT", ".COM", null, true, true); - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(script)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(script))) { // add the environment as logicals to the DCL script if (env != null) { @@ -123,8 +117,6 @@ public class VmsCommandLauncher extends Java13CommandLauncher { out.newLine(); out.write(cmd[i]); } - } finally { - FileUtils.close(out); } return script; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java index 2ed40e5..2ca2443 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/ANTLR.java @@ -118,8 +118,9 @@ public class ANTLR extends Task { * @param superGrammar the super grammar filename * @deprecated since ant 1.6 */ + @Deprecated public void setGlib(String superGrammar) { - String sg = null; + String sg; if (Os.isFamily("dos")) { sg = superGrammar.replace('\\', '/'); } else { @@ -127,6 +128,7 @@ public class ANTLR extends Task { } setGlib(FILE_UTILS.resolveFile(getProject().getBaseDir(), sg)); } + /** * Sets an optional super grammar file * @param superGrammar the super grammar file @@ -135,6 +137,7 @@ public class ANTLR extends Task { public void setGlib(File superGrammar) { this.superGrammar = superGrammar; } + /** * Sets a flag to enable ParseView debugging * @param enable a <code>boolean</code> value @@ -200,7 +203,6 @@ public class ANTLR extends Task { * @param s a <code>boolean</code> value */ public void setFork(boolean s) { - //this.fork = s; } /** @@ -235,6 +237,7 @@ public class ANTLR extends Task { * specify it directly. * @throws BuildException on error */ + @Override public void init() throws BuildException { addClasspathEntry("/antlr/ANTLRGrammarParseBehavior.class"); } @@ -278,6 +281,7 @@ public class ANTLR extends Task { * Execute the task. * @throws BuildException on error */ + @Override public void execute() throws BuildException { validateAttributes(); @@ -302,12 +306,11 @@ public class ANTLR extends Task { int err = run(commandline.getCommandline()); if (err != 0) { throw new BuildException("ANTLR returned: " + err, getLocation()); - } else { - String output = bos.toString(); - if (output.indexOf("error:") > -1) { - throw new BuildException("ANTLR signaled an error: " - + output, getLocation()); - } + } + String output = bos.toString(); + if (output.indexOf("error:") > -1) { + throw new BuildException("ANTLR signaled an error: " + + output, getLocation()); } } else { log("Skipped grammar file. Generated file " + generatedFile @@ -357,7 +360,6 @@ public class ANTLR extends Task { if (targetFile == null || !targetFile.isFile()) { throw new BuildException("Invalid target: " + targetFile); } - // if no output directory is specified, used the target's directory if (outputDirectory == null) { setOutputdirectory(new File(targetFile.getParent())); @@ -369,8 +371,8 @@ public class ANTLR extends Task { private File getGeneratedFile() throws BuildException { String generatedFileName = null; - try { - BufferedReader in = new BufferedReader(new FileReader(targetFile)); + try (BufferedReader in = + new BufferedReader(new FileReader(targetFile))) { String line; while ((line = in.readLine()) != null) { int extendsIndex = line.indexOf(" extends "); @@ -380,7 +382,6 @@ public class ANTLR extends Task { break; } } - in.close(); } catch (Exception e) { throw new BuildException("Unable to determine generated class", e); } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java index 11c091a..43acdbe 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Cab.java @@ -23,7 +23,8 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; -import java.util.Enumeration; +import java.io.PrintWriter; +import java.util.Collections; import java.util.Vector; import org.apache.tools.ant.BuildException; @@ -46,9 +47,9 @@ import org.apache.tools.ant.util.FileUtils; public class Cab extends MatchingTask { private static final int DEFAULT_RESULT = -99; + private File cabFile; private File baseDir; - private Vector filesets = new Vector(); private boolean doCompress = true; private boolean doVerbose = false; private String cmdOptions; @@ -59,6 +60,10 @@ public class Cab extends MatchingTask { private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + { + fileset = null; + } + /** * The name/location of where to create the .cab file. * @param cabFile the location of the cab file. @@ -101,13 +106,13 @@ public class Cab extends MatchingTask { /** * Adds a set of files to archive. - * @param set a set of files to archive. + * @param fileset a set of files to archive. */ - public void addFileset(FileSet set) { - if (filesets.size() > 0) { + public void addFileset(FileSet fileset) { + if (fileset != null) { throw new BuildException("Only one nested fileset allowed"); } - filesets.addElement(set); + this.fileset = fileset; } /* @@ -120,15 +125,15 @@ public class Cab extends MatchingTask { * @throws BuildException on error. */ protected void checkConfiguration() throws BuildException { - if (baseDir == null && filesets.size() == 0) { - throw new BuildException("basedir attribute or one " - + "nested fileset is required!", - getLocation()); + if (baseDir == null && fileset == null) { + throw new BuildException( + "basedir attribute or one nested fileset is required!", + getLocation()); } if (baseDir != null && !baseDir.exists()) { throw new BuildException("basedir does not exist!", getLocation()); } - if (baseDir != null && filesets.size() > 0) { + if (baseDir != null && fileset != null) { throw new BuildException( "Both basedir attribute and a nested fileset is not allowed"); } @@ -145,8 +150,7 @@ public class Cab extends MatchingTask { * @throws BuildException on error. */ protected ExecTask createExec() throws BuildException { - ExecTask exec = new ExecTask(this); - return exec; + return new ExecTask(this); } /** @@ -154,17 +158,10 @@ public class Cab extends MatchingTask { * @param files the list of files to check. * @return true if the cab file is newer than its dependents. */ - protected boolean isUpToDate(Vector files) { - boolean upToDate = true; - final int size = files.size(); - for (int i = 0; i < size && upToDate; i++) { - String file = files.elementAt(i).toString(); - if (FILE_UTILS.resolveFile(baseDir, file).lastModified() - > cabFile.lastModified()) { - upToDate = false; - } - } - return upToDate; + protected boolean isUpToDate(Vector<String> files) { + final long cabModified = cabFile.lastModified(); + return files.stream().map(f -> FILE_UTILS.resolveFile(baseDir, f)) + .mapToLong(File::lastModified).allMatch(t -> t < cabModified); } /** @@ -177,23 +174,15 @@ public class Cab extends MatchingTask { * @return the list file created. * @throws IOException if there is an error. */ - protected File createListFile(Vector files) + protected File createListFile(Vector<String> files) throws IOException { File listFile = FILE_UTILS.createTempFile("ant", "", null, true, true); - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(listFile)); - - final int size = files.size(); - for (int i = 0; i < size; i++) { - writer.write('\"' + files.elementAt(i).toString() + '\"'); - writer.newLine(); - } - } finally { - FileUtils.close(writer); + try (PrintWriter writer = + new PrintWriter(new BufferedWriter(new FileWriter(listFile)))) { + files.stream().map(f -> String.format("\"%s\"", f)) + .forEach(writer::println); } - return listFile; } @@ -202,12 +191,8 @@ public class Cab extends MatchingTask { * @param files the vector to append the files to. * @param ds the scanner to get the files from. */ - protected void appendFiles(Vector files, DirectoryScanner ds) { - String[] dsfiles = ds.getIncludedFiles(); - - for (int i = 0; i < dsfiles.length; i++) { - files.addElement(dsfiles[i]); - } + protected void appendFiles(Vector<String> files, DirectoryScanner ds) { + Collections.addAll(files, ds.getIncludedFiles()); } /** @@ -217,18 +202,16 @@ public class Cab extends MatchingTask { * @return the list of files. * @throws BuildException if there is an error. */ - protected Vector getFileList() throws BuildException { - Vector files = new Vector(); + protected Vector<String> getFileList() throws BuildException { + Vector<String> files = new Vector<>(); if (baseDir != null) { // get files from old methods - includes and nested include appendFiles(files, super.getDirectoryScanner(baseDir)); } else { - FileSet fs = (FileSet) filesets.elementAt(0); - baseDir = fs.getDir(); - appendFiles(files, fs.getDirectoryScanner(getProject())); + baseDir = fileset.getDir(); + appendFiles(files, fileset.getDirectoryScanner(getProject())); } - return files; } @@ -236,11 +219,12 @@ public class Cab extends MatchingTask { * execute this task. * @throws BuildException on error. */ + @Override public void execute() throws BuildException { checkConfiguration(); - Vector files = getFileList(); + Vector<String> files = getFileList(); // quick exit if the target is up to date if (isUpToDate(files)) { @@ -252,21 +236,17 @@ public class Cab extends MatchingTask { if (!Os.isFamily("windows")) { log("Using listcab/libcabinet", Project.MSG_VERBOSE); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); - Enumeration fileEnum = files.elements(); + files.forEach(f -> sb.append(f).append("\n")); - while (fileEnum.hasMoreElements()) { - sb.append(fileEnum.nextElement()).append("\n"); - } sb.append("\n").append(cabFile.getAbsolutePath()).append("\n"); try { Process p = Execute.launch(getProject(), - new String[] {"listcab"}, null, - baseDir != null ? baseDir - : getProject().getBaseDir(), - true); + new String[] { "listcab" }, null, + baseDir != null ? baseDir : getProject().getBaseDir(), + true); OutputStream out = p.getOutputStream(); // Create the stream pumpers to forward listcab's stdout and stderr to the log @@ -278,8 +258,8 @@ public class Cab extends MatchingTask { StreamPumper errPump = new StreamPumper(p.getErrorStream(), errLog); // Pump streams asynchronously - (new Thread(outPump)).start(); - (new Thread(errPump)).start(); + new Thread(outPump).start(); + new Thread(errPump).start(); out.write(sb.toString().getBytes()); out.flush(); @@ -306,8 +286,9 @@ public class Cab extends MatchingTask { log("Error executing listcab; error code: " + result); } } catch (IOException ex) { - String msg = "Problem creating " + cabFile + " " + ex.getMessage(); - throw new BuildException(msg, getLocation()); + throw new BuildException( + "Problem creating " + cabFile + " " + ex.getMessage(), + getLocation()); } } else { try { @@ -349,8 +330,9 @@ public class Cab extends MatchingTask { listFile.delete(); } catch (IOException ioe) { - String msg = "Problem creating " + cabFile + " " + ioe.getMessage(); - throw new BuildException(msg, getLocation()); + throw new BuildException( + "Problem creating " + cabFile + " " + ioe.getMessage(), + getLocation()); } } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java index f6681f8..8132f36 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/EchoProperties.java @@ -17,7 +17,6 @@ */ package org.apache.tools.ant.taskdefs.optional; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -31,25 +30,25 @@ import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.Vector; - +import java.util.function.Function; +import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.LogOutputStream; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.PropertySet; -import org.apache.tools.ant.util.CollectionUtils; import org.apache.tools.ant.util.DOMElementWriter; -import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.JavaEnvUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -127,7 +126,7 @@ public class EchoProperties extends Task { */ private boolean failonerror = true; - private Vector propertySets = new Vector(); + private List<PropertySet> propertySets = new Vector<>(); private String format = "text"; @@ -157,7 +156,6 @@ public class EchoProperties extends Task { this.destfile = destfile; } - /** * If true, the task will fail if an error occurs writing the properties * file, otherwise errors are just logged. @@ -169,7 +167,6 @@ public class EchoProperties extends Task { this.failonerror = failonerror; } - /** * If the prefix is set, then only properties which start with this * prefix string will be recorded. If regex is not set and if this @@ -209,7 +206,7 @@ public class EchoProperties extends Task { * @since Ant 1.7 */ public void setRegex(String regex) { - if (regex != null && regex.length() != 0) { + if (!(regex == null || regex.isEmpty())) { this.regex = regex; PropertySet ps = new PropertySet(); ps.setProject(getProject()); @@ -224,7 +221,7 @@ public class EchoProperties extends Task { * @since Ant 1.6 */ public void addPropertyset(PropertySet ps) { - propertySets.addElement(ps); + propertySets.add(ps); } /** @@ -240,12 +237,13 @@ public class EchoProperties extends Task { * The values are "xml" and "text". */ public static class FormatAttribute extends EnumeratedAttribute { - private String [] formats = new String[]{"xml", "text"}; + private String[] formats = new String[] { "xml", "text" }; /** * @see EnumeratedAttribute#getValues() * @return accepted values */ + @Override public String[] getValues() { return formats; } @@ -256,27 +254,28 @@ public class EchoProperties extends Task { * *@exception BuildException trouble, probably file IO */ + @Override public void execute() throws BuildException { if (prefix != null && regex != null) { - throw new BuildException("Please specify either prefix" - + " or regex, but not both", getLocation()); + throw new BuildException( + "Please specify either prefix or regex, but not both", + getLocation()); } //copy the properties file - Hashtable allProps = new Hashtable(); + Hashtable<Object, Object> allProps = new Hashtable<>(); /* load properties from file if specified, otherwise use Ant's properties */ - if (inFile == null && propertySets.size() == 0) { + if (inFile == null && propertySets.isEmpty()) { // add ant properties allProps.putAll(getProject().getProperties()); } else if (inFile != null) { - if (inFile.exists() && inFile.isDirectory()) { + if (inFile.isDirectory()) { String message = "srcfile is a directory!"; if (failonerror) { throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); } + log(message, Project.MSG_ERR); return; } @@ -290,9 +289,7 @@ public class EchoProperties extends Task { return; } - InputStream in = null; - try { - in = Files.newInputStream(inFile.toPath()); + try (InputStream in = Files.newInputStream(inFile.toPath())) { Properties props = new Properties(); props.load(in); allProps.putAll(props); @@ -301,72 +298,35 @@ public class EchoProperties extends Task { "Could not find file " + inFile.getAbsolutePath(); if (failonerror) { throw new BuildException(message, fnfe, getLocation()); - } else { - log(message, Project.MSG_WARN); } + log(message, Project.MSG_WARN); return; } catch (IOException ioe) { String message = "Could not read file " + inFile.getAbsolutePath(); if (failonerror) { throw new BuildException(message, ioe, getLocation()); - } else { - log(message, Project.MSG_WARN); } + log(message, Project.MSG_WARN); return; - } finally { - FileUtils.close(in); } } - Enumeration e = propertySets.elements(); - while (e.hasMoreElements()) { - PropertySet ps = (PropertySet) e.nextElement(); - allProps.putAll(ps.getProperties()); - } - - OutputStream os = null; - try { - if (destfile == null) { - os = new ByteArrayOutputStream(); - saveProperties(allProps, os); - log(os.toString(), Project.MSG_INFO); - } else { - if (destfile.exists() && destfile.isDirectory()) { - String message = "destfile is a directory!"; - if (failonerror) { - throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); - } - return; - } + propertySets.stream().map(PropertySet::getProperties) + .forEach(allProps::putAll); - if (destfile.exists() && !destfile.canWrite()) { - String message = - "Can not write to the specified destfile!"; - if (failonerror) { - throw new BuildException(message, getLocation()); - } else { - log(message, Project.MSG_ERR); - } - return; - } - os = Files.newOutputStream(this.destfile.toPath()); + try (OutputStream os = createOutputStream()) { + if (os != null) { saveProperties(allProps, os); } } catch (IOException ioe) { if (failonerror) { throw new BuildException(ioe, getLocation()); - } else { - log(ioe.getMessage(), Project.MSG_INFO); } - } finally { - FileUtils.close(os); + log(ioe.getMessage(), Project.MSG_INFO); } } - /** * Send the key/value pairs in the hashtable to the given output stream. * Only those properties matching the <tt>prefix</tt> constraint will be @@ -378,37 +338,37 @@ public class EchoProperties extends Task { * @throws IOException on output errors * @throws BuildException on other errors */ - protected void saveProperties(Hashtable allProps, OutputStream os) + protected void saveProperties(Hashtable<Object, Object> allProps, OutputStream os) throws IOException, BuildException { - final List keyList = new ArrayList(allProps.keySet()); - Collections.sort(keyList); + final List<Object> keyList = new ArrayList<>(allProps.keySet()); + Properties props = new Properties() { private static final long serialVersionUID = 5090936442309201654L; - public Enumeration keys() { - return CollectionUtils.asEnumeration(keyList.iterator()); + + @Override + public Enumeration<Object> keys() { + return keyList.stream() + .sorted(Comparator.comparing(Object::toString)) + .collect(Collectors.collectingAndThen(Collectors.toList(), + Collections::enumeration)); } - public Set entrySet() { - Set result = super.entrySet(); + + @Override + public Set<Map.Entry<Object,Object>> entrySet() { + Set<Map.Entry<Object, Object>> result = super.entrySet(); if (JavaEnvUtils.isKaffe()) { - TreeSet t = new TreeSet(new Comparator() { - public int compare(Object o1, Object o2) { - String key1 = (String) ((Map.Entry) o1).getKey(); - String key2 = (String) ((Map.Entry) o2).getKey(); - return key1.compareTo(key2); - } - }); + Set<Map.Entry<Object, Object>> t = + new TreeSet<>(Comparator.comparing( + ((Function<Map.Entry<Object, Object>, Object>) Map.Entry::getKey) + .andThen(Object::toString))); t.addAll(result); - result = t; + return t; } return result; } }; - final int size = keyList.size(); - for (int i = 0; i < size; i++) { - String name = keyList.get(i).toString(); - String value = allProps.get(name).toString(); - props.setProperty(name, value); - } + allProps.forEach((k, v) -> props.put(String.valueOf(k), String.valueOf(v))); + if ("text".equals(format)) { jdkSaveProperties(props, os, "Ant properties"); } else if ("xml".equals(format)) { @@ -419,7 +379,7 @@ public class EchoProperties extends Task { /** * a tuple for the sort list. */ - private static final class Tuple implements Comparable { + private static final class Tuple implements Comparable<Tuple> { private String key; private String value; @@ -436,9 +396,9 @@ public class EchoProperties extends Task { * @throws ClassCastException if the specified object's type prevents it * from being compared to this Object. */ - public int compareTo(Object o) { - Tuple that = (Tuple) o; - return key.compareTo(that.key); + @Override + public int compareTo(Tuple o) { + return Comparator.<String> naturalOrder().compare(key, o.key); } @Override @@ -450,26 +410,21 @@ public class EchoProperties extends Task { return false; } Tuple that = (Tuple) o; - return (key == null ? that.key == null : key.equals(that.key)) - && (value == null ? that.value == null : value.equals(that.value)); + return Objects.equals(key, that.key) + && Objects.equals(value, that.value); } @Override public int hashCode() { - return key != null ? key.hashCode() : 0; + return Objects.hash(key); } } - private List sortProperties(Properties props) { + private List<Tuple> sortProperties(Properties props) { //sort the list. Makes SCM and manual diffs easier. - List sorted = new ArrayList(props.size()); - Enumeration e = props.propertyNames(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - sorted.add(new Tuple(name, props.getProperty(name))); - } - Collections.sort(sorted); - return sorted; + return props.stringPropertyNames().stream() + .map(k -> new Tuple(k, props.getProperty(k))).sorted() + .collect(Collectors.toList()); } /** @@ -484,29 +439,22 @@ public class EchoProperties extends Task { Document doc = getDocumentBuilder().newDocument(); Element rootElement = doc.createElement(PROPERTIES); - List sorted = sortProperties(props); - + List<Tuple> sorted = sortProperties(props); // output properties - Iterator iten = sorted.iterator(); - while (iten.hasNext()) { - Tuple tuple = (Tuple) iten.next(); + for (Tuple tuple : sorted) { Element propElement = doc.createElement(PROPERTY); propElement.setAttribute(ATTR_NAME, tuple.key); propElement.setAttribute(ATTR_VALUE, tuple.value); rootElement.appendChild(propElement); } - Writer wri = null; - try { - wri = new OutputStreamWriter(os, "UTF8"); + try (Writer wri = new OutputStreamWriter(os, "UTF8")) { wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - (new DOMElementWriter()).write(rootElement, wri, 0, "\t"); + new DOMElementWriter().write(rootElement, wri, 0, "\t"); wri.flush(); } catch (IOException ioe) { throw new BuildException("Unable to write XML file", ioe); - } finally { - FileUtils.close(wri); } } @@ -524,7 +472,6 @@ public class EchoProperties extends Task { String header) throws IOException { try { props.store(os, header); - } catch (IOException ioe) { throw new BuildException(ioe, getLocation()); } finally { @@ -538,6 +485,29 @@ public class EchoProperties extends Task { } } + private OutputStream createOutputStream() throws IOException { + if (destfile == null) { + return new LogOutputStream(this); + } + if (destfile.exists() && destfile.isDirectory()) { + String message = "destfile is a directory!"; + if (failonerror) { + throw new BuildException(message, getLocation()); + } + log(message, Project.MSG_ERR); + return null; + } + if (destfile.exists() && !destfile.canWrite()) { + String message = + "Can not write to the specified destfile!"; + if (failonerror) { + throw new BuildException(message, getLocation()); + } + log(message, Project.MSG_ERR); + return null; + } + return Files.newOutputStream(this.destfile.toPath()); + } /** * Uses the DocumentBuilderFactory to get a DocumentBuilder instance. @@ -552,4 +522,3 @@ public class EchoProperties extends Task { } } } - http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java index 06e1d11..dd3e107 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/Javah.java @@ -19,10 +19,11 @@ package org.apache.tools.ant.taskdefs.optional; import java.io.File; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.StringTokenizer; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import java.util.Vector; +import java.util.stream.Stream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -70,7 +71,7 @@ import org.apache.tools.ant.util.facade.ImplementationSpecificArgument; public class Javah extends Task { - private Vector classes = new Vector(2); + private List<ClassArgument> classes = new Vector<>(2); private String cls; private File destDir; private Path classpath = null; @@ -80,9 +81,8 @@ public class Javah extends Task { private boolean old = false; private boolean stubs = false; private Path bootclasspath; - //private Path extdirs; private FacadeTaskHelper facade = null; - private Vector files = new Vector(); + private Vector<FileSet> files = new Vector<>(); private JavahAdapter nestedAdapter = null; /** @@ -106,7 +106,7 @@ public class Javah extends Task { */ public ClassArgument createClass() { ClassArgument ga = new ClassArgument(); - classes.addElement(ga); + classes.add(ga); return ga; } @@ -117,10 +117,6 @@ public class Javah extends Task { public class ClassArgument { private String name; - /** Constructor for ClassArgument. */ - public ClassArgument() { - } - /** * Set the name attribute. * @param name the name attribute. @@ -152,33 +148,21 @@ public class Javah extends Task { * @since Ant 1.6.3 */ public String[] getClasses() { - ArrayList al = new ArrayList(); + Stream<String> stream = Stream.concat( + files.stream() + .map(fs -> fs.getDirectoryScanner(getProject()) + .getIncludedFiles()) + .flatMap(Stream::of) + .map(s -> s.replace('\\', '.').replace('/', '.') + .replaceFirst("\\.class$", "")), + classes.stream().map(ClassArgument::getName)); + if (cls != null) { - StringTokenizer tok = new StringTokenizer(cls, ",", false); - while (tok.hasMoreTokens()) { - al.add(tok.nextToken().trim()); - } + stream = Stream.concat(Stream.of(cls.split(",")).map(String::trim), + stream); } - if (files.size() > 0) { - for (Enumeration e = files.elements(); e.hasMoreElements();) { - FileSet fs = (FileSet) e.nextElement(); - String[] includedClasses = fs.getDirectoryScanner( - getProject()).getIncludedFiles(); - for (int i = 0; i < includedClasses.length; i++) { - String className = - includedClasses[i].replace('\\', '.').replace('/', '.') - .substring(0, includedClasses[i].length() - 6); - al.add(className); - } - } - } - Enumeration e = classes.elements(); - while (e.hasMoreElements()) { - ClassArgument arg = (ClassArgument) e.nextElement(); - al.add(arg.getName()); - } - return (String[]) al.toArray(new String[al.size()]); + return stream.toArray(String[]::new); } /** @@ -423,8 +407,7 @@ public class Javah extends Task { */ public void add(JavahAdapter adapter) { if (nestedAdapter != null) { - throw new BuildException("Can't have more than one javah" - + " adapter"); + throw new BuildException("Can't have more than one javah adapter"); } nestedAdapter = adapter; } @@ -434,17 +417,22 @@ public class Javah extends Task { * * @throws BuildException is there is a problem in the task execution. */ + @Override public void execute() throws BuildException { // first off, make sure that we've got a srcdir + final Set<Settings> settings = EnumSet.noneOf(Settings.class); - if ((cls == null) && (classes.size() == 0) && (files.size() == 0)) { - throw new BuildException("class attribute must be set!", - getLocation()); + if (cls != null) { + settings.add(Settings.cls); } - - if ((cls != null) && (classes.size() > 0) && (files.size() > 0)) { - throw new BuildException("set class attribute OR class element OR fileset, " - + "not 2 or more of them.", getLocation()); + if (!classes.isEmpty()) { + settings.add(Settings.classes); + } + if (!files.isEmpty()) { + settings.add(Settings.files); + } + if (settings.size() > 1) { + throw new BuildException("Exactly one of " + Settings.values() + " attributes is required", getLocation()); } if (destDir != null) { @@ -459,7 +447,7 @@ public class Javah extends Task { } if (classpath == null) { - classpath = (new Path(getProject())).concatSystemClasspath("last"); + classpath = new Path(getProject()).concatSystemClasspath("last"); } else { classpath = classpath.concatSystemClasspath("ignore"); } @@ -492,22 +480,21 @@ public class Javah extends Task { log("Compilation " + cmd.describeArguments(), Project.MSG_VERBOSE); - StringBuffer niceClassList = new StringBuffer(); String[] c = getClasses(); - for (int i = 0; i < c.length; i++) { - cmd.createArgument().setValue(c[i]); - niceClassList.append(" "); - niceClassList.append(c[i]); - niceClassList.append(StringUtils.LINE_SEP); - } - - StringBuffer prefix = new StringBuffer("Class"); + StringBuilder message = new StringBuilder("Class"); if (c.length > 1) { - prefix.append("es"); + message.append("es"); + } + message.append(" to be compiled:"); + message.append(StringUtils.LINE_SEP); + for (String element : c) { + cmd.createArgument().setValue(element); + message.append(" ").append(element).append(StringUtils.LINE_SEP); } - prefix.append(" to be compiled:"); - prefix.append(StringUtils.LINE_SEP); + log(message.toString(), Project.MSG_VERBOSE); + } - log(prefix.toString() + niceClassList.toString(), Project.MSG_VERBOSE); + private enum Settings { + cls, files, classes; } } \ No newline at end of file
