org.apache.http.entity.InputStreamEntity Java Examples

The following examples show how to use org.apache.http.entity.InputStreamEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 7 votes vote down vote up
private void doAddFormBook(String address, String resourceName, int status) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(address);

    String ct = "multipart/form-data; boundary=bqJky99mlBWa-ZuqjC53mG6EzbmlxB";
    post.setHeader("Content-Type", ct);
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/" + resourceName);
    post.setEntity(new InputStreamEntity(is));

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(status, response.getStatusLine().getStatusCode());
        if (status == 200) {
            InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
            assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                         stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
        }
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example #2
Source File: DCContentUploader.java    From documentum-rest-client-java with Apache License 2.0 7 votes vote down vote up
public DCContentUploader upload() throws IOException
{
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/octet-stream");
    post.setEntity(new InputStreamEntity(content));

    HttpResponse httpResponse = client.execute(post);
    status = httpResponse.getStatusLine().getStatusCode();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(httpResponse.getEntity().getContent(), os);
    response = os.toString("UTF-8");
    headers = new HttpHeaders();
    for(Header header : httpResponse.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    post.releaseConnection();
    return this;
}
 
Example #3
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 6 votes vote down vote up
private List<RequestRunner> createPutRequestRunners(Map<String, InputStream> uriAndStreamMap, Map<String, String> headers, List<BintrayCallException> errors) {
    List<RequestRunner> runners = new ArrayList<>();
    List<HttpPut> requests = new ArrayList<>();
    log.debug("Creating PUT requests and RequestRunners for execution");
    for (String apiPath : uriAndStreamMap.keySet()) {
        HttpPut putRequest;
        try {
            putRequest = new HttpPut(createUrl(apiPath));
        } catch (BintrayCallException bce) {
            errors.add(bce);
            continue;
        }
        HttpEntity requestEntity = new InputStreamEntity(uriAndStreamMap.get(apiPath));
        putRequest.setEntity(requestEntity);
        setHeaders(putRequest, headers);
        requests.add(putRequest);
    }

    for (HttpPut request : requests) {
        RequestRunner runner = new RequestRunner(request, client, responseHandler);
        runners.add(runner);
    }
    return runners;
}
 
Example #4
Source File: IppSendDocumentOperation.java    From cups4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
private IppResult sendRequest(URI uri, ByteBuffer ippBuf, InputStream documentStream) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(getRequestConfig());
    
    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);
    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);

    InputStream inputStream = new SequenceInputStream(headerStream, documentStream);
    InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);
    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    CloseableHttpClient client = HttpClients.custom().build();
    try {
        CloseableHttpResponse httpResponse = client.execute(httpPost);
        LOG.info("Received from {}: {}", uri, httpResponse);
        return getIppResult(httpResponse);
    } finally {
        client.close();
    }
}
 
Example #5
Source File: IppCreateJobOperation.java    From cups4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static IppResult sendRequest(URI uri, ByteBuffer ippBuf) throws IOException {
    CloseableHttpClient client = HttpClients.custom().build();

    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(getRequestConfig());

    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);

    // set length to -1 to advice the entity to read until EOF
    InputStreamEntity requestEntity = new InputStreamEntity(headerStream, -1);

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);
    CloseableHttpResponse httpResponse = client.execute(httpPost);
    return toIppResult(httpResponse);
}
 
Example #6
Source File: RawHttpComponentsClient.java    From rawhttp with Apache License 2.0 6 votes vote down vote up
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException {
    RequestBuilder builder = RequestBuilder.create(request.getMethod());
    builder.setUri(request.getUri());
    builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion()));
    request.getHeaders().getHeaderNames().forEach((name) ->
            request.getHeaders().get(name).forEach(value ->
                    builder.addHeader(new BasicHeader(name, value))));

    request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asRawStream())));

    CloseableHttpResponse response = httpClient.execute(builder.build());

    RawHttpHeaders headers = readHeaders(response);
    StatusLine statusLine = adaptStatus(response.getStatusLine());

    @Nullable LazyBodyReader body;
    if (response.getEntity() != null) {
        FramedBody framedBody = http.getFramedBody(statusLine, headers);
        body = new LazyBodyReader(framedBody, response.getEntity().getContent());
    } else {
        body = null;
    }

    return new RawHttpResponse<>(response, request, statusLine, headers, body);
}
 
