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:org.apache.synapse.transport.passthru.jmx.LatencyCollector.java

public LatencyCollector(HttpContext context, boolean isS2S) {
    Object o1, o2, o3, o4;//from  ww  w  . j a va2s.  com
    o1 = context.getAttribute(PassThroughConstants.REQ_ARRIVAL_TIME);
    o2 = context.getAttribute(PassThroughConstants.REQ_DEPARTURE_TIME);
    if (isS2S) {
        o3 = context.getAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME);
        o4 = context.getAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_START_TIME);
    } else {
        o3 = context.getAttribute(PassThroughConstants.RES_ARRIVAL_TIME);
        o4 = context.getAttribute(PassThroughConstants.RES_DEPARTURE_TIME);
    }
    if (o1 != null && o2 != null && o3 != null && o4 != null) {
        long tReqArrival = (Long) o1;
        long tReqDeparture = (Long) o2;
        long tResArrival = (Long) o3;
        long tResDeparture = (Long) o4;

        backendLatency = (tResArrival - tReqDeparture);
        latency = (tResDeparture - tReqArrival) - backendLatency;
    }
    o1 = context.getAttribute(PassThroughConstants.REQ_FROM_CLIENT_READ_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.REQ_FROM_CLIENT_READ_END_TIME);
    if (o1 != null && o2 != null) {
        serverDecodeLatency = (Long) o2 - (Long) o1;
    }
    o1 = context.getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME);
    if (o1 != null && o2 != null) {
        clientEncodeLatency = (Long) o2 - (Long) o1;
    }
    o1 = context.getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME);
    if (o1 != null && o2 != null) {
        clientDecodeLatency = (Long) o2 - (Long) o1;
    }
    o1 = context.getAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_END_TIME);
    if (o1 != null && o2 != null) {
        serverEncodeLatency = (Long) o2 - (Long) o1;
    }
    o1 = context.getAttribute(PassThroughConstants.SERVER_WORKER_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.SERVER_WORKER_INIT_TIME);
    if (o1 != null && o2 != null) {
        serverWorkerQueuedTime = (Long) o1 - (Long) o2;
    }
    o1 = context.getAttribute(PassThroughConstants.CLIENT_WORKER_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.CLIENT_WORKER_INIT_TIME);
    if (o1 != null && o2 != null) {
        clientWorkerQueuedTime = (Long) o1 - (Long) o2;
    }
    o1 = context.getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.SERVER_WORKER_START_TIME);
    if (o1 != null && o2 != null) {
        serverWorkerLatency = (Long) o1 - (Long) o2;
    }
    o1 = context.getAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_START_TIME);
    o2 = context.getAttribute(PassThroughConstants.CLIENT_WORKER_START_TIME);
    if (o1 != null && o2 != null) {
        clientWorkerLatency = (Long) o1 - (Long) o2;
    }
}

From source file:com.xebialabs.deployit.ci.server.PreemptiveAuthenticationInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request.getFirstHeader("Authorization") == null) {
        LOGGER.trace("No 'Authorization' header found for request: {}", request.getRequestLine());
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        CredentialsProvider credentialsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);
        if (credentialsProvider != null) {
            Credentials credentials = credentialsProvider
                    .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (credentials != null) {
                request.setHeader(new BasicScheme().authenticate(credentials, request, context));
                LOGGER.trace("Set 'Authorization' header {} for request: {}", credentials.getUserPrincipal(),
                        request.getRequestLine());
            }/*ww  w .  j a  v a2 s . com*/
        }
    }
}

From source file:org.deviceconnect.message.intent.impl.client.IntentRequestDirector.java

@Override
public HttpResponse execute(final HttpHost target, final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    RequestWrapper origWrapper = new RequestWrapper(request);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);
    Object userToken = context.getAttribute(ClientContext.USER_TOKEN);
    long timeout = HttpConnectionParams.getConnectionTimeout(params);

    ClientConnectionRequest connRequest = connManager.requestConnection(origRoute, userToken);
    ManagedClientConnection managedConn;
    try {// ww w  .  j  av a2 s .  c om
        managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }

    if (request.getFirstHeader(HttpHeaders.HOST) == null) {
        request.setHeader(HttpHeaders.HOST, "org.deviceconnect.manager/.DConnectBroadcastReceiver");
    }

    // requestExec.preProcess(request, httpProcessor, context);
    HttpResponse response = requestExec.execute(request, managedConn, context);
    // requestExec.postProcess(response, httpProcessor, context);

    return response;
}

From source file:com.frochr123.helper.CachedFileDownloader.java

