Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

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

Prototype

public BasicHttpContext(HttpContext httpContext) 

Source Link

Usage

From source file:org.Cherry.Modules.Web.Engine.RequestWorker.java

@Override
public void run() {
    log.debug("New connection thread");

    final HttpContext context = new BasicHttpContext(null);

    while (getHttpServerConnection().isOpen()) {
        if (Thread.interrupted())
            throw new IllegalStateException(new InterruptedException());

        try {//from w  w  w .  java2 s  .  c o  m
            getHttpService().handleRequest(getHttpServerConnection(), context);
        } catch (final ConnectionClosedException err) {
            log.debug("[{}]", err.getMessage());
            break;
        } catch (final Throwable err) {
            log.error(err.getMessage(), err);
            break;
        }
    }

    getMetricsService().examine(getHttpServerConnection());
}

From source file:ru.apertum.qsystem.reports.net.RunnableSocket.java

@Override
public void run() {

    final DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
    try {//w  w  w.  j  a  v a  2s  .  com
        conn.bind(socket, QSystemHtmlInstance.htmlInstance().getParams());
    } catch (IOException ex) {
        throw new ReportException("Not bind socket to connection." + ex);
    }

    final HttpContext context = new BasicHttpContext(null);
    try {
        while (!Thread.interrupted() && conn.isOpen()) {
            QSystemHtmlInstance.htmlInstance().getHttpService().handleRequest(conn, context);
        }
    } catch (ConnectionClosedException ex) {
        QLog.l().logRep().error("Client closed connection", ex);
    } catch (IOException ex) {
        QLog.l().logRep().error("I/O error: " + ex.getMessage(), ex);
    } catch (HttpException ex) {
        QLog.l().logRep().error("Unrecoverable HTTP protocol violation: " + ex.getMessage(), ex);
    } catch (Exception ex) {
        QLog.l().logRep().error("Something with HTTP server.", ex);
    } finally {
        try {
            conn.shutdown();
        } catch (IOException ex) {
            QLog.l().logRep().error("Default Http Server Connection have error then shutdown.", ex);
        } catch (Exception ex) {
            QLog.l().logRep().error("Something with runnableSocket.", ex);
        }
    }

}

From source file:org.pepstock.jem.node.https.Worker.java

@Override
public void run() {
    // creates a custom context
    HttpContext context = new BasicHttpContext(null);
    // adds the IP address of the client
    // necessary when the job ends and client is waiting the end of the job
    context.setAttribute(SubmitHandler.JOB_SUBMIT_IP_ADDRESS_KEY, clientAddress.getHostAddress());
    try {/*from   w w  w  . j ava2 s  .c om*/
        // till connection is open
        while (!Thread.interrupted() && httpConnection.isOpen()) {
            // starts the HTTP request
            httpService.handleRequest(httpConnection, context);
        }
    } catch (ConnectionClosedException ex) {
        // client close the connection
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E,
                "Client closed connection (" + clientAddress.getHostAddress() + ")");
    } catch (IOException ex) {
        // any I/O error
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E, "I/O error (" + clientAddress.getHostAddress() + ")");
    } catch (HttpException ex) {
        // Protocol exception
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E,
                "Unrecoverable HTTP protocol violation (" + clientAddress.getHostAddress() + ")");
    } finally {
        // ALWAYS close connection
        try {
            httpConnection.shutdown();
        } catch (IOException e) {
            LogAppl.getInstance().ignore(e.getMessage(), e);
        }
    }
}

From source file:org.aludratest.service.gui.web.selenium.httpproxy.RequestProcessorThread.java

