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.okta.sdk.impl.http.httpclient.RepeatableInputStreamEntity.java

/**
 * Creates a new RepeatableInputStreamEntity 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.//  w  w w. j  a  va  2s .  co  m
 *
 * @param request The details of the request being written out (content type,
 *                content length, and content).
 */
RepeatableInputStreamEntity(Request request) {
    setChunked(false);

    MediaType contentType = request.getHeaders().getContentType();
    long contentLength = request.getHeaders().getContentLength();
    InputStream body = request.getBody();

    this.inputStreamEntity = new InputStreamEntity(body, contentLength);
    this.inputStreamEntity.setContentType(contentType.getType());
    this.content = body;

    setContent(content);
    setContentType(contentType.getType());
    setContentLength(contentLength);
}

From source file:com.autonomy.nonaci.indexing.impl.PostDataImpl.java

public PostDataImpl(final InputStream inputStream, final long length) {
    this.httpEntity = new InputStreamEntity(inputStream, length);
}

From source file:com.hoccer.http.AsyncHttpRequestWithBody.java

public void setBody(StreamableContent pStreamableData) throws Exception {

    final long streamLength = pStreamableData.getNewStreamLength();

    InputStreamEntity entity = new InputStreamEntity(
            new MonitoredInputStream(pStreamableData.openNewInputStream()) {

                @Override/*  w  w w.ja v a2s.  c  o m*/
                public void onBytesRead(long totalNumBytesRead) {

                    double progress = (totalNumBytesRead / (double) streamLength) * 100;
                    setUploadProgress((int) progress);
                }

            }, pStreamableData.getNewStreamLength());

    getRequest().addHeader("Content-Disposition",
            " attachment; filename=\"" + pStreamableData.getFilename() + "\"");
    entity.setContentType(pStreamableData.getContentType());
    getRequest().setEntity(entity);
    getRequest().addHeader("Content-Type", pStreamableData.getContentType());
}

From source file:edu.jhu.pha.vospace.protocol.HttpPutProtocolHandler.java

@Override
public void invoke(JobDescription job) throws IOException {
    String putFileUrl = job.getProtocols()
            .get(SettingsServlet.getConfig().getString("transfers.protocol.httpput"));

    StorageManager backend = StorageManagerFactory.getStorageManager(job.getUsername());

    HttpClient client = MyHttpConnectionPoolProvider.getHttpClient();
    InputStream fileInp = backend.getBytes(job.getTargetId().getNodePath());

    HttpPut put = new HttpPut(putFileUrl);

    Node node = NodeFactory.getNode(job.getTargetId(), job.getUsername());

    put.setEntity(new InputStreamEntity(fileInp, node.getNodeInfo().getSize()));

    try {/*from   w  ww. jav  a  2 s. c om*/
        HttpResponse response = client.execute(put);
        response.getEntity().getContent().close();
    } catch (IOException ex) {
        put.abort();
        ex.printStackTrace();
        throw ex;
    } finally {
        try {
            if (null != fileInp)
                fileInp.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.betfair.application.util.HttpCallable.java

public HttpUriRequest getMethod(String contentType, Object[] paramValues, int size, HttpCallLogEntry cle) {
    cle.setMethod(name);//  w ww  .j  a  v a 2s  .  c o m
    cle.setProtocol(contentType);
    if (contentType.equals("RPC")) {
        HttpPost pm = new HttpPost(rpcEndpoint);

        final ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonRPCCall.getBytes());
        final InputStreamEntity is = new InputStreamEntity(inputStream, inputStream.available());
        pm.addHeader("Content-Type", "application/json");
        pm.addHeader("Accept", "application/json");
        pm.addHeader("X-ExpectedReturnCode", String.valueOf(expectedHTTP));
        pm.setEntity(is);
        return pm;
    } else if (contentType.equals("SOAP")) {
        HttpPost pm = new HttpPost(soapEndpoint);

        final ByteArrayInputStream inputStream = bodySOAP.buildBodyToBytes(size);
        final InputStreamEntity is = new InputStreamEntity(inputStream, inputStream.available());
        pm.addHeader("Content-Type", "application/soap+xml");
        pm.addHeader("X-ExpectedReturnCode", String.valueOf(expectedHTTP));
        pm.setEntity(is);
        return pm;
    } else {
        if (bodyJSON != null) {
            HttpPost pm = new HttpPost(String.format(restURL, paramValues));
            InputStreamEntity is;
            if (contentType.endsWith("json")) {
                final ByteArrayInputStream inputStream = bodyJSON.buildBody(size);
                is = new InputStreamEntity(inputStream, inputStream.available());
            } else {
                final ByteArrayInputStream inputStream = bodyXML.buildBody(size);
                is = new InputStreamEntity(inputStream, inputStream.available());
            }
            pm.addHeader("Content-Type", contentType);
            pm.addHeader("Accept", contentType);
            pm.setEntity(is);
            return pm;
        } else {
            HttpGet gm = new HttpGet(String.format(restURL, paramValues));
            gm.addHeader("Accept", contentType);
            return gm;
        }
    }
}

From source file:com.jonbanjo.cups.operations.HttpPoster.java

static OperationResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream, final AuthInfo auth)
        throws IOException {

    final OperationResult opResult = new OperationResult();

    if (ippBuf == null) {
        return null;
    }//  w  w  w.j a v a2s.c  o m

    if (url == null) {
        return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();

    // will not work with older versions of CUPS!
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092));
    // probabaly not working with older CUPS versions
    client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true));

    HttpPost httpPost;

    try {
        httpPost = new HttpPost(url.toURI());
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }

    httpPost.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);

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

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);
    // If we need to send a document, concatenate InputStreams
    InputStream inputStream = headerStream;
    if (documentStream != null) {
        inputStream = new SequenceInputStream(headerStream, documentStream);
    }

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

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    if (auth.reason == AuthInfo.AUTH_REQUESTED) {
        AuthHeader.makeAuthHeader(httpPost, auth);
        if (auth.reason == AuthInfo.AUTH_OK) {
            httpPost.addHeader(auth.getAuthHeader());
            //httpPost.addHeader("Authorization", "Basic am9uOmpvbmJveQ==");
        }
    }

    ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
        @Override
        public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (response.getStatusLine().getStatusCode() == 401) {
                auth.setHttpHeader(response.getFirstHeader("WWW-Authenticate"));
            } else {
                auth.reason = AuthInfo.AUTH_OK;
            }
            HttpEntity entity = response.getEntity();
            opResult.setHttResult(response.getStatusLine().toString());
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                return null;
            }
        }
    };

    if (url.getProtocol().equals("https")) {

        Scheme scheme = JfSSLScheme.getScheme();
        if (scheme == null)
            return null;
        client.getConnectionManager().getSchemeRegistry().register(scheme);
    }

    byte[] result = client.execute(httpPost, handler);
    //String test = new String(result);
    IppResponse ippResponse = new IppResponse();

    opResult.setIppResult(ippResponse.getResponse(ByteBuffer.wrap(result)));
    opResult.setAuthInfo(auth);
    client.getConnectionManager().shutdown();
    return opResult;
}