Example #7
Source File: RepeatableInputStreamRequestEntity.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new RepeatableInputStreamRequestEntity using the information
 * from the specified request. If the input stream containing the request's
 * contents is repeatable, then this RequestEntity will report as being
 * repeatable.
 *
 * @param request The details of the request being written out (content type,
 *                content length, and content).
 */
public RepeatableInputStreamRequestEntity(final HttpExecuteRequest request) {
    setChunked(false);

    /*
     * If we don't specify a content length when we instantiate our
     * InputStreamRequestEntity, then HttpClient will attempt to
     * buffer the entire stream contents into memory to determine
     * the content length.
     */
    long contentLength = request.httpRequest().firstMatchingHeader("Content-Length")
                                .map(this::parseContentLength)
                                .orElse(-1L);

    content = getContent(request.contentStreamProvider());
    // TODO v2 MetricInputStreamEntity
    inputStreamRequestEntity = new InputStreamEntity(content, contentLength);
    setContent(content);
    setContentLength(contentLength);

    request.httpRequest().firstMatchingHeader("Content-Type").ifPresent(contentType -> {
        inputStreamRequestEntity.setContentType(contentType);
        setContentType(contentType);
    });
}
 
Example #8
Source File: AuthenticatorTestCase.java    From hadoop with Apache License 2.0 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
Example #9
Source File: AuthenticatorTestCase.java    From big-c with Apache License 2.0 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
Example #10
Source File: HttpClientBuilderTest.java    From wechatpay-apache-httpclient with Apache License 2.0 6 votes vote down vote up
@Test
public void postNonRepeatableEntityTest() throws IOException {
  HttpPost httpPost = new HttpPost(
      "https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");


  InputStream stream = new ByteArrayInputStream(reqdata.getBytes("utf-8"));
  InputStreamEntity reqEntity = new InputStreamEntity(stream);
  reqEntity.setContentType("application/json");
  httpPost.setEntity(reqEntity);
  httpPost.addHeader("Accept", "application/json");

  CloseableHttpResponse response = httpClient.execute(httpPost);
  assertTrue(response.getStatusLine().getStatusCode() != 401);
  try {
    HttpEntity entity2 = response.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);
  } finally {
    response.close();
  }
}
 
Example #11
Source File: HttpSolrClient.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void fillSingleContentStream(Collection<ContentStream> streams, HttpEntityEnclosingRequestBase postOrPut) throws IOException {
  // 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;
  }
  Long size = contentStream[0].getSize();
  postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
    @Override
    public Header getContentType() {
      return new BasicHeader("Content-Type", contentStream[0].getContentType());
    }

    @Override
    public boolean isRepeatable() {
      return false;
    }
  });

}
 
Example #12
Source File: SolrSchemalessExampleTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testArbitraryJsonIndexing() throws Exception  {
  HttpSolrClient client = (HttpSolrClient) getSolrClient();
  client.deleteByQuery("*:*");
  client.commit();
  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(StandardCharsets.UTF_8)), -1));
  HttpResponse response = httpClient.execute(post, HttpClientUtil.createNewHttpClientRequestContext());
  Utils.consumeFully(response.getEntity());
  assertEquals(200, response.getStatusLine().getStatusCode());
  client.commit();
  assertNumFound("*:*", 2);
}
 
Example #13
Source File: AuthenticatorTestCase.java    From registry with Apache License 2.0 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
    start();
    try {
        SystemDefaultHttpClient httpClient = getHttpClient();
        doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

        // Always do a GET before POST to trigger the SPNego negotiation
        if (doPost) {
            HttpPost post = new HttpPost(getBaseURL());
            byte[] postBytes = POST.getBytes();
            ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
            InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

            // Important that the entity is not repeatable -- this means if
            // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
            // the test will fail.
            Assert.assertFalse(entity.isRepeatable());
            post.setEntity(entity);
            doHttpClientRequest(httpClient, post);
        }
    } finally {
        stop();
    }
}
 
