Java 类org.apache.commons.httpclient.protocol.Protocol 实例源码

项目:Equella    文件:BlackboardConnectorServiceImpl.java   
private void initStub(Stub stub) throws AxisFault
{
    if( stub != null )
    {
        final ServiceClient client = stub._getServiceClient();

        final Options options = client.getOptions();
        options.setProperty(WSHandlerConstants.PW_CALLBACK_REF, this);
        options.setProperty(WSSHandlerConstants.OUTFLOW_SECURITY, ofc.getProperty());
        options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true");
        options.setProperty(HTTPConstants.HTTP_PROTOCOL_VERSION, HTTPConstants.HEADER_PROTOCOL_11);
        URI uri = URI.create(bbUrl);
        if( uri.getScheme().toLowerCase().startsWith("https") )
        {
            Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
            options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, myhttps);
        }
        client.engageModule("rampart-1.5.1");
    }
}
项目:alfresco-repository    文件:HttpClientTransmitterImpl.java   
public HttpClientTransmitterImpl()
{
    protocolMap = new TreeMap<String,Protocol>();
    protocolMap.put(HTTP_SCHEME_NAME, httpProtocol);
    protocolMap.put(HTTPS_SCHEME_NAME, httpsProtocol);

    httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
    httpMethodFactory = new StandardHttpMethodFactoryImpl();
    jsonErrorSerializer = new ExceptionJsonSerializer();

    // Create an HTTP Proxy Host if appropriate system properties are set
    httpProxyHost = HttpClientHelper.createProxyHost("http.proxyHost", "http.proxyPort", DEFAULT_HTTP_PORT);
    httpProxyCredentials = HttpClientHelper.createProxyCredentials("http.proxyUser", "http.proxyPassword");
    httpAuthScope = createProxyAuthScope(httpProxyHost);

    // Create an HTTPS Proxy Host if appropriate system properties are set
    httpsProxyHost = HttpClientHelper.createProxyHost("https.proxyHost", "https.proxyPort", DEFAULT_HTTPS_PORT);
    httpsProxyCredentials = HttpClientHelper.createProxyCredentials("https.proxyUser", "https.proxyPassword");
    httpsAuthScope = createProxyAuthScope(httpsProxyHost);
}
项目:alfresco-core    文件:HttpClientFactory.java   
/** Get a host for the given parameters. This method need not be thread-safe. */
public HttpHost getHost(String host, int port, String scheme)
{
    if(scheme == null)
    {
        scheme = "http";
    }
    Protocol protocol = protocols.get(scheme);
    if(protocol == null)
    {
        protocol = Protocol.getProtocol("http");
        if(protocol == null)
        {
            throw new IllegalArgumentException("Unrecognised scheme parameter");
        }
    }

    return new HttpHost(host, port, protocol);
}
项目:lib-commons-httpclient    文件:HttpConnection.java   
/**
 * Creates a new HTTP connection for the given host with the virtual 
 * alias and port via the given proxy host and port using the given 
 * protocol.
 * 
 * @param proxyHost the host to proxy via
 * @param proxyPort the port to proxy via
 * @param host the host to connect to. Parameter value must be non-null.
 * @param port the port to connect to
 * @param protocol The protocol to use. Parameter value must be non-null.
 */
public HttpConnection(
    String proxyHost,
    int proxyPort,
    String host,
    int port,
    Protocol protocol) {

    if (host == null) {
        throw new IllegalArgumentException("host parameter is null");
    }
    if (protocol == null) {
        throw new IllegalArgumentException("protocol is null");
    }

    proxyHostName = proxyHost;
    proxyPortNumber = proxyPort;
    hostName = host;
    portNumber = protocol.resolvePort(port);
    protocolInUse = protocol;
}
项目:lib-commons-httpclient    文件:HttpHost.java   
/**
 * Constructor for HttpHost.
 *   
 * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
 * @param port the port. Value <code>-1</code> can be used to set default protocol port
 * @param protocol the protocol. Value <code>null</code> can be used to set default protocol
 */
