/**
  * Creates absolute request URI with full path from passed in context, honoring proxy if in play.
  */
 @Nonnull
 private URI getRequestURI(final HttpContext context) {
   final HttpClientContext clientContext = HttpClientContext.adapt(context);
   final HttpRequest httpRequest = clientContext.getRequest();
   try {
     URI uri;
     if (httpRequest instanceof HttpUriRequest) {
       uri = ((HttpUriRequest) httpRequest).getURI();
     } else {
       uri = URI.create(httpRequest.getRequestLine().getUri());
     }
     final RouteInfo routeInfo = clientContext.getHttpRoute();
     if (routeInfo != null) {
       if (routeInfo.getHopCount() == 1 && uri.isAbsolute()) {
         return uri;
       }
       HttpHost target = routeInfo.getHopTarget(0);
       return URIUtils.resolve(URI.create(target.toURI()), uri);
     } else {
       return uri;
     }
   } catch (Exception e) {
     log.warn("Could not create absolute request URI", e);
     return URI.create(clientContext.getTargetHost().toURI());
   }
 }
示例#2
0
  /**
   * Creates the CONNECT request for tunnelling. Called by {@link #createTunnelToTarget
   * createTunnelToTarget}.
   *
   * @param route the route to establish
   * @param context the context for request execution
   * @return the CONNECT request for tunnelling
   */
  protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers

    HttpHost target = route.getTargetHost();

    String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(target.getSchemeName());
      port = scheme.getDefaultPort();
    }

    StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));

    String authority = buffer.toString();
    ProtocolVersion ver = HttpProtocolParams.getVersion(params);
    HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);

    return req;
  }
示例#3
0
 public static boolean validateProxy(HttpHost p) {
   if (localAddr == null) {
     logger.error("cannot get local IP");
     return false;
   }
   boolean isReachable = false;
   Socket socket = null;
   try {
     socket = new Socket();
     socket.bind(new InetSocketAddress(localAddr, 0));
     InetSocketAddress endpointSocketAddr =
         new InetSocketAddress(p.getAddress().getHostAddress(), p.getPort());
     socket.connect(endpointSocketAddr, 3000);
     logger.debug(
         "SUCCESS - connection established! Local: "
             + localAddr.getHostAddress()
             + " remote: "
             + p);
     isReachable = true;
   } catch (IOException e) {
     logger.warn(
         "FAILRE - CAN not connect! Local: " + localAddr.getHostAddress() + " remote: " + p);
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e) {
         logger.warn("Error occurred while closing socket of validating proxy", e);
       }
     }
   }
   return isReachable;
 }
  public void init() {
    /*
    loadLiferayProperties();

    hostname = liferayProperties.getProperty(FFPORTAL_SERVER_HOSTNAME);
    port = liferayProperties.getProperty(FFPORTAL_SERVER_PORT);
    companyId = liferayProperties.getProperty(FFPORTAL_REPOSITORY_COMPANYID);
    loginGroupId = liferayProperties.getProperty(FFPORTAL_USER_GROUP_ID);
    loginEmail = liferayProperties.getProperty(FFPORTAL_USER_EMAIL);
    loginPassword = liferayProperties.getProperty(FFPORTAL_USER_PASSWORD);
    */
    targetHost = new HttpHost(hostname, Integer.valueOf(port), "http");
    PoolingClientConnectionManager cxMgr =
        new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);
    httpclient = new DefaultHttpClient(cxMgr);

    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(loginEmail, loginPassword));

    // Create AuthCache instance
    this.authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
  }
示例#5
0
    public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException {

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

      if (request.getFirstHeader("Authorization") != null) {
        // Using OAuth, leave as is
      } else if (request.getFirstHeader("X-No-Auth") != null) {
        // No auth required, leave as is
      } else {
        // If no auth scheme avaialble yet, try to initialize it preemptively
        if (authState.getAuthScheme() == null) {
          AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
          CredentialsProvider credsProvider =
              (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
          HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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");
            } else {
              authState.setAuthScheme(authScheme);
              authState.setCredentials(creds);
            }
          }
        }
      }
    }
示例#6
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      if (authState.getAuthScheme() != null) {
        return;
      }

      AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
      if (authScheme == null) {
        return;
      }

      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      Credentials creds =
          credsProvider.getCredentials(
              new AuthScope(targetHost.getHostName(), targetHost.getPort()));
      if (creds == null) {
        return;
      }

      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
