org.apache.http.protocol.HttpCoreContext Java Examples

The following examples show how to use org.apache.http.protocol.HttpCoreContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SavingConnectionDetailsHttpResponseInterceptor.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public void process(HttpResponse response, HttpContext context)
{
    ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection) context
            .getAttribute(HttpCoreContext.HTTP_CONNECTION);
    // Connection may be stale, when no response body is returned
    if (routedConnection.isOpen() && (response.getEntity() != null || !routedConnection.isStale()))
    {
        SSLSession sslSession = routedConnection.getSSLSession();
        boolean secure = sslSession != null;
        ConnectionDetails connectionDetails = new ConnectionDetails();
        connectionDetails.setSecure(secure);
        if (secure)
        {
            connectionDetails.setSecurityProtocol(sslSession.getProtocol());
        }
        httpTestContext.putConnectionDetails(connectionDetails);
    }
}
 
Example #2
Source File: CookiesPathTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void login(String requestURI, CookieStore cookieStore) throws IOException {
    HttpCoreContext httpContext = new HttpCoreContext();
    HttpGet request = new HttpGet(requestURI);

    // send an initial request, we are redirected to login page
    String entityContent;
    try (CloseableHttpResponse response = sendRequest(request, cookieStore, httpContext)) {
        entityContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    }

    // send credentials to login form
    HttpPost post = new HttpPost(ActionURIUtils.getActionURIFromPageSource(entityContent));
    List<NameValuePair> params = new LinkedList<>();
    params.add(new BasicNameValuePair("username", "foo"));
    params.add(new BasicNameValuePair("password", "password"));

    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setEntity(new UrlEncodedFormEntity(params));

    try (CloseableHttpResponse response = sendRequest(post, cookieStore, httpContext)) {
        Assert.assertThat("Expected successful login.", response.getStatusLine().getStatusCode(), is(equalTo(200)));
    }
}
 
Example #3
Source File: CookiesPathTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private CookieStore getCorrectCookies(String uri) throws IOException {
    CookieStore cookieStore = new BasicCookieStore();

    HttpGet request = new HttpGet(uri);
    try (CloseableHttpResponse response = sendRequest(request, new BasicCookieStore(), new HttpCoreContext())) {
        for (org.apache.http.Header h: response.getHeaders("Set-Cookie")) {
            if (h.getValue().contains(AuthenticationSessionManager.AUTH_SESSION_ID)) {
                cookieStore.addCookie(parseCookie(h.getValue(), AuthenticationSessionManager.AUTH_SESSION_ID));
            } else if (h.getValue().contains(KC_RESTART)) {
                cookieStore.addCookie(parseCookie(h.getValue(), KC_RESTART));
            }
        }
    }

    return cookieStore;
}
 
Example #4
Source File: TwitterSecurityTest.java    From streams with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcess() throws Exception {
  URI testURI = new URIBuilder()
      .setPath("/1/statuses/update.json")
      .setParameter("include_entities", "true")
      .build();
  HttpPost testRequest = new HttpPost(testURI);
  testRequest.setEntity(new StringEntity("status="+security.encode("Hello Ladies + Gentlemen, a signed OAuth request!")));
  HttpHost host = new HttpHost("api.twitter.com", -1, "https");
  HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(testRequest, host);
  TwitterOAuthConfiguration testOauthConfiguration = new TwitterOAuthConfiguration()
      .withConsumerKey("xvz1evFS4wEEPTGEFPHBog")
      .withConsumerSecret("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw")
      .withAccessToken("370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb")
      .withAccessTokenSecret("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE");
  TwitterOAuthRequestInterceptor interceptor = Mockito.spy(new TwitterOAuthRequestInterceptor(testOauthConfiguration));
  Mockito.when(interceptor.generateNonce()).thenReturn("kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg");
  Mockito.when(interceptor.generateTimestamp()).thenReturn("1318622958");
  interceptor.process(wrapper, new HttpCoreContext());
  assertEquals(1, wrapper.getHeaders("Authorization").length);
  String actual = wrapper.getFirstHeader("Authorization").getValue();
  String expected = "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\"";
  assertEquals(expected, actual);
}
 
Example #5
Source File: UriStrategy.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@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);
      }
   }
}
 
Example #6
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: WingtipsApacheHttpClientInterceptorTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void process_response_closes_span_no_matter_what() {

    // given
    Span spanMock = mock(Span.class);
    httpContext = spy(httpContext);
    httpContext.setAttribute(SPAN_TO_CLOSE_HTTP_CONTEXT_ATTR_KEY, spanMock);
    RuntimeException expectedEx = new RuntimeException("boom");
    doThrow(expectedEx).when(httpContext).getAttribute(HttpCoreContext.HTTP_REQUEST);

    // when
    Throwable ex = catchThrowable(() -> interceptor.process(responseMock, httpContext));

    // then
    assertThat(ex).isSameAs(expectedEx);
    verify(httpContext).getAttribute(HttpCoreContext.HTTP_REQUEST);
    verify(spanMock).close();
}
 
