Example usage for org.apache.commons.httpclient.contrib.ssl AuthSSLProtocolSocketFactory AuthSSLProtocolSocketFactory

List of usage examples for org.apache.commons.httpclient.contrib.ssl AuthSSLProtocolSocketFactory AuthSSLProtocolSocketFactory

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.contrib.ssl AuthSSLProtocolSocketFactory AuthSSLProtocolSocketFactory.

Prototype

public AuthSSLProtocolSocketFactory(final URL keystoreUrl, final String keystorePassword,
        final URL truststoreUrl, final String truststorePassword) 

Source Link

Document

Constructor for AuthSSLProtocolSocketFactory.

Usage

From source file:httpsdemo.client.Client.java

public static void main(String args[]) throws Exception {

    File clientKeystore = new File("certs/clientKeystore.jks");
    File truststore = new File("certs/commonTruststore.jks");

    // Send HTTP GET request to query customer info - using portable HttpClient method
    Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(clientKeystore.toURI().toURL(),
            "password", truststore.toURI().toURL(), "password"), 9000);
    Protocol.registerProtocol("https", authhttps);

    System.out.println("Sending HTTPS GET request to query customer info");
    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod(BASE_SERVICE_URL + "/123");
    httpget.addRequestHeader("Accept", "text/xml");

    // If Basic Authentication required could use: 
    /*/*www.  j av a  2  s.  c o  m*/
    String authorizationHeader = "Basic " 
       + org.apache.cxf.common.util.Base64Utility.encode("username:password".getBytes());
    httpget.addRequestHeader("Authorization", authorizationHeader);
    */
    try {
        httpclient.executeMethod(httpget);
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        httpget.releaseConnection();
    }

    /*
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("Sending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);

    /*
     *  Send HTTP POST request to add customer, using JAXRSClientProxy
     *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n");
    System.out.println("Sending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
            CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);

    System.out.println("\n");
    System.exit(0);
}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * Sets up Authentication for the client.
 * // w w w . j  a v a2 s. c o  m
 * @param extraConnectData
 * @param client
 * @throws ExtraTransportException
 */
private void setupAuthentification(final HttpOutputPluginConnectConfiguration extraConnectData,
        final HttpClient client) throws ExtraTransportException {
    HttpOutputPluginSenderDataConfiguration senderData = extraConnectData.getSenderData();

    // Check if J2EE security is requested (default)
    if (senderData.isServerJ2EESecurity()) {

        String j2eeUser = null;
        String j2eePwd = null;

        // Pass our credentials to HttpClient, they will only be used for
        // authenticating to servers with realm "extra"
        if (senderData.isCertificateAuthentication()) {
            j2eeUser = ExtraCryptoUtil.decrypt(senderData.getServerJ2EEUser());
            j2eePwd = ExtraCryptoUtil.decrypt(senderData.getServerJ2EEPwd());
        } else {
            j2eeUser = senderData.getServerJ2EEUser();
            j2eePwd = senderData.getServerJ2EEPwd();
        }

        // Prfung, ob Benutzer und Passwort fr die Autentifizierung
        // gesetzt sind
        if (j2eeUser == null || j2eePwd == null) {
            throw new ExtraTransportException(
                    "Benutzer und/oder Passwort fr die J2EE-Sicherheit wurden nicht definiert.");
        }

        client.getState().setCredentials(new AuthScope(extraConnectData.getServerHost(), AuthScope.ANY_PORT,
                senderData.getServerJ2EERealm()), new UsernamePasswordCredentials(j2eeUser, j2eePwd));

        // Send authentication data without extra request
        client.getParams().setAuthenticationPreemptive(true);
    }
    // Load TrustStoreLocation from properties
    String truststoreLocation = extraConnectData.getSslTruststoreLocation();

    // If no location specified -> fallback to JRE default
    if (truststoreLocation == null || truststoreLocation.length() == 0) {
        truststoreLocation = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar
                + "security" + File.separatorChar + "cacerts";
    }

    try {

        URL keystoreUrl = null;
        String keyPasswd = "";

        if (senderData.isCertificateAuthentication()) {

            keystoreUrl = new URL("file:/" + senderData.getPrivateKeyStoreLocation());
            keyPasswd = senderData.getPrivateKeyPassword();

        }

        ProtocolSocketFactory authSSLProtocolSocketFactory = new AuthSSLProtocolSocketFactory(keystoreUrl,
                keyPasswd, new URL("file:/" + truststoreLocation), extraConnectData.getSslTruststorePassword());
        Protocol authhttps = new Protocol("https", authSSLProtocolSocketFactory, 9443);
        Protocol.registerProtocol("https", authhttps);
    } catch (MalformedURLException e) {
        throw new ExtraTransportException("SSL-Client Authentification nicht richtig konfiguriert", e);
    }

}

From source file:org.codice.proxy.http.HttpProxyServiceImpl.java