示例#7
0
  static void testBasicAuth() throws ClientProtocolException, IOException {
    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("newuser", "tomcat"));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/simpleweb/protected");
    System.out.println(httpget.getURI());

    HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

    HttpEntity entity = response.getEntity();

    System.out.println(response.getStatusLine().getStatusCode());
    String charset = HttpclientTutorial.getResponseCharset(response);
    HttpclientTutorial.output(entity, charset);

    EntityUtils.consume(entity);
  }
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.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 (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
        CredentialsProvider credentialsProvider =
            (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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);
      }
    }
  /**
   * Run the query that has been set up in this instance. Next step would be to get the results with
   * {@link getQueryResult()}
   */
  public void doQuery() {
    DefaultHttpClient client = new DefaultHttpClient();

    client
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(_targetHost.getHostName(), _targetHost.getPort()),
            new UsernamePasswordCredentials(this.getAppid(), this.getAppid()));

    URI uri;
    try {
      String full_path = getQueryPath();
      String full_query = getUrlQuery();
      uri = new URI(AZURESEARCH_SCHEME, AZURESEARCH_AUTHORITY, full_path, full_query, null);
      // Bing and java URI disagree about how to represent + in query
      // parameters. This is what we have to do instead...
      uri =
          new URI(
              uri.getScheme()
                  + "://"
                  + uri.getAuthority()
                  + uri.getPath()
                  + "?"
                  + uri.getRawQuery().replace("+", "%2b"));

      // log.log(Level.WARNING, uri.toString());
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      return;
    }

    HttpGet get = new HttpGet(uri);

    get.addHeader("Accept", "application/xml");
    get.addHeader("Content-Type", "application/xml");

    try {
      _responsePost = client.execute(get);
      _resEntity = _responsePost.getEntity();

      if (this.getProcessHTTPResults()) {
        _rawResult = loadXMLFromStream(_resEntity.getContent());
        this.loadResultsFromRawResults();
      }

      // Adding an automatic HTTP Result to String really requires
      // Apache Commons IO. That would break
      // Android compatibility. I'm not going to do that unless I
      // re-implement IOUtils.
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    }
  }
 @Override
 protected HttpHost determineProxy(
     final HttpHost target, final HttpRequest request, final HttpContext context)
     throws HttpException {
   if (noProxyFor(target.getHostName())) {
     return null;
   }
   return proxies.get(target.getSchemeName());
 }
 /**
  * Instantiates a new digest authentication client wrapper.
  *
  * @param hostname the hostname
  * @param port the port
  * @param scheme the scheme
  * @param username the username
  * @param password the password
  */
 public DigestAuthenticationClientWrapper(
     String hostname, int port, String scheme, String username, String password) {
   // logger.trace("==== DigestAuthenticationHttpClientWrapper ENTRY ========");
   target = new HttpHost(hostname, port, scheme);
   credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(target.getHostName(), target.getPort()),
       new UsernamePasswordCredentials(username, password));
   logger.fine("==== DigestAuthenticationHttpClientWrapper EXIT ========");
 }
 public SocketAddress resolveRemoteAddress(final HttpRoute route) {
   HttpHost firsthop = route.getProxyHost();
   if (firsthop == null) {
     firsthop = route.getTargetHost();
   }
   String hostname = firsthop.getHostName();
   int port = firsthop.getPort();
   if (port < 0) {
     Scheme scheme = this.schemeRegistry.getScheme(firsthop);
     port = scheme.resolvePort(port);
   }
   return new InetSocketAddress(hostname, port);
 }
示例#13
0
 @Override
 public HttpParams setParameter(String name, Object value) {
   if (name.equals(ConnRouteParams.DEFAULT_PROXY)) {
     HttpHost host = (HttpHost) value;
     Proxy proxy = null;
     if (host != null) {
       proxy = new Proxy(HTTP, new InetSocketAddress(host.getHostName(), host.getPort()));
     }
     client.setProxy(proxy);
     return this;
   }
   throw new IllegalArgumentException(name);
 }
