Search in sources :

Example 1 with LocalTrustStoreSSLSocketFactory

use of org.apache.jmeter.protocol.smtp.sampler.protocol.LocalTrustStoreSSLSocketFactory in project jmeter by apache.

the class MailReaderSampler method sample.

/**
     * {@inheritDoc}
     */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    // Did sample succeed?
    boolean isOK = false;
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();
    parent.setSampleLabel(getName());
    String samplerString = toString();
    parent.setSamplerData(samplerString);
    /*
         * Perform the sampling
         */
    // Start timing
    parent.sampleStart();
    try {
        // Create empty properties
        Properties props = new Properties();
        if (isUseStartTLS()) {
            // $NON-NLS-1$
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE);
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE);
            }
        }
        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            } else if (isUseStartTLS()) {
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
                // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  " + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$ 
                props.put(// $NON-NLS-1$ 
                mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
                // $NON-NLS-1$
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                // $NON-NLS-1$
                props.put(// $NON-NLS-1$
                mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
                // $NON-NLS-1$
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
            }
        }
        // Get session
        Session session = Session.getInstance(props, null);
        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());
        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }
        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }
        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        // $NON-NLS-1$
        parent.setContentType("text/plain");
        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();
            // $NON-NLS-1$
            cdata.append("Message ");
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);
            final String contentType = message.getContentType();
            // Store the content-type
            child.setContentType(contentType);
            // RFC 822 uses ascii per default
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING);
            // Parse the content-type
            child.setEncodingAndType(contentType);
            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                // Save raw message
                child.setResponseData(bout.toByteArray());
                child.setDataType(SampleResult.TEXT);
            } else {
                // Javadoc for the API says this is OK
                @SuppressWarnings("unchecked") Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                    // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }
            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {
                // Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }
        // Close connection
        folder.close(true);
        store.close();
        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        // No need to log normally, as we set the status
        log.debug("", ex);
        // $NON-NLS-1$
        parent.setResponseCode("500");
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        // No need to log normally, as we set the status
        log.debug("", ex);
        // $NON-NLS-1$
        parent.setResponseCode("500");
        // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString);
    } finally {
        busy = false;
    }
    if (parent.getEndTime() == 0) {
        // not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) Store(javax.mail.Store) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) Folder(javax.mail.Folder) LocalTrustStoreSSLSocketFactory(org.apache.jmeter.protocol.smtp.sampler.protocol.LocalTrustStoreSSLSocketFactory) Header(javax.mail.Header) SampleResult(org.apache.jmeter.samplers.SampleResult) File(java.io.File) Session(javax.mail.Session)

Aggregations

ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Properties (java.util.Properties)1 Folder (javax.mail.Folder)1 Header (javax.mail.Header)1 Message (javax.mail.Message)1 MessagingException (javax.mail.MessagingException)1 Session (javax.mail.Session)1 Store (javax.mail.Store)1 LocalTrustStoreSSLSocketFactory (org.apache.jmeter.protocol.smtp.sampler.protocol.LocalTrustStoreSSLSocketFactory)1 SampleResult (org.apache.jmeter.samplers.SampleResult)1