public HttpHost(final String hostname, int port, final Protocol protocol) {
    super();
    if (hostname == null) {
        throw new IllegalArgumentException("Host name may not be null");
    }
    if (protocol == null) {
        throw new IllegalArgumentException("Protocol may not be null");
    }
    this.hostname = hostname;
    this.protocol = protocol;
    if (port >= 0) {
        this.port = port;
    } else {
        this.port = this.protocol.getDefaultPort();
    }
}
项目:lib-commons-httpclient    文件:TestHttpParams.java   
public void testDefaults() throws IOException {
    this.server.setHttpService(new SimpleService());

    this.client.getParams().setParameter(HttpMethodParams.USER_AGENT, "test");
    HostConfiguration hostconfig = new HostConfiguration();
    hostconfig.setHost(
            this.server.getLocalAddress(), 
            this.server.getLocalPort(),
            Protocol.getProtocol("http"));

    GetMethod httpget = new GetMethod("/miss/");
    try {
        this.client.executeMethod(hostconfig, httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
    assertEquals("test", httpget.getRequestHeader("User-Agent").getValue());
    assertEquals("test", httpget.getParams().
            getParameter(HttpMethodParams.USER_AGENT));
    assertEquals("test", hostconfig.getParams().
            getParameter(HttpMethodParams.USER_AGENT));
    assertEquals("test", client.getParams().
            getParameter(HttpMethodParams.USER_AGENT));
}
项目:lib-commons-httpclient    文件:TestVirtualHost.java   
public void testRedirectWithVirtualHost() throws IOException {
    String host = this.server.getLocalAddress();
    int port = this.server.getLocalPort();

    Protocol testhttp = new Protocol("http", new VirtualSocketFactory(host, port), port);
    Protocol.registerProtocol("testhttp", testhttp);
    try {
        this.server.setHttpService(new VirtualHostService());
        this.client.getHostConfiguration().setHost(host, port, "testhttp");
        this.client.getHostConfiguration().getParams().setVirtualHost("whatever.com");
        GetMethod httpget = new GetMethod("/");
        httpget.setFollowRedirects(true);
        try {
            this.client.executeMethod(httpget);
            assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
            assertEquals("http://www.whatever.co.nz/", httpget.getURI().toString());
        } finally {
            httpget.releaseConnection();
        }
    } finally {
        Protocol.unregisterProtocol("testhttp");
    }

}
项目:lib-commons-httpclient    文件:TestHttpConnection.java   
public void testConnTimeout() {

        // create a custom protocol that will delay for 500 milliseconds
        Protocol testProtocol = new Protocol(
            "timeout",
            new DelayedProtocolSocketFactory(
                500, 
                Protocol.getProtocol("http").getSocketFactory()
            ),
            this.server.getLocalPort()
        );

        HttpConnection conn = new HttpConnection(
                this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol);
        // 1 ms is short enough to make this fail
        conn.getParams().setConnectionTimeout(1);
        try {
            conn.open();
            fail("Should have timed out");
        } catch(IOException e) {
            assertTrue(e instanceof ConnectTimeoutException);
            /* should fail */
        }
    }
项目:lib-commons-httpclient    文件:TestNTLMAuth.java   
public void testNTLMAuthenticationRetry() throws Exception {

        this.server.setHttpService(new NTLMAuthService());

        // configure the client
        this.client.getHostConfiguration().setHost(
                server.getLocalAddress(), server.getLocalPort(),
                Protocol.getProtocol("http"));

        this.client.getState().setCredentials(AuthScope.ANY, 
                new NTCredentials("username", "password", "host", "domain"));

        FakeHttpMethod httpget = new FakeHttpMethod("/");
        try {
            client.executeMethod(httpget);
        } finally {
            httpget.releaseConnection();
        }
        assertNull(httpget.getResponseHeader("WWW-Authenticate"));
        assertEquals(200, httpget.getStatusCode());
    }
项目:lib-commons-httpclient    文件:TestHostConfiguration.java   
public void testRelativeURLHitWithDefaultHost() throws IOException {
    this.server.setHttpService(new EchoService());
    // Set default host
    this.client.getHostConfiguration().setHost(
            this.server.getLocalAddress(), 
            this.server.getLocalPort(),
            Protocol.getProtocol("http"));

    GetMethod httpget = new GetMethod("/test/");
    try {
        this.client.executeMethod(httpget);
        assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
    } finally {
        httpget.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:HttpHostFactory.java   
/**
 * Get a Protocol for the given parameters. The default implementation
 * selects a protocol based only on the scheme. Subclasses can do fancier
 * things, such as select SSL parameters based on the host or port. This
 * method must not return null.
 */
protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port)
{
    final Protocol oldProtocol = old.getProtocol();
    if (oldProtocol != null) {
        final String oldScheme = oldProtocol.getScheme();
        if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) {
            // The old protocol has the desired scheme.
            return oldProtocol; // Retain it.
        }
    }
    Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol
            : httpProtocol;
    if (newProtocol == null) {
        newProtocol = Protocol.getProtocol(scheme);
    }
    return newProtocol;
}
项目:Java_Certificado    文件:CertificadoService.java   
/**
 * Metodo Que Inicializa as Informações de Certificado Digital
 *
 * @param certificado
 * @param cacert
 * @throws CertificadoException
 */
public static void inicializaCertificado(Certificado certificado, InputStream cacert) throws CertificadoException {

    try {

        KeyStore keyStore = getKeyStore(certificado);
        X509Certificate certificate = getCertificate(certificado, keyStore);
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(certificado.getNome(), certificado.getSenha().toCharArray());
        if (certificado.isAtivarProperties()) {
            CertificadoProperties.inicia(certificado, cacert);
        } else {
            SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privateKey, cacert, certificado.getSslProtocol());
            Protocol protocol = new Protocol("https", socketFactory, 443);
            Protocol.registerProtocol("https", protocol);
        }

    } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException | IOException e) {
        throw new CertificadoException(e.getMessage());
    }

}
项目:nfe-a3-hostapp    文件:SocketFactoryDinamico.java   
public static void load(KeyStore ks, String alias, char[] pin, String patOfCacerts)  
        throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {  
    if (!isLoaded) {  
        if ((alias == null) || ("".equals(alias))) {  
            Enumeration<String> aliasesEnum = ks.aliases();  
            while (aliasesEnum.hasMoreElements()) {  
                alias = (String) aliasesEnum.nextElement();  
                if (ks.isKeyEntry(alias)) {  
                    break;  
                }  
            }  
        }  

        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);  
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, pin);  
        SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);  
        socketFactoryDinamico.setFileCacerts(patOfCacerts);  

        Protocol protocol = new Protocol("https", socketFactoryDinamico, 443);  
        Protocol.registerProtocol("https", protocol);  

        isLoaded = true;  
    }  
}
项目:MyVirtualDirectory    文件:GetSSLCert.java   
public static javax.security.cert.X509Certificate getCert(String host, int port) {
    GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
    Protocol myhttps = new Protocol("https", certFactory, port);
    HttpClient httpclient = new HttpClient();
    httpclient.getHostConfiguration().setHost(host, port, myhttps);
    GetMethod httpget = new GetMethod("/");
    try {
      httpclient.executeMethod(httpget);
      //System.out.println(httpget.getStatusLine());
    } catch (Throwable t) {
        //do nothing
    }

    finally {
      httpget.releaseConnection();
    }

    return certFactory.getCertificate();
}
项目:MyVirtualDirectory    文件:GetSSLCert.java   
public static javax.security.cert.X509Certificate getCert(String host, int port) {
    GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
    Protocol myhttps = new Protocol("https", certFactory, port);
    HttpClient httpclient = new HttpClient();
    httpclient.getHostConfiguration().setHost(host, port, myhttps);
    GetMethod httpget = new GetMethod("/");
    try {
      httpclient.executeMethod(httpget);
      //System.out.println(httpget.getStatusLine());
    } catch (Throwable t) {
        //do nothing
    }

    finally {
      httpget.releaseConnection();
    }

    return certFactory.getCertificate();
}
项目:http4e    文件:HttpPerformer.java   
private void doSSL( HttpClient client, HostConfiguration hostConf, String host, int port){
   if (hostConf.getProtocol().isSecure()) {

      // System.setProperty("javax.net.ssl.trustStore", sslKeystore);
      // Protocol sslPprotocol = new Protocol("https", new
      // org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(),
      // 443);
      // client.getHostConfiguration().setHost(host, 443, sslPprotocol);

      try {
         ProtocolSocketFactory factory = new InsecureSSLProtocolSocketFactory();
         Protocol https = new Protocol("https", factory, port);
         Protocol.registerProtocol("https", https);
         client.getHostConfiguration().setHost(host, port, https);

      } catch (GeneralSecurityException e) {
         throw new CoreException(CoreException.SSL, e);
      }
   }
}
项目:http4e    文件:HttpConnection.java   
/**
 * Creates a new HTTP connection for the given host with the virtual 
 * alias and port via the given proxy host and port using the given 
 * protocol.
 * 
 * @param proxyHost the host to proxy via
 * @param proxyPort the port to proxy via
 * @param host the host to connect to. Parameter value must be non-null.
 * @param port the port to connect to
 * @param protocol The protocol to use. Parameter value must be non-null.
 */
