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:org.dataconservancy.access.connector.AbstractHttpConnectorTest.java

@BeforeClass
public static void setUp() throws Exception {

    XMLUnit.setIgnoreComments(true);//from   w  w w . ja v a  2  s  .c o  m
    XMLUnit.setIgnoreWhitespace(true);

    final BasicHttpProcessor httpProc = new BasicHttpProcessor();
    testServer = new LocalTestServer(httpProc, null);

    testServer.register("/entity/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            final String requestURI = request.getRequestLine().getUri();
            final String requestedEntity = requestURI.substring(requestURI.lastIndexOf("/") + 1);
            log.trace("processing request for entity {}", requestedEntity);
            final File requestedEntityFile = new File(entitiesDir, requestedEntity + ".xml");
            if (!requestedEntityFile.exists()) {
                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            } else {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setHeader("content-type", "application/xml");
                response.setEntity(new InputStreamEntity(new FileInputStream(requestedEntityFile), -1));
            }
        }
    });

    testServer.register("/query/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            final String requestURI = request.getRequestLine().getUri();
            final String query = requestURI.substring(requestURI.lastIndexOf("/") + 1);

            int max = -1;
            int offset = 0;

            //For some reason request.getParams wasn't working so parse the string
            String[] params = query.split("&");

            for (String param : params) {
                String name = param.split("=")[0];
                if (name.equalsIgnoreCase("max")) {
                    max = Integer.parseInt(param.split("=")[1]);
                } else if (name.equalsIgnoreCase("offset")) {
                    offset = Integer.parseInt(param.split("=")[1]);
                }
            }

            if (max == -1) {
                max = allTestEntities.size();
            }

            log.trace(
                    "processing request for query {} (note that the query itself is ignored and the response is hardcoded)",
                    query);
            // basically we iterate over all the entities in the file system and return a DCP of Files.  The actual query is ignored

            final Dcp dcp = new Dcp();
            int count = 0;
            for (DcsEntity e : allTestEntities) {
                if (e instanceof DcsFile) {
                    if (count >= offset) {
                        dcp.addFile((DcsFile) e);
                    }
                    count++;
                    if (count == max) {
                        break;
                    }
                }
            }

            count = dcp.getFiles().size();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mb.buildSip(dcp, baos);

            response.setStatusCode(HttpStatus.SC_OK);
            response.setHeader("content-type", "application/xml");
            response.setHeader("X-TOTAL-MATCHES", String.valueOf(count));
            response.setEntity(new BufferedHttpEntity(new ByteArrayEntity(baos.toByteArray())));
        }
    });

    testServer.register("/deposit/file", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            log.trace("file upload");

            response.setStatusCode(HttpStatus.SC_ACCEPTED);
            response.setHeader("content-type", "application/atom+xml;type=entry");
            response.setHeader("Location", "http://dataconservancy.org/deposit/003210.atom");
            response.setHeader("X-dcs-src", "http://dataconservancy.org/deposit/003210.file");
            response.setEntity(new StringEntity("<?xml version='1.0'?>"
                    + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:dc='http://dataconservancy.org/ns/'>"
                    + "</entry>", "UTF-8"));
        }
    });

    testServer.register("/deposit/sip", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            log.trace("sip upload");

            response.setStatusCode(HttpStatus.SC_ACCEPTED);
            response.setHeader("content-type", "application/atom+xml;type=entry");
            response.setHeader("Location", "http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419");
            response.setEntity(new StringEntity("<?xml version='1.0'?>"
                    + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sword='http://purl.org/net/sword/'><id>deposit:/sipDeposit/4331419</id><content type='application/xml' src='http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419' /><title type='text'>Deposit 4331419</title><updated>2011-10-28T18:12:50.171Z</updated><author><name>Depositor</name></author><summary type='text'>ingesting</summary><link href='http://dcservice.moo.org:8080/dcs/status/sipDeposit/4331419' type='application/atom+xml; type=feed' rel='alternate' title='Processing Status' /><sword:treatment>Deposit processing</sword:treatment></entry>"));
        }
    });

    testServer.start();
    log.info("Test HTTP server listening on {}:{}", testServer.getServiceHostName(),
            testServer.getServicePort());
}

From source file:org.apache.solr.client.solrj.embedded.SolrExampleJettyTest.java

