Example usage for javax.net.ssl SSLContext getDefault

List of usage examples for javax.net.ssl SSLContext getDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getDefault.

Prototype

public static SSLContext getDefault() throws NoSuchAlgorithmException 

Source Link

Document

Returns the default SSL context.

Usage

From source file:com.amazonaws.services.dynamodbv2.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from   www . j a v a  2  s .c o  m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public CloseableHttpAsyncClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);
    HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive());

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams);

    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

    /* httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton);
     httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());
            
     if (config.getConnectionMaxIdleMillis() > 0) {
    httpClient.setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(
            config.getConnectionMaxIdleMillis()));
     }*/

    if (config.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress());
    }

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory();
        if (sf == null) {
            sf = new SdkTLSSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        }
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        //httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    /*if (proxyHost != null && proxyPort > 0) {
    AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
    HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);
            
    String proxyUsername    = config.getProxyUsername();
    String proxyPassword    = config.getProxyPassword();
    String proxyDomain      = config.getProxyDomain();
    String proxyWorkstation = config.getProxyWorkstation();
            
    if (proxyUsername != null && proxyPassword != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
    }
            
    // Add a request interceptor that sets up proxy authentication pre-emptively if configured
    if (config.isPreemptiveBasicProxyAuth()){
        httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
    }
    }
    */
    /* Accept Gzip response if configured */
    if (config.useGzip()) {
        /*
                    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                
        @Override
        public void process(final HttpRequest request,
                final HttpContext context) throws HttpException,
                IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
                
                    });
                
                    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                
        @Override
        public void process(final HttpResponse response,
                final HttpContext context) throws HttpException,
                IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName()
                                .equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
                
                    });*/
    }

    return httpClient;
}

From source file:org.nuxeo.ecm.core.storage.marklogic.MarkLogicRepository.java

protected static SecurityOptions newTrustOptions() {
    try {//from w  ww.  j a  va2s .  co  m
        SSLContext sslContext = SSLContext.getDefault();
        return new SecurityOptions(sslContext);
    } catch (GeneralSecurityException e) {
        throw new NuxeoException("Unable to initialize Security options for MarkLogic connection.", e);
    }
}

From source file:com.jkoolcloud.jesl.net.http.HttpClient.java

/**
 * {@inheritDoc}/*w  w  w. ja v a2  s  .  co  m*/
 */