public HttpConnection(
    String proxyHost,
    int proxyPort,
    String host,
    int port,
    Protocol protocol) {

    if (host == null) {
        throw new IllegalArgumentException("host parameter is null");
    }
    if (protocol == null) {
        throw new IllegalArgumentException("protocol is null");
    }

    proxyHostName = proxyHost;
    proxyPortNumber = proxyPort;
    hostName = host;
    portNumber = protocol.resolvePort(port);
    protocolInUse = protocol;
}
项目:http4e    文件:HttpHostFactory.java   
/**
 * Get a Protocol for the given parameters. The default implementation
 * selects a protocol based only on the scheme. Subclasses can do fancier
 * things, such as select SSL parameters based on the host or port. This
 * method must not return null.
 */
protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port)
{
    final Protocol oldProtocol = old.getProtocol();
    if (oldProtocol != null) {
        final String oldScheme = oldProtocol.getScheme();
        if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) {
            // The old protocol has the desired scheme.
            return oldProtocol; // Retain it.
        }
    }
    Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol
            : httpProtocol;
    if (newProtocol == null) {
        newProtocol = Protocol.getProtocol(scheme);
    }
    return newProtocol;
}
项目:es-hadoop-v2.2.0    文件:CommonsHttpTransport.java   
private void replaceProtocol(HostConfiguration hostConfig, ProtocolSocketFactory socketFactory, String schema, int defaultPort) {
    //
    // switch protocol
    // due to how HttpCommons work internally this dance is best to be kept as is
    //

    // NB: not really needed (see below that the protocol is reseted) but in place just in case
    hostConfig = new ProtocolAwareHostConfiguration(hostConfig);
    Protocol directHttp = Protocol.getProtocol(schema);
    Protocol proxiedHttp = new DelegatedProtocol(socketFactory, directHttp, schema, defaultPort);
    // NB: register the new protocol since when using absolute URIs, HttpClient#executeMethod will override the configuration (#387)
    // NB: hence why the original/direct http protocol is saved - as otherwise the connection is not closed since it is considered different
    // NB: (as the protocol identities don't match)

    // this is not really needed since it's being replaced later on
    // hostConfig.setHost(proxyHost, proxyPort, proxiedHttp);
    Protocol.registerProtocol(schema, proxiedHttp);

    // end dance
}
项目:cloud-meter    文件:LoopbackHttpClientSocketFactory.java   
/**
 * Convenience method to set up the necessary HttpClient protocol and URL handler.
 *
 * Only works for HttpClient, because it's not possible (or at least very difficult)
 * to provide a different socket factory for the HttpURLConnection class.
 */
