Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext getAttribute.

Prototype

Object getAttribute(String str);

Source Link

Usage

From source file:com.seajas.search.contender.service.modifier.SourceElementModifierService.java

/**
 * Retrieve the result content for the given URI.
 *
 * @param encodingOverride/*from  w  w  w . j  ava2  s .  com*/
 * @param resultHeaders
 * @param userAgent
 * @return Content
 */
public Content getContent(final URI resultUri, final String encodingOverride,
        final Map<String, String> resultHeaders, final String userAgent) {
    URI uriAfterRedirects = null;

    // Retrieve the content

    Header contentType = null;

    try {
        InputStream inputStream;

        // Local file streams can only be read if the parent scheme is also local

        if (!resultUri.getScheme().equalsIgnoreCase("file")) {
            HttpGet method = new HttpGet(resultUri);

            if (resultHeaders != null)
                for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                    method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
            if (userAgent != null)
                method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

            HttpContext context = new BasicHttpContext();

            SizeRestrictedHttpResponse response = httpClient.execute(method,
                    new SizeRestrictedResponseHandler(maximumContentLength, resultUri), context);

            if (response != null) {
                HttpUriRequest currentRequest = (HttpUriRequest) context
                        .getAttribute(ExecutionContext.HTTP_REQUEST);
                HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                try {
                    uriAfterRedirects = new URI(currentHost.toURI()).resolve(currentRequest.getURI());
                } catch (URISyntaxException e) {
                    logger.error(String.format("Final URI '%s' is mysteriously invalid", currentHost.toURI()),
                            e);
                }

                inputStream = new ByteArrayInputStream(response.getResponse());
                contentType = response.getContentType();
            } else
                return null;
        } else
            inputStream = new FileInputStream(resultUri.getPath());

        // Convert the stream to a reset-able one

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        IOUtils.copy(inputStream, outputStream);

        inputStream.close();
        inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        outputStream.close();

        // Now determine the content type and create a reader in case of structured content

        Metadata metadata = new Metadata();

        if (encodingOverride != null && contentType != null && StringUtils.hasText(contentType.getValue())) {
            MediaType type = MediaType.parse(contentType.getValue());

            metadata.add(HttpHeaders.CONTENT_TYPE,
                    type.getType() + "/" + type.getSubtype() + "; charset=" + encodingOverride);
        } else if (contentType != null && StringUtils.hasText(contentType.getValue()))
            metadata.add(HttpHeaders.CONTENT_TYPE, contentType.getValue());
        else if (encodingOverride != null)
            metadata.add(HttpHeaders.CONTENT_ENCODING, encodingOverride);

        MediaType mediaType = autoDetectParser.getDetector().detect(inputStream, metadata);

        return new Content(new ByteArrayInputStream(outputStream.toByteArray()),
                mediaType.getBaseType() + "/" + mediaType.getSubtype(),
                contentType != null ? contentType.getValue() : null,
                uriAfterRedirects != null ? uriAfterRedirects : resultUri);
    } catch (IOException e) {
        logger.error("Could not retrieve the given URL", e);

        return null;
    }
}

From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java

/**
 * Perform trust evaluation by extracting the server TLS {@link X509Credential} from the 
 * {@link SSLSession} and evaluating it via a {@link TrustEngine<Credential>} 
 * and {@link CriteriaSet} supplied by the caller via the {@link HttpContext}.
 * //from ww w.  j a  va 2 s . co m
 * @param socket the socket instance being processed
 * @param context the HttpClient context being processed
 * 
 * @throws IOException if the server TLS credential is untrusted, or if there is a fatal error
 *           attempting trust evaluation.
 */
protected void performTrustEval(@Nonnull final Socket socket, @Nonnull final HttpContext context)
        throws IOException {
    if (!(socket instanceof SSLSocket)) {
        log.debug("Socket was not an instance of SSLSocket, skipping trust eval");
        return;
    }
    SSLSocket sslSocket = (SSLSocket) socket;

    log.debug("Attempting to evaluate server TLS credential against supplied TrustEngine and CriteriaSet");

    @SuppressWarnings("unchecked")
    TrustEngine<? super X509Credential> trustEngine = (TrustEngine<? super X509Credential>) context
            .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_TRUST_ENGINE);
    if (trustEngine == null) {
        log.debug("No trust engine supplied by caller, skipping trust eval");
        return;
    } else {
        log.trace("Saw trust engine of type: {}", trustEngine.getClass().getName());
    }

    CriteriaSet criteriaSet = (CriteriaSet) context
            .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_CRITERIA_SET);
    if (criteriaSet == null) {
        log.debug("No criteria set supplied by caller, building new criteria set with signing criteria");
        criteriaSet = new CriteriaSet(new UsageCriterion(UsageType.SIGNING));
    } else {
        log.trace("Saw CriteriaSet: {}", criteriaSet);
    }

    X509Credential credential = extractCredential(sslSocket);

    try {
        if (trustEngine.validate(credential, criteriaSet)) {
            log.debug("Credential evaluated as trusted");
            context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED,
                    Boolean.TRUE);
        } else {
            log.debug("Credential evaluated as untrusted");
            context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED,
                    Boolean.FALSE);
            throw new SSLPeerUnverifiedException(
                    "Trust engine could not establish trust of server TLS credential");
        }
    } catch (SecurityException e) {
        log.error("Trust engine error evaluating credential", e);
        throw new IOException("Trust engine error evaluating credential", e);
    }

}