示例#14
0
 private static String getUrlAfterRedirects(HttpContext context) {
   String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL);
   if (lastRedirectUrl != null) return lastRedirectUrl;
   else {
     HttpUriRequest currentReq =
         (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
     HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
     String currentUrl =
         (currentReq.getURI().isAbsolute())
             ? currentReq.getURI().toString()
             : (currentHost.toURI() + currentReq.getURI());
     return currentUrl;
   }
 }
  @Test
  public void testAuthenticationUserinfoInRequestFailure() throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    HttpHost target = getServerHttp();
    HttpGet httpget = new HttpGet("http://*****:*****@" + target.toHostString() + "/");

    HttpResponse response = this.httpclient.execute(getServerHttp(), httpget);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
  }
 private HttpResponse forward(
     HttpClient httpclient,
     String verb,
     String uri,
     HttpServletRequest request,
     MultiValueMap<String, String> headers,
     MultiValueMap<String, String> params,
     InputStream requestEntity)
     throws Exception {
   Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
   URL host = RequestContext.getCurrentContext().getRouteHost();
   HttpHost httpHost = getHttpHost(host);
   uri = StringUtils.cleanPath(host.getPath() + uri);
   HttpRequest httpRequest;
   switch (verb.toUpperCase()) {
     case "POST":
       HttpPost httpPost = new HttpPost(uri + getQueryString());
       httpRequest = httpPost;
       httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PUT":
       HttpPut httpPut = new HttpPut(uri + getQueryString());
       httpRequest = httpPut;
       httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     case "PATCH":
       HttpPatch httpPatch = new HttpPatch(uri + getQueryString());
       httpRequest = httpPatch;
       httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
       break;
     default:
       httpRequest = new BasicHttpRequest(verb, uri + getQueryString());
       log.debug(uri + getQueryString());
   }
   try {
     httpRequest.setHeaders(convertHeaders(headers));
     log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
     HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
     this.helper.appendDebug(
         info,
         zuulResponse.getStatusLine().getStatusCode(),
         revertHeaders(zuulResponse.getAllHeaders()));
     return zuulResponse;
   } finally {
     // When HttpClient instance is no longer needed,
     // shut down the connection manager to ensure
     // immediate deallocation of all system resources
     // httpclient.getConnectionManager().shutdown();
   }
 }
示例#17
0
  /**
   * Define the Credentials
   *
   * @param httpClientBuilder
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url)
      throws DSSException {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry :
        authenticationMap.entrySet()) {

      final HttpHost httpHost = entry.getKey();
      final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
      credsProvider.setCredentials(
          new AuthScope(httpHost.getHostName(), httpHost.getPort()), usernamePasswordCredentials);
    }
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credsProvider, url);
    return httpClientBuilder;
  }
  public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context)
      throws HttpException {

    if (request == null) {
      throw new IllegalStateException("Request must not be null.");
    }

    // If we have a forced route, we can do without a target.
    HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams());
    if (route != null) return route;

    // If we get here, there is no forced route.
    // So we need a target to compute a route.

    if (target == null) {
      throw new IllegalStateException("Target host must not be null.");
    }

    final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams());
    final HttpHost proxy = ConnRouteParams.getDefaultProxy(request.getParams());

    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    // as it is typically used for TLS/SSL, we assume that
    // a layered scheme implies a secure connection
    final boolean secure = schm.isLayered();

    if (proxy == null) {
      route = new HttpRoute(target, local, secure);
    } else {
      route = new HttpRoute(target, local, proxy, secure);
    }
    return route;
  }
  /**
   * Tests that an abort called after a redirect has found a new host still aborts in the correct
   * place (while trying to get the new host's route, not while doing the subsequent request).
   */
  @Test
  public void testAbortAfterRedirectedRoute() throws Exception {
    final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    this.serverBootstrap.setHandlerMapper(reqistry);

    final CountDownLatch connLatch = new CountDownLatch(1);
    final CountDownLatch awaitLatch = new CountDownLatch(1);
    final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch);
    final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
    final CountDownLatch getLatch = new CountDownLatch(1);
    this.clientBuilder.setConnectionManager(conMan);
    final HttpContext context = new BasicHttpContext();
    final HttpGet httpget = new HttpGet("a");

    final HttpHost target = start();
    reqistry.register("*", new BasicRedirectService(target.getPort()));

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  final HttpHost host = new HttpHost("127.0.0.1", target.getPort());
                  httpclient.execute(host, httpget, context);
                } catch (final Throwable t) {
                  throwableRef.set(t);
                } finally {
                  getLatch.countDown();
                }
              }
            })
        .start();

    Assert.assertTrue(
        "should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));

    httpget.abort();

    Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
    Assert.assertTrue(
        "should be instanceof IOException, was: " + throwableRef.get(),
        throwableRef.get() instanceof IOException);
    Assert.assertTrue(
        "cause should be InterruptedException, was: " + throwableRef.get().getCause(),
        throwableRef.get().getCause() instanceof InterruptedException);
  }