public static void setup(){
    final String LOOPBACK = "loopback"; // $NON-NLS-1$

    // This ensures tha HttpClient knows about the protocol
    Protocol.registerProtocol(LOOPBACK, new Protocol(LOOPBACK,new LoopbackHttpClientSocketFactory(),1));

    // Now allow the URL handling to work.
    URLStreamHandlerFactory ushf = new URLStreamHandlerFactory(){
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            if (protocol.equalsIgnoreCase(LOOPBACK)){
                return new URLStreamHandler(){
                    @Override
                    protected URLConnection openConnection(URL u) throws IOException {
                        return null;// not needed for HttpClient
                    }
                };
            }
            return null;
        }
    };

    java.net.URL.setURLStreamHandlerFactory(ushf);
}
项目:gluu    文件:Shibboleth3ConfService.java   
public String saveSpMetadataFile(String uri, String spMetadataFileName) {
           //TODO: change for IDP3
    if (StringHelper.isEmpty(uri)) {
        return null;
    }
    HTTPFileDownloader.setEasyhttps(new Protocol("https", new EasyCASSLProtocolSocketFactory(), 443));
    String spMetadataFileContent = HTTPFileDownloader.getResource(uri, "application/xml, text/xml", null, null);

    if (StringHelper.isEmpty(spMetadataFileContent)) {
        return null;
    }

    // Save new file
    ByteArrayInputStream is;
    try {
        byte[] spMetadataFileContentBytes = spMetadataFileContent.getBytes("UTF-8");
        is = new ByteArrayInputStream(spMetadataFileContentBytes);
    } catch (UnsupportedEncodingException ex) {
        return null;
    }

    FileUploadWrapper tmpfileWrapper = new FileUploadWrapper();
    tmpfileWrapper.setStream(is);

    return saveSpMetadataFile(spMetadataFileName, tmpfileWrapper.getStream());
}
项目:gluu    文件:Shibboleth2ConfService.java   
public String saveSpMetadataFile(String uri, String spMetadataFileName) {
    if (StringHelper.isEmpty(uri)) {
        return null;
    }
    HTTPFileDownloader.setEasyhttps(new Protocol("https", new EasyCASSLProtocolSocketFactory(), 443));
    String spMetadataFileContent = HTTPFileDownloader.getResource(uri, "application/xml, text/xml", null, null);

    if (StringHelper.isEmpty(spMetadataFileContent)) {
        return null;
    }

    // Save new file
    ByteArrayInputStream is;
    try {
        byte[] spMetadataFileContentBytes = spMetadataFileContent.getBytes("UTF-8");
        is = new ByteArrayInputStream(spMetadataFileContentBytes);
    } catch (UnsupportedEncodingException ex) {
        return null;
    }

    FileUploadWrapper tmpfileWrapper = new FileUploadWrapper();
    tmpfileWrapper.setStream(is);

    return saveSpMetadataFile(spMetadataFileName, tmpfileWrapper.getStream());
}
项目:Camel    文件:HttpsSslContextParametersGetTest.java   
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() {                
            SSLContextParameters params = new SSLContextParameters();

            ProtocolSocketFactory factory = 
                new SSLContextParametersSecureProtocolSocketFactory(params, context);

            Protocol.registerProtocol("https",
                    new Protocol(
                            "https",
                            factory,
                            443));

            from("direct:start")
                .to("https://mail.google.com/mail/").to("mock:results");
        }
    };
}
项目:picframe    文件:NetworkUtils.java   
/**
    * Registers or unregisters the proper components for advanced SSL handling.
    * @throws IOException 
    */
   @SuppressWarnings("deprecation")