Example #8
Source File: S3HttpRequestRetryHandler.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: AWSRequestSigningApacheInterceptorTest.java    From aws-request-signing-apache-interceptor with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: AWSRequestSigningApacheInterceptorTest.java    From aws-request-signing-apache-interceptor with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #11
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSaveConnectionDetailsForSecuredConnectionAndDoNotCheckStalenessForResponsesWithEntity()
{
    String protocol = "TLSv1.3";
    SSLSession sslSession = mock(SSLSession.class);
    when(sslSession.getProtocol()).thenReturn(protocol);
    HttpContext context = mock(HttpContext.class);
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    when(connection.isOpen()).thenReturn(true);
    when(connection.getSSLSession()).thenReturn(sslSession);
    HttpResponse response = mock(HttpResponse.class);
    when(response.getEntity()).thenReturn(mock(HttpEntity.class));
    interceptor.process(response, context);
    verify(httpTestContext).putConnectionDetails(argThat(connectionDetails -> connectionDetails.isSecure()
            && protocol.equals(connectionDetails.getSecurityProtocol())));
    verify(connection, never()).isStale();
}
 
Example #12
Source File: FutureCallbackWrapper.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
private void finishSpan(@Nullable Exception e) {
    // start by reading the volatile field
    final Span localSpan = span;
    try {
        if (context != null) {
            Object responseObject = context.getAttribute(HttpCoreContext.HTTP_RESPONSE);
            if (responseObject instanceof HttpResponse) {
                StatusLine statusLine = ((HttpResponse) responseObject).getStatusLine();
                if (statusLine != null) {
                    span.getContext().getHttp().withStatusCode(statusLine.getStatusCode());
                }
            }
        }
        localSpan.captureException(e);
    } finally {
        localSpan.end();
    }
}
 
Example #13
Source File: AbstractODataRouteTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected String getRealRefServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest)httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost)httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    return currentReq.getURI().isAbsolute() ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
}
 
Example #14
Source File: Olingo4IntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private String getRealServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());

    return currentUrl;
}
 
Example #15
Source File: HttpClientConnectionManagementLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
// @Ignore
// 5.1
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException {
    final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
            final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                final HeaderElement he = it.nextElement();
                final String param = he.getName();
                final String value = he.getValue();
                if ((value != null) && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            if ("localhost".equalsIgnoreCase(target.getHostName())) {
                return 10 * 1000;
            } else {
                return 5 * 1000;
            }
        }

    };
    client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build();
    client.execute(get1);
    client.execute(get2);
}
 
Example #16
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
Example #17
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSaveNoConnectionDetailsIfConnectionClosed()
{
    HttpContext context = mock(HttpContext.class);
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(connection.isOpen()).thenReturn(Boolean.FALSE);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    intercept(context);
    verifyNoInteractions(httpTestContext);
    verify(connection, never()).isStale();
}
 
Example #18
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected void storeHeadersSent(HttpResponse response, HttpContext context) {
    if (context instanceof HttpCoreContext) {
        Header[] headersSent = ((HttpCoreContext)context).getRequest().getAllHeaders();
        for (Header header : headersSent) {
            response.addRequestHeader(header.getName(), header.getValue());
        }
    }
}
 
Example #19
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
protected HttpContext createContext(HttpResponse response) {
    HttpContext localContext = new HttpCoreContext();
    CookieStore store = response.getCookieStore();
    if (store != null) {
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, store);
    }
    return localContext;
}
 
Example #20
Source File: HttpUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 重试策略.
 */
private HttpRequestRetryHandler retryPolicy() {
    return (IOException exception, int executionCount, HttpContext context) -> {
        // Do not retry if over max retry count
        if (executionCount >= MAX_RETRY) return false;
        // Retry if the server dropped connection on us
        if (exception instanceof NoHttpResponseException) return true;
        // Do not retry on SSL handshake exception
        if (exception instanceof SSLHandshakeException) return false;
        HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        // Retry if the request is considered idempotent
        return !(request instanceof HttpEntityEnclosingRequest);
    };
}
 
Example #21
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private static ManagedHttpClientConnection mockHttpConnection(Boolean stale, HttpContext context, Boolean closed)
{
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(connection.isStale()).thenReturn(stale);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    when(connection.isOpen()).thenReturn(closed);
    return connection;
}
 
