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:leap.lang.http.client.apache.ApacheHttpRequest.java

protected void initRequest() {
    if (null != body) {
        entity = new ByteArrayEntity(body);
    } else if (null != inputStream) {
        entity = new InputStreamEntity(inputStream);
    } else if (!formParams.isEmpty()) {
        entity = new UrlEncodedFormEntity(formParams, charset);
    }//from   w  ww .  j  a v a  2s. c om

    if (null == method) {

        if (null != entity) {
            method = HTTP.Method.POST;
        } else {
            method = HTTP.Method.GET;
        }

    }
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

public static String post(String uri, File file) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    try {/*from   w  w  w  . j  a  va  2 s . c  om*/
        InputStreamEntity inputStreamEntity = new InputStreamEntity(new FileInputStream(file));
        //????
        httpPost.setEntity(inputStreamEntity);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            httpResponse.close();
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (IOException e) {
            logger.error(":{}", e.getMessage());
        }
    } catch (FileNotFoundException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

@Override
public void register(final URI uri) {
    init.await();/*from   w  w w  .  j a  va 2s  .c o  m*/
    try {
        LOG.debug("Registering service {} ", uri);

        final HttpPatch patch = new HttpPatch(registryContainer);
        patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE);
        patch.setEntity(new InputStreamEntity(patchAddService(uri)));

        try (CloseableHttpResponse resp = execute(patch)) {
            LOG.info("Adding service {} to registry {}", uri, registryContainer);
        }
    } catch (final Exception e) {
        throw new RuntimeException(
                String.format("Could not add <%s> to service registry <%s>", uri, registryContainer), e);
    }

    update(uri);
}

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

/**
 * Make a POST request/*from   w  w  w  . j a  v a 2 s.co  m*/
 * @param url the URL of the resource to which to POST
 * @param body the content to be sent to the server
 * @param contentType the Content-Type of the body
 * @return the repository response
 * @throws FcrepoOperationFailedException when the underlying HTTP request results in an error
 */
public FcrepoResponse post(final URI url, final InputStream body, final String contentType)
        throws FcrepoOperationFailedException {

    final HttpMethods method = HttpMethods.POST;
    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 POST request headers: {}", request.getAllHeaders());

    final HttpResponse response = executeRequest(request);

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

    return fcrepoGenericResponse(url, response, throwExceptionOnFailure);
}

From source file:org.fcrepo.apix.jena.impl.LdpContainerRegistry.java

@Override
public URI put(final WebResource resource, final boolean asBinary) {
    init.await();/*from   w ww. j a v a2  s.  c  o  m*/
    HttpEntityEnclosingRequestBase request = null;

    if (resource.uri() == null || !resource.uri().isAbsolute()) {
        request = new HttpPost(containerId);
        final String name = slugText(resource);
        if (name != null) {
            request.addHeader("Slug", name);
        }

        if (asBinary) {
            request.addHeader("Content-Disposition",
                    String.format("attachment; filename=%s", name != null ? name : "file.bin"));
        }

    } else {
        request = new HttpPut(resource.uri());
        if (!asBinary) {
            request.addHeader("Prefer", "handling=lenient; received=\"minimal\"");
        }
    }

    if (resource.representation() != null) {
        request.setEntity(new InputStreamEntity(resource.representation()));
    }
    request.setHeader(HttpHeaders.CONTENT_TYPE, resource.contentType());

    try {
        return client.execute(request, (response -> {
            final int status = response.getStatusLine().getStatusCode();

            if (status == HttpStatus.SC_CREATED) {
                return URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
            } else if (status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_OK) {
                return resource.uri();
            } else {
                throw new RuntimeException(String.format("Resource creation failed: %s; %s",
                        response.getStatusLine().toString(), EntityUtils.toString(response.getEntity())));
            }
        }));
    } catch (final Exception e) {
        throw new RuntimeException(String.format("Error executing %s request to %s",
                request.getClass().getSimpleName(), request.getURI().toString()), e);
    }

}

From source file:onl.area51.httpd.action.Actions.java

static void renderResource(Class<?> clazz, Request r, URI uri, String base) throws IOException {
    String url = uri.getPath();/*ww w .  j  ava 2 s  . c  o m*/
    if (url.contains("//")) {
        url = url.replace("//", "/");
    }
    if (!url.contains("/..")) {
        String path = base + (url.startsWith("/") ? "" : "/") + url;
        if (path.endsWith("/")) {
            path = path + "index.html";
        }
        InputStream is = clazz.getResourceAsStream(path);
        if (is != null) {
            if (r.isResponsePresent()) {
                // Hope the content type is the same, just add to the existing response.
                // This is usually due to including html content into an existing page
                try {
                    r.getResponse().copy(is);
                } finally {
                    is.close();
                }
            } else {
                // Treat as it's own entity
                r.getHttpResponse().setEntity(new InputStreamEntity(is));
            }
        }
    }
}

From source file:opendial.plugins.NuanceSpeech.java

/**
 * Processes the audio data contained in tempFile (based on the recognition
 * grammar whenever provided) and updates the dialogue state with the new user
 * inputs./*from w w  w. j  a v a  2 s  .c om*/
 * 
 * @param stream the speech stream containing the audio data
 */
private void recognise(SpeechData stream) {

    int sampleRate = (int) stream.getFormat().getSampleRate();
    log.fine("calling Nuance server for recognition... " + "(sample rate: " + sampleRate + " Hz.)");
    try {

        HttpPost httppost = new HttpPost(asrURI);
        String format = "audio/x-wav;codec=pcm;bit=" + stream.getFormat().getFrameSize() * 8 + ";rate="
                + sampleRate;
        String lang = system.getSettings().params.getProperty("lang");
        httppost.addHeader("Content-Type", format);
        httppost.addHeader("Accept", "application/xml");
        httppost.addHeader("Accept-Language", lang);
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType(format);
        httppost.setEntity(reqEntity);

        HttpResponse response = asrClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (resEntity == null) {
            log.warning("Response entity is null, aborting");
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));

        if (response.getStatusLine().getStatusCode() != 200) {
            log.warning(
                    "(speech could not be recognised: error " + response.getStatusLine().getStatusCode() + ")");
            String sentence;
            while ((sentence = reader.readLine()) != null) {
                log.warning(sentence);
            }
        } else {

            String sentence;
            Map<String, Double> lines = new HashMap<String, Double>();
            while ((sentence = reader.readLine()) != null) {
                lines.put(sentence, 1.0 / (lines.size() + 1));
            }
            lines = InferenceUtils.normalise(lines);
            for (String s : new ArrayList<String>(lines.keySet())) {
                lines.put(s, ((int) (lines.get(s) * 100)) / 100.0);
            }

            log.fine("recognition results: " + lines);
            reader.close();
            if (!lines.isEmpty()) {
                system.addUserInput(lines);
            }
        }
        httppost.releaseConnection();
    } catch (Exception e) {
        log.warning("could not extract ASR results: " + e);
    }
}

