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.olat.core.commons.services.webdav.WebDAVCommandsTest.java

/**
 * In the this test, an author and its assistant try to concurrently
 * lock a file./* w w w . j a v a 2s .c  o m*/
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testLock() throws IOException, URISyntaxException {
    //create a user
    Identity author = JunitTestHelper
            .createAndPersistIdentityAsAuthor("webdav-4-" + UUID.randomUUID().toString());
    Identity assistant = JunitTestHelper
            .createAndPersistIdentityAsAuthor("webdav-5-" + UUID.randomUUID().toString());
    deployTestCourse(author, assistant);

    WebDAVConnection authorConn = new WebDAVConnection();
    authorConn.setCredentials(author.getName(), "A6B7C8");

    WebDAVConnection assistantConn = new WebDAVConnection();
    assistantConn.setCredentials(assistant.getName(), "A6B7C8");

    //author check course folder
    URI courseUri = authorConn.getBaseURI().path("webdav").path("coursefolders").build();
    String publicXml = authorConn.propfind(courseUri, 2);
    Assert.assertTrue(
            publicXml.indexOf("<D:href>/webdav/coursefolders/other/Kurs/_courseelementdata/</D:href>") > 0);

    //coauthor check course folder
    String assistantPublicXml = assistantConn.propfind(courseUri, 2);
    Assert.assertTrue(assistantPublicXml
            .indexOf("<D:href>/webdav/coursefolders/other/Kurs/_courseelementdata/</D:href>") > 0);

    //PUT a file to lock
    URI putUri = UriBuilder.fromUri(courseUri).path("other").path("Kurs").path("test.txt").build();
    HttpPut put = authorConn.createPut(putUri);
    InputStream dataStream = WebDAVCommandsTest.class.getResourceAsStream("text.txt");
    InputStreamEntity entity = new InputStreamEntity(dataStream, -1);
    put.setEntity(entity);
    HttpResponse putResponse = authorConn.execute(put);
    Assert.assertEquals(201, putResponse.getStatusLine().getStatusCode());
    EntityUtils.consume(putResponse.getEntity());

    //author lock the file in the course folder
    String authorLockToken = UUID.randomUUID().toString().replace("-", "").toLowerCase();
    String authorResponseLockToken = authorConn.lock(putUri, authorLockToken);
    Assert.assertNotNull(authorResponseLockToken);

    //coauthor try to lock the same file
    String coauthorLockToken = UUID.randomUUID().toString().replace("-", "").toLowerCase();
    int coauthorLock = assistantConn.lockTry(putUri, coauthorLockToken);
    Assert.assertEquals(423, coauthorLock);// it's lock

    //author unlock the file
    int unlockCode = authorConn.unlock(putUri, authorResponseLockToken);
    Assert.assertEquals(204, unlockCode);

    //coauthor try a second time to lock the file
    String coauthorLockToken_2 = UUID.randomUUID().toString().replace("-", "").toLowerCase();
    int coauthorLock_2 = assistantConn.lockTry(putUri, coauthorLockToken_2);
    Assert.assertEquals(200, coauthorLock_2);// it's lock

    IOUtils.closeQuietly(authorConn);
    IOUtils.closeQuietly(assistantConn);
}

From source file:org.perfrepo.client.PerfRepoClient.java

/**
 * Add attachment to an existing test execution.
 *
 * @param testExecutionId Test execution id
 * @param file File to upload//w ww.  ja v  a 2s . co m
 * @param mimeType Mime type
 * @param fileNameInRepo The name the attachment will have in the perf repo.
 * @return Id of the new attachment
 * @throws Exception
 */
public Long uploadAttachment(Long testExecutionId, File file, String mimeType, String fileNameInRepo)
        throws Exception {
    InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file), file.length());
    return uploadAttachment(testExecutionId, entity, mimeType, fileNameInRepo);
}

From source file:com.semagia.cassa.client.GraphClient.java

private boolean _updateGraph(final URI graphURI, final InputStream in, final MediaType mediaType)
        throws IOException {
    final HttpPost post = new HttpPost(getGraphURI(graphURI));
    final InputStreamEntity entity = new InputStreamEntity(in, -1);
    entity.setContentType(mediaType != null ? mediaType.toString() : null);
    post.setEntity(entity);//  w  ww. j  a v  a 2  s .com
    final int status = getStatusCode(post);
    return status == 201 || status == 204;
}

