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

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

Introduction

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

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:net.sourcewalker.garanbot.api.GaranboClient.java

/**
 * Execute HTTP PUT with URL and provided content.
 * //from   w w  w . j  a  va2 s.  com
 * @param path
 *            Path to PUT to.
 * @param contentType
 *            MIMEtype of content.
 * @param stream
 *            Stream with data to send to server.
 * @param streamSize
 *            Length of data.
 * @return HTTP Response return by server.
 * @throws IOException
 *             When there was an error communicating with the server.
 */
public HttpResponse put(final String path, final String contentType, final InputStream stream,
        final long streamSize) throws IOException {
    HttpPut request = new HttpPut(ApiConstants.BASE + path);
    request.setEntity(new InputStreamEntity(stream, streamSize));
    prepareRequest(contentType, request);
    return client.execute(request);
}

From source file:com.autonomy.aci.client.services.impl.DocumentProcessorTest.java

@Test
public void testCheckACIResponseForErrorWithBadDateErrorResponse() throws IOException, ProcessorException {
    try {/*from  ww  w  .j  a  v  a 2  s  .  c  om*/
        // Setup with a error response file...
        final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
        response.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/AciException-2.xml"), -1));

        // Set the AciResponseInputStream...
        final AciResponseInputStream stream = new AciResponseInputStreamImpl(response);

        // Process...
        processor.process(stream);
        fail("Should have raised an AciErrorException.");
    } catch (final AciErrorException aee) {
        assertThat("errorTime property not as expected.", aee.getErrorTime(), is(nullValue()));
    }
}

From source file:com.semagia.cassa.client.GraphClient.java

private boolean _createGraph(final URI graphURI, final InputStream in, final MediaType mediaType)
        throws IOException {
    final HttpPut put = new HttpPut(getGraphURI(graphURI));
    final InputStreamEntity entity = new InputStreamEntity(in, -1);
    entity.setContentType(mediaType != null ? mediaType.toString() : null);
    put.setEntity(entity);/* w ww  .j  av a 2 s .  c o m*/
    final int status = getStatusCode(put);
    return status == 200 || status == 201 || status == 204;
}

From source file:org.fcrepo.oai.AbstractOAIProviderIT.java

protected void createSet(String setName, String setSpec) throws Exception {
    final ObjectFactory fac = new ObjectFactory();
    SetType set = fac.createSetType();/*from ww w.  j a  va2  s .co m*/
    set.setSetName(setName);
    if (setSpec != null) {
        set.setSetSpec(setSpec);
    } else {
        set.setSetSpec(setName);
    }
    HttpPost post = new HttpPost(serverAddress + "/oai/sets");
    post.setEntity(new InputStreamEntity(toStream(set), ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    assertEquals(201, resp.getStatusLine().getStatusCode());
}

From source file:org.coffeebreaks.validators.nu.NuValidator.java

public ValidationResult validateContent(InputStream inputStream, ValidationRequest request) throws IOException {
    String parser = request.getValue("parser", null);
    HttpRequestBase method;//from  w w w.j ava  2s. c o  m
    HttpPost httpPost = new HttpPost(baseUrl + "?out=json&parser=" + parser);
    httpPost.addHeader("Content-Type", "text/html");
    InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, -1);
    httpPost.setEntity(inputStreamEntity);
    method = httpPost;
    return validate(method);
}

From source file:org.apache.sling.testing.tools.sling.SlingClient.java

/** Upload using a PUT request.
 *  @param path the path of the uploaded file
 *  @param data the content//from  ww w. j ava  2  s  .  c om
 *  @param length Use -1 if unknown
 *  @param createFolders if true, intermediate folders are created via mkdirs
 */
public void upload(String path, InputStream data, int length, boolean createFolders) throws IOException {
    final HttpEntity e = new InputStreamEntity(data, length);
    if (createFolders) {
        mkdirs(getParentPath(path));
    }
    executor.execute(builder.buildOtherRequest(new HttpPut(builder.buildUrl(path))).withEntity(e)
            .withCredentials(username, password)).assertStatus(201);
}

From source file:com.mnxfst.testing.activities.http.TestHTTPRequestActivity.java

public void testExecuteHTTPRequest() throws HttpException, IOException {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, false);

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.heise.de", 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {//  w  w w  .  j  av a 2s  .c o  m

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }

}

From source file:org.apache.abdera2.common.protocol.Session.java

/**
 * Sends an HTTP PUT request to the specified URI.
 * /*from ww w  .  jav a 2 s .com*/
 * @param uri The request URI
 * @param in An InputStream providing the payload of the request
 * @param options The request options
 */
public <T extends ClientResponse> T put(String uri, InputStream in, RequestOptions options) {
    return (T) wrap(execute("PUT", uri, new InputStreamEntity(in, -1), options));
}

From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    String location = locations.get(new Random().nextInt(locations.size()));
    URI locationUri = URI.create(location);
    HttpHost host = URIUtils.extractHost(locationUri);

    LOGGER.debug("CELLAR HTTP BALANCER: proxying to");
    LOGGER.debug("CELLAR HTTP BALANCER:     URI: {}", locationUri);
    LOGGER.debug("CELLAR HTTP BALANCER:     Host: {}", host);

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    LOGGER.debug("CELLAR HTTP BALANCER:     Method: {}", method);
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest, location);
    LOGGER.debug("CELLAR HTTP BALANCER:     Proxy Request URI: {}", proxyRequestUri);
    HttpRequest proxyRequest;/* w w  w. j a v a2  s  .  co  m*/
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    LOGGER.debug("CELLAR HTTP BALANCER:     copying request headers");
    copyRequestHeaders(servletRequest, proxyRequest, host);

    LOGGER.debug("CELLAR HTTP BALANCER:     set X-Forwarded header");
    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        LOGGER.debug("CELLAR HTTP BALANCER:     executing proxy request");
        proxyResponse = proxyClient.execute(host, proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();
        LOGGER.debug("CELLAR HTTP BALANCER:     status code: {}", statusCode);

        // copying response headers to make sure SESSIONID or other Cookie which comes from remote server
        // will be saved in client when the proxied url was redirected to another one.
        // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51)
        LOGGER.debug("CELLAR HTTP BALANCER:     copying response headers");
        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode,
                location)) {
            //the response is already "committed" now without any body to send
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        LOGGER.debug("CELLAR HTTP BALANCER:     set response status code");
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        // Send the content to the client
        LOGGER.debug("CELLAR HTTP BALANCER:     copying response entity");
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:photosharing.api.conx.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * /*from  ww  w. java 2s  . co  m*/
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            Executor exec = ExecutorUtil.getExecutor();

            Response apiResponse = exec.execute(post);
            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            logger.info("code is " + code);

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("IOException " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("SAXException " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

            logger.severe("JSONException " + e.toString());
        }
    }
}