Example usage for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity

List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity.

Prototype

public ByteArrayRequestEntity(byte[] paramArrayOfByte) 

Source Link

Usage

From source file:org.apache.synapse.mediators.json.SynapseJsonSender.java

public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    //Fix Me For Sending Only
    // Trasnport URL can be different from the WSA-To. So processing
    // that now.//  w  ww.  j  a v a 2  s. c  o  m
    EndpointReference epr = null;
    String transportURL = (String) msgContext.getProperty(Constants.Configuration.TRANSPORT_URL);

    if (transportURL != null) {
        epr = new EndpointReference(transportURL);
    } else if ((msgContext.getTo() != null)
            && !AddressingConstants.Submission.WSA_ANONYMOUS_URL.equals(msgContext.getTo().getAddress())
            && !AddressingConstants.Final.WSA_ANONYMOUS_URL.equals(msgContext.getTo().getAddress())) {
        epr = msgContext.getTo();
    }

    if (epr == null) {
        throw new AxisFault("EndpointReference is not available");
    }

    // Get the JSONObject
    JSONObject jsonObject = (JSONObject) msgContext.getProperty("JSONObject");
    if (jsonObject == null) {
        throw new AxisFault("Couldn't Find JSONObject");

    }
    HttpClient agent = new HttpClient();
    PostMethod postMethod = new PostMethod(epr.getAddress());
    try {
        postMethod.setRequestEntity(new ByteArrayRequestEntity(XML.toString(jsonObject).getBytes()));
        agent.executeMethod(postMethod);

        if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
            processResponse(postMethod, msgContext);
        } else if (postMethod.getStatusCode() == HttpStatus.SC_ACCEPTED) {
        } else if (postMethod.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            Header contenttypeHheader = postMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
            String value = contenttypeHheader.getValue();

            if (value != null) {
                if ((value.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0)
                        || (value.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >= 0)) {
                    processResponse(postMethod, msgContext);
                }
            }
        } else {
            throw new AxisFault(Messages.getMessage("transportError",
                    String.valueOf(postMethod.getStatusCode()), postMethod.getResponseBodyAsString()));
        }
    } catch (JSONException e) {
        log.error(e);
        throw new AxisFault(e);
    } catch (IOException e) {
        log.error(e);
        throw new AxisFault(e);
    }

    return InvocationResponse.CONTINUE;
}

From source file:org.apache.wink.itest.exceptions.NullValuesDuringTargettingTest.java

/**
 * Tests that a request to a method with no content type, a request entity,
 * but with a {@link Consumes} method results in a 415 error.
 * //from w w  w  . j a  va2s.  c  o  m
 * @throws IOException
 */