From source file:org.openqa.selenium.remote.internal.ApacheHttpClient.java

private HttpResponse createResponse(org.apache.http.HttpResponse response, HttpContext context)
        throws IOException {
    HttpResponse internalResponse = new HttpResponse();

    internalResponse.setStatus(response.getStatusLine().getStatusCode());
    for (Header header : response.getAllHeaders()) {
        internalResponse.addHeader(header.getName(), header.getValue());
    }//from   w w w .j  a va 2  s. c o  m

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            internalResponse.setContent(EntityUtils.toByteArray(entity));
        } finally {
            EntityUtils.consume(entity);
        }
    }

    Object host = context.getAttribute(HTTP_TARGET_HOST);
    if (host instanceof HttpHost) {
        internalResponse.setTargetHost(((HttpHost) host).toURI());
    }

    return internalResponse;
}

From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClientTest.java

@Test
public void createHttpContextWithCookiesTest() {
    CloseableHttpResponse closeableHttpResponseMock = Mockito.mock(CloseableHttpResponse.class);

    Header[] headers = new Header[1];
    Mockito.doReturn(headers).when(closeableHttpResponseMock).getAllHeaders();

    Mockito.doNothing().when(apacheCloudStackClient)
            .createAndAddCookiesOnStoreForHeaders(Mockito.any(BasicCookieStore.class), Mockito.eq(headers));
    HttpContext httpContextWithCookies = apacheCloudStackClient
            .createHttpContextWithCookies(closeableHttpResponseMock);

    Assert.assertNotNull(httpContextWithCookies);
    Assert.assertNotNull(httpContextWithCookies.getAttribute(HttpClientContext.COOKIE_STORE));

    Mockito.verify(apacheCloudStackClient)
            .createAndAddCookiesOnStoreForHeaders(Mockito.any(BasicCookieStore.class), Mockito.eq(headers));

}

From source file:ro.zg.netcell.datasources.executors.http.HttpCommandExecutor.java

public HttpCommandResponse executeCommand(CommandContext commandContext) throws Exception {
    HttpClient httpClient = (HttpClient) commandContext.getConnectionManager().getConnection();
    ScriptDaoCommand command = commandContext.getCommand();
    String method = (String) command.getArgument("method");
    String url = (String) command.getArgument("url");
    /* encode the url passed on the http request */
    // URI requestUri = new URI(url);
    // requestUri = URIUtils.createURI(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(),
    // requestUri.getPath(), URLEncoder.encode(requestUri.getQuery(),HTTP.DEFAULT_PROTOCOL_CHARSET),
    // requestUri.getFragment());
    String encodedUrl = URLEncoder.encode(url, HTTP.DEFAULT_PROTOCOL_CHARSET);
    boolean returnHeaders = false;
    Object rh = command.getArgument("returnHeaders");
    if (rh != null) {
        returnHeaders = (Boolean) rh;
    }/* w  w  w. j ava 2  s .  c  o  m*/

    HttpRequestBase request = null;
    if ("GET".equals(method)) {
        request = new HttpGet(encodedUrl);
    } else if ("POST".equals(method)) {
        HttpPost post = new HttpPost(encodedUrl);
        String content = (String) command.getArgument("content");
        if (content != null) {
            post.setEntity(new StringEntity(content));
        }
        request = post;
    } else if ("HEAD".equals(method)) {
        request = new HttpHead(encodedUrl);
    }

    Map<String, String> requestHeaders = (Map) command.getArgument("requestHeaders");
    if (requestHeaders != null) {
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            request.setHeader(entry.getKey(), entry.getValue());
        }
    }
    HttpContext localContext = new BasicHttpContext();
    HttpEntity responseEntity = null;
    HttpCommandResponse commandResponse = new HttpCommandResponse();
    try {
        HttpResponse response = httpClient.execute(request, localContext);
        responseEntity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();

        commandResponse.setStatusCode(statusLine.getStatusCode());
        commandResponse.setProtocol(statusLine.getProtocolVersion().getProtocol());
        commandResponse.setReasonPhrase(statusLine.getReasonPhrase());
        commandResponse.setRequestUrl(url);
        HttpRequest actualRequest = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        commandResponse.setTargetUrl(targetHost.toURI() + actualRequest.getRequestLine().getUri());

        if (returnHeaders) {
            Map<String, String> headers = new HashMap<String, String>();
            for (Header h : response.getAllHeaders()) {
                headers.put(h.getName().toLowerCase(), h.getValue().toLowerCase());
            }
            commandResponse.setHeaders(headers);
        }
        if (responseEntity != null) {
            long responseLength = responseEntity.getContentLength();
            String responseContent = EntityUtils.toString(responseEntity, HTTP.UTF_8);
            if (responseLength == -1) {
                responseLength = responseContent.length();
            }
            commandResponse.setLength(responseLength);
            commandResponse.setContent(responseContent);
        }
    } finally {
        if (responseEntity != null) {
            responseEntity.consumeContent();
        } else {
            request.abort();
        }
    }

    return commandResponse;
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Set Authentication to a given {@link DefaultHttpClient} instance.
 * /*from   www .  j av a 2 s  . co  m*/
 * @param url
 *            URL of resource.
 * @param username
 *            User name for authentication
 * @param password
 *            Password for authentication.
 * @throws WebserverSystemException
 *             Thrown if connection failed.
 */