public static void registerAdvancedSslContext(boolean register, Context context) 
        throws GeneralSecurityException, IOException {
       Protocol pr = null;
       try {
           pr = Protocol.getProtocol("https");
           if (pr != null && mDefaultHttpsProtocol == null) {
               mDefaultHttpsProtocol = pr;
           }
       } catch (IllegalStateException e) {
           // nothing to do here; really
       }
       boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
       if (register && !isRegistered) {
           Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));

       } else if (!register && isRegistered) {
           if (mDefaultHttpsProtocol != null) {
               Protocol.registerProtocol("https", mDefaultHttpsProtocol);
           }
       }
   }
项目:picframe    文件:MoveFileTest.java   
public MoveFileTest() {
    super();

    Protocol pr = Protocol.getProtocol("https");
    if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
        try {
            ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
            Protocol.registerProtocol(
                    "https",
                    new Protocol("https", psf, 443));

        } catch (GeneralSecurityException e) {
            throw new AssertionFailedError(
                    "Self-signed confident SSL context could not be loaded");
        }
    }

}
项目:picframe    文件:SingleSessionManagerTest.java   
public SingleSessionManagerTest() {
    super();

    Protocol pr = Protocol.getProtocol("https");
    if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
        try {
            ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
            Protocol.registerProtocol(
                    "https",
                    new Protocol("https", psf, 443));

        } catch (GeneralSecurityException e) {
            throw new AssertionFailedError(
                    "Self-signed confident SSL context could not be loaded");
        }
    }
}
项目:picframe    文件:SimpleFactoryManagerTest.java   
public SimpleFactoryManagerTest() {
    super();

    Protocol pr = Protocol.getProtocol("https");
    if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
        try {
            ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
            Protocol.registerProtocol(
                    "https",
                    new Protocol("https", psf, 443));

        } catch (GeneralSecurityException e) {
            throw new AssertionFailedError(
                    "Self-signed confident SSL context could not be loaded");
        }
    }
}
项目:picframe    文件:OwnCloudClientTest.java   
public OwnCloudClientTest() {
    super();

    Protocol pr = Protocol.getProtocol("https");
    if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
        try {
            ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
            Protocol.registerProtocol(
                    "https",
                    new Protocol("https", psf, 443));

        } catch (GeneralSecurityException e) {
            throw new AssertionFailedError(
                    "Self-signed confident SSL context could not be loaded");
        }
    }
}
项目:Telepathology    文件:FederationProxyUtilities.java   
/**
 * Configure the Federation certificate protocol to use certificates to communicate with remote server
 * @param federationConfiguration The configuration for the federation data source
 */
