Example usage for org.apache.http.protocol HTTP TRANSFER_ENCODING

List of usage examples for org.apache.http.protocol HTTP TRANSFER_ENCODING

Introduction

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

Prototype

String TRANSFER_ENCODING

To view the source code for org.apache.http.protocol HTTP TRANSFER_ENCODING.

Click Source Link

Usage

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

/**
 * Remove unwanted headers from the given header map.
 *
 * @param headers Header map//from   w  ww . j  a  va 2 s. c  o m
 * @param nHttpConfiguration NHttp transporter base configurations
 */
private void removeUnwantedHeadersFromHeaderMap(Map headers, NHttpConfiguration nHttpConfiguration) {

    Iterator iter = headers.keySet().iterator();
    while (iter.hasNext()) {
        String headerName = (String) iter.next();
        if (HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName)
                || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)
                || HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName)
                || HTTP.CONTENT_LEN.equalsIgnoreCase(headerName)) {
            iter.remove();
        }

        if (HTTP.SERVER_HEADER.equalsIgnoreCase(headerName)
                && !nHttpConfiguration.isPreserveHttpHeader(HTTP.SERVER_HEADER)) {
            iter.remove();
        }

        if (HTTP.USER_AGENT.equalsIgnoreCase(headerName)
                && !nHttpConfiguration.isPreserveHttpHeader(HTTP.USER_AGENT)) {
            iter.remove();
        }

        if (HTTP.DATE_HEADER.equalsIgnoreCase(headerName)
                && !nHttpConfiguration.isPreserveHttpHeader(HTTP.DATE_HEADER)) {
            iter.remove();
        }

    }
}

From source file:org.apache.synapse.message.senders.blocking.BlockingMsgSenderUtils.java

private static boolean isSkipTransportHeader(String headerName) {

    return HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName)
            || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)
            || HTTP.DATE_HEADER.equalsIgnoreCase(headerName) || HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName)
            || HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) || HTTP.SERVER_HEADER.equalsIgnoreCase(headerName)
            || HTTP.USER_AGENT.equalsIgnoreCase(headerName) || "SOAPAction".equalsIgnoreCase(headerName);

}

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

/**
  * Handles browser exception.//from w ww .j av a2s  .c o  m
  *
  * @param response HttpResponse
  * @param conn     NHttpServerConnection
  * @param os       OutputStream
  * @param msg      message
  * @param e        Exception
  */
protected void handleBrowserException(HttpResponse response, MessageContext msgContext,
        NHttpServerConnection conn, OutputStream os, String msg, Exception e) {
    if (e == null) {
        log.error(msg);
    } else {
        log.error(msg, e);
    }

    if (!response.containsHeader(HTTP.TRANSFER_ENCODING)) {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.setReasonPhrase(msg);
        response.addHeader(CONTENT_TYPE, TEXT_HTML);
        sourceHandler.commitResponseHideExceptions(conn, response);
        try {
            write(conn, os, msg.getBytes());
            os.close();
        } catch (IOException ignore) {
        }
    }

    if (conn != null) {
        try {
            conn.shutdown();
        } catch (IOException ignore) {
        }
    }
    msgContext.setProperty(GET_REQUEST_HANDLED, Boolean.TRUE);
}

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

/**
 * Process the incoming request/*from w w  w. j a va2  s .  co m*/
 */