示例#20
0
 public static String getRedirectedUrl(String url) {
   DefaultHttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   try {
     HttpContext context = new BasicHttpContext();
     HttpResponse response = client.execute(get, context);
     if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
       throw new IOException(response.getStatusLine().toString());
     HttpUriRequest currentReq =
         (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
     HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
     return currentHost.toURI() + currentReq.getURI();
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return url;
 }
示例#21
0
 /*  15:    */
 /*  16:    */ public static HttpHost getDefaultProxy(HttpParams params) /*  17:    */ {
   /*  18: 77 */ if (params == null) {
     /*  19: 78 */ throw new IllegalArgumentException("Parameters must not be null.");
     /*  20:    */ }
   /*  21: 80 */ HttpHost proxy = (HttpHost) params.getParameter("http.route.default-proxy");
   /*  22: 82 */ if ((proxy != null) && (NO_HOST.equals(proxy))) {
     /*  23: 84 */ proxy = null;
     /*  24:    */ }
   /*  25: 86 */ return proxy;
   /*  26:    */ }
示例#22
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      // If not auth scheme has been initialized yet
      if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
          authState.setAuthScheme(new BasicScheme());
          authState.setCredentials(creds);
        }
      }
    }
  public void process(final HttpRequest request, final HttpContext context)
      throws HttpException, IOException {

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

    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
      Credentials creds =
          credsProvider.getCredentials(
              new AuthScope(targetHost.getHostName(), targetHost.getPort()));
      if (creds == null) {
        throw new HttpException("No credentials for preemptive authentication");
      }
      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
  }
  @Override
  public synchronized HttpClient getHttpClient() {
    if (myHttpClient == null) {

      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);

      // @formatter:off
      RequestConfig defaultRequestConfig =
          RequestConfig.custom()
              .setSocketTimeout(mySocketTimeout)
              .setConnectTimeout(myConnectTimeout)
              .setConnectionRequestTimeout(myConnectionRequestTimeout)
              .setStaleConnectionCheckEnabled(true)
              .setProxy(myProxy)
              .build();

      HttpClientBuilder builder =
          HttpClients.custom()
              .setConnectionManager(connectionManager)
              .setDefaultRequestConfig(defaultRequestConfig)
              .disableCookieManagement();

      if (myProxy != null
          && StringUtils.isNotBlank(myProxyUsername)
          && StringUtils.isNotBlank(myProxyPassword)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(myProxy.getHostName(), myProxy.getPort()),
            new UsernamePasswordCredentials(myProxyUsername, myProxyPassword));
        builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        builder.setDefaultCredentialsProvider(credsProvider);
      }

      myHttpClient = builder.build();
      // @formatter:on

    }

    return myHttpClient;
  }
示例#25
0
  @Override
  public String toString() {

    String re =
        String.format(
            "host: %15s >> %5dms >> success: %-3.2f%% >> borrow: %d",
            httpHost.getAddress().getHostAddress(),
            responseTime,
            successNum * 100.0 / borrowNum,
            borrowNum);
    return re;
  }
