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

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

Introduction

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

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomHttpClient.java

public String getRequestHeadString(final HttpHost originalTarget, final HttpRequest request,
        final HttpContext originalContext) throws IOException, HttpException {
    HttpContext context = originalContext;
    HttpHost target = originalTarget;// w w w  .j a  v  a  2  s.c  o  m

    if (context == null) {
        context = createHttpContext();
    }

    if (target == null) {
        URI uri = ((HttpUriRequest) request).getURI();
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
    prepareRequest(request);

    getHttpProcessor().process(request, context);

    String requestString = request.getRequestLine().toString() + "\n";
    for (Header header : request.getAllHeaders()) {
        requestString += header.toString() + "\n";
    }
    return requestString;
}

From source file:org.apache.synapse.transport.passthru.SourceHandler.java

/**
 * Create SourceRequest from NHttpServerConnection conn
 * @param conn the connection being processed
 * @return SourceRequest//from   w w w.ja v  a 2s .  co m
 * @throws IOException
 * @throws HttpException
 */
public SourceRequest getSourceRequest(NHttpServerConnection conn) throws IOException, HttpException {
    HttpContext context = conn.getContext();
    context.setAttribute(PassThroughConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());

    if (!SourceContext.assertState(conn, ProtocolState.REQUEST_READY)
            && !SourceContext.assertState(conn, ProtocolState.WSDL_RESPONSE_DONE)) {
        handleInvalidState(conn, "Request received");
        return null;
    }
    // we have received a message over this connection. So we must inform the pool
    sourceConfiguration.getSourceConnections().useConnection(conn);

    // at this point we have read the HTTP Headers
    SourceContext.updateState(conn, ProtocolState.REQUEST_HEAD);

    SourceRequest request = new SourceRequest(sourceConfiguration, conn.getHttpRequest(), conn);
    SourceContext.setRequest(conn, request);
    request.start(conn);
    metrics.incrementMessagesReceived();
    return request;
}

From source file:com.farmafene.commons.cas.LoginTGT.java

public void doLogout(Cookie cookie) {
    HttpResponse res = null;//from   w  w  w .  ja v a  2 s . co m
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(cookie);

    HttpPost post = new HttpPost(getURL("logout"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    try {
        res = client.execute(post, localContext);
        if (res.getStatusLine().getStatusCode() != 200) {
            AuriusAuthException ex = new AuriusAuthException("Error");
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
    } catch (ClientProtocolException e) {
        AuriusAuthException ex = new AuriusAuthException("ClientProtocolException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
}

From source file:com.ryan.ryanreader.cache.CacheDownload.java

private void downloadGet(final HttpClient httpClient) {

    httpGet = new HttpGet(initiator.url);
    if (initiator.isJson)
        httpGet.setHeader("Accept-Encoding", "gzip");

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, initiator.getCookies());

    final HttpResponse response;
    final StatusLine status;

    try {//from   ww  w  .j a va 2  s . com
        if (cancelled) {
            notifyAllOnFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
            return;
        }
        response = httpClient.execute(httpGet, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {
        t.printStackTrace();
        notifyAllOnFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        return;
    }

    if (status.getStatusCode() != 200) {
        notifyAllOnFailure(RequestFailureType.REQUEST, null, status,
                String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase()));
        return;
    }

    if (cancelled) {
        notifyAllOnFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
        return;
    }

    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        notifyAllOnFailure(RequestFailureType.CONNECTION, null, status,
                "Did not receive a valid HTTP response");
        return;
    }

    final InputStream is;

    try {
        is = entity.getContent();
        mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue();
    } catch (Throwable t) {
        t.printStackTrace();
        notifyAllOnFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream");
        return;
    }

    final NotifyOutputStream cacheOs;
    if (initiator.cache) {
        try {
            cacheFile = manager.openNewCacheFile(initiator, session, mimetype);
            cacheOs = cacheFile.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            notifyAllOnFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache");
            return;
        }
    } else {
        cacheOs = null;
    }

    final long contentLength = entity.getContentLength();

    if (initiator.isJson) {

        final InputStream bis;

        if (initiator.cache) {
            final CachingInputStream cis = new CachingInputStream(is, cacheOs,
                    new CachingInputStream.BytesReadListener() {
                        public void onBytesRead(final long total) {
                            notifyAllOnProgress(total, contentLength);
                        }
                    });

            bis = new BufferedInputStream(cis, 8 * 1024);
        } else {
            bis = new BufferedInputStream(is, 8 * 1024);
        }

        final JsonValue value;

        try {
            value = new JsonValue(bis);
            value.buildInNewThread();

        } catch (Throwable t) {
            t.printStackTrace();
            notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        synchronized (this) {
            this.value = value;
            notifyAllOnJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session);
        }

        try {
            value.join();

        } catch (Throwable t) {
            t.printStackTrace();
            notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        success = true;

    } else {

        if (!initiator.cache) {
            BugReportActivity.handleGlobalError(initiator.context, "Cache disabled for non-JSON request");
            return;
        }

        try {
            final byte[] buf = new byte[8 * 1024];

            int bytesRead;
            long totalBytesRead = 0;
            while ((bytesRead = is.read(buf)) > 0) {
                totalBytesRead += bytesRead;
                cacheOs.write(buf, 0, bytesRead);
                notifyAllOnProgress(totalBytesRead, contentLength);
            }

            cacheOs.flush();
            cacheOs.close();
            success = true;

        } catch (Throwable t) {
            t.printStackTrace();
            notifyAllOnFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted");
        }
    }
}

From source file:com.android.callstat.common.net.MyHttpClient.java

private MyHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override/*from   w w  w  .  j  a  v  a  2  s  . com*/
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            processor.addRequestInterceptor(new CurlLogger());

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }
    };
}

From source file:com.appassit.http.AndroidHttpClient.java

private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override//from  w w w .j a v  a2  s .com
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            processor.addRequestInterceptor(new CurlLogger());

            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
            return context;
        }
    };
}