Example #14
Source File: HttpProxy.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(),
            servletRequest.getContentLength(),
            ContentType.create(contentType));
}
 
Example #15
Source File: ApacheGatewayConnection.java    From vespa with Apache License 2.0 6 votes vote down vote up
protected static InputStreamEntity zipAndCreateEntity(final InputStream inputStream) throws IOException {
    byte[] buffer = new byte[4096];
    GZIPOutputStream gzos = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        gzos = new GZIPOutputStream(baos);
        while (inputStream.available() > 0) {
            int length = inputStream.read(buffer);
            gzos.write(buffer, 0,length);
        }
    } finally {
        if (gzos != null)  {
            gzos.close();
        }
    }
    byte[] fooGzippedBytes = baos.toByteArray();
    return new InputStreamEntity(new ByteArrayInputStream(fooGzippedBytes), -1);
}
 
Example #16
Source File: SwiftAPIDirect.java    From stocator with Apache License 2.0 6 votes vote down vote up
/**
 * @param path path to object
 * @param inputStream input stream
 * @param account JOSS Account object
 * @param metadata custom metadata
 * @param size the object size
 * @param type the content type
 * @return HTTP response code
 * @throws IOException if error
 */
private static int httpPUT(String path,
    InputStream inputStream, JossAccount account, SwiftConnectionManager scm,
    Map<String, String> metadata, long size, String type)
        throws IOException {
  LOG.debug("HTTP PUT {} request on {}", path);
  final HttpPut httpPut = new HttpPut(path);
  httpPut.addHeader("X-Auth-Token", account.getAuthToken());
  httpPut.addHeader("Content-Type", type);
  httpPut.addHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT);
  if (metadata != null && !metadata.isEmpty()) {
    for (Map.Entry<String, String> entry : metadata.entrySet()) {
      httpPut.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue());
    }
  }
  final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();
  httpPut.setConfig(config);
  final InputStreamEntity entity = new InputStreamEntity(inputStream, size);
  httpPut.setEntity(entity);
  final CloseableHttpClient httpclient = scm.createHttpConnection();
  final CloseableHttpResponse response = httpclient.execute(httpPut);
  int responseCode = response.getStatusLine().getStatusCode();
  LOG.debug("HTTP PUT {} response. Status code {}", path, responseCode);
  response.close();
  return responseCode;
}
 
Example #17
Source File: OrientPyPiProxyFacetImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected HttpRequestBase buildFetchHttpRequest(final URI uri, final Context context) {
  Request request = context.getRequest();
  // If we're doing a search operation, we have to proxy the content of the XML-RPC POST request to the PyPI server...
  if (isSearchRequest(request)) {
    Payload payload = checkNotNull(request.getPayload());
    try {
      ContentType contentType = ContentType.parse(payload.getContentType());
      HttpPost post = new HttpPost(uri);
      post.setEntity(new InputStreamEntity(payload.openInputStream(), payload.getSize(), contentType));
      return post;
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  return super.buildFetchHttpRequest(uri, context); // URI needs to be replaced here
}
 
Example #18
Source File: SearchProxyControllerTest.java    From elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void willForwardSearchRequestToAChosenNode() throws Exception {
    final String chosenNode = "1.0.0.1:1002";

    when(elasticsearchScheduler.getTasks()).thenReturn(createTasksMap(3));
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class))).thenReturn(httpResponse);
    when(httpResponse.getEntity()).thenReturn(new InputStreamEntity(new ByteArrayInputStream("Search result".getBytes("UTF-8"))));

    final ResponseEntity<InputStreamResource> search = controller.search("test", chosenNode);
    assertEquals(200, search.getStatusCode().value());

    assertEquals(chosenNode, search.getHeaders().getFirst("X-ElasticSearch-host"));
    final ArgumentCaptor<HttpHost> httpHostArgumentCaptor = ArgumentCaptor.forClass(HttpHost.class);
    final ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    verify(httpClient).execute(httpHostArgumentCaptor.capture(), httpRequestArgumentCaptor.capture());
    assertEquals(HOSTNAME, httpHostArgumentCaptor.getValue().getHostName());
    assertEquals("/_search?q=test", httpRequestArgumentCaptor.getValue().getRequestLine().getUri());
}
 