示例#26
0
  private void updateAuthState(
      final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) {

    if (!authState.isValid()) {
      return;
    }

    String hostname = host.getHostName();
    int port = host.getPort();
    if (port < 0) {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(host);
      port = scheme.getDefaultPort();
    }

    AuthScheme authScheme = authState.getAuthScheme();
    AuthScope authScope =
        new AuthScope(hostname, port, authScheme.getRealm(), authScheme.getSchemeName());

    if (this.log.isDebugEnabled()) {
      this.log.debug("Authentication scope: " + authScope);
    }
    Credentials creds = authState.getCredentials();
    if (creds == null) {
      creds = credsProvider.getCredentials(authScope);
      if (this.log.isDebugEnabled()) {
        if (creds != null) {
          this.log.debug("Found credentials");
        } else {
          this.log.debug("Credentials not found");
        }
      }
    } else {
      if (authScheme.isComplete()) {
        this.log.debug("Authentication failed");
        creds = null;
      }
    }
    authState.setAuthScope(authScope);
    authState.setCredentials(creds);
  }
  // non-javadoc, see interface ClientConnectionOperator
  public void updateSecureConnection(
      OperatedClientConnection conn, HttpHost target, HttpContext context, HttpParams params)
      throws IOException {

    if (conn == null) {
      throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
      throw new IllegalArgumentException("Target host must not be null.");
    }
    // @@@ is context allowed to be null?
    if (params == null) {
      throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (!conn.isOpen()) {
      throw new IllegalArgumentException("Connection must be open.");
    }

    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    if (!(schm.getSocketFactory() instanceof LayeredSocketFactory)) {
      throw new IllegalArgumentException(
          "Target scheme (" + schm.getName() + ") must have layered socket factory.");
    }

    final LayeredSocketFactory lsf = (LayeredSocketFactory) schm.getSocketFactory();
    final Socket sock;
    try {
      sock =
          lsf.createSocket(
              conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), true);
    } catch (ConnectException ex) {
      throw new HttpHostConnectException(target, ex);
    }
    prepareSocket(sock, context, params);
    conn.update(sock, target, lsf.isSecure(sock), params);
    // @@@ error handling: close the layered socket in case of exception?

  } // updateSecureConnection
 @Override
 public CloseableHttpResponse execute(final HttpHost target, final HttpRequest request)
     throws IOException, ClientProtocolException {
   return HttpClientTracing.execute(
       target.toURI().toString(),
       traceHeaderName,
       request,
       new HttpClientTracing.Executor<CloseableHttpResponse>() {
         @Override
         public CloseableHttpResponse execute() throws IOException {
           return client.execute(target, request);
         }
       });
 }
示例#29
0
 private void zza(zzaf zzaf1, HttpHost httphost, zzi zzi1, zzl zzl1)
 {
     zzaf1.zzk("_bs", zzi1.toString());
     zzaf1.zzk("_cs", zzl1.toString());
     zzi1 = zzaf1.zzgx();
     if (TextUtils.isEmpty(zzi1))
     {
         return;
     }
     if (httphost == null)
     {
         try
         {
             httphost = new URL("https://ssl.google-analytics.com");
             httphost = new HttpHost(httphost.getHost(), httphost.getPort(), httphost.getProtocol());
         }
         // Misplaced declaration of an exception variable
         catch (zzaf zzaf1)
         {
             return;
         }
     }
     zza(((String) (zzi1)), httphost, 1, zzaf1, zzl.zzBF);
 }
示例#30
0
  /**
   * Creates new instance of {@code SSLIOSession} class.
   *
   * @param session I/O session to be decorated with the TLS/SSL capabilities.
   * @param sslMode SSL mode (client or server)
   * @param host original host (applicable in client mode only)
   * @param sslContext SSL context to use for this I/O session.
   * @param handler optional SSL setup handler. May be {@code null}.
   * @param bufferManagementStrategy buffer management strategy
   */
  public SSLIOSession(
      final IOSession session,
      final SSLMode sslMode,
      final HttpHost host,
      final SSLContext sslContext,
      final SSLSetupHandler handler,
      final SSLBufferManagementStrategy bufferManagementStrategy) {
    super();
    Args.notNull(session, "IO session");
    Args.notNull(sslContext, "SSL context");
    Args.notNull(bufferManagementStrategy, "Buffer management strategy");
    this.session = session;
    this.sslMode = sslMode;
    this.appEventMask = session.getEventMask();
    this.channel = new InternalByteChannel();
    this.handler = handler;

    // Override the status buffer interface
    this.session.setBufferStatus(this);

    if (this.sslMode == SSLMode.CLIENT && host != null) {
      this.sslEngine = sslContext.createSSLEngine(host.getHostName(), host.getPort());
    } else {
      this.sslEngine = sslContext.createSSLEngine();
    }

    // Allocate buffers for network (encrypted) data
    final int netBuffersize = this.sslEngine.getSession().getPacketBufferSize();
    this.inEncrypted = bufferManagementStrategy.constructBuffer(netBuffersize);
    this.outEncrypted = bufferManagementStrategy.constructBuffer(netBuffersize);

    // Allocate buffers for application (unencrypted) data
    final int appBuffersize = this.sslEngine.getSession().getApplicationBufferSize();
    this.inPlain = bufferManagementStrategy.constructBuffer(appBuffersize);
    this.outPlain = bufferManagementStrategy.constructBuffer(appBuffersize);
  }