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) 

Source Link

Usage

From source file:pt.sapo.pai.vip.VipServlet.java

private Supplier<HttpRequestBase> withEntity(HttpEntityEnclosingRequestBase method,
        HttpServletRequest request) {/*from   ww w  .  j  a va  2s.c o  m*/
    try {
        method.setEntity(new InputStreamEntity(request.getInputStream()));
    } catch (IOException ex) {
        log.warn(null, ex);
    }
    return () -> method;
}

From source file:mx.ipn.escom.supernaut.nile.logic.CommonBean.java

@Override
public void initNew(Model model) {
    HttpPost request = new HttpPost(baseUri);
    request.addHeader(JSON_OUT_HEAD);//  w  w w .  j  a  va 2s. c om
    HttpResponse response;
    try {
        request.setEntity(new InputStreamEntity(streamedMarshall()));
        response = client.execute(HOST, request);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 299)
        throw new RuntimeException(statusLine.getReasonPhrase());
    this.model = model;
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

private static void populateTest() {
    // Get the bulk index as a stream
    InputStream bulkStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("bulk-insert.json");
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();

    HttpResponse response;//from  w ww  . j  a va  2 s.c o  m
    // Drop the index if it's there
    HttpDelete httpdelete = new HttpDelete("http://localhost:9500/unit");
    try {
        response = httpclient.execute(httpdelete);
        System.out.println("Index Deleted: " + response);
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while deleting index: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while deleting index: " + ioException);
    }

    HttpPost httppost = new HttpPost("http://localhost:9500/_bulk");

    InputStreamEntity isEntity = new InputStreamEntity(bulkStream);
    httppost.setEntity(isEntity);

    try {
        httpclient = HttpClientBuilder.create().build();
        response = httpclient.execute(httppost);
        System.out.println(response.getStatusLine());
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while bulk indexing: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while bulk indexing: " + ioException);
    }
    System.out.println("Waiting for index to settle down...");
    while (countIndexed() < 50) {
        System.out.println("...");
    }
    System.out.println("...done!");
}

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req/*www .j ava  2  s.c om*/
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/dilemmas";
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:com.redhat.red.build.koji.it.AbstractWithSetupIT.java

protected void uploadFile(InputStream resourceStream, String targetPath, CloseableHttpClient client) {
    String url = formatUrl(CONTENT_CGI, targetPath);
    System.out.println("\n\n ##### START: " + name.getMethodName() + " :: Upload -> " + url + " #####\n\n");

    CloseableHttpResponse response = null;
    try {/*from  w ww .  jav a 2s . c  o  m*/
        HttpPut put = new HttpPut(url);
        put.setEntity(new InputStreamEntity(resourceStream));
        response = client.execute(put);
    } catch (IOException e) {
        e.printStackTrace();
        fail(String.format("Failed to execute GET request: %s. Reason: %s", url, e.getMessage()));
    }

    int code = response.getStatusLine().getStatusCode();
    if (code != 201 || code != 200) {
        fail("Failed to upload content: " + targetPath + "\nSERVER RESPONSE STATUS: "
                + response.getStatusLine());
    } else {
        System.out.println("\n\n ##### END: " + name.getMethodName() + " :: Upload -> " + url + " #####\n\n");
    }
}

From source file:com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector.java

/**
 * In case an app is required on the node running the test, upload it to the grid hub
 * This will then be made available through HTTP GET URL to the node (appium will receive an url instead of a file)
 * /*from   ww w  .  ja v a2  s  .c  o  m*/
 */
@Override
public void uploadMobileApp(Capabilities caps) {

    String appPath = (String) caps.getCapability(MobileCapabilityType.APP);

    // check whether app is given and app path is a local file
    if (appPath != null && new File(appPath).isFile()) {

        try (CloseableHttpClient client = HttpClients.createDefault();) {
            // zip file
            List<File> appFiles = new ArrayList<>();
            appFiles.add(new File(appPath));
            File zipFile = FileUtility.createZipArchiveFromFiles(appFiles);

            HttpHost serverHost = new HttpHost(hubUrl.getHost(), hubUrl.getPort());
            URIBuilder builder = new URIBuilder();
            builder.setPath("/grid/admin/FileServlet/");
            builder.addParameter("output", "app");
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString());
            FileInputStream fileInputStream = new FileInputStream(zipFile);
            InputStreamEntity entity = new InputStreamEntity(fileInputStream);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = client.execute(serverHost, httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SeleniumGridException(
                        "could not upload application file: " + response.getStatusLine().getReasonPhrase());
            } else {
                // set path to the mobile application as an URL on the grid hub
                ((DesiredCapabilities) caps).setCapability(MobileCapabilityType.APP,
                        IOUtils.toString(response.getEntity().getContent()) + "/" + appFiles.get(0).getName());
            }

        } catch (IOException | URISyntaxException e) {
            throw new SeleniumGridException("could not upload application file", e);
        }
    }
}

From source file:com.ibm.watson.ta.retail.TAProxyServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req//www.  j ava 2  s .  c o m
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String reqURI = req.getRequestURI();
        String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
        String url = baseURL + "/v1/" + endpoint;
        // concatenate query params
        String queryStr = req.getQueryString();
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");

        String metadata = req.getHeader("x-watson-metadata");
        if (metadata != null) {
            metadata += "client-ip:" + req.getRemoteAddr();
            newReq.addHeader("x-watson-metadata", metadata);
        }

        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:org.fcrepo.camel.FcrepoClient.java

/**
 * Make a PUT request//from   www  .ja  v  a  2 s .  c o  m
 * @param url the URL of the resource to PUT
 * @param body the contents of the resource to send
 * @param contentType the MIMEType of the resource
 * @return the repository response
 * @throws FcrepoOperationFailedException when the underlying HTTP request results in an error
 */
public FcrepoResponse put(final URI url, final InputStream body, final String contentType)
        throws FcrepoOperationFailedException {

    final HttpMethods method = HttpMethods.PUT;
    final HttpEntityEnclosingRequestBase request = (HttpEntityEnclosingRequestBase) method.createRequest(url);

    if (contentType != null) {
        request.addHeader(CONTENT_TYPE, contentType);
    }
    if (body != null) {
        request.setEntity(new InputStreamEntity(body));
    }

    LOGGER.debug("Fcrepo PUT request headers: {}", request.getAllHeaders());

    final HttpResponse response = executeRequest(request);

    LOGGER.debug("Fcrepo PUT request returned status [{}]", response.getStatusLine().getStatusCode());

    return fcrepoGenericResponse(url, response, throwExceptionOnFailure);
}

From source file:org.fcrepo.integration.auth.webac.WebACRecipesIT.java

/**
 * Convenience method to POST the contents of a Turtle file to the repository to create a new resource. Returns
 * the HTTP response from that request. Throws an IOException if the server responds with anything other than a
 * 201 Created response code.//  w w  w .j  a  v a 2  s.co  m
 */
private HttpResponse ingestTurtleResource(final String username, final String path, final String requestURI)
        throws IOException {
    final HttpPost request = postObjMethod(requestURI);

    logger.debug("POST to {} to create {}", requestURI, path);

    setAuth(request, username);

    final InputStream file = this.getClass().getResourceAsStream(path);
    final InputStreamEntity fileEntity = new InputStreamEntity(file);
    request.setEntity(fileEntity);
    request.setHeader("Content-Type", "text/turtle;charset=UTF-8");

    try (final CloseableHttpResponse response = execute(request)) {
        assertEquals("Didn't get a CREATED response!", CREATED.getStatusCode(), getStatus(response));
        return response;
    }

}