@Test
public void testArbitraryJsonIndexing() throws Exception {
    HttpSolrClient client = (HttpSolrClient) getSolrClient();
    client.deleteByQuery("*:*");
    client.commit();//from www . ja v  a2s  .  c  o  m
    assertNumFound("*:*", 0); // make sure it got in

    // two docs, one with uniqueKey, another without it
    String json = "{\"id\":\"abc1\", \"name\": \"name1\"} {\"name\" : \"name2\"}";
    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, HttpClientUtil.createNewHttpClientRequestContext());
    assertEquals(200, response.getStatusLine().getStatusCode());
    client.commit();
    QueryResponse rsp = getSolrClient().query(new SolrQuery("*:*"));
    assertEquals(2, rsp.getResults().getNumFound());

    SolrDocument doc = rsp.getResults().get(0);
    String src = (String) doc.getFieldValue("_src_");
    Map m = (Map) ObjectBuilder.fromJSON(src);
    assertEquals("abc1", m.get("id"));
    assertEquals("name1", m.get("name"));

    doc = rsp.getResults().get(1);
    src = (String) doc.getFieldValue("_src_");
    m = (Map) ObjectBuilder.fromJSON(src);
    assertEquals("name2", m.get("name"));

}

From source file:net.oauth.client.httpclient4.HttpClient4.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpRequestBase httpRequest;/*  www.jav  a 2 s. c o m*/
    if (isPost || isPut) {
        HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            excerpt = e.getExcerpt();
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod
                    .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length)));
        }
        httpRequest = entityEnclosingMethod;
    } else if (isDelete) {
        httpRequest = new HttpDelete(url);
    } else {
        httpRequest = new HttpGet(url);
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpParams params = httpRequest.getParams();
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value));
        } else if (CONNECT_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value));
        }
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
    HttpResponse httpResponse = client.execute(httpRequest);
    return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset());
}

From source file:org.codehaus.httpcache4j.resolver.HTTPClientResponseResolverTest.java

@Test
public void testNotSoSimpleGET() throws IOException {
    HTTPClientResponseResolver resolver = new TestableResolver();
    HttpResponse mockedResponse = mock(HttpResponse.class);
    when(mockedResponse.getAllHeaders()).thenReturn(new org.apache.http.Header[] {
            new BasicHeader("Date", HeaderUtils.toHttpDate("Date", new DateTime()).getValue()) });
    when(mockedResponse.getStatusLine()).thenReturn(new BasicStatusLine(new HttpVersion(1, 1), 200, "OK"));
    when(mockedResponse.getEntity()).thenReturn(new InputStreamEntity(new NullInputStream(1), 1));
    when(client.execute(Mockito.<HttpUriRequest>anyObject())).thenReturn(mockedResponse);
    HTTPResponse response = resolver.resolve(new HTTPRequest(URI.create("http://www.vg.no")));
    assertNotNull("Response was null", response);
    assertEquals("Wrong header size", 1, response.getHeaders().size());
    assertTrue("Response did not have payload", response.hasPayload());
}

From source file:org.mahasen.thread.MahasenUploadWorker.java

public void run() {
    HttpClient uploadHttpClient = new DefaultHttpClient();

    uploadHttpClient = SSLWrapper.wrapClient(uploadHttpClient);

    if (file.exists()) {
        if (!nodeIp.equals(localIp)) {
            HttpPost httppost = new HttpPost(uri);

            try {
                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);

                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true);
                httppost.setEntity(reqEntity);
                System.out.println("Executing Upload request " + httppost.getRequestLine());

                HttpResponse response = uploadHttpClient.execute(httppost);

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                if ((response.getStatusLine().getReasonPhrase().equals("OK"))
                        && (response.getStatusLine().getStatusCode() == 200)) {
                    mahasenResource.addSplitPartStoredIp(currentPart, nodeIp);
                    PutUtil.storedNoOfParts.get(jobId).getAndIncrement();
                }//  ww  w . j av  a 2s. c om

            } catch (IOException e) {
                log.error("Error occurred in Uploading part : " + currentPart, e);
            }
        } else {
            try {
                FileInputStream inputStream = new FileInputStream(file);
                File filePart = new File(
                        MahasenConfiguration.getInstance().getRepositoryPath() + file.getName());
                FileOutputStream outputStream = new FileOutputStream(filePart);
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
                outputStream.close();
                mahasenResource.addSplitPartStoredIp(currentPart, nodeIp);
                PutUtil.storedNoOfParts.get(jobId).getAndIncrement();

            } catch (Exception e) {
                log.error("Error while storing file " + currentPart + " locally", e);
            }
        }
    }
}

From source file:de.hshannover.f4.trust.ifmapj.channel.ApacheCoreCommunicationHandler.java