public String start(final String endpointName, final String targetUri, final Integer timeout,
        final boolean matchOnPrefix, final Object bean) throws Exception {

    // Enable proxy settings for the external target
    enableProxySettings();/*w ww .j av a  2 s  .  c  o m*/

    // Fetch location of trust store and trust store password
    fetchTrustStoreLocation();

    // Create SSL connection Camel protocol for https
    Protocol authhttps = null;
    File certStore = new File(trustStore);
    try {
        authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(certStore.toURI().toURL(),
                trustStorePassword, certStore.toURI().toURL(), trustStorePassword), 443);
    } catch (MalformedURLException e) {
        LOGGER.error(e.getMessage());
    }

    if (authhttps != null) {
        Protocol.registerProtocol("https", authhttps);
    }

    final String matchPrefix = (matchOnPrefix) ? "?matchOnUriPrefix=true" : "";

    final String protocolDelimiter = (routeEndpointType.equals(SERVLET)) ? ":///" : "://";

    // Create Camel route
    RouteBuilder routeBuilder;
    if (bean == null) {
        routeBuilder = new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(routeEndpointType + protocolDelimiter + endpointName + matchPrefix)
                        .removeHeader("Authorization").removeHeader("Cookie")
                        .to(targetUri
                                + "?bridgeEndpoint=true&throwExceptionOnFailure=false&httpClient.soTimeout="
                                + timeout + "&httpClient.connectionManagerTimeout=" + timeout)
                        .routeId(endpointName);
            }
        };
    } else {
        routeBuilder = new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(routeEndpointType + protocolDelimiter + endpointName + matchPrefix)
                        .removeHeader("Authorization").removeHeader("Cookie")
                        .to(targetUri
                                + "?bridgeEndpoint=true&throwExceptionOnFailure=false&httpClient.soTimeout="
                                + timeout + "&httpClient.connectionManagerTimeout=" + timeout)
                        .routeId(endpointName).bean(bean);
            }
        };
    }
    camelContext.addRoutes(routeBuilder);
    camelContext.start();
    LOGGER.debug("Started proxy route at servlet endpoint: {}, routing to: {}", endpointName, targetUri);
    return endpointName;
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.Http.java

/**
 * Loads HTTP client configuration for this web site.
 *//*from  w w w  .  j  a v  a2s .c o m*/
private void configureClient() {
    final HttpConnectionManagerParams params = s_connectionManager.getParams();
    if (_timeout != 0) {
        params.setConnectionTimeout(_timeout);
        params.setSoTimeout(_timeout);
    } else {
        params.setConnectionTimeout(_connectTimeout);
        params.setSoTimeout(_readTimeout);
    }
    params.setSendBufferSize(BUFFER_SIZE);
    params.setReceiveBufferSize(BUFFER_SIZE);
    final HostConfiguration hostConf = s_client.getHostConfiguration();
    final List<Header> headers = new ArrayList<Header>();
    // prefer English
    headers.add(new Header("Accept-Language", "en-us,en-gb,en;q=0.7,*;q=0.3"));
    // prefer UTF-8
    headers.add(new Header("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
    // prefer understandable formats
    headers.add(new Header("Accept",
            "text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8"));
    // accept GZIP content
    headers.add(new Header("Accept-Encoding", "x-gzip, gzip"));
    final String[] webSiteHeaders = getConf().get(HttpProperties.HEADERS).split(SEMICOLON);
    for (String header : webSiteHeaders) {
        final String[] headerInformation = header.split(COLON);
        if (headerInformation.length > 2) {
            headers.add(new Header(headerInformation[0].trim(), headerInformation[1].trim()));
        }
    }
    hostConf.getParams().setParameter("http.default-headers", headers);
    if (_useProxy) {
        hostConf.setProxy(_proxyHost, _proxyPort);
        if (_proxyLogin.length() > 0) {
            final Credentials proxyCreds = new UsernamePasswordCredentials(_proxyLogin, _proxyPassword);
            s_client.getState().setProxyCredentials(new AuthScope(AuthScope.ANY), proxyCreds);
        }
    }
    final List<Rfc2617Authentication> httpAuthentications = _authentication.getRfc2617Authentications();

    for (Rfc2617Authentication auth : httpAuthentications) {
        s_client.getState().setCredentials(
                new AuthScope(auth.getHost(), Integer.valueOf(auth.getPort()), auth.getRealm()),
                new UsernamePasswordCredentials(auth.getLogin(), auth.getPassword()));
    }

    final SslCertificateAuthentication sslAuth = _authentication.getSslCertificateAuthentication();
    if (sslAuth != null) {
        try {
            final URL truststoreURL = new File(sslAuth.getTruststoreUrl()).toURL();
            final URL keystoreURL = new File(sslAuth.getKeystoreUrl()).toURL();

            final ProtocolSocketFactory sslFactory = new AuthSSLProtocolSocketFactory(keystoreURL,
                    sslAuth.getKeystorePassword(), truststoreURL, sslAuth.getTruststorePassword());
            _https = new Protocol(sslAuth.getProtocolName(), sslFactory, Integer.valueOf(sslAuth.getPort()));
            Protocol.registerProtocol(sslAuth.getProtocolName(), _https);
        } catch (MalformedURLException exception) {
            LOG.error("unable to bind https protocol" + exception.toString());
        }
    }
}

From source file:org.kalypso.commons.net.SSLUtilities.java

/**
 * This function configures the whole thing, provided a key- and truststore are available.
 * //from   ww w  . j a  va  2s .  c om
 * @param keyStore
 *          The keystore.
 * @param keyPassphrase
 *          The passphrase of the client certificate.
 * @param trustStore
 *          The truststore.
 * @param trustPassphrase
 */
public static void configureWhole(final URL keyStore, final String keyPassphrase, final URL trustStore,
        final String trustPassphrase) throws Exception {
    final ProtocolSocketFactory authfactory = new AuthSSLProtocolSocketFactory(keyStore, keyPassphrase,
            trustStore, trustPassphrase);
    final Protocol authhttps = new Protocol("https", authfactory, 443); //$NON-NLS-1$
    Protocol.registerProtocol("https", authhttps); //$NON-NLS-1$
}