Example usage for org.apache.http.client RedirectStrategy RedirectStrategy

List of usage examples for org.apache.http.client RedirectStrategy RedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.client RedirectStrategy RedirectStrategy.

Prototype

RedirectStrategy

Source Link

Usage

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduitFactory.java

public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
    if (client != null) {
        return;//ww w .  j ava2s .c o  m
    }

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount)
            .setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger)
            .setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();

    Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();

    ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory() {

        @Override
        public ManagedNHttpClientConnection create(final IOSession iosession, final ConnectionConfig config) {
            ManagedNHttpClientConnection conn = super.create(iosession, config);
            return conn;
        }
    };

    DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
    connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory,
            ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE,
            connectionTTL, TimeUnit.MILLISECONDS);

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnections);

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();

    connectionManager.setDefaultConnectionConfig(connectionConfig);

    RedirectStrategy redirectStrategy = new RedirectStrategy() {

        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return false;
        }

        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return null;
        }
    };

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy)
            .setDefaultCookieStore(new BasicCookieStore() {
                private static final long serialVersionUID = 1L;

                public void addCookie(Cookie cookie) {
                }
            });

    adaptClientBuilder(httpAsyncClientBuilder);

    client = httpAsyncClientBuilder.build();
    // Start the client thread
    client.start();
    if (this.connectionTTL == 0) {
        //if the connection does not have an expiry deadline
        //use the ConnectionMaxIdle to close the idle connection
        new CloseIdleConnectionThread(connectionManager, client).start();
    }
}

From source file:org.frontcache.FrontCacheEngine.java

private CloseableHttpClient newClient() {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5500) // should be slightly more then hystrix timeout for http client
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override//from ww  w. j  a v  a  2s  .com
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    return HttpClients.custom().setConnectionManager(newConnectionManager())
            .setDefaultRequestConfig(requestConfig)
            //            .setSSLHostnameVerifier(new NoopHostnameVerifier()) // for SSL do not verify certificate's host 
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

public static ClientHttpRequestFactory getNoValidatingClientHttpRequestFactory(boolean followRedirects) {
    ClientHttpRequestFactory requestFactory;
    SSLContext sslContext;/*from  w  w  w. java  2 s  .c om*/
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
    //
    CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslContext)
            .setRedirectStrategy(followRedirects ? new DefaultRedirectStrategy() : new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    return requestFactory;
}

From source file:org.springframework.extensions.webscripts.connector.RemoteClient.java

/**
 * Create and configure an HttpClient per thread based on Pooled connection manager.
 * Proxy route will be applied the client based on current settings.
 * //from w  ww.j av  a  2 s.  c om
 * @param url URL
 * @return HttpClient
 */
protected HttpClient createHttpClient(URL url) {
    // use the appropriate HTTP proxy host if required
    HttpRoutePlanner routePlanner = null;
    if (s_httpProxyHost != null && this.allowHttpProxy && url.getProtocol().equals("http")
            && requiresProxy(url.getHost())) {
        routePlanner = new DefaultProxyRoutePlanner(s_httpProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTP proxy host for: " + url);
    } else if (s_httpsProxyHost != null && this.allowHttpsProxy && url.getProtocol().equals("https")
            && requiresProxy(url.getHost())) {
        routePlanner = new DefaultProxyRoutePlanner(s_httpsProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTPS proxy host for: " + url);
    }

    return HttpClientBuilder.create().setConnectionManager(connectionManager).setRoutePlanner(routePlanner)
            .setRedirectStrategy(new RedirectStrategy() {
                // Switch off automatic redirect handling as we want to process them ourselves and maintain cookies
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            })
            .setDefaultRequestConfig(
                    RequestConfig.custom().setStaleConnectionCheckEnabled(httpConnectionStalecheck)
                            .setConnectTimeout(connectTimeout).setSocketTimeout(readTimeout).build())
            .build();

    // TODO: this appears to have vanished from the config that can be set since httpclient 3.1->4.3
    //params.setBooleanParameter("http.tcp.nodelay", httpTcpNodelay);
}

From source file:org.dataconservancy.ui.it.RegisterNewUserIT.java

/**
 * Verify the unregistered user cannot login. Register the unregistered
 * user. Login as admin. List pending registrations. Approve the
 * registration. Logout. Login as the newly registered user.
 * /*ww w .ja v a  2 s.c o  m*/
 * @throws Exception
 */
@Test
public void testApproveNewUserRegistration() throws Exception {
    final DefaultHttpClient hc = new DefaultHttpClient();

    // Override the redirect strategy to redirect on POST.  So we can just test for 200 statuses in the
    // unit test.
    final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    hc.setRedirectStrategy(new RedirectStrategy() {

        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            if (!redirectStrategy.isRedirected(request, response, context)) {
                return response.getStatusLine().getStatusCode() == 302;
            }
            return true;
        }

        @Override
        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return redirectStrategy.getRedirect(request, response, context);
        }
    });

    // Attempt to login as an unregistered user
    final HttpPost request = reqFactory.createLoginRequest(toRegister).asHttpPost();
    HttpResponse resp = hc.execute(request);
    String content = IOUtils.toString(resp.getEntity().getContent());
    assertTrue("Expected response '" + resp + "' to contain failure message '" + loginErrorMsg + "'.  "
            + "Page content was \n[" + content + "]\n", content.contains(loginErrorMsg));

    // Register a new user
    HttpAssert.assertStatus(hc, reqFactory.createRegisterRequest(toRegister).asHttpPost(), 200);

    // Login as admin
    HttpAssert.assertStatus(hc, reqFactory.createLoginRequest(adminUser).asHttpPost(), 200);

    // View pending registrations
    HttpAssert.assertStatus(hc, reqFactory.listPendingRegistrations().asHttpGet(), 200);

    // Approve registration
    HttpAssert.assertStatus(hc, reqFactory.createApproveRegistrationRequest(toRegister).asHttpPost(), 200);

    // Logout admin
    HttpAssert.assertStatus(hc, reqFactory.createLogoutRequest().asHttpGet(), 200);

    // Login as newly registered user
    resp = hc.execute(reqFactory.createLoginRequest(toRegister).asHttpPost());
    content = IOUtils.toString(resp.getEntity().getContent());
    assertFalse("Did NOT expect response '" + resp + "' to contain failure message '" + loginErrorMsg + "'.  "
            + "Page content was \n[" + content + "]\n", content.contains(loginErrorMsg));
    assertEquals(200, resp.getStatusLine().getStatusCode());
}