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.ServerHandler.java

/**
 * Handle  errors while reading or writing to underlying channels
 * @param conn the connection being processed
 * @param e the exception encountered//from  w w w  .j a v a2  s. co m
 */
public void exception(NHttpServerConnection conn, Exception e) {
    String errMsg = "I/O error : " + e.getMessage();
    if (e instanceof HttpException) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }

        HttpContext context = conn.getContext();
        HttpRequest request = conn.getHttpRequest();
        ProtocolVersion ver = HttpVersion.HTTP_1_0;
        if (request != null && request.getRequestLine() != null) {
            ver = request.getRequestLine().getProtocolVersion();
        }
        HttpResponse response = responseFactory.newHttpResponse(ver, HttpStatus.SC_BAD_REQUEST, context);

        byte[] msg = EncodingUtils.getAsciiBytes("Malformed HTTP request: " + e.getMessage());
        ByteArrayEntity entity = new ByteArrayEntity(msg);
        entity.setContentType("text/plain; charset=US-ASCII");
        response.setEntity(entity);
        try {
            commitResponseHideExceptions(conn, response);
        } catch (Exception ignore) {
        }
    } else if (e instanceof ConnectionClosedException
            || (e.getMessage() != null && (e.getMessage().contains("Connection reset by peer")
                    || e.getMessage().contains("forcibly closed")))) {
        if (log.isDebugEnabled()) {
            errMsg = "I/O error (Probably the keepalive connection " + "was closed):" + e.getMessage();
            log.debug(errMsg);
        }
        shutdownConnection(conn, true, errMsg);
    } else if (e instanceof IOException && e.getMessage() != null) {
        errMsg = e.getMessage().toLowerCase();
        if (errMsg.indexOf("broken") != -1) {
            log.warn("I/O error (Probably the connection " + "was closed by the remote party):"
                    + e.getMessage());
        } else {
            log.error("I/O error: " + e.getMessage(), e);
        }
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        shutdownConnection(conn, true, errMsg);
    } else {
        errMsg = "Unexpected I/O error: " + e.getClass().getName();
        log.error(errMsg, e);
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        shutdownConnection(conn, true, errMsg);
    }
}

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

/**
 * Create a new server side worker to process an incoming message and optionally begin creating
 * its output. This however does not force the processor to write a response back as the
 * traditional servlet service() method, but creates the background required to write the
 * response, if one would be created./* w ww .  j  av  a2 s. c om*/
 *
 * @param cfgCtx the configuration context
 * @param metrics metrics collector
 * @param conn the underlying http connection
 * @param serverHandler the handler of the server side messages
 * @param request the http request received (might still be in the process of being streamed)
 * @param is the stream input stream to read the request body
 * @param response the response to be populated if applicable
 * @param os the output stream to write the response body if one is applicable
 */
public ServerWorker(final ConfigurationContext cfgCtx, final String schemeName, final MetricsCollector metrics,
        final NHttpServerConnection conn, final ServerHandler serverHandler, final HttpRequest request,
        final InputStream is, final HttpResponse response, final OutputStream os,
        final boolean isRestDispatching, final HttpGetRequestProcessor httpGetRequestProcessor) {

    this.cfgCtx = cfgCtx;
    this.schemeName = schemeName;
    this.metrics = metrics;
    this.conn = conn;
    this.serverHandler = serverHandler;
    this.request = request;
    this.response = response;
    this.is = is;
    this.os = os;
    this.isRestDispatching = isRestDispatching;
    this.httpGetRequestProcessor = httpGetRequestProcessor;
    this.msgContext = createMessageContext(request);
    conn.getContext().setAttribute(NhttpConstants.SERVER_WORKER_INIT_TIME, System.currentTimeMillis());
}

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

public void process(HttpRequest request, HttpResponse response, MessageContext msgContext,
        NHttpServerConnection conn, OutputStream ostream, boolean isRestDispatching) {

    String uri = request.getRequestLine().getUri();
    String serviceName = getServiceName(request);

    Map<String, String> parameters = new HashMap<String, String>();
    int pos = uri.indexOf("?");
    if (pos != -1) {
        msgContext.setTo(new EndpointReference(uri.substring(0, pos)));
        StringTokenizer st = new StringTokenizer(uri.substring(pos + 1), "&");
        while (st.hasMoreTokens()) {
            String param = st.nextToken();
            pos = param.indexOf("=");
            if (pos != -1) {
                parameters.put(param.substring(0, pos), param.substring(pos + 1));
            } else {
                parameters.put(param, null);
            }/* w  w w  .ja  v a2s  .  c o  m*/
        }
    } else {
        msgContext.setTo(new EndpointReference(uri));
    }

    SimpleOutputBuffer outputBuffer = (SimpleOutputBuffer) conn.getContext()
            .getAttribute(PASS_THROUGH_RESPONSE_SOURCE_BUFFER);
    ContentOutputStream os = new ContentOutputStream(outputBuffer);

    if (isServiceListBlocked(uri)) {
        sendResponseAndFinish(response, HttpStatus.SC_FORBIDDEN, conn, os, msgContext);
    } else if (uri.equals("/favicon.ico")) {
        response.addHeader(LOCATION, "http://ws.apache.org/favicon.ico");
        sendResponseAndFinish(response, HttpStatus.SC_MOVED_PERMANENTLY, conn, os, msgContext);
    } else if (serviceName != null && parameters.containsKey("wsdl")) {
        generateWsdl(response, msgContext, conn, os, serviceName, parameters);
    } else if (serviceName != null && parameters.containsKey("wsdl2")) {
        generateWsdl2(response, msgContext, conn, os, serviceName);
    } else if (serviceName != null && parameters.containsKey("xsd")) {
        generateXsd(response, msgContext, conn, os, serviceName, parameters);
    } else {
        msgContext.setProperty(PassThroughConstants.REST_GET_DELETE_INVOKE, true);
    }
}

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
 *//*www.jav a2 s  . co m*/
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;
    }
}