Example usage for org.apache.http.entity BasicHttpEntity BasicHttpEntity

List of usage examples for org.apache.http.entity BasicHttpEntity BasicHttpEntity

Introduction

In this page you can find the example usage for org.apache.http.entity BasicHttpEntity BasicHttpEntity.

Prototype

public BasicHttpEntity() 

Source Link

Usage

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

/**
 * Create and return a new HttpPost request to the destination EPR
 * @return the HttpRequest to be sent out
 *///from  ww  w . j a  va  2s  .c  o  m
public HttpRequest getRequest() {
    HttpPost httpRequest = new HttpPost(epr.getAddress());
    httpRequest.setEntity(new BasicHttpEntity());
    return httpRequest;
}

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

/**
 * Process a response received for the request sent out
 * @param conn the connection being processed
 *//*  w w  w . j a va 2 s  .co  m*/
public void responseReceived(final NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();

    try {
        Pipe responsePipe = Pipe.open();
        context.setAttribute(RESPONSE_SINK_CHANNEL, responsePipe.sink());

        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        context.setAttribute(HttpContext.HTTP_RESPONSE, response);

        workerPool.execute(new ClientWorker(cfgCtx, Channels.newInputStream(responsePipe.source()),
                (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT)));

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

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

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

    HttpContext context = conn.getContext();
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(HttpContext.HTTP_REQUEST, request);

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

    try {
        Pipe requestPipe = Pipe.open(); // the pipe used to process the request
        Pipe responsePipe = Pipe.open(); // the pipe used to process the response
        context.setAttribute(REQUEST_SINK_CHANNEL, requestPipe.sink());
        context.setAttribute(RESPONSE_SOURCE_CHANNEL, responsePipe.source());

        // create the default response to this request
        HttpVersion httpVersion = request.getRequestLine().getHttpVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);
        response.setParams(this.params);

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

        // hand off processing of the request to a thread off the pool
        workerPool.execute(
                new ServerWorker(cfgCtx, conn, this, request, Channels.newInputStream(requestPipe.source()),
                        response, Channels.newOutputStream(responsePipe.sink())));

    } catch (IOException e) {
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}

From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

public void openConnectionForSend(final String transactionUrl, final Peer peer) throws IOException {

    final CommunicationsSession commSession = peer.getCommunicationsSession();
    final String flowFilesPath = transactionUrl + "/flow-files";
    final HttpPost post = createPost(flowFilesPath);
    // Set uri so that it'll be used as transit uri.
    ((HttpCommunicationsSession) peer.getCommunicationsSession()).setDataTransferUrl(post.getURI().toString());

    post.setHeader("Content-Type", "application/octet-stream");
    post.setHeader("Accept", "text/plain");
    post.setHeader(HttpHeaders.PROTOCOL_VERSION,
            String.valueOf(transportProtocolVersionNegotiator.getVersion()));

    setHandshakeProperties(post);/*from  ww  w .  j a va  2s .  c  o  m*/

    final CountDownLatch initConnectionLatch = new CountDownLatch(1);

    final URI requestUri = post.getURI();
    final PipedOutputStream outputStream = new PipedOutputStream();
    final PipedInputStream inputStream = new PipedInputStream(outputStream,
            DATA_PACKET_CHANNEL_READ_BUFFER_SIZE);
    final ReadableByteChannel dataPacketChannel = Channels.newChannel(inputStream);
    final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() {

        private final ByteBuffer buffer = ByteBuffer.allocate(DATA_PACKET_CHANNEL_READ_BUFFER_SIZE);

        private int totalRead = 0;
        private int totalProduced = 0;

        private boolean requestHasBeenReset = false;

        @Override
        public HttpHost getTarget() {
            return URIUtils.extractHost(requestUri);
        }

        @Override
        public HttpRequest generateRequest() throws IOException, HttpException {

            // Pass the output stream so that Site-to-Site client thread can send
            // data packet through this connection.
            logger.debug("sending data to {} has started...", flowFilesPath);
            ((HttpOutput) commSession.getOutput()).setOutputStream(outputStream);
            initConnectionLatch.countDown();

            final BasicHttpEntity entity = new BasicHttpEntity();
            entity.setChunked(true);
            entity.setContentType("application/octet-stream");
            post.setEntity(entity);
            return post;
        }

        private final AtomicBoolean bufferHasRemainingData = new AtomicBoolean(false);

        /**
         * If the proxy server requires authentication, the same POST request has to be sent again.
         * The first request will result 407, then the next one will be sent with auth headers and actual data.
         * This method produces a content only when it's need to be sent, to avoid producing the flow-file contents twice.
         * Whether we need to wait auth is determined heuristically by the previous POST request which creates transaction.
         * See {@link SiteToSiteRestApiClient#initiateTransactionForSend(HttpPost)} for further detail.
         */
        @Override
        public void produceContent(final ContentEncoder encoder, final IOControl ioControl) throws IOException {

            if (shouldCheckProxyAuth() && proxyAuthRequiresResend.get() && !requestHasBeenReset) {
                logger.debug("Need authentication with proxy server. Postpone producing content.");
                encoder.complete();
                return;
            }

            if (bufferHasRemainingData.get()) {
                // If there's remaining buffer last time, send it first.
                writeBuffer(encoder);
                if (bufferHasRemainingData.get()) {
                    return;
                }
            }

            int read;
            // This read() blocks until data becomes available,
            // or corresponding outputStream is closed.
            if ((read = dataPacketChannel.read(buffer)) > -1) {

                logger.trace("Read {} bytes from dataPacketChannel. {}", read, flowFilesPath);
                totalRead += read;

                buffer.flip();
                writeBuffer(encoder);

            } else {

                final long totalWritten = commSession.getOutput().getBytesWritten();
                logger.debug(
                        "sending data to {} has reached to its end. produced {} bytes by reading {} bytes from channel. {} bytes written in this transaction.",
                        flowFilesPath, totalProduced, totalRead, totalWritten);

                if (totalRead != totalWritten || totalProduced != totalWritten) {
                    final String msg = "Sending data to %s has reached to its end, but produced : read : wrote byte sizes (%d : %d : %d) were not equal. Something went wrong.";
                    throw new RuntimeException(
                            String.format(msg, flowFilesPath, totalProduced, totalRead, totalWritten));
                }
                transferDataLatch.countDown();
                encoder.complete();
                dataPacketChannel.close();
            }

        }

        private void writeBuffer(ContentEncoder encoder) throws IOException {
            while (buffer.hasRemaining()) {
                final int written = encoder.write(buffer);
                logger.trace("written {} bytes to encoder.", written);
                if (written == 0) {
                    logger.trace("Buffer still has remaining. {}", buffer);
                    bufferHasRemainingData.set(true);
                    return;
                }
                totalProduced += written;
            }
            bufferHasRemainingData.set(false);
            buffer.clear();
        }

        @Override
        public void requestCompleted(final HttpContext context) {
            logger.debug("Sending data to {} completed.", flowFilesPath);
            debugProxyAuthState(context);
        }

        @Override
        public void failed(final Exception ex) {
            final String msg = String.format("Failed to send data to %s due to %s", flowFilesPath,
                    ex.toString());
            logger.error(msg, ex);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
        }

        @Override
        public boolean isRepeatable() {
            // In order to pass authentication, request has to be repeatable.
            return true;
        }

        @Override
        public void resetRequest() throws IOException {
            logger.debug("Sending data request to {} has been reset...", flowFilesPath);
            requestHasBeenReset = true;
        }

        @Override
        public void close() throws IOException {
            logger.debug("Closing sending data request to {}", flowFilesPath);
            closeSilently(outputStream);
            closeSilently(dataPacketChannel);
            stopExtendingTtl();
        }
    };

    postResult = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null);

    try {
        // Need to wait the post request actually started so that we can write to its output stream.
        if (!initConnectionLatch.await(connectTimeoutMillis, TimeUnit.MILLISECONDS)) {
            throw new IOException("Awaiting initConnectionLatch has been timeout.");
        }

        // Started.
        transferDataLatch = new CountDownLatch(1);
        startExtendingTtl(transactionUrl, dataPacketChannel, null);

    } catch (final InterruptedException e) {
        throw new IOException("Awaiting initConnectionLatch has been interrupted.", e);
    }

}

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

/**
 * Process a new incoming request/*  w  ww  .ja  va 2s  .  c  om*/
 * @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.ServerWorker.java

/**
 * Get Uri of underlying SourceRequest and  calculate service prefix and add to message context
 * create response buffers for  HTTP GET, DELETE, OPTION and HEAD methods
 * @param msgContext Axis2MessageContext of the request
 * @param method HTTP Method of the request
 *///from  w  ww .  j  a v a 2  s  .  c o m
public void processHttpRequestUri(MessageContext msgContext, String method) {
    String servicePrefixIndex = "://";
    ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext();
    msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getMethod());

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

    String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
    if (servicePrefix.indexOf(servicePrefixIndex) == -1) {
        HttpInetConnection inetConn = (HttpInetConnection) request.getConnection();
        InetAddress localAddr = inetConn.getLocalAddress();
        if (localAddr != null) {
            servicePrefix = sourceConfiguration.getScheme().getName() + servicePrefixIndex
                    + localAddr.getHostAddress() + ":" + inetConn.getLocalPort() + servicePrefix;
        }
    }

    msgContext.setProperty(PassThroughConstants.SERVICE_PREFIX, servicePrefix);
    msgContext.setTo(new EndpointReference(restUrlPostfix));
    msgContext.setProperty(PassThroughConstants.REST_URL_POSTFIX, restUrlPostfix);

    if (HttpMethod.GET.equals(method) || HttpMethod.DELETE.equals(method) || HttpMethod.HEAD.equals(method)
            || "OPTIONS".equals(method)) {
        HttpResponse response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(),
                HttpStatus.SC_OK, request.getConnection().getContext());

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

        httpGetRequestProcessor.process(request.getRequest(), response, msgContext, request.getConnection(), os,
                isRestDispatching);
    }
}

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

