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

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

Introduction

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

Prototype

void submitResponse(HttpResponse response) throws IOException, HttpException;

Source Link

Document

Submits {link @HttpResponse} to be sent to the client.

Usage

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 av  a  2 s  .c om
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.apache.synapse.transport.passthru.SourceRequest.java

/**
 * Start processing the request by connecting the pipe if this request has an entity body.
 * @param conn connection// w w w  .j  a  va 2s.  c om
 * @throws IOException if an error occurs
 * @throws HttpException if an error occurs
 */
public void start(NHttpServerConnection conn) throws IOException, HttpException {
    if (entityEnclosing) {
        pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source",
                sourceConfiguration);

        SourceContext.get(conn).setReader(pipe);

        // See if the client expects a 100-Continue
        if (((HttpEntityEnclosingRequest) request).expectContinue()) {
            HttpResponse ack = new BasicHttpResponse(version, HttpStatus.SC_CONTINUE, "Continue");
            conn.submitResponse(ack);
        }
    } else {
        // this request is completed, there is nothing more to read
        SourceContext.updateState(conn, ProtocolState.REQUEST_DONE);
        // No httpRequest content expected. Suspend client input
        conn.suspendInput();
    }
}

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

/**
 * Commit the response to the connection. Processes the response through the configured
 * HttpProcessor and submits it to be sent out. This method hides any exceptions and is targetted
 * for non critical (i.e. browser requests etc) requests, which are not core messages
 * @param conn the connection being processed
 * @param response the response to commit over the connection
 *//*from   w ww .j ava2  s. c om*/
public void commitResponseHideExceptions(final NHttpServerConnection conn, final HttpResponse response) {
    try {
        conn.suspendInput();
        sourceConfiguration.getHttpProcessor().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.apache.synapse.transport.nhttp.ServerHandler.java

/**
 * Commit the response to the connection. Processes the response through the configured
 * HttpProcessor and submits it to be sent out. This method hides any exceptions and is targetted
 * for non critical (i.e. browser requests etc) requests, which are not core messages
 * @param conn the connection being processed
 * @param response the response to commit over the connection
 *//*  ww  w  .  j  a  va2 s.  c  om*/
public void commitResponseHideExceptions(final NHttpServerConnection conn, final HttpResponse response) {
    try {
        conn.suspendInput();
        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.apache.synapse.transport.nhttp.ServerHandler.java

/**
 * Commit the response to the connection. Processes the response through the configured
 * HttpProcessor and submits it to be sent out. Re-Throws exceptions, after closing connections
 * @param conn the connection being processed
 * @param response the response to commit over the connection
 * @throws IOException if an IO error occurs while sending the response
 * @throws HttpException if a HTTP protocol violation occurs while sending the response
 */// w  w  w  . ja  v a  2s.c om
public void commitResponse(final NHttpServerConnection conn, final HttpResponse response)
        throws IOException, HttpException {
    try {
        BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();
        Header[] headers = response.getAllHeaders();
        int contentLength = -1;
        if (canResponseHaveBody(response, conn)) {
            if (entity == null) {
                entity = new BasicHttpEntity();
            }
            for (Header header : headers) {
                if (header.getName().equals(HTTP.CONTENT_LEN) && Integer.parseInt(header.getValue()) > 0) {
                    contentLength = Integer.parseInt(header.getValue());
                    response.removeHeader(header);
                }
            }
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(true);
            }
        } else {
            if (entity != null) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            }
        }
        response.setEntity(entity);
        conn.suspendInput();
        HttpContext context = conn.getContext();
        httpProcessor.process(response, context);
        conn.getContext().setAttribute(NhttpConstants.RES_TO_CLIENT_WRITE_START_TIME,
                System.currentTimeMillis());
        conn.submitResponse(response);
    } catch (HttpException e) {
        shutdownConnection(conn, true, e.getMessage());
        throw e;
    } catch (IOException e) {
        shutdownConnection(conn, true, e.getMessage());
        throw e;
    }
}

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

/**
 * Process a new incoming request/* w  ww  . ja v  a 2s  .c  o m*/
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {

    HttpContext context = conn.getContext();
    context.setAttribute(NhttpConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());
    context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_START_TIME, System.currentTimeMillis());
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    context.setAttribute(NhttpConstants.MESSAGE_IN_FLIGHT, "true");

    // prepare to collect debug information
    conn.getContext().setAttribute(ServerHandler.SERVER_CONNECTION_DEBUG, new ServerConnectionDebug(conn));

    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    try {
        InputStream is;
        // Only create an input buffer and ContentInputStream if the request has content
        if (request instanceof HttpEntityEnclosingRequest) {
            // Mark request as not yet fully read, to detect timeouts from harmless keepalive deaths
            conn.getContext().setAttribute(NhttpConstants.REQUEST_READ, Boolean.FALSE);

            ContentInputBuffer inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
            context.setAttribute(REQUEST_SINK_BUFFER, inputBuffer);
            is = new ContentInputStream(inputBuffer);
        } else {
            is = null;
            conn.getContext().removeAttribute(NhttpConstants.REQUEST_READ);
        }

        ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
        context.setAttribute(RESPONSE_SOURCE_BUFFER, outputBuffer);
        OutputStream os = new ContentOutputStream(outputBuffer);

        // create the default response to this request
        ProtocolVersion httpVersion = request.getRequestLine().getProtocolVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);

        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);

        if (metrics != null) {
            metrics.incrementMessagesReceived();
        }
        // hand off processing of the request to a thread off the pool
        ServerWorker worker = new ServerWorker(cfgCtx, scheme.getName(), metrics, conn, this, request, is,
                response, os, listenerContext.isRestDispatching(),
                listenerContext.getHttpGetRequestProcessor());

        if (workerPool != null) {
            workerPool.execute(worker);
        } else if (executor != null) {
            Map<String, String> headers = new HashMap<String, String>();
            for (Header header : request.getAllHeaders()) {
                headers.put(header.getName(), header.getValue());
            }

            EvaluatorContext evaluatorContext = new EvaluatorContext(request.getRequestLine().getUri(),
                    headers);
            int priority = parser.parse(evaluatorContext);
            executor.execute(worker, priority);
        }

        // See if the client expects a 100-Continue
        Header expect = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE);
        if (expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue())) {
            HttpResponse ack = new BasicHttpResponse(request.getProtocolVersion(), HttpStatus.SC_CONTINUE,
                    "Continue");
            conn.submitResponse(ack);
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Expect :100 Continue hit, sending ack back to the server");
            }
            return;
        }

    } catch (Exception e) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}

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

