Example usage for org.apache.http.entity InputStreamEntity setChunked

List of usage examples for org.apache.http.entity InputStreamEntity setChunked

Introduction

In this page you can find the example usage for org.apache.http.entity InputStreamEntity setChunked.

Prototype

public void setChunked(boolean z) 

Source Link

Usage

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * PUT??.//  w ww. j  a v  a  2 s . c om
 * @param url ?URL
 * @param contentType 
 * @param is PUT?
 * @return HttpPut
 * @throws DcException DAO
 */
protected final HttpPut makePutRequestByStream(final String url, final String contentType, final InputStream is)
        throws DcException {
    HttpPut request = new HttpPut(url);
    InputStreamEntity body;
    body = new InputStreamEntity(is, -1);
    Boolean chunked = true;
    if (chunked != null) {
        body.setChunked(chunked);
    }
    request.setEntity(body);
    return request;
}

From source file:io.personium.test.jersey.PersoniumRestAdapter.java

/**
 * PUT??.//from www  . j  a v  a 2  s  .com
 * @param url ?URL
 * @param contentType 
 * @param is PUT?
 * @return HttpPut
 * @throws PersoniumException DAO
 */
protected final HttpPut makePutRequestByStream(final String url, final String contentType, final InputStream is)
        throws PersoniumException {
    HttpPut request = new HttpPut(url);
    InputStreamEntity body;
    body = new InputStreamEntity(is, -1);
    Boolean chunked = true;
    if (chunked != null) {
        body.setChunked(chunked);
    }
    request.setEntity(body);
    return request;
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Model> train(Dataset dataset, Algorithm algorithm, Map<String, Object> parameters,
        String predictionFeature, MetaInfo modelMeta, String taskId) {

    CompletableFuture<Model> futureModel = new CompletableFuture<>();

    TrainingRequest trainingRequest = new TrainingRequest();
    trainingRequest.setDataset(dataset);
    trainingRequest.setParameters(parameters);
    trainingRequest.setPredictionFeature(predictionFeature);
    //        String trainingRequestString = serializer.write(trainingRequest);

    final HttpPost request = new HttpPost(algorithm.getTrainingService());

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;//from www  .  j  a va2  s  .c  o  m
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
        return futureModel;
    }
    InputStreamEntity entity = new InputStreamEntity(in, ContentType.APPLICATION_JSON);
    entity.setChunked(true);

    request.setEntity(entity);
    request.addHeader("Accept", "application/json");

    Future futureResponse = client.execute(request, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(final HttpResponse response) {
            futureMap.remove(taskId);
            int status = response.getStatusLine().getStatusCode();
            try {
                InputStream responseStream = response.getEntity().getContent();

                switch (status) {
                case 200:
                case 201:
                    TrainingResponse trainingResponse = serializer.parse(responseStream,
                            TrainingResponse.class);
                    Model model = new Model();
                    model.setId(randomStringGenerator.nextString(20));
                    model.setActualModel(trainingResponse.getRawModel());
                    model.setPmmlModel(trainingResponse.getPmmlModel());
                    model.setAdditionalInfo(trainingResponse.getAdditionalInfo());
                    model.setAlgorithm(algorithm);
                    model.setParameters(parameters);
                    model.setDatasetUri(dataset != null ? dataset.getDatasetURI() : null);

                    //Check if independedFeatures of model exist in dataset
                    List<String> filteredIndependedFeatures = new ArrayList<String>();

                    if (dataset != null && dataset.getFeatures() != null
                            && trainingResponse.getIndependentFeatures() != null)
                        for (String feature : trainingResponse.getIndependentFeatures()) {
                            for (FeatureInfo featureInfo : dataset.getFeatures()) {
                                if (feature.equals(featureInfo.getURI()))
                                    filteredIndependedFeatures.add(feature);
                            }
                        }

                    model.setIndependentFeatures(filteredIndependedFeatures);
                    model.setDependentFeatures(Arrays.asList(predictionFeature));
                    model.setMeta(modelMeta);

                    List<String> predictedFeatures = new ArrayList<>();
                    for (String featureTitle : trainingResponse.getPredictedFeatures()) {
                        Feature predictionFeatureResource = featureHandler.findByTitleAndSource(featureTitle,
                                "algorithm/" + algorithm.getId());
                        if (predictionFeatureResource == null) {
                            // Create the prediction features (POST /feature)
                            String predFeatID = randomStringGenerator.nextString(12);
                            predictionFeatureResource = new Feature();
                            predictionFeatureResource.setId(predFeatID);
                            predictionFeatureResource.setPredictorFor(predictionFeature);
                            predictionFeatureResource.setMeta(MetaInfoBuilder.builder()
                                    .addSources(
                                            /*messageBody.get("base_uri") + */"algorithm/" + algorithm.getId())
                                    .addComments("Feature created to hold predictions by algorithm with ID "
                                            + algorithm.getId())
                                    .addTitles(featureTitle).addSeeAlso(predictionFeature)
                                    .addCreators(algorithm.getMeta().getCreators()).build());
                            /* Create feature */
                            featureHandler.create(predictionFeatureResource);
                        }
                        predictedFeatures.add(baseURI + "feature/" + predictionFeatureResource.getId());
                    }
                    model.setPredictedFeatures(predictedFeatures);
                    futureModel.complete(model);
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new BadRequestException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureModel.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureModel.completeExceptionally(ex);
            }
        }

        @Override
        public void failed(final Exception ex) {
            futureMap.remove(taskId);
            futureModel.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureModel.cancel(true);
        }

    });

    serializer.write(trainingRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureModel.completeExceptionally(ex);
    }

    futureMap.put(taskId, futureResponse);
    return futureModel;
}

