Java 类org.apache.http.protocol.HttpCoreContext 实例源码

项目:Reer    文件:HttpClientConfigurer.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
项目:http-fetcher    文件:SimpleHttpFetcher.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
项目:aws-request-signing-apache-interceptor    文件:AWSRequestSigningApacheInterceptorTest.java   
@Test
public void testSimpleSigner() throws Exception {
    HttpEntityEnclosingRequest request =
            new BasicHttpEntityEnclosingRequest("GET", "/query?a=b");
    request.setEntity(new StringEntity("I'm an entity"));
    request.addHeader("foo", "bar");
    request.addHeader("content-length", "0");

    HttpCoreContext context = new HttpCoreContext();
    context.setTargetHost(HttpHost.create("localhost"));

    createInterceptor().process(request, context);

    assertEquals("bar", request.getFirstHeader("foo").getValue());
    assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
    assertNull(request.getFirstHeader("content-length"));
}
项目:aws-request-signing-apache-interceptor    文件:AWSRequestSigningApacheInterceptorTest.java   
@Test
public void testEncodedUriSigner() throws Exception {
    HttpEntityEnclosingRequest request =
            new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b");
    request.setEntity(new StringEntity("I'm an entity"));
    request.addHeader("foo", "bar");
    request.addHeader("content-length", "0");

    HttpCoreContext context = new HttpCoreContext();
    context.setTargetHost(HttpHost.create("localhost"));

    createInterceptor().process(request, context);

    assertEquals("bar", request.getFirstHeader("foo").getValue());
    assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
    assertNull(request.getFirstHeader("content-length"));
    assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue());
}
项目:cyberduck    文件:S3HttpRequestRetryHandler.java   
@Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
    if(super.retryRequest(exception, executionCount, context)) {
        final Object attribute = context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if(attribute instanceof HttpUriRequest) {
            final HttpUriRequest method = (HttpUriRequest) attribute;
            log.warn(String.format("Retrying request %s", method));
            try {
                // Build the authorization string for the method.
                authorizer.authorizeHttpRequest(method, context, null);
                return true;
            }
            catch(ServiceException e) {
                log.warn("Unable to generate updated authorization string for retried request", e);
            }
        }
    }
    return false;
}
项目:CurseSync    文件:CurseAPI.java   
@Nullable
private String getModSlug0(int id)
{
    try
    {
        log.debug("Getting mod slug from server...");
        URI uri = getURI(CURSEFORGE_URL, String.format(PROJECT_PATH, id), null);
        HttpGet request = new HttpGet(uri.toURL().toString());
        HttpContext context = new BasicHttpContext();
        HttpResponse response = http.execute(request, context);
        EntityUtils.consume(response.getEntity());
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
        Splitter splitter = Splitter.on('/').omitEmptyStrings();
        List<String> pathParts = splitter.splitToList(currentUrl);
        return pathParts.get(pathParts.size() - 1);
    }
    catch (Exception e)
    {
        log.error("Failed to perform request from CurseForge site.", e);
        return null;
    }
}
项目:purecloud-iot    文件:DefaultClientConnectionReuseStrategy.java   
@Override
public boolean keepAlive(final HttpResponse response, final HttpContext context) {

    final HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    if (request != null) {
        final Header[] connHeaders = request.getHeaders(HttpHeaders.CONNECTION);
        if (connHeaders.length != 0) {
            final TokenIterator ti = new BasicTokenIterator(new BasicHeaderIterator(connHeaders, null));
            while (ti.hasNext()) {
                final String token = ti.nextToken();
                if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
                    return false;
                }
            }
        }
    }
    return super.keepAlive(response, context);
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testPreemptiveTargetAndProxyAuth() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNotNull(this.targetState.getAuthScheme());
    Assert.assertSame(this.creds1, this.targetState.getCredentials());
    Assert.assertNotNull(this.proxyState.getAuthScheme());
    Assert.assertSame(this.creds2, this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testCredentialsProviderNotSet() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, null);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testAuthCacheNotSet() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);
    context.setAttribute(HttpClientContext.AUTH_CACHE, null);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testAuthCacheEmpty() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testNoMatchingCredentials() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    this.credProvider.clear();

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testCookiesForConnectRequest() throws Exception {
    final HttpRequest request = new BasicHttpRequest("CONNECT", "www.somedomain.com");

    final HttpRoute route = new HttpRoute(this.target, null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(0, headers1.length);
    final Header[] headers2 = request.getHeaders(SM.COOKIE2);
    Assert.assertNotNull(headers2);
    Assert.assertEquals(0, headers2.length);
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testNoCookieStore() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpRoute route = new HttpRoute(this.target, null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, null);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(0, headers1.length);
    final Header[] headers2 = request.getHeaders(SM.COOKIE2);
    Assert.assertNotNull(headers2);
    Assert.assertEquals(0, headers2.length);
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testNoCookieSpecRegistry() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpRoute route = new HttpRoute(this.target, null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, null);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(0, headers1.length);
    final Header[] headers2 = request.getHeaders(SM.COOKIE2);
    Assert.assertNotNull(headers2);
    Assert.assertEquals(0, headers2.length);
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testNoTargetHost() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpRoute route = new HttpRoute(this.target, null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, null);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(0, headers1.length);
    final Header[] headers2 = request.getHeaders(SM.COOKIE2);
    Assert.assertNotNull(headers2);
    Assert.assertEquals(0, headers2.length);
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testNoHttpConnection() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, null);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(0, headers1.length);
    final Header[] headers2 = request.getHeaders(SM.COOKIE2);
    Assert.assertNotNull(headers2);
    Assert.assertEquals(0, headers2.length);
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testAddCookiesUsingExplicitCookieSpec() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final RequestConfig config = RequestConfig.custom()
        .setCookieSpec(CookieSpecs.NETSCAPE).build();
    final HttpRoute route = new HttpRoute(this.target, null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final CookieSpec cookieSpec = context.getCookieSpec();
    Assert.assertTrue(cookieSpec instanceof NetscapeDraftSpec);

    final Header[] headers1 = request.getHeaders(SM.COOKIE);
    Assert.assertNotNull(headers1);
    Assert.assertEquals(1, headers1.length);
    Assert.assertEquals("name1=value1; name2=value2", headers1[0].getValue());
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testAuthScopeRemotePortWhenDirect() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/stuff");

    this.target = new HttpHost("localhost.local");
    final HttpRoute route = new HttpRoute(new HttpHost("localhost.local", 1234), null, false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final CookieOrigin cookieOrigin = context.getCookieOrigin();
    Assert.assertNotNull(cookieOrigin);
    Assert.assertEquals(this.target.getHostName(), cookieOrigin.getHost());
    Assert.assertEquals(1234, cookieOrigin.getPort());
    Assert.assertEquals("/stuff", cookieOrigin.getPath());
    Assert.assertFalse(cookieOrigin.isSecure());
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testAuthDefaultHttpPortWhenProxy() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/stuff");

    this.target = new HttpHost("localhost.local");
    final HttpRoute route = new HttpRoute(
            new HttpHost("localhost.local", 80), null, new HttpHost("localhost", 8888), false);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final CookieOrigin cookieOrigin = context.getCookieOrigin();
    Assert.assertNotNull(cookieOrigin);
    Assert.assertEquals(this.target.getHostName(), cookieOrigin.getHost());
    Assert.assertEquals(80, cookieOrigin.getPort());
    Assert.assertEquals("/stuff", cookieOrigin.getPath());
    Assert.assertFalse(cookieOrigin.isSecure());
}
项目:purecloud-iot    文件:TestRequestAddCookies.java   
@Test
public void testAuthDefaultHttpsPortWhenProxy() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/stuff");

    this.target = new HttpHost("localhost", -1, "https");
    final HttpRoute route = new HttpRoute(
            new HttpHost("localhost", 443, "https"), null,
            new HttpHost("localhost", 8888), true, TunnelType.TUNNELLED, LayerType.LAYERED);

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);

    final HttpRequestInterceptor interceptor = new RequestAddCookies();
    interceptor.process(request, context);

    final CookieOrigin cookieOrigin = context.getCookieOrigin();
    Assert.assertNotNull(cookieOrigin);
    Assert.assertEquals(this.target.getHostName(), cookieOrigin.getHost());
    Assert.assertEquals(443, cookieOrigin.getPort());
    Assert.assertEquals("/stuff", cookieOrigin.getPath());
    Assert.assertTrue(cookieOrigin.isSecure());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Before
public void setUp() throws Exception {
    this.defltAuthStrategy = Mockito.mock(AuthenticationStrategy.class);
    this.authState = new AuthState();
    this.authScheme = Mockito.mock(ContextAwareAuthScheme.class);
    Mockito.when(this.authScheme.getSchemeName()).thenReturn("Basic");
    Mockito.when(this.authScheme.isComplete()).thenReturn(Boolean.TRUE);
    this.context = new BasicHttpContext();
    this.defaultHost = new HttpHost("localhost", 80);
    this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost);
    this.credentials = Mockito.mock(Credentials.class);
    this.credentialsProvider = new BasicCredentialsProvider();
    this.credentialsProvider.setCredentials(AuthScope.ANY, this.credentials);
    this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
    this.authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory())
        .register("ntlm", new NTLMSchemeFactory()).build();
    this.context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
    this.authCache = Mockito.mock(AuthCache.class);
    this.context.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache);
    this.httpAuthenticator = new HttpAuthenticator();
}
项目:purecloud-iot    文件:TestRedirects.java   
@Override
public void handle(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    final HttpInetConnection conn = (HttpInetConnection) context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
    String localhost = conn.getLocalAddress().getHostName();
    if (localhost.equals("127.0.0.1")) {
        localhost = "localhost";
    }
    final int port = conn.getLocalPort();
    final String uri = request.getRequestLine().getUri();
    if (uri.equals("/oldlocation/")) {
        response.setStatusCode(this.statuscode);
        response.addHeader(new BasicHeader("Location",
                "http://" + localhost + ":" + port + "/newlocation/"));
        response.addHeader(new BasicHeader("Connection", "close"));
    } else if (uri.equals("/newlocation/")) {
        response.setStatusCode(HttpStatus.SC_OK);
        final StringEntity entity = new StringEntity("Successful redirect");
        response.setEntity(entity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
    }
}
项目:fcrepo-java-client    文件:FcrepoHttpClientBuilder.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    final AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
    // If no auth scheme available yet, try to initialize it
    // preemptively
    if (authState.getAuthScheme() == null) {
        final CredentialsProvider credsProvider = (CredentialsProvider)
                context.getAttribute(HttpClientContext.CREDS_PROVIDER);
        final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        final Credentials creds = credsProvider.getCredentials(authScope);
        if (creds == null) {
            LOGGER.debug("Cannot initiate preemtive authentication, Credentials not found!");
        }
        authState.update(new BasicScheme(), creds);
    }
}
项目:Java-Deserialization-Exploit    文件:HttpFileServer.java   
public void handle(
        final HttpRequest request,
        final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {

    String target = request.getRequestLine().getUri();
    final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
    HttpCoreContext coreContext = HttpCoreContext.adapt(context);
    HttpConnection conn = coreContext.getConnection(HttpConnection.class);
    response.setStatusCode(HttpStatus.SC_OK);
    FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null));
    response.setEntity(body);
    System.out.println(conn + ": serving file " + file.getPath());

    new Thread() {
        @Override
        public void run() {
            System.out.println("Stopping HTTP Server...");
            server.stop();
        }
    }.start();
}
项目:activemq-artemis    文件:UriStrategy.java   
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
   AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

   // If no auth scheme available yet, try to initialize it preemptively
   if (authState.getAuthScheme() == null) {
      AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
      CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
      if (authScheme != null) {
         Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
         if (creds == null) {
            throw new HttpException("No credentials for preemptive authentication");
         }
         authState.update(authScheme, creds);
      }
   }
}
项目:ache    文件:SimpleHttpFetcher.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
项目:oap    文件:NioHandlerAdapter.java   
@Override
public void handle( final HttpRequest httpRequest, final HttpAsyncExchange httpAsyncExchange,
                    final HttpContext httpContext ) throws HttpException, IOException {

   LOGGER.trace( "handling [{}]", httpRequest );

   final HttpInetConnection connection = ( HttpInetConnection ) httpContext
      .getAttribute( HttpCoreContext.HTTP_CONNECTION );
   final InetAddress remoteAddress = connection.getRemoteAddress();
   final HttpResponse response = httpAsyncExchange.getResponse();

   final String httpContextProtocol = String.valueOf( httpContext.getAttribute( "protocol" ) );

   if( Protocol.LOCAL.equals( this.protocol ) && !Inet.isLocalAddress( remoteAddress ) ) {
      response.setStatusCode( HTTP_FORBIDDEN );
   } else {
      Request request = new Request( httpRequest, new Context( location, remoteAddress, httpContextProtocol ) );
      handler.handle( request, new Response( response, corsPolicy.getCors( request ) ) );
   }

   httpAsyncExchange.submitResponse();
}
项目:cleverbus    文件:CloseableHttpComponentsMessageSender.java   
/**
 * {@inheritDoc}
 */
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext
                .CREDS_PROVIDER);
        HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        Credentials creds = credsProvider.getCredentials(new AuthScope(host.getHostName(), host.getPort()));
        if (creds == null) {
            throw new HttpException("No credentials for preemptive authentication");
        }
        authState.update(new BasicScheme(), creds);
    }
}
项目:MiniWeb    文件:ReflectionControllerTest.java   
@Test
public void testIntQueryParam() throws Exception {
    MyController controller = new MyController();

    ReflectionControllerRequestHandler handler = new ControllerBuilder(new GsonBuilder().create())
            .addController(controller)
            .withPathPrefix("/")
            .create();


    HttpCoreContext context = HttpCoreContext.create();
    HttpRequest request = new BasicHttpRequest("GET", "/stuff/testInt?apples=5&bananas=4.3");
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ""));

    handler.handle(request, response, context);

    assertTrue(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
}
项目:MiniWeb    文件:ReflectionControllerTest.java   
@Test
public void testJsonBody() throws Exception {
    MyController controller = new MyController();

    ReflectionControllerRequestHandler handler = new ControllerBuilder(new GsonBuilder().create())
            .addController(controller)
            .withPathPrefix("/")
            .create();


    HttpCoreContext context = HttpCoreContext.create();
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("PUT", "/stuff/putthis");
    request.setHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity("{ \"name\": \"paul\" }"));


    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ""));

    handler.handle(request, response, context);

    assertTrue(response.getStatusLine().getStatusCode() == 200);
    String resultBody = EntityUtils.toString(response.getEntity());
    assertTrue("itworked".equals(resultBody));
}
项目:MiniWeb    文件:ReflectionControllerTest.java   
@Test
public void testJsonResponse() throws Exception {
    MyController controller = new MyController();

    ReflectionControllerRequestHandler handler = new ControllerBuilder(new GsonBuilder().create())
            .addController(controller)
            .withPathPrefix("/")
            .create();


    HttpCoreContext context = HttpCoreContext.create();
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", "/stuff/getjson");
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ""));

    handler.handle(request, response, context);

    assertTrue(response.getStatusLine().getStatusCode() == 200);
    String resultBody = EntityUtils.toString(response.getEntity());

    Gson gson = new GsonBuilder().create();
    MyController.TestObj retobj = gson.fromJson(resultBody, MyController.TestObj.class);

    assertNotNull(retobj);
    assertEquals("Jack", retobj.name);
}
项目:hypersocket-framework    文件:HttpUtilsImpl.java   
@Override
  public Socket createSocket(final HttpContext context) throws IOException {

HttpHost currentHost= (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    if(systemConfigurationService.getBooleanValue("proxy.enabled")
            && !checkProxyBypass(currentHost.getHostName()) 
            && !checkProxyBypass(currentHost.getAddress())) {
       InetSocketAddress socksaddr = new InetSocketAddress(systemConfigurationService.getValue("proxy.host"),
            systemConfigurationService.getIntValue("proxy.port"));
       Proxy proxy = new Proxy(Proxy.Type.valueOf(systemConfigurationService.getValue("proxy.type")), socksaddr);  
       return new Socket(proxy);
    } else {
        return new Socket();
    }
  }
项目:hypersocket-framework    文件:HttpUtilsImpl.java   
@Override
  public Socket createSocket(final HttpContext context) throws IOException {

HttpHost currentHost= (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    if(systemConfigurationService.getBooleanValue("proxy.enabled")
            && !checkProxyBypass(currentHost.getHostName()) 
            && !checkProxyBypass(currentHost.getAddress())) {
       InetSocketAddress socksaddr = new InetSocketAddress(systemConfigurationService.getValue("proxy.host"),
            systemConfigurationService.getIntValue("proxy.port"));
       Proxy proxy = new Proxy(Proxy.Type.valueOf(systemConfigurationService.getValue("proxy.type")), socksaddr);  
       return new Socket(proxy);
    } else {
        return new Socket();
    }
  }
项目:stdlib    文件:PreemptiveBearerAuthInterceptor.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException
{
    final AuthState state = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    // Try to initialise an auth scheme if one is not already set
    if (state.getAuthScheme() == null)
    {
        CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
        HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

        final Credentials credentials = credentialsProvider.getCredentials(new AuthScope(host));

        if (credentials == null)
            throw new HttpException("No credentials for preemptive authentication against: " + host);
        else
            state.update(new BearerAuthSchemeProvider().create(context), credentials);
    }
}
项目:stdlib    文件:PreemptiveBasicAuthInterceptor.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException
{
    final AuthState state = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    // Try to initialise an auth scheme if one is not already set
    if (state.getAuthScheme() == null)
    {
        CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
        HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

        final Credentials credentials = credentialsProvider.getCredentials(new AuthScope(host));

        if (credentials == null)
            throw new HttpException("No credentials for preemptive authentication against: " + host);
        else
            state.update(new BasicScheme(), credentials);
    }
}
项目:cyberduck    文件:S3HttpRequestRetryHandlerTest.java   
@Test
public void testRetryRequest() throws Exception {
    final S3HttpRequestRetryHandler h = new S3HttpRequestRetryHandler(new JetS3tRequestAuthorizer() {
        @Override
        public void authorizeHttpRequest(final HttpUriRequest httpUriRequest, final HttpContext httpContext, final String s) throws ServiceException {
            //
        }
    }, 1);
    final HttpClientContext context = new HttpClientContext();
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, new HttpHead());
    assertTrue(h.retryRequest(new SSLException(new SocketException("Broken pipe")), 1, context));
}
项目:Precedented    文件:WatsonRank.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException {
    final AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    if (authState.getAuthScheme() == null) {
        final CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(HttpClientContext.CREDS_PROVIDER);
        final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        final Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(),
                targetHost.getPort()));
        if (creds == null) {
            throw new HttpException("No creds provided for preemptive auth.");
        }
        authState.update(new BasicScheme(), creds);
    }
}
项目:OHMS    文件:HttpUtil.java   
/**
 * Execute post.
 *
 * @param <T> the generic type
 * @param url the url
 * @return the http response
 */
