Example usage for org.apache.commons.net.pop3 POP3Client POP3Client

List of usage examples for org.apache.commons.net.pop3 POP3Client POP3Client

Introduction

In this page you can find the example usage for org.apache.commons.net.pop3 POP3Client POP3Client.

Prototype

POP3Client

Source Link

Usage

From source file:me.schiz.jmeter.protocol.pop3.sampler.POP3Sampler.java

private SampleResult sampleConnect(SampleResult sr) {
    POP3Client client;/*  w ww .ja  v a 2  s  .  co  m*/

    if (getUseSSL()) {
        client = new POP3SClient(true);
        //      } else if(getUseSTARTTLS()) {
        //         client = new POP3SClient(false);
    } else {
        client = new POP3Client();
    }

    StringBuilder requestBuilder = new StringBuilder();
    try {
        //String request = "CONNECT \n";
        requestBuilder.append("CONNECT\n");
        requestBuilder.append("Host : " + getHostname() + ":" + getPort() + "\n");
        requestBuilder.append("Connect Timeout: " + getConnectionTimeout() + "\n");
        requestBuilder.append("Socket Timeout: " + getSoTimeout() + "\n");
        requestBuilder.append("Client : " + getClient() + "\n");
        if (getUseSSL())
            requestBuilder.append("SSL : true\n");
        else
            requestBuilder.append("SSL : false\n");
        //         if(getUseSTARTTLS())    request += "STARTTLS : true\n";
        //         else request += "STARTTLS : false\n";

        sr.setRequestHeaders(requestBuilder.toString());
        sr.sampleStart();
        client.setConnectTimeout(getConnectionTimeout());
        client.connect(getHostname(), getPort());
        if (client.isConnected()) {
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL())
                protoType = SessionStorage.proto_type.SSL;
            //            if(getUseSSL() && !getUseSTARTTLS()) protoType = SessionStorage.proto_type.SSL;
            //            if(!getUseSSL() && getUseSTARTTLS()) protoType = SessionStorage.proto_type.STARTTLS;

            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            client.setTcpNoDelay(getTcpNoDelay());
            sr.setResponseCode(RC_200);
            sr.setResponseData(client.getReplyString().getBytes());
            sr.setSuccessful(true);
        } else {
            sr.setResponseCode(RC_500);
            sr.setSuccessful(false);
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + client + "` ", se);
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + client + "` ", ioe);
    }
    sr.sampleEnd();
    return sr;
}

From source file:ProtocolRunner.java

public static SocketClient getTCPClientInstance(int clientType) {
   switch(clientType) {
        case 0: { // is chargen
            if(charGenTCPClient == null) {
                charGenTCPClient = new CharGenTCPClient();
            }/* w  w w  .  ja va  2s. co  m*/
            return charGenTCPClient;
        }
       case 1: { // is daytime 
           if(daytimeTCPClient == null) {
               daytimeTCPClient = new DaytimeTCPClient();
           }
           return daytimeTCPClient;
       }
       case 2: { // is echo
           if(echoTCPClient == null) {
               echoTCPClient = new EchoTCPClient();
           }
           return echoTCPClient;
       }
       case 3: { // is finger
           if(fingerClient == null) {
               fingerClient = new FingerClient();
           }
           return fingerClient;
       }
       case 4: { // is ftp
           if(ftpClient == null) {
               ftpClient = new FTPClient();
           }
           return ftpClient;
       }
       case 5: { // is nntp
           if(nntpClient == null) {
               nntpClient = new NNTPClient();
           }
           return nntpClient;
       }
       case 6: { // is pop3
           if(pop3Client == null) {
               pop3Client = new POP3Client();
           }
           return pop3Client;
       }
       case 7: { // is smtp
           if(smtpClient == null) {
               smtpClient = new SMTPClient();
           }
           return smtpClient;
       }
       case 8: { // is time
           if(timeTCPClient == null) {
               timeTCPClient = new TimeTCPClient();
           }
           return timeTCPClient;
       }
       case 9: { // is whois
           if(whoisClient == null) {
               whoisClient = new WhoisClient();
           }
           return whoisClient;
       }
    }
    return null;
}

From source file:org.apache.axis.transport.mail.MailSender.java