From source file:com.intel.cosbench.client.amplistor.AmpliClient.java

public String StoreStreamedObject(InputStream stream, long length, String ampliNamespace, String ampliFilename)
        throws IOException, HttpException, AmpliException {
    HttpPut method = null;//  w w w .  j  a  va  2  s .  c om
    HttpResponse response = null;
    try {
        String storageUrl = "http://" + this.host + ":" + this.port + nsRoot;
        method = HttpClientUtil.makeHttpPut(storageUrl + "/" + HttpClientUtil.encodeURL(ampliNamespace) + "/"
                + HttpClientUtil.encodeURL(ampliFilename));

        InputStreamEntity entity = new InputStreamEntity(stream, length);

        if (length < 0)
            entity.setChunked(true);
        else {
            entity.setChunked(false);
        }

        method.setEntity(entity);

        response = client.execute(method);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response.getFirstHeader("ETag").getValue();
        }

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return response.getFirstHeader("ETag").getValue();
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new AmpliException("Etag missmatch", response.getAllHeaders(), response.getStatusLine());
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_LENGTH_REQUIRED) {
            throw new AmpliException("Length miss-match", response.getAllHeaders(), response.getStatusLine());
        } else {
            throw new AmpliException(
                    System.currentTimeMillis() + ": [" + Thread.currentThread().getName() + "]: "
                            + ampliNamespace + "/" + ampliFilename + ": " + response.getStatusLine(),
                    response.getAllHeaders(), response.getStatusLine());
        }
    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }
}

From source file:be.cytomine.client.HttpClient.java

