Example usage for org.apache.commons.net.smtp SMTPClient isConnected

List of usage examples for org.apache.commons.net.smtp SMTPClient isConnected

Introduction

In this page you can find the example usage for org.apache.commons.net.smtp SMTPClient isConnected.

Prototype

public boolean isConnected() 

Source Link

Document

Returns true if the client is currently connected to a server.

Usage

From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    SMTPClient client;

    if (getUseSSL()) {
        client = new SMTPSClient(true);
    } else if (getUseSTARTTLS()) {
        client = new SMTPSClient(false);
    } else {/*from  w  ww  .  ja va  2s .c  o m*/
        client = new SMTPClient();
    }

    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";
        if (getUseSSL())
            request += "SSL : true\n";
        else
            request += "SSL : false\n";
        if (getUseSTARTTLS())
            request += "STARTTLS : true\n";
        else
            request += "STARTTLS : false\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        client.connect(getHostname(), getPort());
        if (client.isConnected()) {
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            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(String.valueOf(client.getReplyCode()));
            sr.setResponseData(client.getReplyString().getBytes());
            setSuccessfulByResponseCode(sr, client.getReplyCode());
        }
    } 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:com.clustercontrol.port.protocol.ReachAddressSMTP.java

/**
 * SMTP????????/*from  w  ww  .  java  2s .  c o m*/
 * 
 * @param addressText
 * @return SMTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the SMTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        SMTPClient client = new SMTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (SMTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(SMTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage(), e);
        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.xpn.xwiki.XWiki.java

/**
 * @deprecated replaced by the <a href="http://code.xwiki.org/xwiki/bin/view/Plugins/MailSenderPlugin">Mail Sender
 *             Plugin</a>/*from w  ww .j  a  v a 2 s  .  c  o  m*/
 */
@Deprecated
private void sendMessageOld(String sender, String[] recipient, String message, XWikiContext context)
        throws XWikiException {
    SMTPClient smtpc = null;
    try {
        String server = getXWikiPreference("smtp_server", context);
        String port = getXWikiPreference("smtp_port", context);
        String login = getXWikiPreference("smtp_login", context);

        if (context.get("debugMail") != null) {
            StringBuffer msg = new StringBuffer(message);
            msg.append("\n Recipient: ");
            msg.append(recipient);
            recipient = ((String) context.get("debugMail")).split(",");
            message = msg.toString();
        }

        if ((server == null) || server.equals("")) {
            server = "127.0.0.1";
        }
        if ((port == null) || (port.equals(""))) {
            port = "25";
        }
        if ((login == null) || login.equals("")) {
            login = InetAddress.getLocalHost().getHostName();
        }

        smtpc = new SMTPClient();
        smtpc.connect(server, Integer.parseInt(port));
        int reply = smtpc.getReplyCode();
        if (!SMTPReply.isPositiveCompletion(reply)) {
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_CONNECT_FAILED,
                    "Could not connect to server {0} port {1} error code {2} ({3})", null, args);
        }

        if (smtpc.login(login) == false) {
            reply = smtpc.getReplyCode();
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_LOGIN_FAILED,
                    "Could not login to mail server {0} port {1} error code {2} ({3})", null, args);
        }

        if (smtpc.sendSimpleMessage(sender, recipient, message) == false) {
            reply = smtpc.getReplyCode();
            Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                    XWikiException.ERROR_XWIKI_EMAIL_SEND_FAILED,
                    "Could not send mail to server {0} port {1} error code {2} ({3})", null, args);
        }

    } catch (IOException e) {
        Object[] args = { sender, recipient };
        throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL,
                XWikiException.ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL,
                "Exception while sending email from {0} to {1}", e, args);
    } finally {
        if ((smtpc != null) && (smtpc.isConnected())) {
            try {
                smtpc.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testTwoSimultaneousMails() throws Exception {
    init(smtpConfiguration);//www . j a v a 2s. c o m

    SMTPClient smtpProtocol1 = new SMTPClient();
    smtpProtocol1.connect("127.0.0.1", smtpListenerPort);
    SMTPClient smtpProtocol2 = new SMTPClient();
    smtpProtocol2.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol1.isConnected());
    assertTrue("second connection taken", smtpProtocol2.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    smtpProtocol1.helo(InetAddress.getLocalHost().toString());
    smtpProtocol2.helo(InetAddress.getLocalHost().toString());

    String sender1 = "mail_sender1@localhost";
    String recipient1 = "mail_recipient1@localhost";
    smtpProtocol1.setSender(sender1);
    smtpProtocol1.addRecipient(recipient1);

    String sender2 = "mail_sender2@localhost";
    String recipient2 = "mail_recipient2@localhost";
    smtpProtocol2.setSender(sender2);
    smtpProtocol2.addRecipient(recipient2);

    smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails1\r\n.\r\n");
    verifyLastMail(sender1, recipient1, null);

    smtpProtocol2.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails2\r\n.\r\n");
    verifyLastMail(sender2, recipient2, null);

    smtpProtocol1.quit();
    smtpProtocol2.quit();

    smtpProtocol1.disconnect();
    smtpProtocol2.disconnect();
}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testTwoMailsInSequence() throws Exception {
    init(smtpConfiguration);//from w w  w.  jav a2  s . c  o  m

    SMTPClient smtpProtocol1 = new SMTPClient();
    smtpProtocol1.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol1.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    smtpProtocol1.helo(InetAddress.getLocalHost().toString());

    String sender1 = "mail_sender1@localhost";
    String recipient1 = "mail_recipient1@localhost";
    smtpProtocol1.setSender(sender1);
    smtpProtocol1.addRecipient(recipient1);

    smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoMailsInSequence1\r\n");
    verifyLastMail(sender1, recipient1, null);

    String sender2 = "mail_sender2@localhost";
    String recipient2 = "mail_recipient2@localhost";
    smtpProtocol1.setSender(sender2);
    smtpProtocol1.addRecipient(recipient2);

    smtpProtocol1.sendShortMessageData("Subject: test2\r\n\r\nTest body2 testTwoMailsInSequence2\r\n");
    verifyLastMail(sender2, recipient2, null);

    smtpProtocol1.quit();
    smtpProtocol1.disconnect();
}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

private void doTestHeloEhloResolv(String heloCommand) throws IOException {
    SMTPClient smtpProtocol = new SMTPClient();
    smtpProtocol.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    String fictionalDomain = "abgsfe3rsf.de";
    String existingDomain = "james.apache.org";
    String mail = "sender@james.apache.org";
    String rcpt = "rcpt@localhost";

    smtpProtocol.sendCommand(heloCommand, fictionalDomain);
    smtpProtocol.setSender(mail);/*from w ww. jav  a  2s . c o  m*/
    smtpProtocol.addRecipient(rcpt);

    // this should give a 501 code cause the helo/ehlo could not resolved
    assertEquals("expected error: " + heloCommand + " could not resolved", 501, smtpProtocol.getReplyCode());

    smtpProtocol.sendCommand(heloCommand, existingDomain);
    smtpProtocol.setSender(mail);
    smtpProtocol.addRecipient(rcpt);

    if (smtpProtocol.getReplyCode() == 501) {
        fail(existingDomain
                + " domain currently cannot be resolved (check your DNS/internet connection/proxy settings to make test pass)");
    }
    // helo/ehlo is resolvable. so this should give a 250 code
    assertEquals(heloCommand + " accepted", 250, smtpProtocol.getReplyCode());

    smtpProtocol.quit();
}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testReverseEqualsHelo() throws Exception {
    smtpConfiguration.setReverseEqualsHelo();
    smtpConfiguration.setAuthorizedAddresses("192.168.0.1");
    // temporary alter the loopback resolution
    try {/*w  w  w. j a va 2  s .  com*/
        dnsServer.setLocalhostByName(InetAddress.getByName("james.apache.org"));
    } catch (UnknownHostException e) {
        fail("james.apache.org currently cannot be resolved (check your DNS/internet connection/proxy settings to make test pass)");
    }
    try {
        init(smtpConfiguration);

        SMTPClient smtpProtocol1 = new SMTPClient();
        smtpProtocol1.connect("127.0.0.1", smtpListenerPort);

        assertTrue("first connection taken", smtpProtocol1.isConnected());

        // no message there, yet
        assertNull("no mail received by mail server", queue.getLastMail());

        String helo1 = "abgsfe3rsf.de";
        String helo2 = "james.apache.org";
        String mail = "sender";
        String rcpt = "recipient";

        smtpProtocol1.sendCommand("helo", helo1);
        smtpProtocol1.setSender(mail);
        smtpProtocol1.addRecipient(rcpt);

        // this should give a 501 code cause the helo not equal reverse of
        // ip
        assertEquals("expected error: helo not equals reverse of ip", 501, smtpProtocol1.getReplyCode());

        smtpProtocol1.sendCommand("helo", helo2);
        smtpProtocol1.setSender(mail);
        smtpProtocol1.addRecipient(rcpt);

        // helo is resolvable. so this should give a 250 code
        assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode());

        smtpProtocol1.quit();
    } finally {
        dnsServer.setLocalhostByName(null);
    }
}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testSenderDomainResolv() throws Exception {
    smtpConfiguration.setSenderDomainResolv();
    smtpConfiguration.setAuthorizedAddresses("192.168.0.1/32");
    init(smtpConfiguration);// w w w .  ja v a 2s  .co m

    SMTPClient smtpProtocol1 = new SMTPClient();
    smtpProtocol1.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol1.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    smtpProtocol1.helo(InetAddress.getLocalHost().toString());

    String sender1 = "mail_sender1@xfwrqqfgfe.de";

    smtpProtocol1.setSender(sender1);
    assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode());

    smtpProtocol1.addRecipient("test@localhost");
    assertEquals("Recipient not accepted cause no valid sender", 503, smtpProtocol1.getReplyCode());
    smtpProtocol1.quit();

}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testSenderDomainResolvRelayClientDefault() throws Exception {
    smtpConfiguration.setSenderDomainResolv();
    init(smtpConfiguration);/*  w  w w.j a  v a 2  s  .  c o  m*/

    SMTPClient smtpProtocol1 = new SMTPClient();
    smtpProtocol1.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol1.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    smtpProtocol1.helo(InetAddress.getLocalHost().toString());

    String sender1 = "mail_sender1@xfwrqqfgfe.de";

    // Both mail shold
    smtpProtocol1.setSender(sender1);

    smtpProtocol1.quit();

}

From source file:org.apache.james.smtpserver.SMTPServerTest.java

@Test
public void testSenderDomainResolvRelayClient() throws Exception {
    smtpConfiguration.setSenderDomainResolv();
    smtpConfiguration.setCheckAuthNetworks(true);
    init(smtpConfiguration);/*from  w ww . j  a  v  a2s.c  o m*/

    SMTPClient smtpProtocol1 = new SMTPClient();
    smtpProtocol1.connect("127.0.0.1", smtpListenerPort);

    assertTrue("first connection taken", smtpProtocol1.isConnected());

    // no message there, yet
    assertNull("no mail received by mail server", queue.getLastMail());

    smtpProtocol1.helo(InetAddress.getLocalHost().toString());

    String sender1 = "mail_sender1@xfwrqqfgfe.de";
    String sender2 = "mail_sender2@james.apache.org";

    smtpProtocol1.setSender(sender1);
    assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode());

    smtpProtocol1.setSender(sender2);

    smtpProtocol1.quit();

}