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:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java

@Override
protected void deploy(List<Binary> binaries, Run run) throws IOException {
    CloseableHttpClient client = null;//from ww  w .  j a  va  2  s .c  om
    try {
        if (credentialsId == null || credentialsId.isEmpty()) {
            client = HttpClients.createDefault();
        } else {
            BasicCredentialsProvider credentials = new BasicCredentialsProvider();
            StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById(
                    credentialsId, StandardUsernamePasswordCredentials.class, run,
                    Lists.<DomainRequirement>newArrayList());
            credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    credentialById.getUsername(), credentialById.getPassword().getPlainText()));

            client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries()
                    .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build();
        }

        for (Binary binary : binaries) {
            BufferedHttpEntity entity = new BufferedHttpEntity(
                    new InputStreamEntity(binary.getFile().open(), binary.getFile().length()));
            HttpPost post = new HttpPost(remoteLocation + binary.getName());
            post.setEntity(entity);

            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    log.fine("Deployed " + binary.getName() + " to " + remoteLocation);
                } else {
                    log.warning("Cannot deploy file " + binary.getName() + ". Response from target was "
                            + statusCode);
                    run.setResult(Result.FAILURE);
                    throw new IOException(response.getStatusLine().toString());
                }
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:edu.wisc.cypress.dao.advrpt.AdvisorReportDaoTest.java

protected HttpResponse setupHttpClient(InputStream benefitStatementsStream, String contentType)
        throws IOException, ClientProtocolException {
    final HttpResponse httpResponse = mock(HttpResponse.class);
    when(httpClient.execute(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(httpResponse);
    when(httpResponse.getStatusLine()).thenReturn(
            new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase()));
    when(httpResponse.getAllHeaders())//from   w  w w  . j  a  v  a2s . c  o m
            .thenReturn(new Header[] { new BasicHeader("Content-Type", contentType) });
    when(httpResponse.getEntity()).thenReturn(new InputStreamEntity(benefitStatementsStream, -1));

    return httpResponse;
}

From source file:com.google.android.apps.iosched.io.StubHttpClient.java

/**
 * Build a stub {@link HttpResponse}, probably for use with
 * {@link #setResponse(HttpResponse)}.//from   w w  w . j a va2 s . c o m
 *
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single
 *            {@link HttpEntity} to be included in the response, loaded
 *            through {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode, String assetName, Context context) throws IOException {
    final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, null);
    final HttpResponse response = new BasicHttpResponse(status);
    if (assetName != null) {
        final InputStream entity = context.getAssets().open(assetName);
        response.setEntity(new InputStreamEntity(entity, entity.available()));
    }
    return response;
}

From source file:com.haulmont.cuba.restapi.FileUploadController.java

protected void uploadToMiddleware(UserSession userSession, InputStream is, FileDescriptor fd)
        throws FileStorageException, InterruptedIOException {
    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }// w w  w  . j ava 2 s.c o  m
    while (true) {
        String url = selectedUrl + CORE_FILE_UPLOAD_CONTEXT + "?s=" + userSession.getId() + "&f="
                + fd.toUrlParam();

        HttpPost method = new HttpPost(url);
        InputStreamEntity entity = new InputStreamEntity(is, -1);

        method.setEntity(entity);
        HttpClient client = new DefaultHttpClient();
        try {
            HttpResponse coreResponse = client.execute(method);
            int statusCode = coreResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                break;
            } else {
                log.debug("Unable to upload file to " + url + "\n" + coreResponse.getStatusLine());
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null)
                    throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode),
                            fd.getName());
            }
        } catch (InterruptedIOException e) {
            log.trace("Uploading has been interrupted");
            throw e;
        } catch (IOException e) {
            log.debug("Unable to upload file to " + url + "\n" + e);
            selectedUrl = failAndGetNextUrl(context);
            if (selectedUrl == null)
                throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
}

From source file:com.comcast.cim.rest.client.xhtml.TestXhtmlResponseHandler.java

@Test
public void testPassesUpIOExceptionIfThrown() {
    HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    resp.setHeader("Content-Type", "application/xhtml+xml;charset=utf-8");
    String xhtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML " + "1.0 Transitional//EN\" "
            + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" " + "xml:lang=\"en\" lang=\"en\"><head/><body/>";
    byte[] bytes = xhtml.getBytes();
    long purportedLength = bytes.length + 6;
    resp.setHeader("Content-Length", "" + purportedLength);

    ByteArrayInputStream buf = new ByteArrayInputStream(bytes);
    InterruptedInputStream iis = new InterruptedInputStream(buf);
    resp.setEntity(new InputStreamEntity(iis, purportedLength));

    try {/*from   w ww. j a  va  2  s .  c om*/
        impl.handleResponse(resp);
        Assert.fail("should have thrown IOException");
    } catch (IOException expected) {
    }
}