Example #19
Source File: BulkV2Connection.java    From components with Apache License 2.0 6 votes vote down vote up
public void uploadDataFromStream(String jobId, InputStream input) throws BulkV2ClientException {
    try {
        String endpoint = getRestEndpoint();
        endpoint = endpoint + "jobs/ingest/" + jobId + "/batches";
        HttpPut httpPut = (HttpPut) createRequest(endpoint, HttpMethod.PUT);

        InputStreamEntity entity = new InputStreamEntity(input, -1);
        entity.setContentType(CSV_CONTENT_TYPE);
        entity.setChunked(config.useChunkedPost());

        httpPut.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPut);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw new BulkV2ClientException(response.getStatusLine().getReasonPhrase());
        }
    } catch (BulkV2ClientException bec) {
        throw bec;
    } catch (IOException e) {
        throw new BulkV2ClientException(MESSAGES.getMessage("error.job.upload"), e);
    }
}
 
Example #20
Source File: CreateOrUpdateDataSet.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * Private constructor.
 *
 * @param id the dataset id.
 * @param name the dataset name.
 * @param dataSetContent the new dataset content.
 */
private CreateOrUpdateDataSet(String id, String name, long size, InputStream dataSetContent) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        try {
            URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/" + id + "/raw/");
            if (!StringUtils.isEmpty(name)) {
                uriBuilder.addParameter("name", name);
            }
            uriBuilder.addParameter("size", String.valueOf(size));
            final HttpPut put = new HttpPut(uriBuilder.build()); // $NON-NLS-1$ //$NON-NLS-2$
            put.setEntity(new InputStreamEntity(dataSetContent));
            return put;
        } catch (URISyntaxException e) {
            throw new TDPException(UNEXPECTED_EXCEPTION, e);
        }
    });
    onError(e -> {
        if (e instanceof TDPException) {
            return passthrough().apply(e);
        }
        return new TDPException(UNABLE_TO_CREATE_OR_UPDATE_DATASET, e);
    });
    on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(emptyString());
    on(HttpStatus.OK).then(asString());
}
 
Example #21
Source File: PreparationUpdateAction.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private HttpRequestBase onExecute(String preparationId, String stepId, AppendStep updatedStep) {
    try {
        final String url = preparationServiceUrl + "/preparations/" + preparationId + "/actions/" + stepId;

        final Optional<StepDiff> firstStepDiff = toStream(StepDiff.class, objectMapper, input).findFirst();
        if (firstStepDiff.isPresent()) { // Only interested in first one
            final StepDiff diff = firstStepDiff.get();
            updatedStep.setDiff(diff);
        }
        final String stepAsString = objectMapper.writeValueAsString(updatedStep);

        final HttpPut actionAppend = new HttpPut(url);
        final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes());

        actionAppend.setHeader(new BasicHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE));
        actionAppend.setEntity(new InputStreamEntity(stepInputStream));
        return actionAppend;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
Example #22
Source File: CXF4130Test.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCxf4130() throws Exception {
    InputStream body = getClass().getResourceAsStream("cxf4130data.txt");
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(ADDRESS);
    post.setEntity(new InputStreamEntity(body, ContentType.TEXT_XML));
    CloseableHttpResponse response = client.execute(post);

    Document doc = StaxUtils.read(response.getEntity().getContent());
    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);
}
 