From source file:com.joyent.manta.client.crypto.EncryptingEntityTest.java

public void doesNotCloseSuppliedOutputStreamWhenFailureOccurs() throws Exception {
    final SupportedCipherDetails cipherDetails = DefaultsConfigContext.DEFAULT_CIPHER;
    final SecretKey secretKey = SecretKeyUtils.generate(cipherDetails);
    final EncryptingEntity encryptingEntity = new EncryptingEntity(secretKey, cipherDetails,
            new InputStreamEntity(new BrokenInputStream(new IOException("bad input"))));

    final OutputStream output = Mockito.mock(OutputStream.class);
    Assert.assertThrows(IOException.class, () -> encryptingEntity.writeTo(output));
    Mockito.verify(output, Mockito.never()).close();
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

@Override
public ServiceInstanceRegistry createInstanceRegistry(final Service service) {
    init.await();// www  . ja v a  2 s .  c  o m
    LOG.debug("POST: Creating service instance registry");

    final HttpPost post = new HttpPost(service.uri());
    post.setHeader(HttpHeaders.CONTENT_TYPE, "text/turtle");
    post.setEntity(new InputStreamEntity(
            this.getClass().getResourceAsStream("objects/service-instance-registry.ttl")));

    final URI uri;
    try (CloseableHttpResponse resp = execute(post)) {
        uri = URI.create(resp.getFirstHeader(HttpHeaders.LOCATION).getValue());
    } catch (final Exception e) {
        throw new RuntimeException("Could not create service instance registry", e);
    }

    final HttpPatch patch = new HttpPatch(uri);
    patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE);
    patch.setEntity(new StringEntity(String.format("INSERT {?instance <%s> <%s> .} WHERE {?instance a <%s> .}",
            PROP_IS_SERVICE_INSTANCE_OF, service.uri(), CLASS_SERVICE_INSTANCE), UTF_8));

    try (CloseableHttpResponse resp = execute(patch)) {
        LOG.info("Updating instance registry for {}", service.uri());
    } catch (final Exception e) {
        throw new RuntimeException("Could not update service instance registry", e);
    }

    return instancesOf(getService(service.uri()));
}