public int post(byte[] data) throws IOException {
    log.debug("POST " + URL.toString());
    HttpPost httpPost = new HttpPost(URL.toString());
    if (isAuthByPrivateKey) {
        httpPost.setHeaders(headersArray);
    }// w  ww.j a  va  2s .com
    log.debug("Post send :" + data.length);

    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(false);
    BufferedHttpEntity myEntity = null;
    try {
        myEntity = new BufferedHttpEntity(reqEntity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error(e);
    }

    httpPost.setEntity(myEntity);
    response = client.execute(targetHost, httpPost, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:be.cytomine.client.HttpClient.java

public int put(byte[] data) throws IOException {
    log.debug("Put " + URL.getPath());
    HttpPut httpPut = new HttpPut(URL.getPath());
    if (isAuthByPrivateKey) {
        httpPut.setHeaders(headersArray);
    }//  w w  w.  j  a va2 s . c  om
    log.debug("Put send :" + data.length);

    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(false);

    BufferedHttpEntity myEntity = null;
    try {
        myEntity = new BufferedHttpEntity(reqEntity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error(e);
    }

    httpPut.setEntity(myEntity);
    response = client.execute(targetHost, httpPut, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java

public SwiftClientResponse PutFaceVerity(String url, String Container, String object_name, InputStream content,
        long content_length, Map<String, String> query, String accesskey, String secretkey)
        throws IOException, CSSPException {
    BasicHttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, soTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    Map<String, String> headers = new LinkedHashMap<String, String>();
    ParameterHandler add_query = new ParameterHandler();
    String query_string = "";
    query_string = add_query.add_query(query);
    String url_storage = url;//  w ww . j  a  va2s.  c om
    if (Container != null) {
        url_storage += "/" + encode(Container);
    }
    if (object_name != null) {

        url_storage += "/" + encode(object_name) + query_string;
    }
    HttpPut httpput = new HttpPut(url_storage);
    //httpput.addHeader(AUTH_TOKEN,  token);

    CSSPSignature signature = new CSSPSignature("PUT", null, "/" + Container + "/" + object_name, null, null);
    signature.getDate();
    String auth = signature.getSinature();
    String signa = signature.HmacSHA1Encrypt(auth, secretkey);
    httpput.addHeader(DATE, signature.Date);
    httpput.addHeader(AUTH, CSSP + accesskey + ":" + signa);
    if (content != null) {
        InputStreamEntity body = new InputStreamEntity(content, content_length);
        body.setChunked(false);
        httpput.setEntity(body);
    }
    HttpResponse response = httpClient.execute(httpput);
    Header[] Headers = response.getAllHeaders();
    for (Header Header : Headers) {
        headers.put(Header.getName(), Header.getValue());
    }
    if (isMatch_2XX(response.getStatusLine().getStatusCode())) {
        return new SwiftClientResponse(headers, response.getStatusLine().getStatusCode(),
                response.getStatusLine(), null, null);
    } else {
        logger.error("[put object: error,  StatusCode is ]" + response.getStatusLine().getStatusCode());
        return new ExceptionHandle().ContainerExceptionHandle(response, headers);
    }

}

From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java

public SwiftClientResponse PutFaceVerity_test(String url, String Container, String object_name,
        InputStream content, long content_length, Map<String, String> query, String accesskey, String secretkey)
        throws IOException, CSSPException {
    BasicHttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, soTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    Map<String, String> headers = new LinkedHashMap<String, String>();
    ParameterHandler add_query = new ParameterHandler();
    String query_string = "";
    query_string = add_query.add_query(query);
    String url_storage = url;//from  w w w . j  a  va2 s.c  o  m
    if (Container != null) {
        url_storage += "/" + encode(Container);
    }
    if (object_name != null) {

        url_storage += "/" + encode(object_name) + query_string;
    }
    HttpPut httpput = new HttpPut(url_storage);
    //httpput.addHeader(AUTH_TOKEN,  token);

    CSSPSignature signature = new CSSPSignature("PUT", null, "/" + Container + "/" + object_name, null, null);
    signature.getDate();
    String auth = signature.getSinature();
    String signa = signature.HmacSHA1Encrypt(auth, secretkey);
    httpput.addHeader(DATE, signature.Date);
    httpput.addHeader(AUTH, CSSP + accesskey + ":" + signa);
    if (content != null) {
        InputStreamEntity body = new InputStreamEntity(content, content_length);
        body.setChunked(false);
        httpput.setEntity(body);
    }
    HttpResponse response = httpClient.execute(httpput);
    Header[] Headers = response.getAllHeaders();
    for (Header Header : Headers) {
        headers.put(Header.getName(), Header.getValue());
    }
    if (isMatch_2XX(response.getStatusLine().getStatusCode())) {
        return new SwiftClientResponse(headers, response.getStatusLine().getStatusCode(),
                response.getStatusLine(), null, null);
    } else {
        logger.error("[put object: error,  StatusCode is ]" + response.getStatusLine().getStatusCode());
        return new ExceptionHandle().ContainerExceptionHandle(response, headers);
    }

}

From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java

public SwiftClientResponse PutObject(String url, String Container, String object_name, InputStream content,
        long content_length, String md5sum, String content_type, Map<String, String> object_metadata,
        String accesskey, String secretkey) throws IOException, CSSPException {
    BasicHttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, soTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    Map<String, String> headers = new LinkedHashMap<String, String>();
    String url_storage = url;/*from  w ww . j  a va 2  s. c o  m*/
    if (Container != null) {
        url_storage += "/" + encode(Container);
    }
    if (object_name != null) {

        url_storage += "/" + encode(object_name);
    }
    HttpPut httpput = new HttpPut(url_storage);
    //httpput.addHeader(AUTH_TOKEN,  token);
    if (content != null) {
        InputStreamEntity body = new InputStreamEntity(content, content_length);
        body.setChunked(false);
        httpput.setEntity(body);
    }
    for (Map.Entry<String, String> entry : object_metadata.entrySet()) {
        httpput.addHeader(entry.getKey(), entry.getValue());
    }
    String content_type_string = null;
    if (content_type != null) {
        httpput.addHeader(CONTENT_TYPE, content_type);
        content_type_string = content_type;
    }
    String mD5 = null;
    if (md5sum != null) {
        httpput.setHeader(HttpHeaders.ETAG, md5sum);
        mD5 = md5sum;
    }
    CSSPSignature signature = new CSSPSignature("PUT", object_metadata, "/" + Container + "/" + object_name,
            mD5, content_type_string);
    signature.getDate();
    String auth = signature.getSinature();
    String signa = signature.HmacSHA1Encrypt(auth, secretkey);
    httpput.addHeader(DATE, signature.Date);
    httpput.addHeader(AUTH, CSSP + accesskey + ":" + signa);
    HttpResponse response = httpClient.execute(httpput);
    Header[] Headers = response.getAllHeaders();
    for (Header Header : Headers) {
        headers.put(Header.getName(), Header.getValue());
    }
    if (isMatch_2XX(response.getStatusLine().getStatusCode())) {
        return new SwiftClientResponse(headers, response.getStatusLine().getStatusCode(),
                response.getStatusLine(), null, null);
    } else {
        logger.error("[put object: error,  StatusCode is ]" + response.getStatusLine().getStatusCode());
        return new ExceptionHandle().ContainerExceptionHandle(response, headers);
    }

}

From source file:com.funambol.platform.HttpConnectionAdapter.java

/**
 * Execute the http post operation with the given input stream to be read to
 * fetch body content./* ww w .  j a  v a 2  s . c  om*/
 *
 * @throws IOException if the output stream cannot be opened.
 */
public void execute(InputStream is, long length) throws IOException {

    Log.debug(TAG_LOG, "Opening url: " + url);
    Log.debug(TAG_LOG, "Opening with method " + requestMethod);

    String contentType = null;
    if (requestHeaders != null) {
        contentType = requestHeaders.get("Content-Type");
    }
    if (contentType == null) {
        contentType = "binary/octet-stream";
    }

    if (POST.equals(requestMethod)) {
        request = new HttpPost(url);
        if (is != null) {
            InputStreamEntity reqEntity = new InputStreamEntity(is, length);
            reqEntity.setContentType(contentType);
            if (chunkLength > 0) {
                reqEntity.setChunked(true);
            }
            ((HttpPost) request).setEntity(reqEntity);
        }
    } else if (PUT.equals(requestMethod)) {
        request = new HttpPut(url);
        if (is != null) {
            InputStreamEntity reqEntity = new InputStreamEntity(is, length);
            reqEntity.setContentType(contentType);
            if (chunkLength > 0) {
                reqEntity.setChunked(true);
            }
            ((HttpPost) request).setEntity(reqEntity);
        }
    } else {
        request = new HttpGet(url);
    }

    performRequest(request);
}