public static SimpleEntry<String, ByteArrayOutputStream> getResultFromURL(String url) throws IOException {
    SimpleEntry<String, ByteArrayOutputStream> result = null;
    String finalUrl = null;//from   w w  w.ja v  a  2 s . c  o m
    ByteArrayOutputStream outputStream = null;

    if (url == null || url.isEmpty()) {
        return null;
    }

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT)
            .setConnectTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT)
            .setConnectionRequestTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT).build();

    // Create HTTP Get request
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);

    // Create context
    HttpContext context = new BasicHttpContext();

    // Check for temporary FabQR download of own configured private FabQR instance
    // In that case Authorization needs to be added
    if (FabQRFunctions.getFabqrPrivateURL() != null && !FabQRFunctions.getFabqrPrivateURL().isEmpty()
            && url.startsWith(FabQRFunctions.getFabqrPrivateURL())
            && url.contains("/" + FabQRFunctions.FABQR_TEMPORARY_MARKER + "/")) {
        // Set authentication information
        String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
                FabQRFunctions.getFabqrPrivatePassword());
        if (!encodedCredentials.isEmpty()) {
            httpGet.addHeader("Authorization", "Basic " + encodedCredentials);
        }
    }

    // Send request
    CloseableHttpResponse response = httpClient.execute(httpGet, context);

    // Get all redirected locations from context, if there are any
    RedirectLocations redirectLocations = (RedirectLocations) (context
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS));
    if (redirectLocations != null) {
        finalUrl = redirectLocations.getAll().get(redirectLocations.getAll().size() - 1).toString();
    } else {
        finalUrl = url;
    }

    // Check response valid and max file size
    if (response.getEntity() == null
            || response.getEntity().getContentLength() > CACHE_DOWNLOADER_MAX_FILESIZE_BYTES) {
        return null;
    }

    // Get data
    outputStream = new ByteArrayOutputStream();
    response.getEntity().writeTo(outputStream);

    // Return result
    result = new SimpleEntry<String, ByteArrayOutputStream>(finalUrl, outputStream);
    return result;
}

From source file:org.dcache.srm.client.GsiConnectionSocketFactory.java

@Override
public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress,
        InetSocketAddress localAddress, HttpContext context) throws IOException {
    Socket socket = socketFactory.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress,
            context);//from   w  ww.j ava  2s.c  o  m
    delegate(socket,
            (HttpClientTransport.Delegation) context
                    .getAttribute(HttpClientTransport.TRANSPORT_HTTP_DELEGATION),
            (X509Credential) context.getAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS));
    return socket;
}

From source file:cloudMe.CloudMeAPI.java

private DefaultHttpClient getConnection() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), USER_AGENT_INFO);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, 80, "os@xcerion.com", "Digest"),
            new UsernamePasswordCredentials(userName, pass)); // Encrypts password & username
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        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) {
                if (creds != null && scheme != null) {
                    authState.setAuthScheme(scheme);
                    authState.setCredentials(creds);
                } else {
                    scheme = authState.getAuthScheme();
                }/*from  w  w  w  .jav a  2s .c  o  m*/
            }
        }
    };
    httpClient.addRequestInterceptor(preemptiveAuth, 0);
    return httpClient;

}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url)
        throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(USERNAME, PASSWORD);

    httpclient.getCredentialsProvider()/*  w w  w .j  ava 2 s  . com*/
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java

private String getActualUrl(PortletRequest portletRequest, HttpContext context, RequestBuilder request,
        HttpResponse response) {/*from w ww .j  a v a  2 s. co m*/
    boolean cacheUsed = (context
            .getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT);
    boolean notFoundResponse = (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND);

    /*
     * ExecutionContext.HTTP_REQUEST and ExecutionContext.HTTP_TARGET_HOST are not set when the cache is used
     * or when the resource is ignored by WIP
     */
    if (cacheUsed || notFoundResponse)
        return request.getRequestedURL();

    // Get final URL (ie. perhaps redirected)
    HttpUriRequest actualRequest = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    return (actualRequest.getURI().isAbsolute()) ? actualRequest.getURI().toString()
            : (actualHost.toURI() + actualRequest.getURI());
}

From source file:org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator.java

@Override
public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) {
    this.authenticator.apply(client, httpContext, target);

    // Enable preemptive basic authentication
    // For nice layering we need to respect existing auth cache if present
    AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null)
        authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET);
    // TODO It is possible that this overwrites existing cached credentials
    // so potentially not ideal.
    authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth);
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.norconex.collector.http.redirect.impl.GenericRedirectURLProvider.java

@Override
public String provideRedirectURL(HttpRequest request, HttpResponse response, HttpContext context) {
    HttpRequest currentReq = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    String originalURL = toAbsoluteURI(currentHost, currentReq);

    //--- Location ---
    Header hl = response.getLastHeader(HttpHeaders.LOCATION);
    if (hl == null) {
        //TODO should throw exception instead?
        LOG.error("Redirect detected to a null Location for: " + toAbsoluteURI(currentHost, currentReq));
        return null;
    }/*  w w w .  j a v  a2  s  .  c om*/
    String redirectLocation = hl.getValue();

    //--- Charset ---
    String charset = null;
    Header hc = response.getLastHeader("Content-Type");
    if (hc != null) {
        String contentType = hc.getValue();
        if (contentType.contains(";")) {
            charset = StringUtils.substringAfterLast(contentType, "charset=");
        }
    }
    if (StringUtils.isBlank(charset)) {
        charset = fallbackCharset;
    }

    //--- Build/fix redirect URL ---
    String targetURL = HttpURL.toAbsolute(originalURL, redirectLocation);
    targetURL = resolveRedirectURL(targetURL, charset);

    if (LOG.isDebugEnabled()) {
        LOG.debug("URL redirect: " + originalURL + " -> " + targetURL);
    }
    return targetURL;
}