public void testNoContentTypeWithRequestEntityIncomingRequestWithConsumesMethod() throws IOException {
    PostMethod postMethod = new PostMethod(getBaseURI() + "/targeting/nullresource/withconsumes");
    postMethod.setRequestEntity(new ByteArrayRequestEntity(new byte[] { 0, 1, 2 }));
    try {
        client.executeMethod(postMethod);
        assertEquals(415, postMethod.getStatusCode());
        String responseBody = postMethod.getResponseBodyAsString();
        ServerContainerAssertions.assertExceptionBodyFromServer(415, responseBody);
        if (responseBody == null || "".equals(responseBody)) {
            assertNull(postMethod.getResponseHeader("Content-Type"));
        }
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.exceptions.NullValuesDuringTargettingTest.java

/**
 * Tests that a request to a method with no content type, a request entity,
 * but without a {@link Consumes} method results in 200 successful method
 * invocation.//  w  w  w . j  a  v  a 2s  . c  o  m
 * 
 * @throws IOException
 */
public void testNoContentTypeWithRequestEntityIncomingRequestWithNoConsumesMethod() throws IOException {
    PostMethod postMethod = new PostMethod(getBaseURI() + "/targeting/nullresource/withoutconsumes");
    postMethod.setRequestEntity(new ByteArrayRequestEntity("calledWithString".getBytes()));
    try {
        client.executeMethod(postMethod);
        assertEquals(200, postMethod.getStatusCode());
        assertEquals("userReadercalledWithString", postMethod.getResponseBodyAsString());
        String contentType = (postMethod.getResponseHeader("Content-Type") == null) ? null
                : postMethod.getResponseHeader("Content-Type").getValue();
        assertNotNull(contentType, contentType);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:org.apache.zeppelin.rest.AbstractTestRestApi.java

protected static PostMethod httpPost(String path, String body) throws IOException {
    LOG.info("Connecting to {}", url + path);
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url + path);
    postMethod.addRequestHeader("Origin", url);
    RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
    postMethod.setRequestEntity(entity);
    httpClient.executeMethod(postMethod);
    LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
    return postMethod;
}

From source file:org.apache.zeppelin.rest.AbstractTestRestApi.java

protected static PutMethod httpPut(String path, String body) throws IOException {
    LOG.info("Connecting to {}", url + path);
    HttpClient httpClient = new HttpClient();
    PutMethod putMethod = new PutMethod(url + path);
    putMethod.addRequestHeader("Origin", url);
    RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
    putMethod.setRequestEntity(entity);//from   w w  w.  j  a  v a  2s.  com
    httpClient.executeMethod(putMethod);
    LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
    return putMethod;
}

From source file:org.appcelerator.transport.ProxyTransportServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    String url = request.getParameter("url");
    if (url == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from  w ww.  j a  v  a 2s . c  o  m
    }

    url = URLDecoder.decode(url, "UTF-8");

    if (url.indexOf("://") == -1) {
        url = new String(Base64.decode(url));
    }

    HttpClient client = new HttpClient();
    HttpMethodBase methodBase = null;

    if (method.equalsIgnoreCase("POST")) {
        methodBase = new PostMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PostMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("GET")) {
        methodBase = new GetMethod(url);
        methodBase.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("PUT")) {
        methodBase = new PutMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PutMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("DELETE")) {
        methodBase = new DeleteMethod(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        methodBase = new OptionsMethod(url);
    }

    methodBase.setRequestHeader("User-Agent", request.getHeader("user-agent") + " (Appcelerator Proxy)");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Proxying url: " + url + ", method: " + method);
    }

    int status = client.executeMethod(methodBase);

    response.setStatus(status);
    response.setContentLength((int) methodBase.getResponseContentLength());

    for (Header header : methodBase.getResponseHeaders()) {
        String name = header.getName();
        if (name.equalsIgnoreCase("Set-Cookie") == false && name.equals("Transfer-Encoding") == false) {
            response.setHeader(name, header.getValue());
        }
    }
    InputStream in = methodBase.getResponseBodyAsStream();
    Util.copy(in, response.getOutputStream());
}

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;/* w ww. j a  v  a 2 s .  co  m*/
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.attribyte.api.http.impl.commons.Commons3Client.java

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpMethod method = null;// ww w  .jav a 2 s  .c o m

    switch (request.getMethod()) {
    case GET:
        method = new GetMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case DELETE:
        method = new DeleteMethod(request.getURI().toString());
        break;
    case HEAD:
        method = new HeadMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case POST:
        method = new PostMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        } else {
            PostMethod postMethod = (PostMethod) method;
            Collection<Parameter> parameters = request.getParameters();
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    postMethod.addParameter(parameter.getName(), value);
                }
            }
        }
        break;
    case PUT:
        method = new PutMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        }
        break;
    }

    if (userAgent != null && Strings.isNullOrEmpty(request.getHeaderValue("User-Agent"))) {
        method.setRequestHeader("User-Agent", userAgent);
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            method.setRequestHeader(header.getName(), value);
        }
    }

    int responseCode;
    InputStream is = null;

    try {
        responseCode = httpClient.executeMethod(method);
        is = method.getResponseBodyAsStream();
        if (is != null) {
            byte[] body = Request.bodyFromInputStream(is, options.maxResponseBytes);
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.setBody(body.length != 0 ? body : null).create();
        } else {
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.create();
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //Ignore
            }
        }
        method.releaseConnection();
    }
}

From source file:org.bits4j.samples.SimpleUpload.java

/**
 * The argument is the URL for the upload location of the BITS server. If
 * none is provided, the url http://localhost/upload-dir is used.
 * //from  ww  w .  j a v  a  2  s  . co  m
 * @param args
 */