From source file:org.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

@Override
public void deleteFromStore(WebApp webApp, AppStore store) throws AppManagementException {
    if (log.isDebugEnabled()) {
        String msg = String.format("Deleting web app : %s from external store : %s ", webApp.getApiName(),
                store.getName());//from  w  w w.ja va2  s . co  m
        log.debug(msg);
    }

    validateStore(store);

    String storeEndpoint = store.getEndpoint();
    HttpClient httpClient = AppManagerUtil.getHttpClient(storeEndpoint);
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    loginToExternalStore(store, httpContext, httpClient);
    deleteFromExternalStore(webApp, store.getUsername(), storeEndpoint, httpContext);
    logoutFromExternalStore(storeEndpoint, httpContext, httpClient);
}

From source file:com.farmafene.commons.cas.LoginTGT.java

/**
 * @return//w  ww  .j  a  v  a 2s . c  om
 */
private LoginTicketContainer processInitRequest() {
    LoginTicketContainer processInitRequest = null;
    HttpResponse res = null;
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    HttpPost post = new HttpPost(getURL("login"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    try {
        res = client.execute(post, localContext);
    } catch (ClientProtocolException e) {
        AuriusAuthException ex = new AuriusAuthException("ClientProtocolException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    InputStream is = null;
    try {
        is = res.getEntity().getContent();
    } catch (IllegalStateException e) {
        AuriusAuthException ex = new AuriusAuthException("IllegalStateException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int leido = 0;
    try {
        while ((leido = is.read(buffer)) > 0) {
            baos.write(buffer, 0, leido);
        }
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    String html = baos.toString().replace("\n", "").replace("\r", "");
    /*
     * Buscamos los tipos de "input"
     */
    String[] inputs = html.split("<\\s*input\\s+");
    processInitRequest = new LoginTicketContainer();
    for (String input : inputs) {
        String value = null;
        if (null != (value = search(input, "lt"))) {
            processInitRequest.setLoginTicket(value);
        } else if (null != (value = search(input, "execution"))) {
            processInitRequest.setExecution(value);
        }
    }
    /*
     * Obtenemos la session Cookie
     */
    if (client.getCookieStore().getCookies() != null) {
        for (Cookie c : client.getCookieStore().getCookies()) {
            if (getJSessionCookieName().equals(c.getName())) {
                processInitRequest.setSessionCookie(c);
            }
        }
    }
    if (null != baos) {
        try {
            baos.close();
        } catch (IOException e) {
            logger.error("Error al cerrar el OutputStream", e);
        }
    }
    if (null != is) {
        try {
            is.close();
        } catch (IOException e) {
            logger.error("Error al cerrar el InputStream", e);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Obtenido: " + processInitRequest);
    }
    return processInitRequest;
}