/**
 * Read from server using POP3/*from  ww  w  . jav a  2  s  .  c  o m*/
 * @param msgContext
 * @throws Exception
 */
private void readUsingPOP3(String id, MessageContext msgContext) throws Exception {
    // Read the response back from the server
    String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
    String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
    String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);

    Reader reader;
    POP3MessageInfo[] messages = null;

    MimeMessage mimeMsg = null;
    POP3Client pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    for (int i = 0; i < 12; i++) {
        pop3.connect(pop3Host);

        if (!pop3.login(pop3User, pop3passwd)) {
            pop3.disconnect();
            AxisFault fault = new AxisFault("POP3", "( Could not login to server.  Check password. )", null,
                    null);
            throw fault;
        }

        messages = pop3.listMessages();
        if (messages != null && messages.length > 0) {
            StringBuffer buffer = null;
            for (int j = 0; j < messages.length; j++) {
                reader = pop3.retrieveMessage(messages[j].number);
                if (reader == null) {
                    AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null,
                            null);
                    throw fault;
                }

                buffer = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(reader);
                int ch;
                while ((ch = bufferedReader.read()) != -1) {
                    buffer.append((char) ch);
                }
                bufferedReader.close();
                if (buffer.toString().indexOf(id) != -1) {
                    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes());
                    Properties prop = new Properties();
                    Session session = Session.getDefaultInstance(prop, null);

                    mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[j].number);
                    break;
                }
                buffer = null;
            }
        }
        pop3.logout();
        pop3.disconnect();
        if (mimeMsg == null) {
            Thread.sleep(5000);
        } else {
            break;
        }
    }

    if (mimeMsg == null) {
        pop3.logout();
        pop3.disconnect();
        AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
        throw fault;
    }

    String contentType = mimeMsg.getContentType();
    String contentLocation = mimeMsg.getContentID();
    Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation);

    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPPartAsString());
    }
}

From source file:org.apache.axis.transport.mail.MailServer.java

/**
 * Server process./*from  w w w.j av  a2s . c  o m*/
 */
public static void main(String args[]) {
    Options opts = null;
    try {
        opts = new Options(args);
    } catch (MalformedURLException e) {
        log.error(Messages.getMessage("malformedURLException00"), e);
        return;
    }

    try {
        doThreads = (opts.isFlagSet('t') > 0);
        String host = opts.getHost();
        int port = ((opts.isFlagSet('p') > 0) ? opts.getPort() : 110);
        POP3Client pop3 = new POP3Client();
        MailServer sas = new MailServer(host, port, opts.getUser(), opts.getPassword());

        sas.setPOP3(pop3);
        sas.start();
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
        return;
    }

}

From source file:org.apache.common.net.examples.mail.POP3Mail.java