public static void configureFederationCertificate(FederationConfiguration federationConfiguration)
{
    try
    {           
        URL keystoreUrl = new URL(federationConfiguration.getKeystoreUrl());    // the keystore containing the key to send as the client
        URL truststoreUrl = new URL(federationConfiguration.getTruststoreUrl());    // the keystore containing the trusted certificates, to validate the server cert against

        ProtocolSocketFactory socketFactory = 
            new AuthSSLProtocolSocketFactory(keystoreUrl, 
                federationConfiguration.getKeystorePassword(), truststoreUrl, 
                federationConfiguration.getTruststorePassword());
        Protocol httpsProtocol = new Protocol(defaultFederationProtocol, socketFactory, defaultFederationSslPort);  

        Protocol.registerProtocol(federationConfiguration.getFederationSslProtocol(), httpsProtocol);
        Logger.getLogger(FederationProxyUtilities.class).info("Federation HTTPS protocol handler successfully registered.");
        dumpSSLProperties();
    } 
    catch (MalformedURLException e)
    {
        Logger.getLogger(ImagingProxy.class).error(
            "Error configuring HTTPS client within federation proxy. \n" +
            "Keystore and/or truststore are unavailable. \n" +
            "Federation functionality will not be available.");
    }
}
项目:WordsDetection    文件:HttpClient.java   
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) {
    connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = connectionManager.getParams();
    params.setDefaultMaxConnectionsPerHost(maxConPerHost);
    params.setConnectionTimeout(conTimeOutMs);
    params.setSoTimeout(soTimeOutMs);

    HttpClientParams clientParams = new HttpClientParams();
    // 忽略cookie 避免 Cookie rejected 警告
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager);
    Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
    Protocol.registerProtocol("https", myhttps);
    this.maxSize = maxSize;
    // 支持proxy
    if (proxyHost != null && !proxyHost.equals("")) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        client.getParams().setAuthenticationPreemptive(true);
        if (proxyAuthUser != null && !proxyAuthUser.equals("")) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword));
            log("Proxy AuthUser: " + proxyAuthUser);
            log("Proxy AuthPassword: " + proxyAuthPassword);
        }
    }
}
项目:superfly    文件:HttpClientFactoryBean.java   
protected void initSocketFactory() throws IOException {
    if (hostConfig != null) {
        URL trustKeyStoreUrl = null;
        if (hostConfig.getTrustKeyStoreResource() != null) {
            trustKeyStoreUrl = hostConfig.getTrustKeyStoreResource().getURL();
        }
        URL keyStoreUrl = null;
        if (hostConfig.getKeyStoreResource() != null) {
            keyStoreUrl = hostConfig.getKeyStoreResource().getURL();
        }
        AuthSSLProtocolSocketFactory factory = new AuthSSLProtocolSocketFactory(
                keyStoreUrl, hostConfig.getKeyStorePassword(),
                trustKeyStoreUrl, hostConfig.getTrustKeyStorePassword());
        if (sslEnabledProtocols != null) {
            factory.setEnabledProtocols(sslEnabledProtocols);
        }
        Protocol protocol = createProtocol(hostConfig, factory);
        httpClient.getHostConfiguration().setHost(hostConfig.getHost(),
                hostConfig.getSecurePort(), protocol);
    }
}
项目:minxing_java_sdk    文件:HttpClient.java   
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs,
            int maxSize) {

//      MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true);
        HttpConnectionManagerParams params = connectionManager.getParams();
        params.setDefaultMaxConnectionsPerHost(maxConPerHost);
        params.setConnectionTimeout(conTimeOutMs);
        params.setSoTimeout(soTimeOutMs);

        HttpClientParams clientParams = new HttpClientParams();
        clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        client = new org.apache.commons.httpclient.HttpClient(clientParams,
                connectionManager);
        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }
项目:haox    文件:TestHttpclientContrib.java   
public static void registerCerts() throws Exception {
    File keyFile = new File("samples/keystores/Sun.jks.ks");
    File trustFile = new File("samples/cacerts-with-78-entries.jks");
    URL ks = keyFile.toURI().toURL();
    URL ts = trustFile.toURI().toURL();

    AuthSSLProtocolSocketFactory sf;
    sf = new AuthSSLProtocolSocketFactory(ks, "changeit", ts, "changeit");
    sf.setCheckHostname(false);

    // There should be 78 certs in this trust-chain.
    assertEquals(78, sf.getTrustChain().getCertificates().size());

    TrustSSLProtocolSocketFactory tf;
    tf = new TrustSSLProtocolSocketFactory(trustFile.getAbsolutePath(), "changeit".toCharArray());
    tf.setCheckHostname(false);

    String scheme1 = "https-test1";
    Protocol.registerProtocol(scheme1, new Protocol(scheme1, (ProtocolSocketFactory) sf, 443));
    String scheme2 = "https-test2";
    Protocol.registerProtocol(scheme2, new Protocol(scheme2, (ProtocolSocketFactory) tf, 443));
}
项目:translationstudio8    文件:ServiceUtil.java   
public static IService getService() throws MalformedURLException {
//      Service srvcModel = new ObjectServiceFactory().create(IService.class);
//      XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//              .newInstance().getXFire());
//
//      IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//      return srvc;

        ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
                SERVICE_NAME, SERVICE_NAMESPACE, null);  

        IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
        Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 

        return service;
    }
项目:translationstudio8    文件:ServiceUtil.java   
public static IService getService() throws MalformedURLException {
//      Service srvcModel = new ObjectServiceFactory().create(IService.class);
//      XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//              .newInstance().getXFire());
//
//      IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//      return srvc;

        ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
                SERVICE_NAME, SERVICE_NAMESPACE, null);  

        IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
        Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 

        return service;
    }
