Example usage for org.apache.http.nio NHttpServerConnection getContext

List of usage examples for org.apache.http.nio NHttpServerConnection getContext

Introduction

In this page you can find the example usage for org.apache.http.nio NHttpServerConnection getContext.

Prototype

HttpContext getContext();

Source Link

Document

Returns an HTTP execution context associated with this connection.

Usage

From source file:org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug.java

public ServerConnectionDebug(NHttpServerConnection conn) {

    super();// w  w w . j  av a2s .c  o  m
    this.connectionCreationTime = (Long) conn.getContext().getAttribute(ServerHandler.CONNECTION_CREATION_TIME);
    this.requestStartTime = System.currentTimeMillis();

    // assume an entity body is not present. If present this would be overwritten
    this.requestCompletionTime = System.currentTimeMillis();

    RequestLine reqLine = conn.getHttpRequest().getRequestLine();
    this.requestURLPAth = reqLine.getUri();
    this.requestHTTPMethod = reqLine.getMethod();
    this.requestHTTPProtocol = reqLine.getProtocolVersion().toString();

    if (conn instanceof HttpInetConnection) {
        HttpInetConnection inetConn = (HttpInetConnection) conn;
        InetAddress remoteAddr = inetConn.getRemoteAddress();
        if (remoteAddr != null) {
            this.remoteClientIP = remoteAddr.getHostAddress();
        }
    }

    HttpRequest req = conn.getHttpRequest();
    this.headers = req.getAllHeaders();
}

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

/**
 * Commit the response to the connection. Processes the response through the configured
 * HttpProcessor and submits it to be sent out
 * @param conn the connection being processed
 * @param response the response to commit over the connection
 *///from  ww  w.j a va  2s . c  o m
public void commitResponse(final NHttpServerConnection conn, final HttpResponse response) {
    try {
        httpProcessor.process(response, conn.getContext());
        conn.submitResponse(response);
    } catch (HttpException e) {
        handleException("Unexpected HTTP protocol error : " + e.getMessage(), e, conn);
    } catch (IOException e) {
        handleException("IO error submiting response : " + e.getMessage(), e, conn);
    }
}

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  . ja  va  2 s .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();
}

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

/**
 * Produce the content in to the pipe.//from w  ww. j  a  v a2 s  . co m
 * @param conn the connection
 * @param decoder content decoder
 *
 * @throws java.io.IOException if an error occurs
 * @return number of bytes read
 */
public int read(NHttpServerConnection conn, ContentDecoder decoder) throws IOException {
    if (pipe == null) {
        throw new IllegalStateException("A Pipe must be connected before calling read");
    }

    if (entityEnclosing) {
        int bytes = pipe.produce(decoder);

        if (decoder.isCompleted()) {
            conn.getContext().setAttribute(PassThroughConstants.REQ_FROM_CLIENT_READ_END_TIME,
                    System.currentTimeMillis());
            sourceConfiguration.getMetrics()
                    .notifyReceivedMessageSize(conn.getMetrics().getReceivedBytesCount());

            // Update connection state
            SourceContext.updateState(conn, ProtocolState.REQUEST_DONE);
            // Suspend client input
            conn.suspendInput();
        }
        return bytes;
    } else {
        throw new IllegalStateException("Only Entity Enclosing Requests " + "can read content in to the pipe");
    }
}

From source file:org.apache.synapse.transport.passthru.api.PassThroughNHttpGetProcessor.java

private void write(NHttpServerConnection conn, OutputStream os, byte[] data) throws IOException {
    synchronized (conn.getContext()) {
        // The SimpleOutputBuffer on which this output stream is based is not thread safe.
        // Explicit synchronization required.
        // Do not worry about running out of buffer space.
        // SimpleOutputBuffer expands to fit the data.
        os.write(data);/*from   www .  j  a  va 2s  .  c om*/
    }
}

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

void sendResponse(int statusCode, IEncodeable responseObject) {
    try {/*from  ww w .  j  a  v a2s. co m*/
        HttpResponse responseHandle = httpExchange.getResponse();
        responseHandle.setHeader("Content-Type", "application/octet-stream");
        responseHandle.setStatusCode(statusCode);

        if (responseObject != null) {
            try {
                logger.trace("sendResponse: requestId={} statusCode={} responseObject={}", requestId,
                        statusCode, responseObject);
                logger.debug("sendResponse: requestId={} statusCode={} responseObject={}", requestId,
                        statusCode, responseObject.getClass().getSimpleName());

                //Check isDebugEnabled() here for possible performance reasons.
                if (logger.isDebugEnabled() && channel.getConnection() != null) {
                    NHttpServerConnection nHttpServerConnection = ((HttpsServerConnection) channel
                            .getConnection()).getNHttpServerConnection();
                    logger.debug("sendResponse: timeout={} {} context={}", httpExchange.getTimeout(),
                            nHttpServerConnection.getSocketTimeout(), nHttpServerConnection.getContext());
                }
                EncoderCalc calc = new EncoderCalc();
                calc.setEncoderContext(endpoint.getEncoderContext());
                calc.putMessage(responseObject);
                int len = calc.getLength();
                byte[] data = new byte[len];
                BinaryEncoder enc = new BinaryEncoder(data);
                enc.setEncoderContext(endpoint.getEncoderContext());
                enc.setEncoderMode(EncoderMode.NonStrict);
                enc.putMessage(responseObject);
                responseHandle.setEntity(new NByteArrayEntity(data));
            } catch (EncodingException e) {
                logger.info("sendResponse: Encoding failed", e);
                // Internal Error
                if (responseObject instanceof ErrorMessage == false) {
                    responseHandle.setStatusCode(500);
                }
            }
        }
        logger.debug("sendResponse: {} length={}", responseHandle,
                responseHandle.getEntity().getContentLength());
        httpExchange.submitResponse(new BasicAsyncResponseProducer(responseHandle));
    } finally {
        endpoint.pendingRequests.remove(requestId);
    }
}

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

private void rollbackTransaction(NHttpServerConnection conn) {
    try {/*ww w . j  a v a2  s . c  o  m*/
        Long serverWorkerThreadId = (Long) conn.getContext()
                .getAttribute(PassThroughConstants.SERVER_WORKER_THREAD_ID);
        if (serverWorkerThreadId != null) {
            TranscationManger.rollbackTransaction(false, serverWorkerThreadId);
        }
    } catch (Exception ex) {
        log.warn("Transaction rollback error after Connection closed " + ex.getMessage() + conn);
    }
}

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

private void endTransaction(NHttpServerConnection conn) {
    try {//from  w w w  .ja  va2  s  .co  m
        Long serverWorkerThreadId = (Long) conn.getContext()
                .getAttribute(PassThroughConstants.SERVER_WORKER_THREAD_ID);
        if (serverWorkerThreadId != null) {
            TranscationManger.endTransaction(false, serverWorkerThreadId);
        }
    } catch (Exception ex) {
        log.warn("Transaction rollback error after Connection closed " + ex.getMessage() + conn);
    }
}

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  ww  .  jav a 2s .  com
 * @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;
}