Example usage for org.apache.commons.net ProtocolCommandEvent getReplyCode

List of usage examples for org.apache.commons.net ProtocolCommandEvent getReplyCode

Introduction

In this page you can find the example usage for org.apache.commons.net ProtocolCommandEvent getReplyCode.

Prototype

public int getReplyCode() 

Source Link

Document

Returns the reply code of the received server reply.

Usage

From source file:examples.mail.IMAPExportMbox.java

public static void main(String[] args) throws IOException {
    int connect_timeout = CONNECT_TIMEOUT;
    int read_timeout = READ_TIMEOUT;

    int argIdx = 0;
    String eol = EOL_DEFAULT;// w w  w. j av a2  s  . c o m
    boolean printHash = false;
    boolean printMarker = false;
    int retryWaitSecs = 0;

    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-c")) {
            connect_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-r")) {
            read_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-R")) {
            retryWaitSecs = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-LF")) {
            eol = LF;
        } else if (args[argIdx].equals("-CRLF")) {
            eol = CRLF;
        } else if (args[argIdx].equals("-.")) {
            printHash = true;
        } else if (args[argIdx].equals("-X")) {
            printMarker = true;
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;

    if (argCount < 2) {
        System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]"
                + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]");
        System.err.println(
                "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)");
        System.err.println("\t-c connect timeout in seconds (default 10)");
        System.err.println("\t-r read timeout in seconds (default 10)");
        System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)");
        System.err.println("\t-. print a . for each complete message received");
        System.err.println("\t-X print the X-IMAP line for each complete message received");
        System.err.println(
                "\tthe mboxfile is where the messages are stored; use '-' to write to standard output.");
        System.err.println(
                "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite.");
        System.err.println(
                "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*");
        System.err
                .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]"
                        + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])");
        System.exit(1);
    }

    final URI uri = URI.create(args[argIdx++]);
    final String file = args[argIdx++];
    String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*";
    final String itemNames;
    // Handle 0, 1 or multiple item names
    if (argCount > 3) {
        if (argCount > 4) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (int i = 4; i <= argCount; i++) {
                if (i > 4) {
                    sb.append(" ");
                }
                sb.append(args[argIdx++]);
            }
            sb.append(")");
            itemNames = sb.toString();
        } else {
            itemNames = args[argIdx++];
        }
    } else {
        itemNames = "(INTERNALDATE BODY.PEEK[])";
    }

    final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence?
    final MboxListener chunkListener;
    if (file.equals("-")) {
        chunkListener = null;
    } else if (file.startsWith("+")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Appending to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash,
                printMarker, checkSequence);
    } else if (file.startsWith("-")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Writing to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash,
                printMarker, checkSequence);
    } else {
        final File mbox = new File(file);
        if (mbox.exists()) {
            throw new IOException("mailbox file: " + mbox + " already exists!");
        }
        System.out.println("Creating file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker,
                checkSequence);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    // suppress login details
    final PrintCommandListener listener = new PrintCommandListener(System.out, true) {
        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener
                super.protocolReplyReceived(event);
            }
        }
    };

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener);

    String maxIndexInFolder = null;

    try {

        imap.setSoTimeout(read_timeout * 1000);

        if (!imap.select(folder)) {
            throw new IOException("Could not select folder: " + folder);
        }

        for (String line : imap.getReplyStrings()) {
            maxIndexInFolder = matches(line, PATEXISTS, 1);
            if (maxIndexInFolder != null) {
                break;
            }
        }

        if (chunkListener != null) {
            imap.setChunkListener(chunkListener);
        } // else the command listener displays the full output without processing

        while (true) {
            boolean ok = imap.fetch(sequenceSet, itemNames);
            // If the fetch failed, can we retry?
            if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) {
                final String replyString = imap.getReplyString(); //includes EOL
                if (startsWith(replyString, PATTEMPFAIL)) {
                    System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds");
                    sequenceSet = (chunkListener.lastSeq + 1) + ":*";
                    try {
                        Thread.sleep(retryWaitSecs * 1000);
                    } catch (InterruptedException e) {
                        // ignored
                    }
                } else {
                    throw new IOException(
                            "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString);
                }
            } else {
                break;
            }
        }

    } catch (IOException ioe) {
        String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total);
        System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count
                + " complete messages ");
        if (chunkListener != null) {
            System.err.println("Last complete response seen: " + chunkListener.lastFetched);
        }
        throw ioe;
    } finally {

        if (printHash) {
            System.err.println();
        }

        if (chunkListener != null) {
            chunkListener.close();
            final Iterator<String> missingIds = chunkListener.missingIds.iterator();
            if (missingIds.hasNext()) {
                StringBuilder sb = new StringBuilder();
                for (;;) {
                    sb.append(missingIds.next());
                    if (!missingIds.hasNext()) {
                        break;
                    }
                    sb.append(",");
                }
                System.err.println("*** Missing ids: " + sb.toString());
            }
        }
        imap.logout();
        imap.disconnect();
    }
    if (chunkListener != null) {
        System.out.println("Processed " + chunkListener.total + " messages.");
    }
    if (maxIndexInFolder != null) {
        System.out.println("Folder contained " + maxIndexInFolder + " messages.");
    }
}