From source file:org.apache.nifi.api.client.impl.AbstractNiFiAPIClient.java

public <U extends Entity> Object post(Class<? extends ApplicationResource> resourceClass, Method nifiApiMethod,
        U u, Map<String, String> pathParams, InputStream payloadData) {

    StringBuilder stringBuilder = new StringBuilder(this.baseUrl);
    stringBuilder.append(resourceClass.getAnnotation(Path.class).value());
    stringBuilder.append("/");
    stringBuilder.append(nifiApiMethod.getAnnotation(Path.class).value());

    String fullRequest = replaceUriWithPathParams(stringBuilder.toString(), pathParams);

    HttpPost request = new HttpPost(fullRequest);

    StringBuffer result = new StringBuffer();
    try {/*w  w w  . j  a v a  2s  .c  om*/

        //Set the Accept and Content-Type headers appropriately.
        String produces = nifiApiMethod.getAnnotation(Produces.class).value()[0];
        String consumes = nifiApiMethod.getAnnotation(Consumes.class).value()[0];

        //Set POST request payload. Can only upload either Inputstream OR Object currently.
        if (u != null || payloadData != null) {
            if (u != null) {
                StringEntity input = new StringEntity(mapper.writeValueAsString(u));
                request.setEntity(input);
                request.setHeader("Content-type", consumes);
            } else {
                InputStreamEntity inputStreamEntity = new InputStreamEntity(payloadData);
                request.setEntity(inputStreamEntity);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

                // This attaches the file to the POST:
                builder.addBinaryBody("template", payloadData, ContentType.APPLICATION_OCTET_STREAM,
                        "SomethingTest.xml");

                HttpEntity multipart = builder.build();
                request.setEntity(multipart);
            }
        }

        request.addHeader("Accept", produces);

        HttpResponse response = client.execute(request);

        //Examine the return type and handle that data appropriately.
        Header rCT = response.getHeaders("Content-Type")[0];
        if (rCT.getValue().equalsIgnoreCase("application/xml")) {
            //                TemplateDTO templateDTO = TemplateDeserializer.deserialize(response.getEntity().getContent());
            //                return templateDTO;
            return null;
        } else {
            return mapper.readValue(response.getEntity().getContent(),
                    nifiApiMethod.getAnnotation(ApiOperation.class).response());
        }

    } catch (Exception ex) {
        logger.error("Unable to complete HTTP POST due to {}", ex.getMessage());
        return null;
    }
}