Example #23
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void doAddBook(String type, String address, InputStream is, int status) throws Exception {

        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(address);

        String ct = type + "; type=\"text/xml\"; " + "start=\"rootPart\"; "
            + "boundary=\"----=_Part_4_701508.1145579811786\"";
        post.setHeader("Content-Type", ct);

        post.setEntity(new InputStreamEntity(is));

        try {
            CloseableHttpResponse response = client.execute(post);
            assertEquals(status, response.getStatusLine().getStatusCode());
            if (status == 200) {
                InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
                assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                             stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
            }
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    }
 
Example #24
Source File: AssetGenerator.java    From VolleyBall with MIT License 6 votes vote down vote up
public HttpResponse generateResponse(Context aContext, Route aRoute, Map<String, String> aReplace) {
    try {
        String test = mText;
        for (String aKey : aReplace.keySet()) {
            android.util.Log.d("AssetGenerator", "Replacing: "+ aKey);
            String regex = "\\{" + aKey.substring(1, aKey.length() - 1) + "\\}";
            test= test.replaceAll(regex, aReplace.get(aKey));
        }

        InputStream is = aContext.getAssets().open(test);
        HttpResponse response = FACTORY.newHttpResponse(HTTP_1_1, 200, CONTEXT);
        response.setEntity(new InputStreamEntity(is, is.available()));
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        return SERVER_ERROR;
    }
}
 
Example #25
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
HttpPost buildSendExportMethod( String type, String load, InputStream is ) throws UnsupportedEncodingException {
  String serviceUrl = RegisterPackageServlet.CONTEXT_PATH;
  if ( type != null && load != null ) {
    serviceUrl +=
      "/?" + RegisterPackageServlet.PARAMETER_TYPE + "=" + type
        + "&" + RegisterPackageServlet.PARAMETER_LOAD + "=" + URLEncoder.encode( load, "UTF-8" );
  }

  String urlString = constructUrl( serviceUrl );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }

  HttpPost method = new HttpPost( urlString );
  method.setEntity( new InputStreamEntity( is ) );
  method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) );

  return method;
}
 
Example #26
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Send a POST request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
 * supplied
 * @param content the content bytes
 * @return a Response object with response detail
 * @throws IOException
 */
public Response post(Cluster cluster, String path, Header[] headers,
    byte[] content) throws IOException {
  HttpPost method = new HttpPost(path);
  try {
    method.setEntity(new InputStreamEntity(new ByteArrayInputStream(content), content.length));
    HttpResponse resp = execute(cluster, method, headers, path);
    headers = resp.getAllHeaders();
    content = getResponseBody(resp);
    return new Response(resp.getStatusLine().getStatusCode(), headers, content);
  } finally {
    method.releaseConnection();
  }
}
 
Example #27
Source File: UpdateDataSet.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private UpdateDataSet(String id, InputStream dataSetContent) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        final HttpPut put = new HttpPut(datasetServiceUrl + "/datasets/" + id); //$NON-NLS-1$ //$NON-NLS-2$
        put.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        put.setEntity(new InputStreamEntity(dataSetContent));
        return put;
    });
    on(HttpStatus.NO_CONTENT).then(emptyString());
    on(HttpStatus.OK).then(asString());
}
 
Example #28
Source File: PreparationAddAction.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private HttpRequestBase onExecute(String preparationId, List<AppendStep> steps) {
    try {
        final String stepAsString = objectMapper.writeValueAsString(steps);
        final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes(StandardCharsets.UTF_8));

        final HttpPost actionAppend =
                new HttpPost(preparationServiceUrl + "/preparations/" + preparationId + "/actions");
        actionAppend.setHeader(new BasicHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE));
        actionAppend.setEntity(new InputStreamEntity(stepInputStream));

        return actionAppend;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
Example #29
Source File: UpdateColumn.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private UpdateColumn(final String dataSetId, final String columnId, final InputStream body) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        final HttpPost post = new HttpPost(datasetServiceUrl + "/datasets/" + dataSetId + "/column/" + columnId); //$NON-NLS-1$ //$NON-NLS-2$
        post.setHeader("Content-Type", APPLICATION_JSON_VALUE);
        post.setEntity(new InputStreamEntity(body));
        return post;
    });
    onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET, e,
            ExceptionContext.build().put("id", dataSetId)));
    on(HttpStatus.OK).then(asNull());
}
 
Example #30
Source File: ServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
    final HttpPut httpPut = new HttpPut(BASE_URL + "1");
    final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
    httpPut.setEntity(new InputStreamEntity(resourceStream));
    httpPut.setHeader("Content-Type", "text/xml");

    final HttpResponse response = client.execute(httpPut);
    assertEquals(304, response.getStatusLine().getStatusCode());
}