@SuppressWarnings({ "unchecked" })
public void run() {

    CustomLogSetter.getInstance().clearThreadLocalContent();
    conn.getContext().setAttribute(NhttpConstants.SERVER_WORKER_START_TIME, System.currentTimeMillis());
    conn.getContext().setAttribute(NhttpConstants.SERVER_WORKER_THREAD_ID, Thread.currentThread().getId());
    String method = request.getRequestLine().getMethod().toUpperCase();
    msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getRequestLine().getMethod());

    if (NHttpConfiguration.getInstance().isHttpMethodDisabled(method)) {
        handleException("Unsupported method : " + method, null);
    }

    //String uri = request.getRequestLine().getUri();
    String oriUri = request.getRequestLine().getUri();
    String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath());

    msgContext.setProperty(NhttpConstants.REST_URL_POSTFIX, restUrlPostfix);
    String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
    if (servicePrefix.indexOf("://") == -1) {
        HttpInetConnection inetConn = (HttpInetConnection) conn;
        InetAddress localAddr = inetConn.getLocalAddress();
        if (localAddr != null) {
            servicePrefix = schemeName + "://" + localAddr.getHostName() + ":" + inetConn.getLocalPort()
                    + servicePrefix;
        }
    }
    msgContext.setProperty(NhttpConstants.SERVICE_PREFIX, servicePrefix);

    if ("GET".equals(method)) {
        httpGetRequestProcessor.process(request, response, msgContext, conn, os, isRestDispatching);
    } else if ("POST".equals(method)) {
        processEntityEnclosingMethod();
    } else if ("PUT".equals(method)) {
        processEntityEnclosingMethod();
    } else if ("HEAD".equals(method)) {
        processNonEntityEnclosingMethod();
    } else if ("OPTIONS".equals(method)) {
        processNonEntityEnclosingMethod();
    } else if ("DELETE".equals(method)) {
        processGetAndDelete("DELETE");
    } else if ("TRACE".equals(method)) {
        processNonEntityEnclosingMethod();
    } else if ("PATCH".equals(method)) {
        processEntityEnclosingMethod();
    } else {
        handleException("Unsupported method : " + method, null);
    }

    // here the RequestResponseTransport plays an important role when it comes to
    // dual channel invocation. This is becasue we need to ACK to the request once the request
    // is received to synapse. Otherwise we will not be able to support the single channel
    // invocation within the actual service and synapse for a dual channel request from the
    // client.
    if (isAckRequired()) {
        String respWritten = "";
        if (msgContext.getOperationContext() != null) {
            respWritten = (String) msgContext.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
        }
        boolean respWillFollow = !Constants.VALUE_TRUE.equals(respWritten) && !"SKIP".equals(respWritten);
        boolean acked = (((RequestResponseTransport) msgContext
                .getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                        .getStatus() == RequestResponseTransport.RequestResponseTransportStatus.ACKED);
        boolean forced = msgContext.isPropertyTrue(NhttpConstants.FORCE_SC_ACCEPTED);
        boolean nioAck = msgContext.isPropertyTrue("NIO-ACK-Requested", false);

        if (respWillFollow || acked || forced || nioAck) {

            if (!nioAck) {
                if (log.isDebugEnabled()) {
                    log.debug("Sending 202 Accepted response for MessageID : " + msgContext.getMessageID()
                            + " response written : " + respWritten + " response will follow : " + respWillFollow
                            + " acked : " + acked + " forced ack : " + forced);
                }
                response.setStatusCode(HttpStatus.SC_ACCEPTED);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Sending ACK response with status " + msgContext.getProperty(NhttpConstants.HTTP_SC)
                                    + ", for MessageID : " + msgContext.getMessageID());
                }
                response.setStatusCode(
                        Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString()));
                Map<String, String> responseHeaders = (Map<String, String>) msgContext
                        .getProperty(MessageContext.TRANSPORT_HEADERS);
                if (responseHeaders != null) {
                    for (String headerName : responseHeaders.keySet()) {
                        response.addHeader(headerName, responseHeaders.get(headerName));

                        String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                        Map map = (Map) msgContext.getProperty(excessProp);
                        if (map != null) {
                            log.debug("Number of excess values for " + headerName + " header is : "
                                    + ((Collection) (map.get(headerName))).size());

                            for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                                String key = (String) iterator.next();

                                for (String excessVal : (Collection<String>) map.get(key)) {
                                    response.addHeader(headerName, (String) excessVal);
                                }

                            }
                        }
                    }

                }
            }

            if (metrics != null) {
                metrics.incrementMessagesSent();
            }

            try {

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

                serverHandler.commitResponse(conn, response);

            } catch (HttpException e) {
                if (metrics != null) {
                    metrics.incrementFaultsSending();
                }
                handleException("Unexpected HTTP protocol error : " + e.getMessage(), e);
            } catch (ConnectionClosedException e) {
                if (metrics != null) {
                    metrics.incrementFaultsSending();
                }
                log.warn("Connection closed by client (Connection closed)");
            } catch (IllegalStateException e) {
                if (metrics != null) {
                    metrics.incrementFaultsSending();
                }
                log.warn("Connection closed by client (Buffer closed)");
            } catch (IOException e) {
                if (metrics != null) {
                    metrics.incrementFaultsSending();
                }
                handleException("IO Error sending response message", e);
            } catch (Exception e) {
                if (metrics != null) {
                    metrics.incrementFaultsSending();
                }
                handleException("General Error sending response message", e);
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignore) {
                }
            }

            // make sure that the output stream is flushed and closed properly
            try {
                os.flush();
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor.java

/**
 * Handles browser exception.//from  w w w.  ja  v  a2 s.  c  o  m
 *
 * @param response HttpResponse
 * @param conn     NHttpServerConnection
 * @param os       OutputStream
 * @param msg      message
 * @param e        Exception
 */
protected void handleBrowserException(HttpResponse response, NHttpServerConnection conn, OutputStream os,
        String msg, Exception e) {
    if (e == null) {
        log.error(msg);
    } else {
        log.error(msg, e);
    }

    if (!response.containsHeader(HTTP.TRANSFER_ENCODING)) {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.setReasonPhrase(msg);
        //response.addHeader(CONTENT_TYPE, TEXT_HTML);
        //serverHandler.commitResponseHideExceptions(conn, response);
        try {
            os.write(msg.getBytes());
            os.close();
        } catch (IOException ignore) {
        }
    }

    if (conn != null) {
        try {
            conn.shutdown();
        } catch (IOException ignore) {
        }
    }
}

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

/**
 * Handles browser exception.// ww w  . j  a va 2s  .  c o m
 *
 * @param response HttpResponse
 * @param conn     NHttpServerConnection
 * @param os       OutputStream
 * @param msg      message
 * @param e        Exception
 */
protected void handleBrowserException(HttpResponse response, NHttpServerConnection conn, OutputStream os,
        String msg, Exception e) {
    if (e == null) {
        log.error(msg);
    } else {
        log.error(msg, e);
    }

    if (!response.containsHeader(HTTP.TRANSFER_ENCODING)) {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.setReasonPhrase(msg);
        response.addHeader(CONTENT_TYPE, TEXT_HTML);
        serverHandler.commitResponseHideExceptions(conn, response);
        try {
            os.write(msg.getBytes());
            os.close();
        } catch (IOException ignore) {
        }
    }

    if (conn != null) {
        try {
            conn.shutdown();
        } catch (IOException ignore) {
        }
    }
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

/**
 * Remove unwanted headers from the transport headers map of outgoing request. These are headers which
 * should be dictated by the transport and not the user. We remove these as these may get
 * copied from the request messages// w w  w.j a va  2  s  .  com
 *
 * @param msgContext the Axis2 Message context from which these headers should be removed
 */
private void removeUnwantedHeaders(MessageContext msgContext) {
    Map headers = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    if (headers == null || headers.isEmpty()) {
        return;
    }

    Iterator iter = headers.keySet().iterator();
    while (iter.hasNext()) {
        String headerName = (String) iter.next();
        if (HTTP.CONN_DIRECTIVE.equalsIgnoreCase(headerName)
                || HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)
                || HTTP.DATE_HEADER.equalsIgnoreCase(headerName)
                || HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName)
                || HTTP.CONTENT_LEN.equalsIgnoreCase(headerName)) {
            iter.remove();
        }
    }
}

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

/**
 * Process a new connection over an existing TCP connection or new
 * /*www . j  a  v a2 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();
        }
    }
}