Example usage for org.apache.commons.httpclient.protocol Protocol Protocol

List of usage examples for org.apache.commons.httpclient.protocol Protocol Protocol

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.protocol Protocol Protocol.

Prototype

public Protocol(String paramString, SecureProtocolSocketFactory paramSecureProtocolSocketFactory,
            int paramInt) 

Source Link

Usage

From source file:org.opensaml.DefaultBootstrap.java

/**
 *  Initializes the Apache Commons HttpClient library.
 *//* ww  w. java  2 s.  c om*/
protected static void initializeHttpClient() {
    if (!Boolean.getBoolean(SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        ProtocolSocketFactory socketFactory = new TLSProtocolSocketFactory(null, null,
                new StrictHostnameVerifier());
        Protocol.registerProtocol("https", new Protocol("https", socketFactory, 443));
    }
}

From source file:org.opensaml.saml2.metadata.provider.HTTPMetadataProvider.java

/**
 * Sets the socket factory used to create sockets to the HTTP server.
 * /*from   ww  w  . j av  a2 s . co  m*/
 * @see <a href="http://jakarta.apache.org/commons/httpclient/sslguide.html">HTTPClient SSL guide</a>
 * 
 * @param newSocketFactory the socket factory used to produce sockets used to connect to the server
 * 
 * @deprecated set this information on HTTP client used by provider
 */
public void setSocketFactory(ProtocolSocketFactory newSocketFactory) {
    log.debug("Using the custom socket factory {} to connect to the HTTP server",
            newSocketFactory.getClass().getName());
    Protocol protocol = new Protocol(metadataURI.getScheme(), newSocketFactory, metadataURI.getPort());
    httpClient.getHostConfiguration().setHost(metadataURI.getHost(), metadataURI.getPort(), protocol);
}

From source file:org.opensaml.ws.soap.client.http.HttpClientBuilder.java

/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created./* w  ww .  j  a v  a 2 s  . c o  m*/
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}

From source file:org.parosproxy.paros.core.proxy.WithBasicInfrastructureIntegrationTest.java

/**
 * Use custom TrustManager that trusts everything.
 * Moreover setup custom ProtocolSocketFactory as done in ZAP.
 * /* ww  w.j  a va2 s . c o  m*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
protected static void initializeLocalSecurity() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } }, new SecureRandom());

    // this doesn't seem to apply to connections through a proxy
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    // setup a hostname verifier that verifies everything
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new SSLConnector(), 443));
}

From source file:org.parosproxy.paros.network.HttpSender.java

public int executeMethod(HttpMethod method, HttpState state) throws IOException {
    int responseCode = -1;

    String hostName;/*w ww.  j  a  va  2s .  c om*/
    hostName = method.getURI().getHost();
    method.setDoAuthentication(true);
    HostConfiguration hc = null;

    HttpClient requestClient;
    if (param.isUseProxy(hostName)) {
        requestClient = clientViaProxy;

    } else {
        // ZAP: use custom client on upgrade connection and on event-source data type
        Header connectionHeader = method.getRequestHeader("connection");
        boolean isUpgrade = connectionHeader != null
                && connectionHeader.getValue().toLowerCase().contains("upgrade");

        // ZAP: try to apply original handling of ParosProxy
        requestClient = client;
        if (isUpgrade) {
            // Unless upgrade, when using another client that allows us to expose the socket
            // connection.
            requestClient = new HttpClient(new ZapHttpConnectionManager());
        }
    }

    if (this.initiator == CHECK_FOR_UPDATES_INITIATOR) {
        // Use the 'strict' SSLConnector, ie one that performs all the usual cert checks
        // The 'standard' one 'trusts' everything
        // This is to ensure that all 'check-for update' calls are made to the expected https urls
        // without this is would be possible to intercept and change the response which could result
        // in the user downloading and installing a malicious add-on
        hc = new HostConfiguration() {
            @Override
            public synchronized void setHost(URI uri) {
                try {
                    setHost(new HttpHost(uri.getHost(), uri.getPort(), getProtocol()));
                } catch (URIException e) {
                    throw new IllegalArgumentException(e.toString());
                }
            };
        };

        hc.setHost(hostName, method.getURI().getPort(),
                new Protocol("https", (ProtocolSocketFactory) new SSLConnector(false), 443));
        if (param.isUseProxy(hostName)) {
            hc.setProxyHost(new ProxyHost(param.getProxyChainName(), param.getProxyChainPort()));
            if (param.isUseProxyChainAuth()) {
                requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
            }
        }
    }

    // ZAP: Check if a custom state is being used
    if (state != null) {
        // Make sure cookies are enabled
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    responseCode = requestClient.executeMethod(hc, method, state);

    return responseCode;
}