Example #22
Source File: Olingo4Test.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
private static String getSession() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(TEST_SERVICE_BASE_URL);
    HttpContext httpContext = new BasicHttpContext();
    httpClient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    return currentReq.getURI().getPath().split("/")[2];
}
 
Example #23
Source File: HcDownloader.java    From SeimiCrawler with Apache License 2.0 5 votes vote down vote up
private String getRealUrl(HttpContext httpContext){
    Object target = httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    Object reqUri = httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    if (target==null||reqUri==null){
        return null;
    }
    HttpHost t = (HttpHost) target;
    HttpUriRequest r = (HttpUriRequest)reqUri;
    return r.getURI().isAbsolute()?r.getURI().toString():t.toString()+r.getURI().toString();
}
 
Example #24
Source File: SSLCertificateLoader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HttpResponseInterceptor getHttpResponseInterceptor() {
	return new HttpResponseInterceptor() {
		@Override
		public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
			ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection)context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
            SSLSession sslSession = routedConnection.getSSLSession();
            if (sslSession != null) {
                Certificate[] certificates = sslSession.getPeerCertificates();
                context.setAttribute(PEER_CERTIFICATES, certificates);
            }
		}
	};
}
 
Example #25
Source File: ConfigServerRestExecutorImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public boolean keepAlive(HttpResponse response, HttpContext context) {
    HttpCoreContext coreContext = HttpCoreContext.adapt(context);
    String host = coreContext.getTargetHost().getHostName();
    if (vips.contains(host)) {
        return false;
    }
    return super.keepAlive(response, context);
}
 
Example #26
Source File: Stats.java    From dx-java with MIT License 5 votes vote down vote up
public Stats(HttpCoreContext context, HttpRequestBase request, HttpResponse response, long startMillis, long endMillis, long startRequestMillis) {
       this._httpRequest = request;
       this._httpResponse = response;
       this._startMillis = startMillis;
       this._endMillis = endMillis;
       this._context = context;
       this._startRequestMillis = startRequestMillis;
}
 
Example #27
Source File: InsightDataManager.java    From dx-java with MIT License 5 votes vote down vote up
private int getRetryCount(HttpCoreContext _context) {
    int retry = 1;
    try {
        retry = new Long(_context.getConnection().getMetrics().getRequestCount()).intValue();
    } catch (Exception e) {
        // DO nothing
    }

    return retry - 1;
}
 
Example #28
Source File: S3HttpRequestRetryHandlerTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testRetryRequest() {
    final S3HttpRequestRetryHandler h = new S3HttpRequestRetryHandler(new JetS3tRequestAuthorizer() {
        @Override
        public void authorizeHttpRequest(final HttpUriRequest httpUriRequest, final HttpContext httpContext, final String s) {
            //
        }
    }, 1);
    final HttpClientContext context = new HttpClientContext();
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, new HttpHead());
    assertTrue(h.retryRequest(new SSLException(new SocketException("Broken pipe")), 1, context));
}
 
Example #29
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
Example #30
Source File: CertificateRetriever.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
  checkNotNull(host);

  log.info("Retrieving certificate from https://{}:{}", host, port);

  // setup custom connection manager so we can configure SSL to trust-all
  SSLContext sc = SSLContext.getInstance("TLS");
  sc.init(trustStore.getKeyManagers(), new TrustManager[]{ACCEPT_ALL_TRUST_MANAGER}, null);
  SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
  Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
      .register(HttpSchemes.HTTPS, sslSocketFactory).build();
  final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

  try {
    final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

    HttpClient httpClient = httpClientManager.create(new Customizer()
    {
      @Override
      public void customize(final HttpClientPlan plan) {
        // replace connection-manager with customized version needed to fetch SSL certificates
        plan.getClient().setConnectionManager(connectionManager);

        // add interceptor to grab peer-certificates
        plan.getClient().addInterceptorFirst(new HttpResponseInterceptor()
        {
          @Override
          public void process(final HttpResponse response, final HttpContext context)
              throws HttpException, IOException
          {
            ManagedHttpClientConnection connection =
                HttpCoreContext.adapt(context).getConnection(ManagedHttpClientConnection.class);

            // grab the peer-certificates from the session
            if (connection != null) {
              SSLSession session = connection.getSSLSession();
              if (session != null) {
                certificates.set(session.getPeerCertificates());
              }
            }
          }
        });
      }
    });

    httpClient.execute(new HttpGet("https://" + host + ":" + port));

    return certificates.get();
  }
  finally {
    // shutdown single-use connection manager
    connectionManager.shutdown();
  }
}