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.axis2.transport.http.server.AxisHttpService.java

protected void doService(final AxisHttpRequest request, final AxisHttpResponse response,
        final HttpContext context, final MessageContext msgContext) throws HttpException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request method: " + request.getMethod());
        LOG.debug("Target URI: " + request.getRequestURI());
    }/*from  w  ww  .j  a  v  a  2 s.c o m*/

    try {
        TransportOutDescription transportOut = this.configurationContext.getAxisConfiguration()
                .getTransportOut(Constants.TRANSPORT_HTTP);
        TransportInDescription transportIn = this.configurationContext.getAxisConfiguration()
                .getTransportIn(Constants.TRANSPORT_HTTP);

        String sessionKey = (String) context.getAttribute(HTTPConstants.COOKIE_STRING);
        msgContext.setTransportIn(transportIn);
        msgContext.setTransportOut(transportOut);
        msgContext.setServerSide(true);
        msgContext.setProperty(HTTPConstants.COOKIE_STRING, sessionKey);
        msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getRequestURI());

        // set the transport Headers
        HashMap headerMap = new HashMap();
        for (Iterator it = request.headerIterator(); it.hasNext();) {
            Header header = (Header) it.next();
            headerMap.put(header.getName(), header.getValue());
        }
        msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, request.getContentType());

        msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream());
        msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, response);
        msgContext.setTo(new EndpointReference(request.getRequestURI()));
        msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL,
                new SimpleHTTPRequestResponseTransport());

        this.worker.service(request, response, msgContext);
    } catch (SocketException ex) {
        // Socket is unreliable. 
        throw ex;
    } catch (HttpException ex) {
        // HTTP protocol violation. Transport is unreliable
        throw ex;
    } catch (Throwable e) {

        msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream());
        msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, response);

        MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e);
        // If the fault is not going along the back channel we should be 202ing
        if (AddressingHelper.isFaultRedirected(msgContext)) {
            response.setStatus(HttpStatus.SC_ACCEPTED);
        } else {
            String state = (String) msgContext.getProperty(Constants.HTTP_RESPONSE_STATE);
            if (state != null) {
                int stateInt = Integer.parseInt(state);
                response.setStatus(stateInt);
                if (stateInt == HttpServletResponse.SC_UNAUTHORIZED) { // Unauthorized
                    String realm = (String) msgContext.getProperty(Constants.HTTP_BASIC_AUTH_REALM);
                    response.addHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"");
                }
            } else {
                if (e instanceof AxisFault) {
                    response.sendError(getStatusFromAxisFault((AxisFault) e), e.getMessage());
                } else {
                    response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            }
        }
        AxisEngine.sendFault(faultContext);
    }
}

From source file:com.nebkat.plugin.url.URLPlugin.java

@EventHandler
public void onMessage(PrivMessageEvent e) {
    // Filter targets and ignores
    if ((mConfig.channels != null && mConfig.channels.stream()
            .noneMatch((channel) -> channel.equalsIgnoreCase(e.getTarget().getName())))
            || (mConfig.ignore != null// www .  j a  v  a 2 s  .c o m
                    && mConfig.ignore.stream().anyMatch((ignore) -> e.getSource().match(ignore)))) {
        return;
    }

    Matcher matcher = URL_MATCHER.matcher(e.getMessage());
    if (!matcher.find()) {
        return;
    }
    String url = matcher.group();

    HttpGet get = new HttpGet(url);

    // Execute the request
    HttpContext context = new BasicHttpContext();
    HttpResponse response;
    try {
        response = ConnectionManager.getHttpClient().execute(get, context);
    } catch (IOException ex) {
        get.abort();
        return;
    }

    Header contentType = response.getEntity().getContentType();
    if (contentType == null) {
        get.abort();
        return;
    }
    String mimeType = contentType.getValue().split(";")[0].trim();
    if (!mimeType.equals("text/html") || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        get.abort();
        return;
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        get.abort();
        return;
    }

    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    boolean redirected = context.getAttribute(ConnectionManager.REDIRECTED) != null;

    StringBuilder page = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            if (page.length() > 2 * 1024 * 1024) {
                reader.close();
                get.abort();
                return;
            }
            page.append(line);
            matcher = TITLE_MATCHER.matcher(page);
            if (matcher.find()) {
                String title = StringEscapeUtils.unescapeHtml4(matcher.group(1).trim());
                if (title.length() <= 0) {
                    return;
                } else if (title.length() > 100) {
                    title = title.substring(0, 100) + "...";
                }
                Irc.message(e.getSession(), e.getTarget(),
                        "[Link] " + Irc.TEXT_BOLD + currentHost.toHostString() + Irc.TEXT_RESET
                                + (redirected ? " [redirected]" : "") + ": " + title);
                return;
            }
        }
    } catch (IOException ex) {
        // Ignore
    }
}

From source file:org.ovirt.engine.sdk.web.ConnectionsPool.java

private void injectHttpRequestRetryHandler(DefaultHttpClient httpclient) {
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        @Override//from w  w w  . j  av a 2 s .  com
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_RETRY_REQUEST) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };

    httpclient.setHttpRequestRetryHandler(myRetryHandler);
}

From source file:org.apache.ambari.view.hive.client.HttpRequestInterceptorBase.java