From source file:org.rundeck.api.ApiCall.java

private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler,
        HttpEntityEnclosingRequestBase httpPost) {
    if (null != apiPath.getAccept()) {
        httpPost.setHeader("Accept", apiPath.getAccept());
    }//  w ww.j a  va 2 s.c om
    // POST a multi-part request, with all attachments
    if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ArrayList<File> tempfiles = new ArrayList<>();

        //attach streams
        for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) {
            if (client.isUseIntermediateStreamFile()) {
                //transfer to file
                File f = copyToTempfile(attachment.getValue());
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), f);
                tempfiles.add(f);
            } else {
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
            }
        }
        if (tempfiles.size() > 0) {
            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        }

        //attach files
        for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) {
            multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
        }

        httpPost.setEntity(multipartEntityBuilder.build());
    } else if (apiPath.getForm().size() > 0) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e);
        }
    } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) {
        if (client.isUseIntermediateStreamFile()) {
            ArrayList<File> tempfiles = new ArrayList<>();
            File f = copyToTempfile(apiPath.getContentStream());
            tempfiles.add(f);
            httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType())));

            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        } else {
            InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(),
                    ContentType.create(apiPath.getContentType()));
            httpPost.setEntity(entity);
        }
    } else if (apiPath.getContents() != null && apiPath.getContentType() != null) {
        ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(),
                ContentType.create(apiPath.getContentType()));

        httpPost.setEntity(bae);
    } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) {
        httpPost.setEntity(
                new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType())));
    } else if (apiPath.getXmlDocument() != null) {
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument())));
    } else if (apiPath.isEmptyContent()) {
        //empty content
    } else {
        throw new IllegalArgumentException("No Form or Multipart entity for POST content-body");
    }

    return execute(httpPost, handler);
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

