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); } } }
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 }
@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"); } }; }
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"); } } }
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"); } } }
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"); } } }
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"); } } }
/** * 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."); } }
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)); }
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; }
@Nullable private static HttpMethod handleCertificateExceptionAndRetry(@NotNull IOException e, @NotNull String host, @NotNull HttpClient client, @NotNull URI uri, @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator) throws IOException { if (!isCertificateException(e)) { throw e; } if (isTrusted(host)) { // creating a special configuration that allows connections to non-trusted HTTPS hosts // see the javadoc to EasySSLProtocolSocketFactory for details Protocol easyHttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443); HostConfiguration hc = new HostConfiguration(); hc.setHost(host, 443, easyHttps); String relativeUri = new URI(uri.getPathQuery(), false).getURI(); // it is important to use relative URI here, otherwise our custom protocol won't work. // we have to recreate the method, because HttpMethod#setUri won't overwrite the host, // and changing host by hands (HttpMethodBase#setHostConfiguration) is deprecated. HttpMethod method = methodCreator.convert(relativeUri); client.executeMethod(hc, method); return method; } throw e; }
static void replaceProtocol(ProtocolSocketFactory socketFactory, String schema, int defaultPort) { // // switch protocol // due to how HttpCommons work internally this dance is best to be kept as is // Protocol directHttp = Protocol.getProtocol(schema); if (directHttp instanceof DelegatedProtocol) { // unwrap the original directHttp = ((DelegatedProtocol)directHttp).getOriginal(); assert directHttp instanceof DelegatedProtocol == false; } 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 }
@Test public void testProtocolReplacement() throws Exception { final ProtocolSocketFactory socketFactory = getSocketFactory(); CommonsHttpTransport.replaceProtocol(socketFactory, "https", 443); Protocol protocol = Protocol.getProtocol("https"); assertThat(protocol, instanceOf(DelegatedProtocol.class)); DelegatedProtocol delegatedProtocol = (DelegatedProtocol) protocol; assertThat(delegatedProtocol.getSocketFactory(), sameInstance(socketFactory)); assertThat(delegatedProtocol.getOriginal(), sameInstance(original)); // ensure we do not re-wrap a delegated protocol CommonsHttpTransport.replaceProtocol(socketFactory, "https", 443); protocol = Protocol.getProtocol("https"); assertThat(protocol, instanceOf(DelegatedProtocol.class)); delegatedProtocol = (DelegatedProtocol) protocol; assertThat(delegatedProtocol.getSocketFactory(), sameInstance(socketFactory)); assertThat(delegatedProtocol.getOriginal(), sameInstance(original)); }
@Override public List<Lifecycle> loadLifecycles() throws Exception { List<Lifecycle> lifecycles = new LinkedList<Lifecycle>(); // this validation of our service list needs to happen after we've // loaded our configs so it's a lifecycle lifecycles.add(new BaseLifecycle() { @Override public void start() throws Exception { // first check if we want to allow self-signed certificates for SSL communication if (Boolean.valueOf(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.KSB_ALLOW_SELF_SIGNED_SSL)).booleanValue()) { Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), 443)); } super.start(); } }); return lifecycles; }
static public ProtocolSocketFactory getSSLSocketFactory(String keyStore, String keyStorePassword, String trustStore, String trustStorePassword, boolean trustAllServerCertificates) { String key = "" + keyStore + "|" + keyStorePassword + "|" + trustStore + "|" + trustStorePassword + "|" + trustAllServerCertificates; synchronized (cache) { MySSLSocketFactory mySSLSocketFactory = cache.get(key); if (mySSLSocketFactory == null) { Engine.logCertificateManager.debug("(MySSLSocketFactory) Create new SSLSocketFactory (" + key + ")"); mySSLSocketFactory = new MySSLSocketFactory(keyStore, keyStorePassword, trustStore, trustStorePassword, trustAllServerCertificates); cache.put(key, mySSLSocketFactory); } else { Engine.logCertificateManager.debug("(MySSLSocketFactory) Retrieve SSLSocketFactory from cache (" + key + ")"); } long now = System.currentTimeMillis(); mySSLSocketFactory.expire = now + 3600000; if (now >= checkExpires) { int removed = 0; for (Iterator<MySSLSocketFactory> i = cache.values().iterator(); i.hasNext();) { MySSLSocketFactory cachedSSLSocketFactory = i.next(); if (now >= cachedSSLSocketFactory.expire) { removed++; i.remove(); } } Engine.logCertificateManager.info("(MySSLSocketFactory) Clear " + removed + " cache entries, remains " + cache.size() + " entries"); checkExpires += 300000; } return mySSLSocketFactory; } }
public void testProtocolSocketFactorySublass() { ProtocolSocketFactory factory1 = new DefaultProtocolSocketFactory(); ProtocolSocketFactory factory2 = new DefaultProtocolSocketFactory() {}; Protocol protocolA = new Protocol("http", factory1, 80); Protocol protocolB = new Protocol("http", factory2, 80); Protocol protocolC = new Protocol("http", factory2, 80); assertTrue(protocolB.equals(protocolC)); assertFalse(protocolA.equals(protocolB)); assertFalse(protocolB.equals(protocolA)); assertFalse(protocolA.equals(protocolB) != protocolB.equals(protocolA)); assertTrue(protocolB.equals(protocolB)); }
/** * Create the SSLContext, and wrap all the X509KeyManagers with * our X509KeyManager so that we can choose our alias. * * @param provider * Description of Parameter */ public JsseSSLManager(Provider provider) { log.debug("ssl Provider = " + provider); setProvider(provider); if (null == this.rand) { // Surely this is always null in the constructor? this.rand = new SecureRandom(); } try { if (SHARED_SESSION_CONTEXT) { log.debug("Creating shared context"); this.defaultContext = createContext(); } else { this.threadlocal = new ThreadLocal<>(); } HttpsURLConnection.setDefaultSSLSocketFactory(new HttpSSLProtocolSocketFactory(this, CPS)); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); /* * Also set up HttpClient defaults */ Protocol protocol = new Protocol( JsseSSLManager.HTTPS, (ProtocolSocketFactory) new HttpSSLProtocolSocketFactory(this, CPS), 443); Protocol.registerProtocol(JsseSSLManager.HTTPS, protocol); log.debug("SSL stuff all set"); } catch (GeneralSecurityException ex) { log.error("Could not set up SSLContext", ex); } log.debug("JsseSSLManager installed"); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); mServerUri = getString(R.string.server_base_url); mUser = getString(R.string.username); mPass = getString(R.string.password); 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) { Log.e(TAG, "Self-signed confident SSL context could not be loaded"); } } mClient = new OwnCloudClient(Uri.parse(mServerUri), NetworkUtils.getMultiThreadedConnManager()); mClient.setDefaultTimeouts( OwnCloudClientFactory.DEFAULT_DATA_TIMEOUT, OwnCloudClientFactory.DEFAULT_CONNECTION_TIMEOUT); mClient.setFollowRedirects(true); mClient.setCredentials( OwnCloudCredentialsFactory.newBasicCredentials( mUser, mPass ) ); mClient.setBaseUri(Uri.parse(mServerUri)); Log.v(TAG, "onCreate finished, ownCloud client ready"); }
protected void initProtocolIfNeeded() throws GeneralSecurityException, IOException { if (sslEnabledProtocols != null) { // have to register our own protocol HttpSecureProtocol psf = new HttpSecureProtocol(); psf.setEnabledProtocols(sslEnabledProtocols); Protocol sslV3OnlyProtocol = new Protocol("https", (ProtocolSocketFactory) psf, 443); Protocol.registerProtocol("https", sslV3OnlyProtocol); } }
public static void main(String[] args) { HttpClient httpclient; String url; GetMethod method; ProtocolSocketFactory fcty; url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd30e31bfd8c207ee&secret=d0f9c44269c0282a1a7337efea1950a1"; //https 证书 fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); httpclient = new HttpClient(); method = new GetMethod(url);// get调用 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println(statusCode + ": " + method.getStatusLine()); } else { System.out.println(new String(method.getResponseBody(), "UTF-8")); } } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
protected void easySSL() { ProtocolSocketFactory easySSLProtocolSocketFactory = new EasySSLProtocolSocketFactory(); Protocol.unregisterProtocol("https"); Protocol.registerProtocol("https", new Protocol("https", easySSLProtocolSocketFactory, getUrl().getPort() == -1 ? 443 : getUrl().getPort())); }
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; }
/** * Set the custom trust manager as the ssl protocol handler for the stub * * @param stub * @throws Exception */ public static void setSSLProtocolHandler(Stub stub) throws Exception { init(); stub._getServiceClient() .getOptions() .setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, new Protocol("https", (ProtocolSocketFactory) new CustomSSLProtocolSocketFactory(sslCtx), 443)); }
protected final HttpClient getClient() { if (httpClient == null) { if (allowToUseSelfSignedCertificates()) { Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), HTTPS_PORT); Protocol.registerProtocol("https", easyhttps); } httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); httpClient.getHostConfiguration().setHost(getHost(), getPort(), getProtocol()); configureClient(httpClient); } return httpClient; }
public static HttpClient getClient(Configuration conf)throws Exception { HttpClient httpClient = new HttpClient(); URL trustStoreUrl; // try { int port = 8181; // trustStoreUrl = new URL("file://" + DataDir + AttestationTruststore); trustStoreUrl = new URL("file://" + conf.getTrimmed(YarnConfiguration.DATADIR,DataDir) + conf.getTrimmed(YarnConfiguration.ATTESTATIONTRUSTSTORE,AttestationTruststore)); // registering the https protocol with a socket factory that // provides client authentication. ProtocolSocketFactory factory = new AuthSSLProtocolSocketFactory( getTrustStore(trustStoreUrl.getPath(), conf.getTrimmed(YarnConfiguration.TRUSTSTOREPASSWORD,truststorePassword) ) ); Protocol clientAuthHTTPS = new Protocol("https", factory, port); httpClient.getHostConfiguration().setHost(conf.getTrimmed(YarnConfiguration.ATTESTATIONSERVER, attestationServer), port, clientAuthHTTPS); //} catch (Exception e) { // log.fatal( // "Failed to init AuthSSLProtocolSocketFactory. SSL connections will not work", // e); // } return httpClient; }
public BigSwitchBcfApi() { _client = createHttpClient(); _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); try { // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), _port)); } catch (IOException e) { S_LOGGER.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); } }
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) { client = createHttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); this.httpClazz = httpClazz; try { // Cast to ProtocolSocketFactory to avoid the deprecated constructor // with the SecureProtocolSocketFactory parameter Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT)); } catch (IOException e) { s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); } }
/** * Create the SSLContext, and wrap all the X509KeyManagers with * our X509KeyManager so that we can choose our alias. * * @param provider * Description of Parameter */ public JsseSSLManager(Provider provider) { log.debug("ssl Provider = " + provider); setProvider(provider); if (null == this.rand) { // Surely this is always null in the constructor? this.rand = new SecureRandom(); } try { if (SHARED_SESSION_CONTEXT) { log.debug("Creating shared context"); this.defaultContext = createContext(); } else { this.threadlocal = new ThreadLocal<SSLContext>(); } HttpsURLConnection.setDefaultSSLSocketFactory(new HttpSSLProtocolSocketFactory(this, CPS)); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); /* * Also set up HttpClient defaults */ Protocol protocol = new Protocol( JsseSSLManager.HTTPS, (ProtocolSocketFactory) new HttpSSLProtocolSocketFactory(this, CPS), 443); Protocol.registerProtocol(JsseSSLManager.HTTPS, protocol); log.debug("SSL stuff all set"); } catch (GeneralSecurityException ex) { log.error("Could not set up SSLContext", ex); } log.debug("JsseSSLManager installed"); }
/** * Establishes a connection to the specified host and port * (via a proxy if specified). * The underlying socket is created from the {@link ProtocolSocketFactory}. * * @throws IOException if an attempt to establish the connection results in an * I/O error. */ public void open() throws IOException { LOG.trace("enter HttpConnection.open()"); final String host = (proxyHostName == null) ? hostName : proxyHostName; final int port = (proxyHostName == null) ? portNumber : proxyPortNumber; assertNotOpen(); if (LOG.isDebugEnabled()) { LOG.debug("Open connection to " + host + ":" + port); } try { if (this.socket == null) { usingSecureSocket = isSecure() && !isProxied(); // use the protocol's socket factory unless this is a secure // proxied connection ProtocolSocketFactory socketFactory = null; if (isSecure() && isProxied()) { Protocol defaultprotocol = Protocol.getProtocol("http"); socketFactory = defaultprotocol.getSocketFactory(); } else { socketFactory = this.protocolInUse.getSocketFactory(); } this.socket = socketFactory.createSocket( host, port, localAddress, 0, this.params); } /* "Nagling has been broadly implemented across networks, including the Internet, and is generally performed by default - although it is sometimes considered to be undesirable in highly interactive environments, such as some client/server situations. In such cases, nagling may be turned off through use of the TCP_NODELAY sockets option." */ socket.setTcpNoDelay(this.params.getTcpNoDelay()); socket.setSoTimeout(this.params.getSoTimeout()); int linger = this.params.getLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } int sndBufSize = this.params.getSendBufferSize(); if (sndBufSize >= 0) { socket.setSendBufferSize(sndBufSize); } int rcvBufSize = this.params.getReceiveBufferSize(); if (rcvBufSize >= 0) { socket.setReceiveBufferSize(rcvBufSize); } int outbuffersize = socket.getSendBufferSize(); if ((outbuffersize > 2048) || (outbuffersize <= 0)) { outbuffersize = 2048; } int inbuffersize = socket.getReceiveBufferSize(); if ((inbuffersize > 2048) || (inbuffersize <= 0)) { inbuffersize = 2048; } inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize); outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize); isOpen = true; } catch (IOException e) { // Connection wasn't opened properly // so close everything out closeSocketAndStreams(); throw e; } }
public DelayedProtocolSocketFactory(int delay, ProtocolSocketFactory realFactory) { this.delay = delay; this.realFactory = realFactory; }
/** * Configures the HTTP client */ private void configureClient() { // Set up an HTTPS socket factory that accepts self-signed certs. // ProtocolSocketFactory factory = new SSLProtocolSocketFactory(); ProtocolSocketFactory factory = new DummySSLProtocolSocketFactory(); Protocol https = new Protocol("https", factory, 443); Protocol.registerProtocol("https", https); HttpConnectionManagerParams params = connectionManager.getParams(); params.setConnectionTimeout(timeout); params.setSoTimeout(timeout); params.setSendBufferSize(BUFFER_SIZE); params.setReceiveBufferSize(BUFFER_SIZE); // -------------------------------------------------------------------------------- // NUTCH-1836: Modification to increase the number of available connections // for multi-threaded crawls. // -------------------------------------------------------------------------------- params.setMaxTotalConnections(conf.getInt( "mapred.tasktracker.map.tasks.maximum", 5) * conf.getInt("fetcher.threads.fetch", maxThreadsTotal)); // Also set max connections per host to maxThreadsTotal since all threads // might be used to fetch from the same host - otherwise timeout errors can // occur params.setDefaultMaxConnectionsPerHost(conf.getInt( "fetcher.threads.fetch", maxThreadsTotal)); // executeMethod(HttpMethod) seems to ignore the connection timeout on the // connection manager. // set it explicitly on the HttpClient. client.getParams().setConnectionManagerTimeout(timeout); HostConfiguration hostConf = client.getHostConfiguration(); ArrayList<Header> headers = new ArrayList<Header>(); // Set the User Agent in the header // headers.add(new Header("User-Agent", userAgent)); //NUTCH-1941 // prefer English headers.add(new Header("Accept-Language", acceptLanguage)); // 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,image/png,*/*;q=0.5")); // accept gzipped content headers.add(new Header("Accept-Encoding", "x-gzip, gzip, deflate")); hostConf.getParams().setParameter("http.default-headers", headers); // HTTP proxy server details if (useProxy) { hostConf.setProxy(proxyHost, proxyPort); if (proxyUsername.length() > 0) { AuthScope proxyAuthScope = getAuthScope(this.proxyHost, this.proxyPort, this.proxyRealm); NTCredentials proxyCredentials = new NTCredentials(this.proxyUsername, this.proxyPassword, Http.agentHost, this.proxyRealm); client.getState().setProxyCredentials(proxyAuthScope, proxyCredentials); } } }
@Bean public ProtocolSocketFactory protocolSocketFactory() { return new TLSProtocolSocketFactory(keyManager(), null, "default"); }
DelegatedProtocol(ProtocolSocketFactory factory, Protocol original, String scheme, int port) { super(scheme, factory, port); this.original = original; }
ProtocolSocketFactory socketFactory() { return new TLSProtocolSocketFactory(keyManager(), null, "default"); }
private Protocol createProtocol(StoresAndSSLConfig config, ProtocolSocketFactory factory) { return new Protocol(config.getSecureSchema(), factory, config.getSecurePort()); }