/**
 * Starts the response by writing the headers
 * @param conn connection//from  w ww. j  a va 2s  . co m
 * @throws java.io.IOException if an error occurs
 * @throws org.apache.http.HttpException if an error occurs
 */
public void start(NHttpServerConnection conn) throws IOException, HttpException {
    // create the response
    response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), this.status,
            request.getConnection().getContext());

    if (statusLine != null) {
        response.setStatusLine(version, status, statusLine);
    } else {
        response.setStatusCode(status);
    }

    BasicHttpEntity entity = null;

    if (canResponseHaveBody(request.getRequest(), response)) {
        entity = new BasicHttpEntity();

        int contentLength = -1;
        String contentLengthHeader = null;
        if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
            contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
        }

        if (contentLengthHeader != null) {
            contentLength = Integer.parseInt(contentLengthHeader);
            headers.remove(HTTP.CONTENT_LEN);
        }

        if (contentLength != -1) {
            entity.setChunked(false);
            entity.setContentLength(contentLength);
        } else {
            entity.setChunked(true);
        }

    }

    response.setEntity(entity);

    // set any transport headers
    Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet();

    for (Map.Entry<String, TreeSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                response.addHeader(entry.getKey(), i.next());
            }
        }
    }
    response.setParams(new DefaultedHttpParams(response.getParams(), sourceConfiguration.getHttpParams()));

    SourceContext.updateState(conn, ProtocolState.RESPONSE_HEAD);

    // Pre-process HTTP response
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_RESPONSE, response);
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, SourceContext.getRequest(conn).getRequest());

    sourceConfiguration.getHttpProcessor().process(response, conn.getContext());
    conn.submitResponse(response);

    // Handle non entity body responses
    if (entity == null) {
        hasEntity = false;
        // Reset connection state
        sourceConfiguration.getSourceConnections().releaseConnection(conn);
        // Make ready to deal with a new request
        conn.requestInput();
    }
}

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