public static HttpResponse executePost( final String url )
{
    // check that url is not null
    if ( StringUtils.isBlank( url ) )
    {
        logger.error( "In executePost, URL is either null or blank." );
        return null;
    }

    HttpResponse httpResponse = null;
    HttpClient httpClient = HttpUtil.getHttpClient();
    HttpPost httpPost = new HttpPost( url );

    // set headers
    httpPost.setHeader( HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON );

    // create a httpContext
    HttpContext httpContext = new BasicHttpContext();

    try
    {
        httpResponse = httpClient.execute( httpPost, httpContext );
        StatusLine statusLine = httpResponse.getStatusLine();
        HttpUriRequest httpUriRequest = (HttpUriRequest) httpContext.getAttribute( HttpCoreContext.HTTP_REQUEST );
        logger.debug( "In executePost, Response {} ({}) received for {} on {}.", statusLine.getStatusCode(),
                      statusLine.getReasonPhrase(), httpUriRequest.getMethod(),
                      httpUriRequest.getURI().toString() );
        return httpResponse;
    }
    catch ( IOException e )
    {
        logger.error( "In executePost, error while invoking POST on {}.", url, e );
        return httpResponse;
    }
}
项目:purecloud-iot    文件:CachingExec.java   
private CloseableHttpResponse handleCacheHit(
        final HttpRoute route,
        final HttpRequestWrapper request,
        final HttpClientContext context,
        final HttpExecutionAware execAware,
        final HttpCacheEntry entry) throws IOException, HttpException {
    final HttpHost target = context.getTargetHost();
    recordCacheHit(target, request);
    CloseableHttpResponse out = null;
    final Date now = getCurrentDate();
    if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
        log.debug("Cache hit");
        out = generateCachedResponse(request, context, entry, now);
    } else if (!mayCallBackend(request)) {
        log.debug("Cache entry not suitable but only-if-cached requested");
        out = generateGatewayTimeout(context);
    } else if (!(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED
            && !suitabilityChecker.isConditional(request))) {
        log.debug("Revalidating cache entry");
        return revalidateCacheEntry(route, request, context, execAware, entry, now);
    } else {
        log.debug("Cache entry not usable; calling backend");
        return callBackend(route, request, context, execAware);
    }
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    context.setAttribute(HttpCoreContext.HTTP_RESPONSE, out);
    context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE);
    return out;
}