From source file:com.consol.citrus.ftp.client.FtpClient.java

@Override
public void afterPropertiesSet() throws Exception {
    if (ftpClient == null) {
        ftpClient = new FTPClient();
    }//from  w ww  .  ja  va  2  s .c  om

    ftpClient.configure(config);

    ftpClient.addProtocolCommandListener(new ProtocolCommandListener() {
        @Override
        public void protocolCommandSent(ProtocolCommandEvent event) {
            log.info("Send FTP command: " + event.getCommand());
        }

        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            log.info("Received FTP command reply: " + event.getReplyCode());
        }
    });
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/***
 * This method is invoked by a ProtocolCommandEvent source after
 * sending a protocol command to a server.
 *
 * @param event The ProtocolCommandEvent fired.
 *//*  w  w  w. ja  va2  s . com*/
public void protocolCommandSent(ProtocolCommandEvent event) {
    if (isLoggingEnabled())
        getLogger().info("cmd sent: " + event.getCommand() + "/" + event.getReplyCode());
    else if (event.getReplyCode() >= 400)
        getLogger().severe("cmd sent: " + event.getCommand() + "/" + event.getReplyCode());
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/***
 * This method is invoked by a ProtocolCommandEvent source after
 * receiving a reply from a server.// w w  w . j a v  a2s  .  c  om
 *
 * @param event The ProtocolCommandEvent fired.
 */
public void protocolReplyReceived(ProtocolCommandEvent event) {
    if (isLoggingEnabled())
        getLogger().info("reply received: " + event.getMessage() + "/" + event.getReplyCode());
    else if (event.getReplyCode() >= 400)
        getLogger().severe("reply received: " + event.getMessage() + "/" + event.getReplyCode());
}

From source file:com.symbian.driver.plugins.ftptelnet.FtpTransfer.java

/**
 * connectFTP : connects to ftp server//from w  ww  . j ava  2  s . co m
 * 
 * @return boolean success/fail
 */
public boolean connectFTP() {
    if (isFTPConnected()) {
        return true;
    }
    // Connect to FTP
    try {

        // 1. create an apache client
        iFTP = new FTPClient();
        iFTP.addProtocolCommandListener(new ProtocolCommandListener() {

            public void protocolCommandSent(ProtocolCommandEvent aProtocolCommandEvent) {
                LOGGER.fine("FTP Command Send: (" + aProtocolCommandEvent.getCommand() + ") "
                        + aProtocolCommandEvent.getMessage());
            }

            public void protocolReplyReceived(ProtocolCommandEvent aProtocolCommandEvent) {
                LOGGER.fine("FTP Command Recieved: (" + aProtocolCommandEvent.getMessage() + ") Returned Code "
                        + aProtocolCommandEvent.getReplyCode());
            }
        });
        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
        iFTP.configure(conf);
        // 2. connect
        iFTP.connect(iIP, iPort);

        // 3. check connection done.
        int reply = iFTP.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnectFTP();
            LOGGER.log(Level.SEVERE, "FTP error: " + reply);
            return false;
        }

        // 4. Login
        if (!iFTP.login(iUserName, iPassword)) {
            LOGGER.log(Level.SEVERE, "FTP failed to login, Username: " + iUserName + " Password: " + iPassword);
            disconnectFTP();
            return false;
        } else {
            if (iPassive.equalsIgnoreCase("true")) {
                iFTP.enterLocalPassiveMode();
            }
            iFTP.setFileType(FTP.BINARY_FILE_TYPE);
            iFTP.setBufferSize(iBufferSize);
        }

    } catch (SocketException lSocketException) {
        LOGGER.log(Level.SEVERE, "Socket exception ", lSocketException);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Socket exception ", lIOException);
        return false;
    }

    LOGGER.info("FTP connection established with transport : " + iIP + ":" + iPort);

    return true;

}

From source file:org.apache.commons.net.examples.mail.IMAPExportMbox.java