public static void main(String[] args) {
    String url = localHost;
    if (args.length == 0) {
        System.out.println("URL is not provided using:" + url);
    } else {
        url = args[0];
    }
    // just making sure that there is an ending /
    url = StringUtils.removeEnd(url, "/") + "/";
    try {
        // BitsHttpClient extends apaches HttpClient
        BitsHttpClient client = new BitsHttpClient();
        client.setAckHeaderHandler(new AckHeaderHandlerImpl());

        /*
         * Needed for Basic Authentication against http (not https).
         */

        /*
        Credentials defaultcreds = new UsernamePasswordCredentials(
              userName, password);
        client.getState()
              .setCredentials(
             new AuthScope(serverDomainOrIpAddress, port80or443, "realm"),
             defaultcreds);
                     
        //preemtive is required for the current bits4j code base.
        client.getParams().setAuthenticationPreemptive(true);
        */

        // Create a BITS Session
        String bitsSessionId = null;
        String contentName = "text.txt";

        String contentUrl = url + contentName;

        BitsPostMethod bitsPost = new BitsPostMethod(contentUrl);
        bitsPost.setRequestHeader(Constants.BITS_PACKET_TYPE, Constants.CREATE_SESSION);
        bitsPost.setRequestHeader(Constants.BITS_SUPPORTED_PROTOCOLS, Constants.BITS_1_5_UPLOAD_PROTOCAL_GUID);
        bitsPost.setRequestHeader(Constants.USER_AGENT, "My BITS Client");
        bitsPost.setRequestHeader(Constants.CONTENT_NAME, contentName);
        bitsPost.setRequestHeader(Constants.CONTENT_LENGTH, "0");
        client.executeMethod(bitsPost);

        // get the BITS server assigned Session Id
        bitsSessionId = ((Header) bitsPost.getResponseHeader(Constants.BITS_SESSION_ID)).getValue();
        bitsPost.releaseConnection();

        // Send Fragment to the BITS Server.
        bitsPost = new BitsPostMethod(contentUrl);
        bitsPost.setRequestHeader(Constants.BITS_SESSION_ID, bitsSessionId);
        String bytesRead = "my very small content of the file";
        ByteArrayRequestEntity byteArrayRequestEntity = new ByteArrayRequestEntity(bytesRead.getBytes());
        bitsPost.setRequestHeader(Constants.BITS_PACKET_TYPE, Constants.FRAGMENT);
        bitsPost.setRequestHeader(Constants.USER_AGENT, "My BITS Client");
        bitsPost.setRequestHeader(Constants.CONTENT_NAME, contentName);
        bitsPost.setRequestHeader(Constants.CONTENT_LENGTH, String.valueOf(bytesRead.getBytes().length));

        // Content-Range: bytes start-(bytesReat-1)/totalFileSize
        StringBuilder contentRange = new StringBuilder("bytes ").append("0").append("-")
                .append(String.valueOf((bytesRead.getBytes().length) - 1)).append("/")
                .append(bytesRead.getBytes().length);
        bitsPost.setRequestHeader(Constants.CONTENT_RANGE, contentRange.toString());
        bitsPost.setRequestEntity(byteArrayRequestEntity);
        client.executeMethod(bitsPost);

        // Close the session
        bitsPost = new BitsPostMethod(contentUrl);
        bitsPost.setRequestHeader(Constants.BITS_SESSION_ID, bitsSessionId);
        bitsPost.setRequestHeader(Constants.BITS_PACKET_TYPE, Constants.CLOSE_SESSION);
        bitsPost.setRequestHeader(Constants.USER_AGENT, "My BITS Client");
        bitsPost.setRequestHeader(Constants.CONTENT_NAME, contentName);
        bitsPost.setRequestHeader(Constants.CONTENT_LENGTH, "0");
        client.executeMethod(bitsPost);

        // There should now be a file called text.txt on the BITS server
        // with the content "my very small content of the file"
        // You should be able to down load it in a browser with the url
        // defined by content above.

    } catch (Throwable t) {
        t.printStackTrace();
    }

}

From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java

@Test
public void testPut() throws HttpException, IOException {
    final HttpClient client = new HttpClient();

    // create file:
    final byte[] testContent = "hello world".getBytes();
    final EntityEnclosingMethod putMethod = new PutMethod(servletRoot + "/foo.txt");
    putMethod.setRequestEntity(new ByteArrayRequestEntity(testContent));
    final int putResponse = client.executeMethod(putMethod);
    Assert.assertEquals(201, putResponse);
    Assert.assertTrue(fs.file("foo.txt").exists());

    // check file contents:
    ByteBuffer buf = ByteBuffer.allocate(testContent.length);
    try (ReadableFile r = fs.file("foo.txt").openReadable()) {
        r.read(buf);// www  .  jav  a 2s  . co m
    }
    Assert.assertArrayEquals(testContent, buf.array());

    putMethod.releaseConnection();
}