From source file:com.blacklocus.jres.http.HttpMethods.java

static HttpEntity createEntity(final Object payload) throws IOException {
    final HttpEntity entity;
    if (payload instanceof InputStream) {

        if (LOG.isDebugEnabled()) {
            String stream = IOUtils.toString((InputStream) payload);
            LOG.debug(stream);//w w  w.jav a2  s. c o  m
            entity = new StringEntity(stream, ContentType.APPLICATION_JSON);
        } else {
            entity = new InputStreamEntity((InputStream) payload, ContentType.APPLICATION_JSON);
        }

    } else if (payload instanceof String) {

        LOG.debug((String) payload);
        entity = new StringEntity((String) payload, ContentType.APPLICATION_JSON);

    } else { // anything else will be serialized with Jackson

        if (LOG.isDebugEnabled()) {
            String json = ObjectMappers.toJson(payload);
            LOG.debug(json);
            entity = new StringEntity(json, ContentType.APPLICATION_JSON);

        } else {
            final PipedOutputStream pipedOutputStream = new PipedOutputStream();
            final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
            PIPER.submit(new ExceptingRunnable() {
                @Override
                protected void go() throws Exception {
                    try {
                        ObjectMappers.NORMAL.writeValue(pipedOutputStream, payload);
                        pipedOutputStream.flush();
                    } finally {
                        IOUtils.closeQuietly(pipedOutputStream);
                    }
                }
            });
            entity = new InputStreamEntity(pipedInputStream, ContentType.APPLICATION_JSON);
        }

    }
    return entity;
}

From source file:org.chaplib.TestHttpResource.java

@Test(expected = RuntimeException.class)
public void transformsIOExceptionOnStreamClose() throws Exception {
    response.setEntity(new InputStreamEntity(mockInputStream, -1));
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
    when(mockParser.parse(entity)).thenReturn(parsed);
    doThrow(new IOException()).when(mockInputStream).close();
    impl.value(mockParser);// ww  w  . j  a  va  2 s  .  co m
}

From source file:com.bigdata.rockstor.console.UploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.error("It is not a MultipartContent, return error.");
        resp.sendError(500, "It is not a MultipartContent, return error.");
        return;//  w  ww.  j a v  a2s  .  c om
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 512);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(req);
        LOG.info("parse requeset success : items num : " + fileItems.size());
    } catch (FileUploadException e) {
        LOG.error("parse requeset failed !");
        resp.sendError(500, "parse requeset failed !");
        return;
    }

    HashMap<String, String> headMap = new HashMap<String, String>();
    FileItem theFile = null;
    long size = -1;
    URI uri = null;

    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = null;
            try {
                value = item.getString("UTF-8").trim();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            LOG.info("Parse head info : " + name + " -- " + value);
            if (name.equals("ObjName")) {
                try {
                    uri = new URI(value);
                } catch (URISyntaxException e) {
                    LOG.info("Parse uri info error : " + value);
                    uri = null;
                }
            } else if (name.equals("ObjSize")) {
                try {
                    size = Long.parseLong(value);
                } catch (Exception e) {
                    LOG.error("Parse objSize error : " + value);
                }
            } else {
                headMap.put(name, value);
            }
        } else {
            theFile = item;
        }
    }

    if (size == -1 || uri == null || theFile == null || headMap.size() == 0) {
        LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        resp.sendError(500,
                "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        return;
    }

    HttpPut put = new HttpPut();
    put.setURI(uri);
    for (Map.Entry<String, String> e : headMap.entrySet()) {
        if ("Filename".equals(e.getKey()))
            continue;
        put.setHeader(e.getKey(), e.getValue());
    }
    put.setEntity(new InputStreamEntity(theFile.getInputStream(), size));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(put);
    if (200 != response.getStatusLine().getStatusCode()) {
        LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : "
                + response.getStatusLine().getReasonPhrase());
        resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        return;
    }
    LOG.info("Put object OK : " + uri);
    response.setStatusCode(200);
}

