List of usage examples for org.apache.commons.net.imap IMAPClient getReplyString
public String getReplyString()
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleLogin(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;//from w ww. j a va 2s . c o m boolean success = false; String request = "LOGIN\n"; request += "Client : " + getClient() + "\n"; request += "Client Name : " + getClientName() + "\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { success = client.login(getClientName(), getClientPassword()); sr.setSuccessful(success); if (getCheckSuccessful()) { sr.setSuccessful(success); if (success) sr.setResponseCodeOK(); else sr.setResponseCode(RC_ERROR); } else sr.setResponseCodeOK(); sr.setResponseData(client.getReplyString().getBytes()); } catch (IOException e) { sr.setSuccessful(false); sr.setResponseData(e.toString().getBytes()); sr.setResponseCode(e.getClass().getName()); log.error("client `" + getClient() + "` ", e); removeClient(); } sr.sampleEnd(); } } return sr; }
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleCommand(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;//from w w w . j a va 2 s . c om boolean success = false; String request = "COMMAND\n"; request += "Client : " + getClient() + "\n"; request += "Client Name : " + getClientName() + "\n"; request += "Command : `" + getCommand() + " " + getCommandArgs() + "`\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { if (getCommandArgs().isEmpty()) { success = client.doCommand(IMAPCommand.valueOf(getCommand())); } else { success = client.doCommand(IMAPCommand.valueOf(getCommand()), getCommandArgs()); } sr.setSuccessful(success); if (getCheckSuccessful()) { sr.setSuccessful(success); if (success) sr.setResponseCodeOK(); else sr.setResponseCode(RC_ERROR); } else sr.setResponseCodeOK(); sr.setResponseData(client.getReplyString().getBytes()); } catch (IOException e) { sr.setSuccessful(false); sr.setResponseData(e.toString().getBytes()); sr.setResponseCode(e.getClass().getName()); log.error("client `" + getClient() + "` ", e); removeClient(); } sr.sampleEnd(); } } return sr; }
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleConnect(SampleResult sr) { IMAPClient client; if (getUseSSL()) { client = new IMAPSClient(true); } else {/*from ww w . j a va 2 s . c om*/ client = new IMAPClient(); } try { String request = "CONNECT \n"; request += "Host : " + getHostname() + ":" + getPort() + "\n"; request += "Default Timeout : " + getDefaultTimeout() + "\n"; request += "Connect Timeout : " + getConnectionTimeout() + "\n"; request += "So Timeout : " + getSoTimeout() + "\n"; request += "Client : " + getClient() + "\n"; sr.setRequestHeaders(request); sr.sampleStart(); client.setDefaultTimeout(getDefaultTimeout()); client.setConnectTimeout(getConnectionTimeout()); if (getLocalAddr().isEmpty()) client.connect(getHostname(), getPort()); else client.connect(getHostname(), getPort(), InetAddress.getByName(getLocalAddr()), 0); if (client.isConnected()) { log.info("imap client " + getClient() + " connected from " + client.getLocalAddress() + ":" + client.getLocalPort()); SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN; if (getUseSSL()) protoType = SessionStorage.proto_type.SSL; SessionStorage.getInstance().putClient(getSOClient(), client, protoType); client.setSoTimeout(getSoTimeout()); sr.setSuccessful(true); sr.setResponseCodeOK(); sr.setResponseData(client.getReplyString().getBytes()); } else { client.close(); sr.setSuccessful(false); sr.setResponseCode("java.net.ConnectException"); sr.setResponseMessage("Not connected"); } } catch (SocketException se) { sr.setResponseMessage(se.toString()); sr.setSuccessful(false); sr.setResponseCode(se.getClass().getName()); log.error("client `" + getClient() + "` ", se); removeClient(); } catch (IOException ioe) { sr.setResponseMessage(ioe.toString()); sr.setSuccessful(false); sr.setResponseCode(ioe.getClass().getName()); log.error("client `" + getClient() + "` ", ioe); removeClient(); } finally { sr.sampleEnd(); } return sr; }
From source file:org.apache.common.net.examples.mail.IMAPMail.java
public static final void main(String[] args) { if (args.length < 3) { System.err.println("Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1);/*from w w w.jav a2 s. c o m*/ } String server = args[0]; String username = args[1]; String password = args[2]; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); imap.capability(); imap.select("inbox"); imap.examine("inbox"); imap.status("inbox", new String[] { "MESSAGES" }); imap.logout(); imap.disconnect(); } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }
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. j a va 2 s. com*/ 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:org.apache.commons.net.examples.mail.IMAPMail.java
public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: IMAPMail imap[s]://username:password@server/"); System.err.println("Connects to server; lists capabilities and shows Inbox status"); System.exit(1);/*from w w w .j a v a 2s . com*/ } URI uri = URI.create(args[0]); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); try { imap.setSoTimeout(6000); imap.capability(); imap.select("inbox"); imap.examine("inbox"); imap.status("inbox", new String[] { "MESSAGES" }); imap.list("", "*"); // Show the folders } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } }