Example usage for org.apache.http.message BasicHttpEntityEnclosingRequest BasicHttpEntityEnclosingRequest

List of usage examples for org.apache.http.message BasicHttpEntityEnclosingRequest BasicHttpEntityEnclosingRequest

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpEntityEnclosingRequest BasicHttpEntityEnclosingRequest.

Prototype

public BasicHttpEntityEnclosingRequest(String str, String str2, ProtocolVersion protocolVersion) 

Source Link

Usage

From source file:org.jclouds.http.httpnio.util.NioHttpUtils.java

public static HttpEntityEnclosingRequest convertToApacheRequest(HttpRequest request) {

    String path = request.getEndpoint().getRawPath();
    if (request.getEndpoint().getQuery() != null)
        path += "?" + request.getEndpoint().getQuery();
    BasicHttpEntityEnclosingRequest apacheRequest = new BasicHttpEntityEnclosingRequest(request.getMethod(),
            path, HttpVersion.HTTP_1_1);

    Object content = request.getEntity();

    // Since we may remove headers, ensure they are added to the apache
    // request after this block
    if (content != null) {
        String lengthString = request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH);
        if (lengthString == null) {
            throw new IllegalStateException("no Content-Length header on request: " + apacheRequest);
        }//from  w  ww .  ja  va2s. c om
        long contentLength = Long.parseLong(lengthString);
        String contentType = request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE);
        addEntityForContent(apacheRequest, content, contentType, contentLength);
    }

    for (String header : request.getHeaders().keySet()) {
        for (String value : request.getHeaders().get(header))
            // apache automatically tries to add content length header
            if (!header.equals(HttpHeaders.CONTENT_LENGTH))
                apacheRequest.addHeader(header, value);
    }
    return apacheRequest;
}

From source file:net.spy.memcached.couch.TestingClient.java

public HttpFuture<String> asyncHttpPut(String uri, String document) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1);
    StringEntity entity = new StringEntity(document);
    ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
    HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() {
        private String json;

        @Override//from www.ja v  a  2 s  . com
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.couchbase.client.TestingClient.java

public HttpFuture<String> asyncHttpPut(String uri, String document) throws UnsupportedEncodingException {
    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout);

    HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1);
    request.setHeader(new BasicHeader("Content-Type", "application/json"));
    StringEntity entity = new StringEntity(document);
    ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
    HttpOperationImpl op = new TestOperationPutImpl(request, new TestCallback() {
        private String json;

        @Override/*  www .  j  a  v a 2s. c o m*/
        public void receivedStatus(OperationStatus status) {
            crv.set(json, status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }

        @Override
        public void getData(String response) {
            json = response;
        }
    });
    crv.setOperation(op);
    addOp(op);
    return crv;
}

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

/**
 * Create and return a new HttpPost request to the destination EPR
 *
 * @return the HttpRequest to be sent out
 * @throws IOException in error retrieving the <code>HttpRequest</code>
 *///from ww  w.ja  v  a 2  s .c om
public HttpRequest getRequest() throws IOException, HttpException {
    String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    if (httpMethod == null) {
        httpMethod = "POST";
    }
    endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);

    boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
    HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;

    HttpRequest httpRequest;

    try {
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {

            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod,
                    uri.toASCIIString(), httpver);

            BasicHttpEntity entity = new BasicHttpEntity();

            if (forceHTTP10) {
                setStreamAsTempData(entity);
            } else {
                entity.setChunked(chunked);
                if (!chunked) {
                    setStreamAsTempData(entity);
                }
            }
            requestWithEntity.setEntity(entity);
            requestWithEntity.setHeader(HTTP.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            httpRequest = requestWithEntity;

        } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {

            URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));

            URI uri = rewriteRequestURI(url.toURI());
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
            /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
            //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
            //        msgContext, format, msgContext.getSoapAction()));

        } else {
            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
        }

    } catch (URISyntaxException ex) {
        throw new HttpException(ex.getMessage(), ex);
    }

    // set any transport headers
    Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;
        for (Object header : headers.keySet()) {
            Object value = headers.get(header);
            if (header instanceof String && value != null && value instanceof String) {
                if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
                    httpRequest.setHeader((String) header, (String) value);

                    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

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

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

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

                        }
                    }

                } else {
                    if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
                        httpRequest.setHeader((String) header,
                                (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
                    }
                }

            }
        }
    }

    // if the message is SOAP 11 (for which a SOAPAction is *required*), and
    // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
    // use that over any transport header that may be available
    String soapAction = msgContext.getSoapAction();
    if (soapAction == null) {
        soapAction = msgContext.getWSAAction();
    }
    if (soapAction == null) {
        msgContext.getAxisOperation().getInputAction();
    }

    if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
        Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
        if (existingHeader != null) {
            httpRequest.removeHeader(existingHeader);
        }
        httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                messageFormatter.formatSOAPAction(msgContext, null, soapAction));
    }

    if (NHttpConfiguration.getInstance().isKeepAliveDisabled()
            || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
        httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    return httpRequest;
}

From source file:com.devoteam.srit.xmlloader.http.MsgHttp.java

/** Creates a new instance of MsgHttp from data scenario */
public MsgHttp(String data) throws Exception {
    data = data.trim();//from   w  ww  .  j a  va 2s .  com
    BasicHttpResponse response = null;
    BasicHttpEntityEnclosingRequest request = null;

    HttpMessage currentMessage = null;

    int endOfLine;
    String line;

    //
    // Clean beginning of first line (XML-related control characters)
    //
    while (data.startsWith("\n") || data.startsWith("\r") || data.startsWith(" ") || data.startsWith("\t")) {
        data = data.substring(1);
    }

    while (data.endsWith("\n") || data.endsWith("\r") || data.endsWith(" ") || data.endsWith("\t")) {
        data = data.substring(0, data.length() - 1);
    }

    String headers = data.split("[\\r]?[\\n][\\r]?[\\n]")[0];
    String datas = data.substring(headers.length());
    if (datas.startsWith("\r"))
        datas = datas.substring(1);
    if (datas.startsWith("\n"))
        datas = datas.substring(1);
    if (datas.startsWith("\r"))
        datas = datas.substring(1);
    if (datas.startsWith("\n"))
        datas = datas.substring(1);

    //
    // Use only \n: remove \r
    //
    headers = headers.replace("\r", "");

    //
    // Whatever the message is, it seems it should end with a new line
    //
    headers += "\n";

    //
    // Get first line
    //
    endOfLine = headers.indexOf("\n");
    line = headers.substring(0, endOfLine);

    // Remove first line from data
    headers = headers.substring(endOfLine + 1, headers.length());

    // Message is a response
    if (line.startsWith("HTTP")) {
        String[] parts = line.split(" ");

        HttpVersion httpVersion = HttpVersion.HTTP_1_1;
        if (parts[0].endsWith("HTTP/1.0")) {
            httpVersion = HttpVersion.HTTP_1_0;
        }

        String phrase = "";
        if (parts.length > 2) {
            phrase = parts[2];
        }

        response = new BasicHttpResponse(httpVersion, Integer.parseInt(parts[1]), phrase);
        currentMessage = response;
    } // Message is a request
    else {
        String[] parts = line.split(" ");
        HttpVersion httpVersion = HttpVersion.HTTP_1_1;

        if ((parts.length == 3) && (parts[2].endsWith("HTTP/1.0"))) {
            httpVersion = HttpVersion.HTTP_1_0;
        }

        request = new BasicHttpEntityEnclosingRequest(parts[0], parts[1], httpVersion);
        currentMessage = request;
    }

    //
    // Parse headers
    //
    endOfLine = headers.indexOf("\n");
    if (endOfLine != -1) {
        line = headers.substring(0, endOfLine);
    }
    while (endOfLine != -1 && line.length() > 0) {
        // Remove line from data since we parse it here
        headers = headers.substring(endOfLine + 1, headers.length());

        // Add header to message
        int index = line.indexOf(":");

        if (index == -1) {
            throw new ExecutionException("Invalid header -> " + line);
        }

        String name = line.substring(0, index).trim();
        String value = line.substring(index + 1, line.length()).trim();
        if (!name.equals("Content-Length") || Utils.isInteger(value)) {
            currentMessage.addHeader(name, value);
        }

        // Read next line
        endOfLine = headers.indexOf("\n");
        if (endOfLine != -1) {
            line = headers.substring(0, endOfLine);
        }
    }

    //
    // Register parsed message into the class variable
    //
    message = currentMessage;

    //
    // Set entity into the message
    //
    if (datas.length() > 0) {
        //
        // Check if we are allowed to have an entity in this message
        //
        if (null != request) {
            if (request.getRequestLine().getMethod().toLowerCase().equals("get")
                    || request.getRequestLine().getMethod().toLowerCase().equals("head")) {
                throw new ExecutionException("Request " + request.getRequestLine().getMethod()
                        + " is not allowed to contain an entity");
            }
        }

        if (null != response || null != request) {
            messageContent = datas;
        }

        //
        // Set the Content-Length header if the transfer-encoding is not "chunked"
        //
        Header[] contentEncoding = currentMessage.getHeaders("Transfer-Encoding");
        Header[] contentType = currentMessage.getHeaders("Content-Type");
        Header[] contentLength = currentMessage.getHeaders("Content-Length");
        if (contentType.length > 0 && contentType[0].getValue().toLowerCase().contains("multipart")) {
            // do nothing, we should not add a CRLF at the end of the data when multipart
        } else {
            messageContent += "\r\n"; // it seems necessary to end the data by a CRLF (???)
        }

        if (contentEncoding.length == 0 || !contentEncoding[0].getValue().contains("chunked")) {
            if (contentLength.length == 0) {
                if (null != messageContent) {
                    currentMessage.addHeader("Content-Length", Integer.toString(messageContent.length()));
                } else {
                    currentMessage.addHeader("Content-Length", Integer.toString(0));
                }
            }
        } else {
            messageContent += "\r\n"; // when chunked, there must be a double CRLF after the last chunk size
        }

        HttpEntity entity = new ByteArrayEntity(messageContent.getBytes());
        if (null != response) {
            response.setEntity(entity);
        } else if (null != request) {
            request.setEntity(entity);
        } else {
            entity = null;
        }

    }
}

From source file:com.lion328.xenonlauncher.minecraft.api.authentication.yggdrasil.YggdrasilMinecraftAuthenticator.java

private ResponseState sendRequest(String endpoint, String data) throws IOException, YggdrasilAPIException {
    URL url = new URL(serverURL, endpoint);

    // HttpURLConnection can only handle 2xx response code for headers
    // so it need to use HttpCore instead
    // maybe I could use an alternative like HttpClient
    // but for lightweight, I think is not a good idea

    BasicHttpEntity entity = new BasicHttpEntity();

    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    entity.setContent(new ByteArrayInputStream(dataBytes));
    entity.setContentLength(dataBytes.length);

    HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getFile(),
            HttpVersion.HTTP_1_1);/*ww w.  j  av  a  2 s  . co m*/
    request.setHeader(new BasicHeader("Host", url.getHost()));
    request.setHeader(new BasicHeader("Content-Type", "application/json"));
    request.setHeader(new BasicHeader("Content-Length", Integer.toString(dataBytes.length)));

    request.setEntity(entity);

    Socket s;
    int port = url.getPort();

    if (url.getProtocol().equals("https")) {
        if (port == -1) {
            port = 443;
        }

        s = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
    } else {
        if (port == -1) {
            port = 80;
        }

        s = new Socket(url.getHost(), port);
    }

    DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(8192);
    connection.bind(s);

    try {
        connection.sendRequestHeader(request);
        connection.sendRequestEntity(request);

        HttpResponse response = connection.receiveResponseHeader();
        connection.receiveResponseEntity(response);

        if (!response.getFirstHeader("Content-Type").getValue().startsWith("application/json")) {
            throw new InvalidImplementationException("Invalid content type");
        }

        InputStream stream = response.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        int b;

        while ((b = stream.read()) != -1) {
            sb.append((char) b);
        }

        return new ResponseState(response.getStatusLine().getStatusCode(), sb.toString());
    } catch (HttpException e) {
        throw new IOException(e);
    }
}

From source file:com.bytelightning.opensource.pokerface.RequestHandler.java

/**
 * This method converts the response from a JavaScript endpoint's 'inspectRequest' method to one of null, <code>HttpRequest</code>, <code>HttpAsyncRequestConsumer<ResponseProducer></code>
 * @param originalRequest   The original request from the client
 * @param result   The result from the JavaScript endpoint's 'inspectRequest' method.
 * @return null, <code>HttpRequest</code>, <code>HttpAsyncRequestConsumer<ResponseProducer></code>
 *///  ww w.j a  v a 2 s.  c om