@Override
public byte[] post(final String url, final byte[] requestBytes) throws DSSException {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Fetching data via POST from url " + url);
    }//from w  w w  .  j  a  v  a 2 s .  c  om
    HttpPost httpPost = null;
    HttpResponse httpResponse = null;
    try {

        final URI uri = DSSUtils.toUri(url.trim());
        httpPost = new HttpPost(uri);

        // 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(requestBytes);

        final HttpEntity httpEntity = new InputStreamEntity(bis, requestBytes.length);
        final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity);
        httpPost.setEntity(requestEntity);
        defineContentType(httpPost);
        defineContentTransferEncoding(httpPost);
        httpResponse = getHttpResponse(httpPost, uri);
        final byte[] returnedBytes = readHttpResponse(uri, httpResponse);
        return returnedBytes;
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {
        if (httpPost != null) {
            httpPost.releaseConnection();
        }
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:org.graphity.core.util.jena.HttpOp.java

/**
 * Executes a HTTP POST with request body from an input stream and response
 * handling.//  w  ww  . jav a 2 s .  c om
 * <p>
 * The input stream is assumed to be UTF-8.
 * </p>
 * 
 * @param url
 *            URL
 * @param contentType
 *            Content Type to POST
 * @param input
 *            Input Stream to POST content from
 * @param length
 *            Length of content to POST
 * @param acceptType
 *            Accept Type
 * @param handler
 *            Response handler called to process the response
 * @param httpClient
 *            HTTP Client
 * @param httpContext
 *            HTTP Context
 * @param authenticator
 *            HTTP Authenticator
 */
public static void execHttpPost(String url, String contentType, InputStream input, long length,
        String acceptType, HttpResponseHandler handler, HttpClient httpClient, HttpContext httpContext,
        HttpAuthenticator authenticator) {
    InputStreamEntity e = new InputStreamEntity(input, length);
    e.setContentType(contentType);
    e.setContentEncoding("UTF-8");
    try {
        execHttpPost(url, e, acceptType, handler, httpClient, httpContext, authenticator);
    } finally {
        closeEntity(e);
    }
}

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

protected void writeFile(FileLocation destination, InputStream fileData, long size, String name,
        String contentType) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + destination.host_name + ":" + port + "/" + destination.path_name + "/"
            + name;/*  ww  w  .ja v a 2  s.com*/

    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 (destination.user_name != null && destination.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(destination.host_name, port),
                    new UsernamePasswordCredentials(destination.user_name, destination.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.apache.solr.client.solrj.impl.HttpSolrClient.java

protected HttpRequestBase createMethod(final SolrRequest request, String collection)
        throws IOException, SolrServerException {

    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;/*  w  w  w  .j a  v  a2s .  c  o  m*/
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    String basePath = baseUrl;
    if (collection != null)
        basePath += "/" + collection;

    if (SolrRequest.METHOD.GET == request.getMethod()) {
        if (streams != null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
        }

        return new HttpGet(basePath + path + wparams.toQueryString());
    }

    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {

        String url = basePath + path;
        boolean hasNullStreamName = false;
        if (streams != null) {
            for (ContentStream cs : streams) {
                if (cs.getName() == null) {
                    hasNullStreamName = true;
                    break;
                }
            }
        }
        boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod())
                || (streams != null && streams.size() > 1)) && !hasNullStreamName;

        LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
        if (streams == null || isMultipart) {
            // send server list and request list as query string params
            ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
            queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
            String fullQueryUrl = url + queryParams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod()
                    ? new HttpPost(fullQueryUrl)
                    : new HttpPut(fullQueryUrl);

            if (!isMultipart) {
                postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }

            List<FormBodyPart> parts = new LinkedList<>();
            Iterator<String> iter = wparams.getParameterNamesIterator();
            while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = wparams.getParams(p);
                if (vals != null) {
                    for (String v : vals) {
                        if (isMultipart) {
                            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                        } else {
                            postOrPutParams.add(new BasicNameValuePair(p, v));
                        }
                    }
                }
            }

            // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
            if (isMultipart && streams != null) {
                for (ContentStream content : streams) {
                    String contentType = content.getContentType();
                    if (contentType == null) {
                        contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                    }
                    String name = content.getName();
                    if (name == null) {
                        name = "";
                    }
                    parts.add(new FormBodyPart(name,
                            new InputStreamBody(content.getStream(), contentType, content.getName())));
                }
            }

            if (parts.size() > 0) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                for (FormBodyPart p : parts) {
                    entity.addPart(p);
                }
                postOrPut.setEntity(entity);
            } else {
                //not using multipart
                postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
            }

            return postOrPut;
        }
        // It is has one stream, it is the post body, put the params in the URL
        else {
            String fullQueryUrl = url + wparams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod()
                    ? new HttpPost(fullQueryUrl)
                    : new HttpPut(fullQueryUrl);

            // 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;
            }
            if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                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;
                            }

                        });
            } else {
                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;
                            }
                        });
            }
            return postOrPut;
        }
    }

    throw new SolrServerException("Unsupported method: " + request.getMethod());

}

From source file:edu.jhu.pha.vospace.storage.SwiftKeystoneStorageManager.java

public static String storeStreamedObject(String container, InputStream data, String contentType, String name,
        Map<String, String> metadata) throws IOException, HttpException, FilesException {
    String objName = name;//  w  ww .j a va 2 s .co m
    if (isValidContainerName(container) && FilesClient.isValidObjectName(objName)) {
        HttpPut method = new HttpPut(
                getFileUrl + "/" + sanitizeForURI(container) + "/" + sanitizeForURI(objName));

        method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
        method.setHeader(FilesConstants.X_AUTH_TOKEN, strToken);
        InputStreamEntity entity = new InputStreamEntity(data, -1);
        entity.setChunked(true);
        entity.setContentType(contentType);
        method.setEntity(entity);
        for (String key : metadata.keySet()) {
            method.setHeader(FilesConstants.X_OBJECT_META + key, sanitizeForURI(metadata.get(key)));
        }
        method.removeHeaders("Content-Length");

        try {
            FilesResponse response = new FilesResponse(client.execute(method));

            if (response.getStatusCode() == HttpStatus.SC_CREATED) {
                return response.getResponseHeader(FilesConstants.E_TAG).getValue();
            } else {
                logger.error(response.getStatusLine());
                throw new FilesException("Unexpected result", response.getResponseHeaders(),
                        response.getStatusLine());
            }
        } finally {
            method.abort();
        }
    } else {
        if (!FilesClient.isValidObjectName(objName)) {
            throw new FilesInvalidNameException(objName);
        } else {
            throw new FilesInvalidNameException(container);
        }
    }
}