/** The {@link Thread}'s worker method which processes the request. */
@Override//from   w ww  .jav a2s.  c  om
public void run() {
    LOGGER.debug("New request processor thread");

    // Create context and bind connection objects to the execution context
    HttpContext context = new BasicHttpContext(null);
    context.setAttribute(HTTP_IN_CONN, this.inconn);
    context.setAttribute(HTTP_OUT_CONN, this.outconn);

    // checking request's keep-alive attribute
    Boolean keepAliveObj = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
    boolean keepAlive = (keepAliveObj != null && keepAliveObj.booleanValue());

    // handle in/out character transfer according to keep-alive setting
    try {
        while (!Thread.interrupted()) {
            if (!this.inconn.isOpen()) {
                this.outconn.close();
                break;
            }
            LOGGER.debug("Handling request");

            this.httpservice.handleRequest(this.inconn, context);

            if (!keepAlive) {
                this.outconn.close();
                this.inconn.close();
                LOGGER.debug("Finishing request");
                break;
            }
        }
    } catch (ConnectionClosedException ex) {
        if (keepAlive && owner.isRunning()) {
            LOGGER.error("Client closed connection");
        } else {
            LOGGER.debug("Client closed connection");
        }
    } catch (IOException ex) {
        LOGGER.error("I/O error: " + ex.getMessage());
    } catch (HttpException ex) {
        LOGGER.error("Unrecoverable HTTP protocol violation: " + ex.getMessage());
    } finally {
        try {
            this.inconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        try {
            this.outconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        LOGGER.debug("Finished connection thread");
    }
}

From source file:mpv5.utils.http.HttpClient.java

/**
 * Connects to the given host// ww w.  j a  v  a  2s .c  om
 * @param toHost
 * @param port
 * @throws UnknownHostException
 * @throws IOException
 * @throws HttpException
 */
public HttpClient(String toHost, int port) throws UnknownHostException, IOException, HttpException {
    params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    httpproc = new BasicHttpProcessor();
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    httpexecutor = new HttpRequestExecutor();
    context = new BasicHttpContext(null);
    host = new HttpHost(toHost, port);
    conn = new DefaultHttpClientConnection();
    connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
}

From source file:org.apache.axis2.transport.http.server.HttpServiceProcessor.java

public void run() {
    LOG.debug("New connection thread");
    HttpContext context = new BasicHttpContext(null);
    try {//  w w  w. j a  v  a2s.c o m
        while (!Thread.interrupted() && !isDestroyed() && this.conn.isOpen()) {
            this.httpservice.handleRequest(this.conn, context);
        }
    } catch (ConnectionClosedException ex) {
        LOG.debug("Client closed connection");
    } catch (IOException ex) {
        if (ex instanceof SocketTimeoutException) {
            LOG.debug(ex.getMessage());
        } else if (ex instanceof SocketException) {
            LOG.debug(ex.getMessage());
        } else {
            LOG.warn(ex.getMessage(), ex);
        }
    } catch (HttpException ex) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("HTTP protocol error: " + ex.getMessage());
        }
    } finally {
        destroy();
        if (this.callback == null) {
            throw new NullPointerException("The callback object can't be null");
        }
        this.callback.completed(this);
    }
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//from   ww  w .  jav a 2s .  com

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

                if (firstParam) {
                    target += "?";
                    firstParam = false;
                } else {
                    target += "&";
                }
                target += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (Exception e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.cyberduck.core.sds.provider.HttpComponentsConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*w w  w.  jav  a  2  s .c o m*/
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(),
                request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:bigbird.benchmark.BenchmarkWorker.java

public BenchmarkWorker(final HttpParams params, int verbosity, final RequestGenerator requestGenerator,
        final HttpHost targetHost, int count, boolean keepalive) {

    super();/* w w w  . j  ava  2s. co  m*/
    this.params = params;
    this.requestGenerator = requestGenerator;
    this.context = new BasicHttpContext(null);
    this.targetHost = targetHost;
    this.count = count;
    this.keepalive = keepalive;

    this.httpProcessor = new BasicHttpProcessor();
    this.httpexecutor = new HttpRequestExecutor();

    // Required request interceptors
    this.httpProcessor.addInterceptor(new RequestContent());
    this.httpProcessor.addInterceptor(new RequestTargetHost());
    // Recommended request interceptors
    this.httpProcessor.addInterceptor(new RequestConnControl());
    this.httpProcessor.addInterceptor(new RequestUserAgent());
    this.httpProcessor.addInterceptor(new RequestExpectContinue());

    this.connstrategy = new DefaultConnectionReuseStrategy();
    this.verbosity = verbosity;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.CommonHttpClient.java

public HttpContext getContext() {
    if (context.get() == null) {
        context.set(new BasicHttpContext(null));
    }
    return context.get();
}