public void setAuthentication(final DefaultHttpClient client, final URL url, final String username,
        final String password) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    final Credentials creds = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(authScope, creds);
    client.setCredentialsProvider(credsProvider);
    // don't wait for auth request
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            final CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            // If not auth scheme has been initialized yet
            if (authState.getAuthScheme() == null) {
                final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                // Obtain credentials matching the target host
                final Credentials creds = credsProvider.getCredentials(authScope);
                // If found, generate BasicScheme preemptively
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };
    client.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:bixo.fetcher.SimpleHttpFetcher.java

private String extractRedirectedUrl(String url, HttpContext localContext) {
    // This was triggered by HttpClient with the redirect count was exceeded.
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest finalRequest = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);

    try {/*from   ww w  . j a v  a2s  .  com*/
        URL hostUrl = new URI(host.toURI()).toURL();
        return new URL(hostUrl, finalRequest.getURI().toString()).toExternalForm();
    } catch (MalformedURLException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    } catch (URISyntaxException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    }
}

From source file:freeipa.client.negotiation.JBossNegotiateScheme.java

/**
 * Produces Negotiate authorization Header based on token created by processChallenge.
 *
 * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
 *        from JAAS will be used instead.
 * @param request The request being authenticated
 *
 * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
 *
 * @return an Negotiate authorization Header
 *//*from www .j  av a2  s  .co  m*/
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = ExecutionContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }

        System.out.println("init " + authServer);

        final Oid negotiationOid = new Oid(SPNEGO_OID);

        final GSSManager manager = GSSManager.getInstance();
        final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid),
                negotiationOid, null, DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);

        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }

        state = State.TOKEN_GENERATED;
        String tokenstr = new String(base64codec.encode(token));
        System.out.println("Sending response '" + tokenstr + "' back to the auth server");

        CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
}

From source file:org.apache.synapse.transport.nhttp.ServerHandler.java

/**
 * Process ready output by writing into the channel
 * @param conn the connection being processed
 * @param encoder the content encoder in use
 *///from   w w w.  j a  va2 s  .  c  o  m
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {

    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    ContentOutputBuffer outBuf = (ContentOutputBuffer) context.getAttribute(RESPONSE_SOURCE_BUFFER);

    if (outBuf == null) {
        // fix for SYNAPSE 584. This is a temporaly fix becuase of HTTPCORE-208
        shutdownConnection(conn, false, null);
        return;
    }

    try {
        int bytesWritten = outBuf.produceContent(encoder);
        if (metrics != null && bytesWritten > 0) {
            metrics.incrementBytesSent(bytesWritten);
        }

        if (encoder.isCompleted()) {
            long currentTime = System.currentTimeMillis();
            context.setAttribute(NhttpConstants.RES_TO_CLIENT_WRITE_END_TIME, currentTime);
            context.setAttribute(NhttpConstants.RES_DEPARTURE_TIME, currentTime);
            updateLatencyView(context);

            context.removeAttribute(NhttpConstants.REQ_ARRIVAL_TIME);
            context.removeAttribute(NhttpConstants.REQ_DEPARTURE_TIME);
            context.removeAttribute(NhttpConstants.RES_ARRIVAL_TIME);

            ((ServerConnectionDebug) conn.getContext().getAttribute(SERVER_CONNECTION_DEBUG))
                    .recordResponseCompletionTime();

            Boolean reqRead = (Boolean) conn.getContext().getAttribute(NhttpConstants.REQUEST_READ);
            Boolean forceConnectionClose = (Boolean) conn.getContext()
                    .getAttribute(NhttpConstants.FORCE_CONNECTION_CLOSE);
            if (reqRead != null && !reqRead) {
                try {
                    // this is a connection we should not re-use
                    conn.close();
                } catch (Exception ignore) {
                }
            } else if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else if (forceConnectionClose != null && forceConnectionClose) {
                conn.close();
            } else {
                conn.requestInput();
            }
        }

    } catch (IOException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("I/O Error at outputReady : " + e.getMessage(), e, conn);
    }
}