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

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

Introduction

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

Prototype

public InputStreamRequestEntity(InputStream paramInputStream, String paramString) 

Source Link

Usage

From source file:org.apache.camel.component.http.RequestEntityConverter.java

private static RequestEntity asRequestEntity(byte[] data, Exchange exchange) throws Exception {
    if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
        return new InputStreamRequestEntity(GZIPHelper
                .compressGzip(exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class), data),
                ExchangeHelper.getContentType(exchange));
    } else {//from  w w  w .  j a va 2 s. c  om
        // should set the content type here
        if (exchange != null) {
            return new InputStreamRequestEntity(new ByteArrayInputStream(data),
                    ExchangeHelper.getContentType(exchange));
        } else {
            return new InputStreamRequestEntity(new ByteArrayInputStream(data));
        }
    }
}

From source file:org.apache.cxf.systest.provider.CXF4130Test.java

@Test
public void testCxf4130() throws Exception {
    InputStream body = getClass().getResourceAsStream("cxf4130data.txt");
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(ADDRESS);
    post.setRequestEntity(new InputStreamRequestEntity(body, "text/xml"));
    client.executeMethod(post);//from   w  w  w .j  av  a  2s.  co m

    Document doc = StaxUtils.read(post.getResponseBodyAsStream());
    Element root = doc.getDocumentElement();
    Node child = root.getFirstChild();

    boolean foundBody = false;
    while (child != null) {
        if ("Body".equals(child.getLocalName())) {
            foundBody = true;
            assertEquals(1, child.getChildNodes().getLength());
            assertEquals("FooResponse", child.getFirstChild().getLocalName());
        }
        child = child.getNextSibling();
    }
    assertTrue("Did not find the soap:Body element", foundBody);
}

From source file:org.apache.cxf.systest.provider.CXF4818Test.java

@Test
public void testCXF4818() throws Exception {
    InputStream body = getClass().getResourceAsStream("cxf4818data.txt");
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(ADDRESS);
    post.setRequestEntity(new InputStreamRequestEntity(body, "text/xml"));
    client.executeMethod(post);/*w w  w  .  j  av  a  2  s .com*/

    Document doc = StaxUtils.read(post.getResponseBodyAsStream());
    //System.out.println(StaxUtils.toString(doc));
    Element root = doc.getDocumentElement();
    Node child = root.getFirstChild();

    boolean foundBody = false;
    boolean foundHeader = false;
    while (child != null) {
        if ("Header".equals(child.getLocalName())) {
            foundHeader = true;
            assertFalse("Already found body", foundBody);
        } else if ("Body".equals(child.getLocalName())) {
            foundBody = true;
            assertTrue("Did not find header before the body", foundHeader);
        }
        child = child.getNextSibling();
    }
    assertTrue("Did not find the soap:Body element", foundBody);
    assertTrue("Did not find the soap:Header element", foundHeader);
}

From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Uploads file as Input Stream to Swift
 *
 * @param path           path to Swift/*from ww  w . j  ava 2  s .  com*/
 * @param data           object data
 * @param length         length of data
 * @param requestHeaders http headers
 * @throws IOException on IO Faults
 */
public void upload(SwiftObjectPath path, final InputStream data, final long length,
        final Header... requestHeaders) throws IOException {
    preRemoteCommand("upload");
    perform(pathToURI(path), new PutMethodProcessor<byte[]>() {
        @Override
        public byte[] extractResult(PutMethod method) throws IOException {
            return method.getResponseBody();
        }

        @Override
        protected void setup(PutMethod method) throws SwiftInternalStateException {
            method.setRequestEntity(new InputStreamRequestEntity(data, length));
            setHeaders(method, requestHeaders);
        }
    });
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

/**
 * @see RepositoryService#importXml(SessionInfo, NodeId, InputStream, int)
 *//*from w w  w .  j av  a  2s  .  c  o  m*/
public void importXml(SessionInfo sessionInfo, NodeId parentId, InputStream xmlStream, int uuidBehaviour)
        throws RepositoryException {
    // TODO: improve. currently random name is built instead of retrieving name of new resource from top-level xml element within stream
    Name nodeName = getNameFactory().create(Name.NS_DEFAULT_URI, UUID.randomUUID().toString());
    String uri = getItemUri(parentId, nodeName, sessionInfo);
    MkColMethod method = new MkColMethod(uri);
    method.addRequestHeader(ItemResourceConstants.IMPORT_UUID_BEHAVIOR, new Integer(uuidBehaviour).toString());
    method.setRequestEntity(new InputStreamRequestEntity(xmlStream, "text/xml"));
    execute(method, sessionInfo);
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

/**
 * @see RepositoryService#importXml(SessionInfo, NodeId, InputStream, int)
 *///from w  w  w  . j ava2s  .c o  m
public void importXml(SessionInfo sessionInfo, NodeId parentId, InputStream xmlStream, int uuidBehaviour)
        throws RepositoryException {
    // TODO: improve. currently random name is built instead of retrieving name of new resource from top-level xml element within stream
    Name nodeName = getNameFactory().create(Name.NS_DEFAULT_URI, UUID.randomUUID().toString());
    String uri = getItemUri(parentId, nodeName, sessionInfo);
    MkColMethod method = new MkColMethod(uri);
    method.addRequestHeader(JcrRemotingConstants.IMPORT_UUID_BEHAVIOR, Integer.toString(uuidBehaviour));
    method.setRequestEntity(new InputStreamRequestEntity(xmlStream, "text/xml"));
    execute(method, sessionInfo);
}

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;//from  www  .ja  v a 2 s .  co m
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.apache.wink.itest.standard.JAXRSBytesArrayTest.java

/**
 * Tests posting a byte array./*from   w ww . j  ava2 s.  co  m*/
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testPostByteArray() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/bytesarray");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "text/plain"));
    postMethod.addRequestHeader("Accept", "text/plain");
    try {
        client.executeMethod(postMethod);

        assertEquals(200, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        assertEquals("text/plain", postMethod.getResponseHeader("Content-Type").getValue());
        assertEquals(barr.length,
                Integer.valueOf(postMethod.getResponseHeader("Content-Length").getValue()).intValue());
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSBytesArrayTest.java

/**
 * Tests putting and then getting a byte array.
 * /* www. j av a 2s . c o  m*/
 * @throws HttpException
 * @throws IOException
 */
public void testPutByteArray() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/bytesarray");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "bytes/array"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/bytesarray");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        String contentType = (getMethod.getResponseHeader("Content-Type") == null) ? null
                : getMethod.getResponseHeader("Content-Type").getValue();
        assertNotNull(contentType, contentType);
        assertEquals(barr.length,
                Integer.valueOf(getMethod.getResponseHeader("Content-Length").getValue()).intValue());
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSBytesArrayTest.java

/**
 * Tests receiving an empty byte array./* www  .j a v  a 2s .co  m*/
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testWithRequestAcceptHeaderWillReturnRequestedContentType() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/bytesarray");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "any/type"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/bytesarray");
    getMethod.addRequestHeader("Accept", "mytype/subtype");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[1000];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        assertEquals("mytype/subtype", getMethod.getResponseHeader("Content-Type").getValue());
        assertEquals(barr.length,
                Integer.valueOf(getMethod.getResponseHeader("Content-Length").getValue()).intValue());
    } finally {
        getMethod.releaseConnection();
    }
}