public static void main(String[] args) throws IOException, URISyntaxException {
    int connect_timeout = CONNECT_TIMEOUT;
    int read_timeout = READ_TIMEOUT;

    int argIdx = 0;
    String eol = EOL_DEFAULT;//from  w  ww  . java 2  s. co m
    boolean printHash = false;
    boolean printMarker = false;
    int retryWaitSecs = 0;

    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-c")) {
            connect_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-r")) {
            read_timeout = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-R")) {
            retryWaitSecs = Integer.parseInt(args[++argIdx]);
        } else if (args[argIdx].equals("-LF")) {
            eol = LF;
        } else if (args[argIdx].equals("-CRLF")) {
            eol = CRLF;
        } else if (args[argIdx].equals("-.")) {
            printHash = true;
        } else if (args[argIdx].equals("-X")) {
            printMarker = true;
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;

    if (argCount < 2) {
        System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]"
                + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]");
        System.err.println(
                "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)");
        System.err.println("\t-c connect timeout in seconds (default 10)");
        System.err.println("\t-r read timeout in seconds (default 10)");
        System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)");
        System.err.println("\t-. print a . for each complete message received");
        System.err.println("\t-X print the X-IMAP line for each complete message received");
        System.err.println(
                "\tthe mboxfile is where the messages are stored; use '-' to write to standard output.");
        System.err.println(
                "\tPrefix file name with '+' to append to the file. Prefix with '-' to allow overwrite.");
        System.err.println(
                "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*");
        System.err
                .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]"
                        + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])");
        System.exit(1);
    }

    final String uriString = args[argIdx++];
    URI uri;
    try {
        uri = URI.create(uriString);
    } catch (IllegalArgumentException e) { // cannot parse the path as is; let's pull it apart and try again
        Matcher m = Pattern.compile("(imaps?://[^/]+)(/.*)").matcher(uriString);
        if (m.matches()) {
            uri = URI.create(m.group(1)); // Just the scheme and auth parts
            uri = new URI(uri.getScheme(), uri.getAuthority(), m.group(2), null, null);
        } else {
            throw e;
        }
    }
    final String file = args[argIdx++];
    String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*";
    final String itemNames;
    // Handle 0, 1 or multiple item names
    if (argCount > 3) {
        if (argCount > 4) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (int i = 4; i <= argCount; i++) {
                if (i > 4) {
                    sb.append(" ");
                }
                sb.append(args[argIdx++]);
            }
            sb.append(")");
            itemNames = sb.toString();
        } else {
            itemNames = args[argIdx++];
        }
    } else {
        itemNames = "(INTERNALDATE BODY.PEEK[])";
    }

    final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence?
    final MboxListener chunkListener;
    if (file.equals("-")) {
        chunkListener = null;
    } else if (file.startsWith("+")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Appending to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash,
                printMarker, checkSequence);
    } else if (file.startsWith("-")) {
        final File mbox = new File(file.substring(1));
        System.out.println("Writing to file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash,
                printMarker, checkSequence);
    } else {
        final File mbox = new File(file);
        if (mbox.exists() && mbox.length() > 0) {
            throw new IOException("mailbox file: " + mbox + " already exists and is non-empty!");
        }
        System.out.println("Creating file " + mbox);
        chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker,
                checkSequence);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    // suppress login details
    final PrintCommandListener listener = new PrintCommandListener(System.out, true) {
        @Override
        public void protocolReplyReceived(ProtocolCommandEvent event) {
            if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener
                super.protocolReplyReceived(event);
            }
        }
    };

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener);

    String maxIndexInFolder = null;

    try {

        imap.setSoTimeout(read_timeout * 1000);

        if (!imap.select(folder)) {
            throw new IOException("Could not select folder: " + folder);
        }

        for (String line : imap.getReplyStrings()) {
            maxIndexInFolder = matches(line, PATEXISTS, 1);
            if (maxIndexInFolder != null) {
                break;
            }
        }

        if (chunkListener != null) {
            imap.setChunkListener(chunkListener);
        } // else the command listener displays the full output without processing

        while (true) {
            boolean ok = imap.fetch(sequenceSet, itemNames);
            // If the fetch failed, can we retry?
            if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) {
                final String replyString = imap.getReplyString(); //includes EOL
                if (startsWith(replyString, PATTEMPFAIL)) {
                    System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds");
                    sequenceSet = (chunkListener.lastSeq + 1) + ":*";
                    try {
                        Thread.sleep(retryWaitSecs * 1000);
                    } catch (InterruptedException e) {
                        // ignored
                    }
                } else {
                    throw new IOException(
                            "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString);
                }
            } else {
                break;
            }
        }

    } catch (IOException ioe) {
        String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total);
        System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count
                + " complete messages ");
        if (chunkListener != null) {
            System.err.println("Last complete response seen: " + chunkListener.lastFetched);
        }
        throw ioe;
    } finally {

        if (printHash) {
            System.err.println();
        }

        if (chunkListener != null) {
            chunkListener.close();
            final Iterator<String> missingIds = chunkListener.missingIds.iterator();
            if (missingIds.hasNext()) {
                StringBuilder sb = new StringBuilder();
                for (;;) {
                    sb.append(missingIds.next());
                    if (!missingIds.hasNext()) {
                        break;
                    }
                    sb.append(",");
                }
                System.err.println("*** Missing ids: " + sb.toString());
            }
        }
        imap.logout();
        imap.disconnect();
    }
    if (chunkListener != null) {
        System.out.println("Processed " + chunkListener.total + " messages.");
    }
    if (maxIndexInFolder != null) {
        System.out.println("Folder contained " + maxIndexInFolder + " messages.");
    }
}

From source file:uk.me.sa.android.notify_smtp.net.AuthSMTPTLSClient.java

@Override
public void protocolReplyReceived(ProtocolCommandEvent event) {
    if (SMTPReply.isPositiveCompletion(event.getReplyCode())) {
        log.info("{} {}", command, getReplyStrings()[0]);
    } else {/* www .ja  v  a  2s  . c  o  m*/
        log.error("{} {}", command, event.getMessage());
    }
}