public void exception(NHttpServerConnection conn, Exception ex) {
    boolean isFault = false;
    if (ex instanceof IOException) {
        logIOException(conn, (IOException) ex);

        metrics.incrementFaultsReceiving();

        ProtocolState state = SourceContext.getState(conn);
        if (state == ProtocolState.REQUEST_BODY || state == ProtocolState.REQUEST_HEAD) {
            informReaderError(conn);//from w  w w  .ja  v  a2  s  . c  o  m
        } else if (state == ProtocolState.RESPONSE_BODY || state == ProtocolState.RESPONSE_HEAD) {
            informWriterError(conn);
        } else if (state == ProtocolState.REQUEST_DONE) {
            informWriterError(conn);
        } else if (state == ProtocolState.RESPONSE_DONE) {
            informWriterError(conn);
        }
        isFault = true;
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    } else if (ex instanceof HttpException) {
        try {
            if (conn.isResponseSubmitted()) {
                sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
                return;
            }
            HttpContext httpContext = conn.getContext();

            HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST,
                    "Bad request");
            response.setParams(
                    new DefaultedHttpParams(sourceConfiguration.getHttpParams(), response.getParams()));
            response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

            // Pre-process HTTP request
            httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            httpContext.setAttribute(ExecutionContext.HTTP_REQUEST, null);
            httpContext.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

            sourceConfiguration.getHttpProcessor().process(response, httpContext);

            conn.submitResponse(response);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            conn.close();
        } catch (Exception ex1) {
            log.error(ex.getMessage(), ex);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
            isFault = true;
        }
    } else {
        log.error("Unexpected error: " + ex.getMessage(), ex);
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
        isFault = true;
    }

    if (isFault) {
        rollbackTransaction(conn);
    }
}