Example usage for org.apache.http.nio NHttpClientConnection submitRequest

List of usage examples for org.apache.http.nio NHttpClientConnection submitRequest

Introduction

In this page you can find the example usage for org.apache.http.nio NHttpClientConnection submitRequest.

Prototype

void submitRequest(HttpRequest request) throws IOException, HttpException;

Source Link

Document

Submits HttpRequest to be sent to the target server.

Usage

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

/**
 * Triggered when the connection is ready to send an HTTP request.
 *
 * @see NHttpClientConnection/*from   w  ww . j  a va  2 s . c  o m*/
 *
 * @param conn HTTP connection that is ready to send an HTTP request
 */
public void requestReady(final NHttpClientConnection conn) {
    System.out.println(conn + " [proxy->origin] request ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    // TODO: change it to ReentrantLock
    synchronized (proxyTask) {
        if (requestReadyValidateConnectionState(proxyTask))
            return;

        HttpRequest request = proxyTask.getRequest();
        if (request == null) {
            throw new IllegalStateException("HTTP request is null");
        }

        requestReadyCleanUpHeaders(request);

        HttpHost targetHost = proxyTask.getTarget();

        try {

            request.setParams(new DefaultedHttpParams(request.getParams(), this.params));

            // Pre-process HTTP request
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);

            this.httpProcessor.process(request, context);
            // and send it to the origin server
            Request originalRequest = proxyTask.getOriginalRequest();
            int length = originalRequest.getContentLength();
            if (length > 0) {
                BasicHttpEntity httpEntity = new BasicHttpEntity();
                httpEntity.setContentLength(originalRequest.getContentLengthLong());
                /*
                          httpEntity.setContent(((InternalInputBuffer) originalRequest.getInputBuffer()).getInputStream());
                          ((BasicHttpEntityEnclosingRequest) request).setEntity(httpEntity);
                */
            }
            conn.submitRequest(request);
            // Update connection state
            proxyTask.setOriginState(ConnState.REQUEST_SENT);

            System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString());

        } catch (IOException ex) {
            shutdownConnection(conn);
        } catch (HttpException ex) {
            shutdownConnection(conn);
        }

    }
}

From source file:org.apache.axis2.transport.nhttp.ClientHandler.java

/**
 * Submit a new request over an already established connection, which has been 
 * 'kept alive'/* www  .j av  a2 s  .c om*/
 * @param conn the connection to use to send the request, which has been kept open
 * @param axis2Req the new request
 */
public void submitRequest(final NHttpClientConnection conn, Axis2HttpRequest axis2Req) {

    try {
        HttpContext context = conn.getContext();

        context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost());

        context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
        context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel());

        HttpRequest request = axis2Req.getRequest();
        request.getParams().setDefaults(this.params);
        this.httpProcessor.process(request, context);

        conn.submitRequest(request);
        context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    } catch (HttpException e) {
        handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.axis2.transport.nhttp.ClientHandler.java

/**
 * Invoked when the destination is connected
 * @param conn the connection being processed
 * @param attachment the attachment set previously
 *//*from  w  ww.j av  a 2 s .c  om*/
public void connected(final NHttpClientConnection conn, final Object attachment) {
    try {
        HttpContext context = conn.getContext();
        Axis2HttpRequest axis2Req = (Axis2HttpRequest) attachment;

        context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost());

        // allocate temporary buffers to process this request
        context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(2048));
        context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(2048));

        context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
        context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel());

        HttpRequest request = axis2Req.getRequest();
        request.getParams().setDefaults(this.params);
        this.httpProcessor.process(request, context);

        conn.submitRequest(request);
        context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    } catch (HttpException e) {
        handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.http.impl.nio.client.NHttpClientProtocolHandler.java

public void requestReady(final NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    HttpExchange httpexchange = getHttpExchange(context);
    HttpAsyncExchangeHandler<?> handler = getHandler(context);
    if (this.log.isDebugEnabled()) {
        this.log.debug("Request ready " + formatState(conn, httpexchange));
    }/*from  w w w.ja v  a  2  s. c om*/
    if (httpexchange.getRequestState() != MessageState.READY) {
        return;
    }
    if (handler == null || handler.isDone()) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("No request submitted " + formatState(conn, httpexchange));
        }
        return;
    }
    try {
        HttpRequest request = handler.generateRequest();
        httpexchange.setRequest(request);

        HttpEntityEnclosingRequest entityReq = null;
        if (request instanceof HttpEntityEnclosingRequest) {
            entityReq = (HttpEntityEnclosingRequest) request;
        }

        conn.submitRequest(request);

        if (entityReq != null) {
            if (entityReq.expectContinue()) {
                int timeout = conn.getSocketTimeout();
                httpexchange.setTimeout(timeout);
                timeout = request.getParams().getIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
                conn.setSocketTimeout(timeout);
                httpexchange.setRequestState(MessageState.ACK);
            } else {
                httpexchange.setRequestState(MessageState.BODY_STREAM);
            }
        } else {
            httpexchange.setRequestState(MessageState.COMPLETED);
        }
    } catch (IOException ex) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("I/O error: " + ex.getMessage(), ex);
        }
        shutdownConnection(conn);
        handler.failed(ex);
    } catch (HttpException ex) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("HTTP protocol exception: " + ex.getMessage(), ex);
        }
        closeConnection(conn);
        handler.failed(ex);
    }
}

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