@Override
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    try {/* w  w  w.j  av  a 2  s. c om*/
        // If cookie based authentication is allowed, generate ticket only when necessary.
        // The necessary condition is either when there are no server side cookies in the
        // cookiestore which can be send back or when the server returns a 401 error code
        // indicating that the previous cookie has expired.
        if (isCookieEnabled) {
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        }
        // Generate the kerberos ticket under the following scenarios:
        // 1. Cookie Authentication is disabled OR
        // 2. The first time when the request is sent OR
        // 3. The server returns a 401, which sometimes means the cookie has expired
        // 4. The cookie is secured where as the client connect does not use SSL
        if (!isCookieEnabled || ((httpContext.getAttribute(Utils.HIVE_SERVER2_RETRY_KEY) == null
                && (cookieStore == null || (cookieStore != null
                        && Utils.needToSendCredentials(cookieStore, cookieName, isSSL))))
                || (httpContext.getAttribute(Utils.HIVE_SERVER2_RETRY_KEY) != null && httpContext
                        .getAttribute(Utils.HIVE_SERVER2_RETRY_KEY).equals(Utils.HIVE_SERVER2_RETRY_TRUE)))) {
            addHttpAuthHeader(httpRequest, httpContext);
        }
        if (isCookieEnabled) {
            httpContext.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_FALSE);
        }
        // Insert the additional http headers
        if (additionalHeaders != null) {
            for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
                httpRequest.addHeader(entry.getKey(), entry.getValue());
            }
        }
    } catch (Exception e) {
        throw new HttpException(e.getMessage(), e);
    }
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302RedirectTarget() throws Exception {
    HttpContext localContext = new BasicHttpContext();
    HttpGet get = new HttpGet("http://example.com/302");
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    BasicHttpResponse redirect = new BasicHttpResponse(_302);
    redirect.setHeader("Location", "http://example.com/200");
    responses.add(redirect);//  ww w.j  a  va  2s.c  om
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }
    }, localContext);
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null);
    assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString());
}

From source file:org.alfresco.cacheserver.http.CacheHttpClient.java

private CloseableHttpClient getHttpClient(HttpHost target, HttpClientContext localContext, String username,
        String password) {//from   www  . ja v  a2  s  .  c  o m
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
            HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
            if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
                // Keep alive for 5 seconds only
                return 5 * 1000;
            } else {
                // otherwise keep alive for 30 seconds
                return 30 * 1000;
            }
        }

    };

    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            //                .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .setDefaultCredentialsProvider(credsProvider).setKeepAliveStrategy(keepAliveStrategy)
            .setRetryHandler(retryHandler).build();
    return httpclient;
}

From source file:io.opentracing.contrib.elasticsearch.common.TracingHttpClientConfigCallback.java

@Override
public HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) {

    httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {
        @Override//from www  .j  a  va  2 s.com
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            Tracer.SpanBuilder spanBuilder = tracer.buildSpan(spanNameProvider.apply(request))
                    .ignoreActiveSpan().withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);

            SpanContext parentContext = extract(request);

            if (parentContext != null) {
                spanBuilder.asChildOf(parentContext);
            }

            Span span = spanBuilder.start();
            SpanDecorator.onRequest(request, span);

            tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpTextMapInjectAdapter(request));

            context.setAttribute("span", span);
        }
    });

    httpClientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            Object spanObject = context.getAttribute("span");
            if (spanObject instanceof Span) {
                Span span = (Span) spanObject;
                SpanDecorator.onResponse(response, span);
                span.finish();
            }
        }
    });

    return httpClientBuilder;
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;/*from  www  .  ja v  a 2  s.  c  o  m*/
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:org.opcfoundation.ua.transport.https.HttpsServerEndpointHandler.java

@Override
public void handle(HttpRequest request, HttpAsyncExchange httpExchange, HttpContext context)
        throws HttpException, IOException {

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from   w w  w  . j  ava  2s.c  o m

    HttpsServerPendingRequest req = new HttpsServerPendingRequest(this, httpExchange, request,
            singleSecureChannel, requestIdCounter.getAndIncrement());
    pendingRequests.put(req.requestId, req);

    //Check isDebugEnabled() here for possible performance reasons.
    //if (logger.isDebugEnabled()) {
    // Request URI is already set.
    //String requestUri = request.getRequestLine().getUri();
    //requestUri = URLDecoder.decode(requestUri, "UTF-8");            
    NHttpServerConnection connection = (NHttpServerConnection) context.getAttribute("http.connection");
    //logger.debug(method+" "+requestUri+"from"+connection);          
    logger.debug("handle: {} context={}: {}", connection, connection.getContext(), request);
    //}

    HttpsServerConnection currentConnection = (HttpsServerConnection) singleSecureChannel.getConnection();

    if (currentConnection == null || !connection.equals(currentConnection.getNHttpServerConnection())) {
        HttpsServerConnection httpsConnection = new HttpsServerConnection(this.endpointServer, connection);
        singleSecureChannel.setConnection(httpsConnection);
        logger.info("HttpsServerEndpointHandler.handle(): singleSecureChannel.setConnection({})", connection);
    }
    // Run in worker thread.
    //StackUtils.getBlockingWorkExecutor().execute( req );
    // Run in current thread
    req.run();
}