public static final void main(String[] args) {
    if (args.length < 3) {
        System.err//from   w w w.  ja v a 2  s .  c  o  m
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = args.length > 3 ? args[3] : null;
    boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }

        POP3MessageInfo[] messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        for (POP3MessageInfo msginfo : messages) {
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            printMessageInfo(reader, msginfo.number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

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

public static void main(String[] args) {
    int argIdx;//from   w w  w. j  a  v a2 s .c  o m
    String file = null;
    for (argIdx = 0; argIdx < args.length; argIdx++) {
        if (args[argIdx].equals("-F")) {
            file = args[++argIdx];
        } else {
            break;
        }
    }

    final int argCount = args.length - argIdx;
    if (argCount < 3) {
        System.err.println(
                "Usage: POP3Mail [-F file/directory] <server[:port]> <username> <password|-|*|VARNAME> [TLS [true=implicit]]");
        System.exit(1);
    }

    String arg0[] = args[argIdx++].split(":");
    String server = arg0[0];
    String username = args[argIdx++];
    String password = args[argIdx++];
    // prompt for the password if necessary
    try {
        password = Utils.getPassword(username, password);
    } catch (IOException e1) {
        System.err.println("Could not retrieve password: " + e1.getMessage());
        return;
    }

    String proto = argCount > 3 ? args[argIdx++] : null;
    boolean implicit = argCount > 4 ? Boolean.parseBoolean(args[argIdx++]) : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }

    int port;
    if (arg0.length == 2) {
        port = Integer.parseInt(arg0[1]);
    } else {
        port = pop3.getDefaultPort();
    }
    System.out.println("Connecting to server " + server + " on " + port);

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        return;
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            return;
        }

        POP3MessageInfo status = pop3.status();
        if (status == null) {
            System.err.println("Could not retrieve status.");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        System.out.println("Status: " + status);
        int count = status.number;
        if (file != null) {
            System.out.println("Getting messages: " + count);
            File mbox = new File(file);
            if (mbox.isDirectory()) {
                System.out.println("Writing dir: " + mbox);
                // Currently POP3Client uses iso-8859-1
                for (int i = 1; i <= count; i++) {
                    OutputStreamWriter fw = new OutputStreamWriter(
                            new FileOutputStream(new File(mbox, i + ".eml")), Charset.forName("iso-8859-1"));
                    writeFile(pop3, fw, i);
                    fw.close();
                }
            } else {
                System.out.println("Writing file: " + mbox);
                // Currently POP3Client uses iso-8859-1
                OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(mbox),
                        Charset.forName("iso-8859-1"));
                for (int i = 1; i <= count; i++) {
                    writeMbox(pop3, fw, i);
                }
                fw.close();
            }
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

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

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println(//from   ww  w. j  a va  2 s. c om
                "Usage: POP3Mail <server[:port]> <username> <password|-|*|VARNAME> [TLS [true=implicit]]");
        System.exit(1);
    }

    String arg0[] = args[0].split(":");
    String server = arg0[0];
    String username = args[1];
    String password = args[2];
    // prompt for the password if necessary
    try {
        password = Utils.getPassword(username, password);
    } catch (IOException e1) {
        System.err.println("Could not retrieve password: " + e1.getMessage());
        return;
    }

    String proto = args.length > 3 ? args[3] : null;
    boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }

    int port;
    if (arg0.length == 2) {
        port = Integer.parseInt(arg0[1]);
    } else {
        port = pop3.getDefaultPort();
    }
    System.out.println("Connecting to server " + server + " on " + port);

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        return;
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            return;
        }

        POP3MessageInfo status = pop3.status();
        if (status == null) {
            System.err.println("Could not retrieve status.");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        System.out.println("Status: " + status);

        POP3MessageInfo[] messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.logout();
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        System.out.println("Message count: " + messages.length);

        for (POP3MessageInfo msginfo : messages) {
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.logout();
                pop3.disconnect();
                return;
            }
            printMessageInfo(reader, msginfo.number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:org.apache.james.pop3server.POP3ServerTest.java

@Test
public void testAuthenticationFail() throws Exception {
    finishSetUp(pop3Configuration);

    pop3Client = new POP3Client();
    pop3Client.connect("127.0.0.1", pop3Port);

    usersRepository.addUser("known", "test2");

    pop3Client.login("known", "test");
    assertEquals(0, pop3Client.getState());
    assertTrue(pop3Client.getReplyString().startsWith("-ERR"));
}

From source file:org.apache.james.pop3server.POP3ServerTest.java

@Test
public void testUnknownUser() throws Exception {
    finishSetUp(pop3Configuration);

    pop3Client = new POP3Client();
    pop3Client.connect("127.0.0.1", pop3Port);

    pop3Client.login("unknown", "test");
    assertEquals(0, pop3Client.getState());
    assertTrue(pop3Client.getReplyString().startsWith("-ERR"));
}

From source file:org.apache.james.pop3server.POP3ServerTest.java

@Test
public void testKnownUserEmptyInbox() throws Exception {
    finishSetUp(pop3Configuration);

    pop3Client = new POP3Client();
    pop3Client.connect("127.0.0.1", pop3Port);

    usersRepository.addUser("foo", "bar");

    // not authenticated
    POP3MessageInfo[] entries = pop3Client.listMessages();
    assertNull(entries);//from  w ww. jav a2s.  co  m

    pop3Client.login("foo", "bar");
    System.err.println(pop3Client.getState());
    assertEquals(1, pop3Client.getState());

    entries = pop3Client.listMessages();
    assertEquals(1, pop3Client.getState());

    assertNotNull(entries);
    assertEquals(entries.length, 0);

    POP3MessageInfo p3i = pop3Client.listMessage(1);
    assertEquals(1, pop3Client.getState());
    assertNull(p3i);
}