public void start(NHttpClientConnection conn) throws IOException, HttpException {
    if (pipe != null) {
        TargetContext.get(conn).setWriter(pipe);
    }//from  w w w .java 2  s .  c  o  m

    String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString()
            : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");

    long contentLength = -1;
    String contentLengthHeader = null;
    if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
        contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
    }

    if (contentLengthHeader != null) {
        contentLength = Integer.parseInt(contentLengthHeader);
        headers.remove(HTTP.CONTENT_LEN);
    }

    MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();

    if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) {
        contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH);
    }

    //fix for  POST_TO_URI
    if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) {
        path = url.toString();
    }

    //fix GET request empty body
    if ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) {
        hasEntityBody = false;
        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
        if (formatter != null && format != null) {
            URL _url = formatter.getTargetAddress(requestMsgCtx, format, url);
            if (_url != null && !_url.toString().isEmpty()) {
                if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString()
                        .equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) {
                    path = _url.toString();
                } else {
                    path = _url.getPath()
                            + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery())
                                    : "");
                }

            }
            headers.remove(HTTP.CONTENT_TYPE);
        }
    }

    Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof TreeMap) {
        Map _headers = (Map) o;
        String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE);
        if (trpContentType != null && !trpContentType.equals("")) {
            if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                addHeader(HTTP.CONTENT_TYPE, trpContentType);
            }

        }

    }

    if (hasEntityBody) {
        request = new BasicHttpEntityEnclosingRequest(method, path,
                version != null ? version : HttpVersion.HTTP_1_1);

        BasicHttpEntity entity = new BasicHttpEntity();

        boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
        boolean forceContentLengthCopy = requestMsgCtx
                .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);

        if (forceContentLength) {
            entity.setChunked(false);
            if (forceContentLengthCopy && contentLength > 0) {
                entity.setContentLength(contentLength);
            }
        } else {
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(chunk);
            }
        }

        ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);

    } else {
        request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
    }

    Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet();
    for (Map.Entry<String, TreeSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                request.addHeader(entry.getKey(), i.next());
            }
        }
    }

    //setup wsa action..
    if (request != null) {

        String soapAction = requestMsgCtx.getSoapAction();
        if (soapAction == null) {
            soapAction = requestMsgCtx.getWSAAction();
        }
        if (soapAction == null) {
            requestMsgCtx.getAxisOperation().getInputAction();
        }

        if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) {
            Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
            if (existingHeader != null) {
                request.removeHeader(existingHeader);
            }
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory
                    .createMessageFormatterDecorator(requestMsgCtx);
            request.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                    messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction));
            //request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO");
        }
    }

    request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams()));

    //Chucking is not performed for request has "http 1.0" and "GET" http method
    if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0))
            || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) {
        this.processChunking(conn, requestMsgCtx);
    }

    if (!keepAlive) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    // Pre-process HTTP request
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);

    // start the request
    targetConfiguration.getHttpProcessor().process(request, conn.getContext());

    if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null
            && !route.isTunnelled()) {
        targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext());
    }

    conn.submitRequest(request);

    if (hasEntityBody) {
        TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
    } else {
        TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
    }
}

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

/**
 * Starts the response//from   w w  w .j a  v  a2  s  .  c  o m
 * @param conn the client connection
 */
public void start(NHttpClientConnection conn) {
    TargetContext.updateState(conn, ProtocolState.RESPONSE_HEAD);

    if (expectResponseBody) {
        pipe = new Pipe(conn, targetConfiguration.getBufferFactory().getBuffer(), "target",
                targetConfiguration);

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

        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getProtocolVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
    } else {
        if (!connStrategy.keepAlive(response, conn.getContext()) || forceShutdownConnectionOnComplete) {
            try {
                // this is a connection we should not re-use
                TargetContext.updateState(conn, ProtocolState.CLOSING);
                targetConfiguration.getConnections().shutdownConnection(conn);

            } catch (Exception ignore) {

            }
        } else {
            targetConfiguration.getConnections().releaseConnection(conn);
        }
    }
}

From source file:org.fcrepo.auth.xacml.XACMLTestUtil.java

/**
 * Links an object to a policy(set)./*from w  w  w .j a v a  2  s.c om*/
 *
 * @param client
 * @param serverAddress
 * @param objectPath
 * @param policyPath
 * @throws Exception
 */
public static void linkPolicy(final HttpClient client, final String serverAddress, final String objectPath,
        final String policyPath) throws Exception {
    final String subjectURI = serverAddress + objectPath;
    final String policyURI = policyPath;
    final HttpPatch patch = new HttpPatch(subjectURI);
    // setAuth(patch, "fedoraAdmin");
    patch.addHeader("Content-Type", "application/sparql-update");
    final BasicHttpEntity e = new BasicHttpEntity();
    final StringBuilder sb = new StringBuilder();
    sb.append("INSERT { ")
            .append(MessageFormat.format(
                    "<{0}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "
                            + "<http://fedora.info/definitions/v4/authorization#xacmlAssignable> . ",
                    subjectURI))
            .append(MessageFormat.format(
                    "<{0}> <http://fedora.info/definitions/v4/authorization#policy> <{1}> . ", subjectURI,
                    policyURI))
            .append("} WHERE { }");
    e.setContent(new ByteArrayInputStream(sb.toString().getBytes()));
    patch.setEntity(e);
    LOGGER.debug("PATCH: {}", patch.getURI());
    final HttpResponse response = client.execute(patch);
    assertEquals(NO_CONTENT.getStatusCode(), response.getStatusLine().getStatusCode());
}