From source file:org.apache.solr.client.solrj.SolrSchemalessExampleTest.java

@Test
public void testFieldMutating() throws Exception {
    HttpSolrClient client = (HttpSolrClient) getSolrClient();
    client.deleteByQuery("*:*");
    client.commit();/* w w  w  . ja v  a  2s  . c  o m*/
    assertNumFound("*:*", 0); // make sure it got in
    // two docs, one with uniqueKey, another without it
    String json = "{\"name one\": \"name\"} " + "{\"name  two\" : \"name\"}" + "{\"first-second\" : \"name\"}"
            + "{\"x+y\" : \"name\"}" + "{\"p%q\" : \"name\"}" + "{\"p.q\" : \"name\"}" + "{\"a&b\" : \"name\"}";
    HttpClient httpClient = client.getHttpClient();
    HttpPost post = new HttpPost(client.getBaseURL() + "/update/json/docs");
    post.setHeader("Content-Type", "application/json");
    post.setEntity(new InputStreamEntity(new ByteArrayInputStream(json.getBytes("UTF-8")), -1));
    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    client.commit();
    List<String> expected = Arrays.asList("name_one", "name__two", "first-second", "a_b", "p_q", "p.q", "x_y");
    HashSet set = new HashSet();
    QueryResponse rsp = assertNumFound("*:*", expected.size());
    for (SolrDocument doc : rsp.getResults())
        set.addAll(doc.getFieldNames());
    for (String s : expected) {
        assertTrue(s + " not created " + rsp, set.contains(s));
    }

}

From source file:co.bugjar.android.monitor.BugjarMonitor.java

/**
 * Submit any saved stack traces//from w  ww.  j av a 2 s .c  om
 * @param context
 */
private void submitStackTraces(Context context) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    final String widthPixels = String.valueOf(metrics.widthPixels);
    final String heightPixels = String.valueOf(metrics.heightPixels);

    Runnable submitter = new Runnable() {

        @Override
        public void run() {
            HttpPost request = new HttpPost(BJ_SERVER);

            request.addHeader("version", BM_VERSION);
            request.addHeader("versionName", versionName);
            request.addHeader("versionCode", versionCode);
            request.addHeader("apiKey", apiKey);
            request.addHeader("widthPixels", widthPixels);
            request.addHeader("heightPixels", heightPixels);

            try {
                File d = new File(filesDir);
                File[] stackTraces = d.listFiles(new ExceptionHandler.StackTraceFilter());
                if (stackTraces != null && stackTraces.length > 0) {
                    for (int i = 0; i < stackTraces.length; i++) {
                        File f = stackTraces[i];

                        Log.d(TAG, "sending " + f.getAbsolutePath());
                        request.setEntity(new InputStreamEntity(new FileInputStream(f), f.length()));

                        HttpResponse response = httpClient.execute(request);
                        if (response.getStatusLine().getStatusCode() == 200) {
                            f.delete();
                        } else {
                            Log.w(TAG, "Bugjar server returned " + response.getStatusLine().toString());
                        }
                    }
                } else {
                    // say hello
                    HttpResponse response = httpClient.execute(request);
                    Log.d(TAG, response.getStatusLine().toString());
                }
            } catch (IOException e) {
                Log.e(TAG, e.getClass().getSimpleName() + " caught submitting stack trace: " + e.getMessage());
            }
        }
    };

    new Thread(submitter).start();
}