Search in sources :

Example 16 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project developNote by cheng2016.

the class HttpUtil method getNewHttpClient.

private static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) KeyStore(java.security.KeyStore) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) UnknownHostException(java.net.UnknownHostException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 17 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project wso2-synapse by wso2.

the class HttpCoreNIOSender method init.

/**
 * Initialize the transport sender, and execute reactor in new separate thread
 * @param cfgCtx the Axis2 configuration context
 * @param transportOut the description of the http/s transport from Axis2 configuration
 * @throws AxisFault thrown on an error
 */
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    this.configurationContext = cfgCtx;
    cfg = NHttpConfiguration.getInstance();
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000)).setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)).setParameter(CoreProtocolPNames.USER_AGENT, "Synapse-HttpComponents-NIO");
    // .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,
    // cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,HTTP.DEFAULT_PROTOCOL_CHARSET)); //TODO:This does not works with HTTPCore 4.3
    name = transportOut.getName().toUpperCase(Locale.US) + " Sender";
    ClientConnFactoryBuilder contextBuilder = initConnFactoryBuilder(transportOut);
    connFactory = contextBuilder.createConnFactory(params);
    connpool = new ConnectionPool();
    proxyConfig = new ProxyConfigBuilder().build(transportOut);
    log.info(proxyConfig.logProxyConfig());
    Parameter param = transportOut.getParameter("warnOnHTTP500");
    if (param != null) {
        String[] warnOnHttp500 = ((String) param.getValue()).split("\\|");
        cfgCtx.setNonReplicableProperty("warnOnHTTP500", warnOnHttp500);
    }
    IOReactorConfig ioReactorConfig = new IOReactorConfig();
    ioReactorConfig.setIoThreadCount(NHttpConfiguration.getInstance().getClientIOWorkers());
    ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000));
    ioReactorConfig.setConnectTimeout(cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000));
    ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1);
    if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) {
        ioReactorConfig.setInterestOpQueued(true);
    }
    try {
        String prefix = name + " I/O dispatcher";
        ioReactor = new DefaultConnectingIOReactor(ioReactorConfig, new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix));
        ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {

            public boolean handle(IOException ioException) {
                log.warn("System may be unstable: IOReactor encountered a checked exception : " + ioException.getMessage(), ioException);
                return true;
            }

            public boolean handle(RuntimeException runtimeException) {
                log.warn("System may be unstable: IOReactor encountered a runtime exception : " + runtimeException.getMessage(), runtimeException);
                return true;
            }
        });
    } catch (IOException e) {
        log.error("Error starting the IOReactor", e);
        throw new AxisFault(e.getMessage(), e);
    }
    metrics = new NhttpMetricsCollector(false, transportOut.getName());
    handler = new ClientHandler(connpool, connFactory, proxyConfig, cfgCtx, params, metrics);
    iodispatch = new ClientIODispatch(handler, connFactory);
    final IOEventDispatch ioEventDispatch = iodispatch;
    // start the Sender in a new seperate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                log.fatal("Reactor Interrupted");
            } catch (IOException e) {
                log.fatal("Encountered an I/O error: " + e.getMessage(), e);
            }
            log.info(name + " Shutdown");
        }
    }, "HttpCoreNIOSender");
    t.start();
    log.info(name + " starting");
    // register with JMX
    mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportOut.getName());
    mbeanSupport.register();
    state = BaseConstants.STARTED;
}
Also used : IOReactorExceptionHandler(org.apache.http.nio.reactor.IOReactorExceptionHandler) AxisFault(org.apache.axis2.AxisFault) InterruptedIOException(java.io.InterruptedIOException) ProxyConfigBuilder(org.apache.synapse.transport.nhttp.config.ProxyConfigBuilder) ClientConnFactoryBuilder(org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder) NhttpMetricsCollector(org.apache.synapse.transport.nhttp.util.NhttpMetricsCollector) TransportMBeanSupport(org.apache.axis2.transport.base.TransportMBeanSupport) NativeThreadFactory(org.apache.axis2.transport.base.threads.NativeThreadFactory) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) Parameter(org.apache.axis2.description.Parameter) IOEventDispatch(org.apache.http.nio.reactor.IOEventDispatch) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 18 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project knox by apache.

the class WebHdfsHaDispatchTest method testConnectivityFailover.

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();
    BasicHttpParams params = new BasicHttpParams();
    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();
    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<SynchronousServletOutputStreamAdapter>() {

        @Override
        public SynchronousServletOutputStreamAdapter answer() throws Throwable {
            return new SynchronousServletOutputStreamAdapter() {

                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }
            };
        }
    }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    WebHdfsHaDispatch dispatch = new WebHdfsHaDispatch();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    dispatch.setHttpClient(client);
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
    // this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    // test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) DefaultHaProvider(org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) IAnswer(org.easymock.IAnswer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig) SynchronousServletOutputStreamAdapter(org.apache.knox.gateway.servlet.SynchronousServletOutputStreamAdapter) HaDescriptor(org.apache.knox.gateway.ha.provider.HaDescriptor) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHaProvider(org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider) HaProvider(org.apache.knox.gateway.ha.provider.HaProvider) Test(org.junit.Test)

Example 19 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project MDM-Android-Agent by wso2-attic.

the class ServerUtilities method getCertifiedHttpClient.

public static HttpClient getCertifiedHttpClient(Context context) {
    try {
        KeyStore localTrustStore = KeyStore.getInstance("BKS");
        InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);
        localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        HttpClient client = new DefaultHttpClient(cm, params);
        return client;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) InputStream(java.io.InputStream) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) KeyStore(java.security.KeyStore) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.apache.http.ParseException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 20 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project opencast by opencast.

the class WorkspaceImpl method createGetRequest.

/**
 * Create a get request to the given URI.
 */
private HttpGet createGetRequest(final URI src, final File dst, Tuple<String, String>... params) throws IOException {
    final String url = src.toString();
    final HttpGet get = new HttpGet(url);
    // if the destination file already exists add the If-None-Match header
    if (dst.isFile() && dst.length() > 0) {
        get.setHeader("If-None-Match", md5(dst));
    }
    for (final Tuple<String, String> a : params) {
        get.setParams(new BasicHttpParams().setParameter(a.getA(), a.getB()));
    }
    return get;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Aggregations

BasicHttpParams (org.apache.http.params.BasicHttpParams)105 HttpParams (org.apache.http.params.HttpParams)75 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)50 IOException (java.io.IOException)41 HttpResponse (org.apache.http.HttpResponse)33 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)32 Scheme (org.apache.http.conn.scheme.Scheme)31 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)30 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)25 ClientProtocolException (org.apache.http.client.ClientProtocolException)16 HttpGet (org.apache.http.client.methods.HttpGet)16 HttpClient (org.apache.http.client.HttpClient)15 Test (org.junit.Test)15 HttpPost (org.apache.http.client.methods.HttpPost)14 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)14 Socket (java.net.Socket)11 URI (java.net.URI)11 StringEntity (org.apache.http.entity.StringEntity)11 TestHttpClient (io.undertow.testutils.TestHttpClient)10 KeyManagementException (java.security.KeyManagementException)9