From source file:org.apache.camel.component.http4.HttpEntityConverter.java

private static HttpEntity asHttpEntity(byte[] data, Exchange exchange) throws Exception {
    InputStreamEntity entity;/*from w w w.j a v a  2s.  c  om*/
    if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
        String contentEncoding = exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class);
        InputStream stream = GZIPHelper.compressGzip(contentEncoding, data);
        entity = new InputStreamEntity(stream,
                stream instanceof ByteArrayInputStream ? stream.available() != 0 ? stream.available() : -1
                        : -1);
    } else {
        entity = new InputStreamEntity(new ByteArrayInputStream(data), data.length);
    }
    if (exchange != null) {
        String contentEncoding = exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class);
        String contentType = ExchangeHelper.getContentType(exchange);
        entity.setContentEncoding(contentEncoding);
        entity.setContentType(contentType);
    }
    return entity;
}

From source file:org.codice.alliance.nsili.endpoint.requests.FtpDestinationSink.java

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType,
        List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/"
            + name;/*w w w .  jav a2s. co m*/

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port),
                    new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.jclouds.http.httpnio.util.NioHttpUtils.java

public static void addEntityForContent(BasicHttpEntityEnclosingRequest apacheRequest, Object content,
        String contentType, long length) {
    if (content instanceof InputStream) {
        InputStream inputStream = (InputStream) content;
        if (length == -1)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
        entity.setContentType(contentType);
        apacheRequest.setEntity(entity);
    } else if (content instanceof String) {
        NStringEntity nStringEntity = null;
        try {/*  w  w  w  .  j  av  a  2 s.  co  m*/
            nStringEntity = new NStringEntity((String) content);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(contentType);
        apacheRequest.setEntity(nStringEntity);
    } else if (content instanceof File) {
        apacheRequest.setEntity(new NFileEntity((File) content, contentType, true));
    } else if (content instanceof byte[]) {
        NByteArrayEntity entity = new NByteArrayEntity((byte[]) content);
        entity.setContentType(contentType);
        apacheRequest.setEntity(entity);
    } else {
        throw new UnsupportedOperationException("Content class not supported: " + content.getClass().getName());
    }
}

From source file:org.commonjava.indy.hostedbyarc.client.IndyHostedByArchiveClientModule.java

public HostedRepository createRepo(final File zipFile, final String repoName, final String ignorePathPrefix)
        throws IndyClientException {
    final String endPath = StringUtils.isBlank(ignorePathPrefix) ? "compressed-content"
            : "compressed-content?pathPrefixToIgnore=" + ignorePathPrefix;
    final String urlPath = UrlUtils.buildUrl(http.getBaseUrl(), HOSTED_BY_ARC_PATH, repoName, endPath);

    HttpPost postRequest = new HttpPost(urlPath);
    HttpResources resources = null;//from  w ww  .j ava  2 s.com

    try {
        postRequest.setHeader("Content-Type", CONTENT_TYPE_ZIP.getMimeType());
        InputStreamEntity entity = new InputStreamEntity(new FileInputStream(zipFile), CONTENT_TYPE_ZIP);
        postRequest.setEntity(entity);

        resources = http.execute(postRequest);

        if (resources != null) {
            HttpResponse response = resources.getResponse();
            final StatusLine sl = response.getStatusLine();

            if (sl.getStatusCode() != SC_OK && sl.getStatusCode() != SC_CREATED) {
                if (sl.getStatusCode() == SC_NOT_FOUND) {
                    return null;
                }

                throw new IndyClientException(sl.getStatusCode(), "Error create %s with file: %s", repoName,
                        zipFile.getName());
            }

            final String json = entityToString(response);
            logger.debug("Got JSON:\n\n{}\n\n", json);
            final HostedRepository value = http.getObjectMapper().readValue(json, HostedRepository.class);

            logger.debug("Got result object: {}", value);

            return value;
        }
        return null;
    } catch (IOException e) {
        throw new IndyClientException("Indy request failed: %s", e);
    } finally {
        if (resources != null) {
            cleanupResources(postRequest, resources.getResponse(), (CloseableHttpClient) resources.getClient());
        }
    }

}