public void requestReady(final NHttpClientConnection conn) throws IOException, HttpException {
    // The connection is ready for submission of a new request
    HttpContext context = conn.getContext();
    ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER);
    if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
        if (!tunnelHandler.isRequested()) {
            HttpRequest request = tunnelHandler.generateRequest(context);
            if (proxyauthenticator != null) {
                proxyauthenticator.authenticatePreemptively(request, context);
            }//from   ww w .ja  v a  2s. co m
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy());
            }
            conn.submitRequest(request);
            tunnelHandler.setRequested();
        }
        return;
    }

    Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.removeAttribute(ATTACHMENT_KEY);
    if (axis2Req == null || axis2Req.isCompleted()) {
        return;
    }
    try {
        processConnection(conn, axis2Req);
    } catch (ConnectionClosedException e) {
        metrics.incrementFaultsSending();
        handleException("I/O Error submitting request : " + e.getMessage(), e, conn);
    }
}

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

/**
 * Process a new connection over an existing TCP connection or new
 * // w ww . j a va 2 s. c  o  m
 * @param conn HTTP connection to be processed
 * @param axis2Req axis2 representation of the message in the connection
 * @throws ConnectionClosedException if the connection is closed 
 */
private void processConnection(final NHttpClientConnection conn, final Axis2HttpRequest axis2Req)
        throws ConnectionClosedException {

    // record start time of request
    ClientConnectionDebug cd = (ClientConnectionDebug) axis2Req.getMsgContext()
            .getProperty(CLIENT_CONNECTION_DEBUG);
    if (cd != null) {
        cd.recordRequestStartTime(conn, axis2Req);
        conn.getContext().setAttribute(CLIENT_CONNECTION_DEBUG, cd);
    }

    try {
        // Reset connection metrics
        conn.getMetrics().reset();

        HttpContext context = conn.getContext();
        ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
        axis2Req.setOutputBuffer(outputBuffer);
        context.setAttribute(REQUEST_SOURCE_BUFFER, outputBuffer);

        HttpRoute route = axis2Req.getRoute();
        context.setAttribute(AXIS2_HTTP_REQUEST, axis2Req);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, route.getTargetHost());
        context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());

        HttpRequest request = axis2Req.getRequest();
        request.setParams(new DefaultedHttpParams(request.getParams(), this.params));

        /*
         * Remove Content-Length and Transfer-Encoding headers, if already present.
         * */
        request.removeHeaders(HTTP.TRANSFER_ENCODING);
        request.removeHeaders(HTTP.CONTENT_LEN);

        this.httpProcessor.process(request, context);
        if (proxyauthenticator != null && route.getProxyHost() != null && !route.isTunnelled()) {
            proxyauthenticator.authenticatePreemptively(request, context);
        }
        if (axis2Req.getTimeout() > 0) {
            conn.setSocketTimeout(axis2Req.getTimeout());
        }

        context.setAttribute(NhttpConstants.ENDPOINT_PREFIX, axis2Req.getEndpointURLPrefix());
        context.setAttribute(NhttpConstants.HTTP_REQ_METHOD, request.getRequestLine().getMethod());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        setServerContextAttribute(NhttpConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis(), conn);
        setServerContextAttribute(NhttpConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis(),
                conn);

        conn.submitRequest(request);
    } catch (ConnectionClosedException e) {
        throw e;
    } catch (IOException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("I/O Error submitting request : " + e.getMessage(), e, conn);
    } catch (HttpException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("HTTP protocol error submitting request : " + e.getMessage(), e, conn);
    } finally {
        synchronized (axis2Req) {
            axis2Req.setReadyToStream(true);
            axis2Req.notifyAll();
        }
    }
}