From source file:org.paxle.crawler.http.impl.HttpCrawler.java

@Activate
public void activate(BundleContext context, Map<String, Object> config) {
    // reading the configuration
    this.modified(config);

    // registering the protocol handler for https 
    Protocol.registerProtocol("https", new Protocol("https", new AllSSLProtocolSocketFactory(), 443));

    // getting the component preferences   
    if (this.propstore != null) {
        this.props = this.propstore.getProperties(context);
        if (props != null) {
            final Set<Object> keySet = props.keySet();
            this.hostSettings = new ConcurrentHashMap<String, Integer>(keySet.size(), 0.75f, 10);
            for (final Object o : keySet) {
                final String key = (String) o;
                this.hostSettings.put(key, Integer.valueOf(props.getProperty(key)));
            }// www  .ja v a2s . c o m
        }
    }

    if (this.hostSettings == null) {
        this.hostSettings = new ConcurrentHashMap<String, Integer>(10, 0.75f, 10);
    }
}

From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

/**
 * Set the identity for the communications to the XMLRPC controller. Eventually
 * we may talk to several controller with different identities. For now only
 * one is configured./*from ww w  .j a v a2s .  com*/
 */
private void setSSLIdentity() throws Exception {

    //if (sslIdentitySet)
    //   return;

    //System.out.println("In setSSLIdentity()");

    try {
        // create multikeymanager
        mkm = new MultiKeyManager();
        //TODO
        //URL ctrlrUrl = new URL(GUI.getInstance().getSelectedController());
        URL ctrlrUrl = new URL(CONTROLLER_URL);
        // TODO

        // register a new protocol
        ContextualSSLProtocolSocketFactory regSslFact = new ContextualSSLProtocolSocketFactory();

        // add this multikey context factory for the controller host/port
        regSslFact.addHostContextFactory(new MultiKeySSLContextFactory(mkm, trustAllCerts), ctrlrUrl.getHost(),
                ctrlrUrl.getPort());

        if (rmProperties == null) {
            System.out.println("ERROR ... Property File with user credentials not supplied...");
            return;
        }

        KeyStore ks = null;

        //File keyStorePath = loadUserFile("/Users/anirban/Misc/tmp/renci-openvpn/flukes.jks");
        //File certFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        //File certKeyFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        File keyStorePath = null;
        File certFilePath = null;
        File certKeyFilePath = null;

        if (rmProperties.getProperty(USER_KEYSTORE_PATH_PROP) != null) {
            keyStorePath = loadUserFile(rmProperties.getProperty(USER_KEYSTORE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTFILE_PATH_PROP) != null) {
            certFilePath = loadUserFile(rmProperties.getProperty(USER_CERTFILE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP) != null) {
            certKeyFilePath = loadUserFile(rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP));
        }

        String keyAlias = null, keyPassword = null;
        if (keyStorePath != null && keyStorePath.exists()) {
            // load keystore and get the right cert from it
            System.out.println("Reading auth details from keystore");
            //TODO
            keyAlias = rmProperties.getProperty(USER_KEYSTORE_KEYALIAS_PROP);
            keyPassword = rmProperties.getProperty(USER_KEYSTORE_KEYPASS_PROP);
            //TODO
            FileInputStream jksIS = new FileInputStream(keyStorePath);
            ks = loadJKSData(jksIS, keyAlias, keyPassword);
            jksIS.close();
        } else if (certFilePath != null && certKeyFilePath != null && certFilePath.exists()
                && certKeyFilePath.exists()) {
            System.out.println("Reading auth details from cert file and certkeyfile");
            FileInputStream certIS = new FileInputStream(certFilePath);
            FileInputStream keyIS = new FileInputStream(certKeyFilePath);
            keyAlias = "x509convert";
            //TODO
            keyPassword = rmProperties.getProperty(USER_KEYPASS_PROP);
            //TODO
            ks = loadX509Data(certIS, keyIS, keyAlias, keyPassword);
            certIS.close();
            keyIS.close();
        }

        if (ks == null)
            throw new Exception("Was unable to find either: " + keyStorePath.getCanonicalPath()
                    + " or the pair of: " + certFilePath.getCanonicalPath() + " and "
                    + certKeyFilePath.getCanonicalPath() + " as specified.");

        // check that the spelling of key alias is proper
        Enumeration<String> as = ks.aliases();
        while (as.hasMoreElements()) {
            String a = as.nextElement();
            if (keyAlias.toLowerCase().equals(a.toLowerCase())) {
                keyAlias = a;
                break;
            }
        }

        // alias has to exist and have a key and cert present
        if (!ks.containsAlias(keyAlias)) {
            throw new Exception("Alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getKey(keyAlias, keyPassword.toCharArray()) == null)
            throw new Exception(
                    "Key with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");

        if (ks.getCertificate(keyAlias) == null) {
            throw new Exception(
                    "Certificate with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getCertificate(keyAlias).getType().equals("X.509")) {
            X509Certificate x509Cert = (X509Certificate) ks.getCertificate(keyAlias);
            try {
                x509Cert.checkValidity();
            } catch (Exception e) {
                throw new Exception("Certificate with alias " + keyAlias + " is not yet valid or has expired.");
            }
        }

        // add the identity into it
        mkm.addPrivateKey(keyAlias, (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray()),
                ks.getCertificate(keyAlias));

        // before we do SSL to this controller, set our identity
        mkm.setCurrentGuid(keyAlias);

        // register the protocol (Note: All xmlrpc clients must use XmlRpcCommonsTransportFactory
        // for this to work). See ContextualSSLProtocolSocketFactory.
        Protocol reghhttps = new Protocol("https", (ProtocolSocketFactory) regSslFact, 443);
        Protocol.registerProtocol("https", reghhttps);

        sslIdentitySet = true;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Unable to load user private key and certificate from the keystore: " + e);
    }

    //System.out.println("Exiting setSSLIdentity");

}

From source file:org.rhq.enterprise.server.util.security.UntrustedSSLProtocolSocketFactory.java

public static void register() {
    // make sure to accept self-signed certs

    if (!isRegistered()) {
        if (untrustSSL == null) {
            untrustSSL = new Protocol("https", (ProtocolSocketFactory) new UntrustedSSLProtocolSocketFactory(),
                    443);// w  w w .  j a va 2s .  c o  m
        }

        Protocol.registerProtocol("https", untrustSSL);
    }
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private synchronized void initSSLProtocol() {
    if (fgSSLInitialized)
        return;//w  w  w  . ja  v a2  s . c o  m

    /* Register Easy Protocol Socket Factory with HTTPS */
    Protocol easyHttpsProtocol = new Protocol(URIUtils.HTTPS_SCHEME,
            (ProtocolSocketFactory) Owl.getConnectionService().getSecureProtocolSocketFactory(), 443);
    Protocol.registerProtocol(URIUtils.HTTPS_SCHEME, easyHttpsProtocol);

    fgSSLInitialized = true;
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private synchronized void initFeedProtocol() {
    if (fgFeedProtocolInitialized)
        return;//from   www. jav  a 2 s . co m

    Protocol feed = new Protocol(URIUtils.FEED_SCHEME, new DefaultProtocolSocketFactory(), 80);
    Protocol.registerProtocol(URIUtils.FEED_SCHEME, feed);

    fgFeedProtocolInitialized = true;
}