@SuppressWarnings("unchecked")
private Object transformScriptInspectionResult(HttpRequest originalRequest, Object result) {
    if (result == null)
        return null;
    if (result instanceof HttpRequest)
        return (HttpRequest) result;
    if (result instanceof HttpAsyncRequestConsumer<?>)
        return (HttpAsyncRequestConsumer<ResponseProducer>) result;
    if (result instanceof ScriptObjectMirror)
        return (ScriptObjectMirror) result;

    if (result instanceof URL) {
        try {
            result = ((URL) result).toURI();
        } catch (URISyntaxException ex) {
            Logger.error("The endpoint at " + originalRequest.getRequestLine().getUri()
                    + " returned an invalid URL instance", ex);
            return null;
        }
    } else if (result instanceof String) {
        try {
            result = new URI((String) result);
        } catch (URISyntaxException ex) {
            Logger.error("The endpoint at " + originalRequest.getRequestLine().getUri()
                    + " returned an invalid URL String", ex);
            return null;
        }
    }
    if (result instanceof URI) {
        String str = ((URI) result).toString();
        RequestLine origReqLine = originalRequest.getRequestLine();
        if (originalRequest instanceof HttpEntityEnclosingRequest) {
            BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(origReqLine.getMethod(),
                    str, origReqLine.getProtocolVersion());
            r.setEntity(((HttpEntityEnclosingRequest) originalRequest).getEntity());
            return r;
        } else
            return new BasicHttpRequest(origReqLine.getMethod(), str, origReqLine.getProtocolVersion());
    } else {
        Logger.error("The endpoint at " + originalRequest.getRequestLine().getUri()
                + " returned an illegal result [class=" + result.getClass().getName() + "]");
        return null;
    }
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
* Store a design document in the cluster.
*
* @param name the name of the design document.
* @param value the full design document definition as a string.
* @return a future containing the result of the creation operation.
*//*from   www .j  av  a  2 s .co  m*/
public HttpFuture<Boolean> asyncCreateDesignDoc(String name, String value) throws UnsupportedEncodingException {
    getLogger().info("Creating Design Document:" + name);
    String bucket = ((CouchbaseConnectionFactory) connFactory).getBucketName();
    final String uri = "/" + bucket + "/_design/" + MODE_PREFIX + name;

    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<Boolean> crv = new HttpFuture<Boolean>(couchLatch, 60000);
    HttpRequest request = new BasicHttpEntityEnclosingRequest("PUT", uri, HttpVersion.HTTP_1_1);
    request.setHeader(new BasicHeader("Content-Type", "application/json"));
    StringEntity entity = new StringEntity(value);
    ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);

    HttpOperationImpl op = new DesignDocOperationImpl(request, new OperationCallback() {
        @Override
        public void receivedStatus(OperationStatus status) {
            crv.set(status.getMessage().equals("Error Code: 201"), status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }
    });

    crv.setOperation(op);
    addOp(op);
    return crv;
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
* Delete a design document in the cluster.
*
* @param name the design document to delete.
* @return a future containing the result of the deletion operation.
*//*from  w  w w  .  jav a 2s.c o m*/
public HttpFuture<Boolean> asyncDeleteDesignDoc(final String name) throws UnsupportedEncodingException {
    getLogger().info("Deleting Design Document:" + name);
    String bucket = ((CouchbaseConnectionFactory) connFactory).getBucketName();

    final String uri = "/" + bucket + "/_design/" + MODE_PREFIX + name;

    final CountDownLatch couchLatch = new CountDownLatch(1);
    final HttpFuture<Boolean> crv = new HttpFuture<Boolean>(couchLatch, 60000);
    HttpRequest request = new BasicHttpEntityEnclosingRequest("DELETE", uri, HttpVersion.HTTP_1_1);
    request.setHeader(new BasicHeader("Content-Type", "application/json"));

    HttpOperationImpl op = new DesignDocOperationImpl(request, new OperationCallback() {
        @Override
        public void receivedStatus(OperationStatus status) {
            crv.set(status.getMessage().equals("Error Code: 200"), status);
        }

        @Override
        public void complete() {
            couchLatch.countDown();
        }
    });

    crv.setOperation(op);
    addOp(op);
    return crv;
}