@Override
public InputStream doActualRequest(InputStream is) throws IOException {
    InputStreamEntity ise = null;//from w  w w. j av  a  2 s  . com
    HttpResponse response = null;
    InputStream ret = null;
    Header hdr = null;
    HttpEntity respEntity = null;
    StatusLine status = null;

    ise = new InputStreamEntity(is, is.available());
    ise.setChunked(false);
    mHttpPost.setEntity(ise);

    // do the actual request
    try {
        mHttpConnection.sendRequestHeader(mHttpPost);
        mHttpConnection.sendRequestEntity(mHttpPost);
        response = mHttpConnection.receiveResponseHeader();
        mHttpConnection.receiveResponseEntity(response);
    } catch (HttpException e) {
        throw new IOException(e);
    }

    // check if we got a 200 status back, otherwise go crazy
    status = response.getStatusLine();
    if (status.getStatusCode() != 200) {
        throw new IOException("HTTP Status Code: " + status.getStatusCode() + " " + status.getReasonPhrase());
    }

    // check whether the response uses gzip
    hdr = response.getFirstHeader("Content-Encoding");
    mResponseGzip = hdr == null ? false : hdr.getValue().contains("gzip");
    respEntity = response.getEntity();

    if (respEntity != null) {
        ret = respEntity.getContent();
    }

    if (ret == null) {
        throw new IOException("no content in response");
    }

    return ret;
}

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

@Test
public void testConvertACIResponseToDOMParserConfigurationException() throws AciErrorException, IOException {
    // Set the property to be our mock implementation that will throw a ParserConfigurationException...
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
            "com.autonomy.aci.client.mock.MockDocumentBuilderFactory");

    try {/*from ww w  .j ava2 s  .  c om*/
        // Setup with a proper XML response file...
        final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
        response.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/GetVersion.xml"), -1));

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

        // Process...
        processor.process(stream);
        fail("Should have raised an ProcessorException.");
    } catch (final ProcessorException pe) {
        // Check for the correct causes...
        assertThat("Cause not correct.", pe.getCause(), is(instanceOf(ParserConfigurationException.class)));
    } finally {
        // Remove the duff system property...
        System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
    }
}

From source file:com.hoccer.api.FileCache.java

public String store(StreamableContent data, int secondsUntilExipred)
        throws ClientProtocolException, IOException, Exception {

    String url = ClientConfig.getFileCacheBaseUri() + "/" + UUID.randomUUID() + "/?expires_in="
            + secondsUntilExipred;// ww  w.  j a v  a 2 s . com
    LOG.finest("put uri = " + url);
    HttpPut request = new HttpPut(sign(url));

    InputStreamEntity entity = new InputStreamEntity(data.openNewInputStream(), data.getNewStreamLength());
    request.addHeader("Content-Disposition", " attachment; filename=\"" + data.getFilename() + "\"");
    entity.setContentType(data.getContentType());
    request.setEntity(entity);
    request.addHeader("Content-Type", data.getContentType());

    HttpResponse response = getHttpClient().execute(request);

    String responseString = convertResponseToString(response, false);
    LOG.finest("response = " + responseString);

    return responseString;
}

From source file:org.digidoc4j.impl.bdoc.SkDataLoader.java

@Override
public byte[] post(final String url, final byte[] content) throws DSSException {
    logger.info("Getting OCSP response from " + url);
    if (userAgent == null) {
        throw new TechnicalException("User Agent must be set for OCSP requests");
    }//from  w  w  w.j  a v  a 2 s  .co  m

    HttpPost httpRequest = null;
    HttpResponse httpResponse = null;
    CloseableHttpClient client = null;

    try {
        final URI uri = URI.create(url.trim());
        httpRequest = new HttpPost(uri);
        httpRequest.setHeader("User-Agent", userAgent);

        // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this information.
        // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards.
        // This is because, it may not be possible to reset the stream (= go to position 0).
        // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a byte-array.
        final ByteArrayInputStream bis = new ByteArrayInputStream(content);

        final HttpEntity httpEntity = new InputStreamEntity(bis, content.length);
        final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity);
        httpRequest.setEntity(requestEntity);
        if (contentType != null) {
            httpRequest.setHeader(CONTENT_TYPE, contentType);
        }

        client = getHttpClient(url);
        httpResponse = getHttpResponse(client, httpRequest, url);

        final byte[] returnedBytes = readHttpResponse(url, httpResponse);
        return returnedBytes;
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {
        try {
            if (httpRequest != null) {
                httpRequest.releaseConnection();
            }
            if (httpResponse != null) {
                EntityUtils.consumeQuietly(httpResponse.getEntity());
            }
        } finally {
            IOUtils.closeQuietly(client);
        }
    }
}