@Override
public synchronized void connect() throws IOException {
    try {
        if (secure) {
            SSLSocketFactory ssf = null;
            if (!StringUtils.isEmpty(sslKeystore)) {
                SSLContextFactory scf = new SSLContextFactory(sslKeystore, sslKeystorePwd, sslKeystorePwd);
                ssf = new SSLSocketFactory(scf.getSslContext(true));
            } else {
                ssf = new SSLSocketFactory(SSLContext.getDefault());
            }
            Scheme secureScheme = new Scheme("https", port, ssf);
            schemeReg = new SchemeRegistry();
            schemeReg.register(secureScheme);
        }
        route = new HttpRoute(httpHost, null, httpProxy, secure, RouteInfo.TunnelType.PLAIN,
                RouteInfo.LayerType.PLAIN);
        if (schemeReg != null) {
            connMgr = new BasicClientConnectionManager(schemeReg);
        } else {
            connMgr = new BasicClientConnectionManager();
        }
        connReq = connMgr.requestConnection(route, null);
        connection = connReq.getConnection(0, null);
        connection.open(route, new BasicHttpContext(), new BasicHttpParams());
        logger.log(OpLevel.DEBUG, "Connected to {0}{1}", uri,
                (httpProxy != null ? " via proxy " + httpProxy : ""));
    } catch (Throwable e) {
        close();
        throw new IOException("Failed to connect to uri=" + uri + ", reason=" + e.getMessage(), e);
    }
}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException/*w  w  w. j a v  a  2 s  .c om*/
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.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 (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:org.openehealth.ipf.platform.camel.ihe.mllp.core.MllpComponent.java

/**
 * Creates and configures the endpoint./*w w  w  . j  a v a  2s.  c om*/
 */
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {
    // replace URL parts
    int pos = uri.indexOf(":");
    uri = new StringBuilder(uri).replace(0, pos, "mina:tcp").toString();
    remaining = "tcp://" + remaining;

    // extract & exclude parameters which cannot be handled by camel-mina
    boolean audit = getAndRemoveParameter(parameters, "audit", boolean.class, true);
    boolean allowIncompleteAudit = getAndRemoveParameter(parameters, "allowIncompleteAudit", boolean.class,
            false);

    boolean secure = getAndRemoveParameter(parameters, "secure", boolean.class, false);
    ClientAuthType clientAuthType = getAndRemoveParameter(parameters, "clientAuth", ClientAuthType.class,
            ClientAuthType.NONE);
    String sslProtocolsString = getAndRemoveParameter(parameters, "sslProtocols", String.class, null);
    String sslCiphersString = getAndRemoveParameter(parameters, "sslCiphers", String.class, null);

    boolean supportInteractiveContinuation = getAndRemoveParameter(parameters, "supportInteractiveContinuation",
            boolean.class, false);
    int interactiveContinuationDefaultThreshold = getAndRemoveParameter(parameters,
            "interactiveContinuationDefaultThreshold", int.class, -1); // >= 1 data record

    boolean supportUnsolicitedFragmentation = getAndRemoveParameter(parameters,
            "supportUnsolicitedFragmentation", boolean.class, false);
    int unsolicitedFragmentationThreshold = getAndRemoveParameter(parameters,
            "unsolicitedFragmentationThreshold", int.class, -1); // >= 3 segments

    boolean supportSegmentFragmentation = getAndRemoveParameter(parameters, "supportSegmentFragmentation",
            boolean.class, false);
    int segmentFragmentationThreshold = getAndRemoveParameter(parameters, "segmentFragmentationThreshold",
            int.class, -1); // >= 5 characters

    InteractiveContinuationStorage interactiveContinuationStorage = resolveAndRemoveReferenceParameter(
            parameters, "interactiveContinuationStorage", InteractiveContinuationStorage.class);

    UnsolicitedFragmentationStorage unsolicitedFragmentationStorage = resolveAndRemoveReferenceParameter(
            parameters, "unsolicitedFragmentationStorage", UnsolicitedFragmentationStorage.class);

    boolean autoCancel = getAndRemoveParameter(parameters, "autoCancel", boolean.class, false);

    // explicitly overwrite some standard camel-mina parameters
    if (parameters == Collections.EMPTY_MAP) {
        parameters = new HashMap<String, Object>();
    }
    parameters.put("sync", true);
    parameters.put("lazySessionCreation", true);
    parameters.put("transferExchange", false);
    if (!parameters.containsKey("codec")) {
        parameters.put("codec", DEFAULT_HL7_CODEC_FACTORY_BEAN_NAME);
    }

    // adopt character set configured for the HL7 codec
    ProtocolCodecFactory codecFactory = getCamelContext().getRegistry()
            .lookup(extractBeanName((String) parameters.get("codec")), ProtocolCodecFactory.class);
    Charset charset = null;
    try {
        charset = ((HL7MLLPCodec) codecFactory).getCharset();
    } catch (ClassCastException cce) {
        LOG.error("Unsupported HL7 codec factory type " + codecFactory.getClass().getName());
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    parameters.put("encoding", charset.name());

    // construct the endpoint
    Endpoint endpoint = super.createEndpoint(uri, remaining, parameters);
    MinaEndpoint minaEndpoint = (MinaEndpoint) endpoint;

    SSLContext sslContext = secure
            ? resolveAndRemoveReferenceParameter(parameters, "sslContext", SSLContext.class,
                    SSLContext.getDefault())
            : null;

    List<Hl7v2Interceptor> customInterceptors = resolveAndRemoveReferenceListParameter(parameters,
            "interceptors", Hl7v2Interceptor.class);

    String[] sslProtocols = sslProtocolsString != null ? sslProtocolsString.split(",") : null;
    String[] sslCiphers = sslCiphersString != null ? sslCiphersString.split(",") : null;

    // wrap and return
    return new MllpEndpoint(this, minaEndpoint, audit, allowIncompleteAudit, sslContext, clientAuthType,
            customInterceptors, sslProtocols, sslCiphers, supportInteractiveContinuation,
            supportUnsolicitedFragmentation, supportSegmentFragmentation,
            interactiveContinuationDefaultThreshold, unsolicitedFragmentationThreshold,
            segmentFragmentationThreshold, interactiveContinuationStorage, unsolicitedFragmentationStorage,
            autoCancel);
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.RTCClient.java

private void setSSLTrustStrategy(boolean sslVerify) throws IOException {
    try {/*w ww . j a  v a 2  s  .c  om*/
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc;

        if (sslVerify) {
            sc = SSLContext.getDefault();
        } else {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
        }

        SSLSocketFactory sf = new SSLSocketFactory(sc);
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());
        SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sf, 443));
    } catch (Exception any) {
        throw new IOException(any);
    }
}

From source file:com.googlesource.gerrit.plugins.its.rtc.network.RTCClient.java

private void setSSLTrustStrategy(boolean sslVerify) throws IOException {
    try {//from w w  w  .  j  a  va2  s.co m
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc;

        if (sslVerify) {
            sc = SSLContext.getDefault();
        } else {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
        }

        SSLSocketFactory sf = new SSLSocketFactory(sc);
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());
        SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sf, 443));
    } catch (Exception any) {
        throw new IOException(any);
    }
}

From source file:pt.lunacloud.http.AmazonHttpClient.java

/**
 * Disables the default strict hostname verification in this client and
 * instead uses a browser compatible hostname verification strategy (i.e.
 * cert hostname wildcards are evaulated more liberally).
 *//*from  ww  w .  java2s.co  m*/
public void disableStrictHostnameVerification() {
    try {
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new LunacloudClientException(
                "Unable to access default SSL context to disable strict hostname verification");
    }
}

From source file:groovyx.net.http.ApacheHttpBuilder.java

private SSLContext sslContext(final HttpObjectConfig config) {
    try {/* ww w  .j a  v  a 2 s  . co  m*/
        return (config.getExecution().getSslContext() != null ? config.getExecution().getSslContext()
                : SSLContext.getDefault());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}