项目:community-edition-old    文件:HttpClientTransmitterImpl.java   
/**
 * @param target TransferTarget
 * @return HostConfiguration
 */
private HostConfiguration getHostConfig(TransferTarget target)
{
    String requiredProtocol = target.getEndpointProtocol();
    if (requiredProtocol == null)
    {
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] {target.getEndpointProtocol()});
    }

    Protocol protocol = protocolMap.get(requiredProtocol.toLowerCase().trim());
    if (protocol == null) {
        log.error("Unsupported protocol: " + target.getEndpointProtocol());
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] {target.getEndpointProtocol()});
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(target.getEndpointHost(), target.getEndpointPort(), protocol);
    return hostConfig;
}
项目:CardDAVSyncOutlook    文件:ManageWebDAVContacts.java   
/**
 *
 * Public Section
 *
 */
public void connectHTTP(String strUser, String strPass, String strHost, boolean insecure) {
    //Connect WebDAV with credentials
    hostConfig = new HostConfiguration();
    hostConfig.setHost(strHost);
    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManagerParams = new HttpConnectionManagerParams();
    connectionManagerParams.setMaxConnectionsPerHost(hostConfig, this.intMaxConnections);
    connectionManager.setParams(connectionManagerParams);
    client = new HttpClient(connectionManager);
    creds = new UsernamePasswordCredentials(strUser, strPass);
    client.getState().setCredentials(AuthScope.ANY, creds);
    client.setHostConfiguration(hostConfig);

    if (insecure) {
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", easyhttps);
    }

    Status.print("WebDav Connection generated");
}
项目:Runner    文件:LocalResponseManager.java   
private String getRequest()
{

    if (!Server.serving) return "";

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost host = new HttpHost("localhost", Server.frontPort, Protocol.getProtocol("http"));
    HttpGet request = new HttpGet(host.toURI().concat("/" + Server.RESPONSES));
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else throw new ClientProtocolException("Unexpected response status: " + status);
        }
    };
    String responseBody = null;
    try {
        responseBody = httpclient.execute(request, responseHandler);
    } catch (IOException e) { Runner.LOGGER.warn(e); }

    return responseBody;
}
项目:axelor-business-suite    文件:CalendarService.java   
public boolean testConnect(Calendar cal) throws MalformedURLException, ObjectStoreException
{
    boolean connected = false;
    PathResolver RESOLVER = getPathResolver(cal.getTypeSelect());
    Protocol protocol = getProtocol(cal.getIsSslConnection());
    URL url = new URL(protocol.getScheme(), cal.getUrl(), cal.getPort(), "");
    ICalendarStore store = new ICalendarStore(url, RESOLVER);

    try 
    {
        connected = store.connect(cal.getLogin(), cal.getPassword());
    }
    finally {
        store.disconnect();
    }
    return connected;
}
项目:axelor-business-suite    文件:CalendarService.java   
@Transactional
public void sync(Calendar calendar)
        throws ICalendarException, MalformedURLException {
    PathResolver RESOLVER = getPathResolver(calendar.getTypeSelect());
    Protocol protocol = getProtocol(calendar.getIsSslConnection());
    URL url = new URL(protocol.getScheme(), calendar.getUrl(), calendar.getPort(), "");
    ICalendarStore store = new ICalendarStore(url, RESOLVER);
    try {
        if(calendar.getLogin() != null && calendar.getPassword() != null && store.connect(calendar.getLogin(), calendar.getPassword())){
            List<CalDavCalendarCollection> colList = store.getCollections();
            if(!colList.isEmpty()){
                calendar = doSync(calendar, colList.get(0));
                calendarRepo.save(calendar);
            }
        }
        else{
            throw new AxelorException(String.format(I18n.get(IExceptionMessage.CALENDAR_NOT_VALID)), IException.CONFIGURATION_ERROR);
        }
    } catch (Exception e) {
        throw new ICalendarException(e);
    }
    finally {
        store.disconnect();
    }
}