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.baidubce.http.BceHttpClient.java

/**
 * Creates HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the internal request.
 *
 * @param request The request to convert to an HttpClient method object.
 * @return The converted HttpClient method object with any parameters, headers, etc. from the original request set.
 *///from  w  w w  .  ja  v a  2s  .com
protected HttpRequestBase createHttpRequest(InternalRequest request) {
    String uri = request.getUri().toASCIIString();
    String encodedParams = HttpUtils.getCanonicalQueryString(request.getParameters(), false);

    if (encodedParams.length() > 0) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    long contentLength = -1;
    String contentLengthString = request.getHeaders().get(Headers.CONTENT_LENGTH);
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
    }
    if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;
        if (request.getContent() != null) {
            putMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);
        httpRequest = postMethod;
        if (request.getContent() != null) {
            postMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new BceClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    httpRequest.addHeader(Headers.HOST, HttpUtils.generateHostHeader(request.getUri()));

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if it's already present, so we skip it here.
         * We also skip the Host header to avoid sending it twice, which will interfere with some signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase(Headers.CONTENT_LENGTH)
                || entry.getKey().equalsIgnoreCase(Headers.HOST)) {
            continue;
        }

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    checkNotNull(httpRequest.getFirstHeader(Headers.CONTENT_TYPE), Headers.CONTENT_TYPE + " not set");
    return httpRequest;
}

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;/* w w w .  j a v a  2s  .  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:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

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

    LOG.debug("Fetching data via POST from url " + url);

    HttpPost httpRequest = null;/*from  ww  w.  j  av a  2 s.  c  om*/
    HttpResponse httpResponse = null;

    try {
        final URI uri = URI.create(url.trim());
        httpRequest = 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(content);

        final HttpEntity httpEntity = new InputStreamEntity(bis, content.length);
        final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity);
        httpRequest.setEntity(requestEntity);
        if (contentType != null) {
            httpRequest.setHeader(CONTENT_TYPE, contentType);
        }

        httpResponse = getHttpResponse(httpRequest, url);

        final byte[] returnedBytes = readHttpResponse(url, httpResponse);
        return returnedBytes;
    } catch (IOException e) {
        throw new DSSException(e);
    } finally {
        if (httpRequest != null) {
            httpRequest.releaseConnection();
        }
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:bookkeepr.xmlable.DatabaseManager.java

private synchronized void saveExternals(List<IdAble> items) throws RemoteDatabaseNotContactableException {
    List[] itemsPerServer = new ArrayList[256];
    for (int i = 0; i < itemsPerServer.length; i++) {
        itemsPerServer[i] = new ArrayList();
    }/*from  w  ww .  j  a v a 2s  .  com*/

    for (IdAble item : items) {
        itemsPerServer[this.getOrigin(item)].add(item);
    }

    for (int i = 0; i < itemsPerServer.length; i++) {

        if (!itemsPerServer[i].isEmpty()) {
            // we need to get in touch with the server...
            BookkeeprHost host = null;
            for (BookkeeprHost testHost : bookkeepr.getConfig().getBookkeeprHostList()) {
                if (testHost.getOriginId() == i) {
                    host = testHost;
                    break;
                }
            }
            if (host != null) {
                try {
                    // found the host
                    Logger.getLogger(DatabaseManager.class.getName()).log(Level.FINE,
                            "Need to modify " + itemsPerServer[i].size() + " items in external server " + i);
                    Index[] arr = new Index[256];

                    Arrays.fill(arr, null);
                    for (Object o : itemsPerServer[i]) {
                        IdAble item = (IdAble) o;
                        int type = getType(item);
                        if (arr[type] == null) {
                            arr[type] = TypeIdManager.getIndexFromClass(item.getClass());
                        }
                        arr[type].addItem(item);
                    }
                    IndexIndex result = new IndexIndex();
                    for (Index idx : arr) {
                        if (idx == null) {
                            continue;
                        } else {
                            result.addIndex(idx);
                        }
                    }
                    HttpPost httppost = new HttpPost(host.getUrl() + "/insert/");
                    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

                    XMLWriter.write(out, result);
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

                    httppost.setEntity(new InputStreamEntity(in, -1));
                    Logger.getLogger(DatabaseManager.class.getName()).log(Level.INFO,
                            "Database posting to " + host.getUrl() + "/insert/ to modify items");
                    HttpClient httpclient = bookkeepr.checkoutHttpClient();
                    HttpResponse httpresp = httpclient.execute(httppost);
                    int statuscode = httpresp.getStatusLine().getStatusCode();

                    bookkeepr.returnHttpClient(httpclient);
                    httpclient = null;
                    httpresp = null;

                    if (statuscode == 200) {
                        // ok, the remote database is updated... force a sync now.
                    } else {
                        Logger.getLogger(DatabaseManager.class.getName()).log(Level.WARNING,
                                "Could not modify external elements. Could not contact master server");
                        throw new RemoteDatabaseNotContactableException("Got a status code '" + statuscode
                                + "' from the external server, was expecting a '200 OK'");
                    }
                    break;
                } catch (HttpException ex) {
                    Logger.getLogger(DatabaseManager.class.getName()).log(Level.WARNING,
                            "Could not modify external elements. Could not contact master server", ex);
                    throw new RemoteDatabaseNotContactableException("External server was not comunicatable");
                } catch (IOException ex) {
                    Logger.getLogger(DatabaseManager.class.getName()).log(Level.WARNING,
                            "Could not modify external elements. Could not contact master server", ex);
                    throw new RemoteDatabaseNotContactableException("External server was not comunicatable");
                } catch (URISyntaxException ex) {
                    Logger.getLogger(DatabaseManager.class.getName()).log(Level.WARNING,
                            "Could not modify external elements. Could not contact master server", ex);
                    throw new RemoteDatabaseNotContactableException(
                            "External server was not configured correctly!");
                }
            } else {
                // At some point we should try some other servers to see if they have heard of the server we want.

                Logger.getLogger(DatabaseManager.class.getName()).log(Level.WARNING,
                        "Could not modify external elements. I don't know who the master server is");
                throw new RemoteDatabaseNotContactableException("External server was not avaliable");

            }
        }

    }
}

From source file:ingestor.SingleFileProcessor.java

public Boolean WriteObjectToHCP(URL encodedPathURL, File inSourceFile) throws Exception {
    if (inSourceFile.toString().endsWith(".inuse"))
        throw new IOException();
    ScreenLog.begin("Write Object to HCP");
    HCPClient client = new HCPClient(CometProperties.getInstance());
    client.setRootpath(CometProperties.getInstance().getDestinationRootPath(pathPrefix));
    FileInputStream fis = null;/*  w  w w.  j av a  2s  .  c  o  m*/
    Boolean fileLock = false;
    //FileLocker fis=null;
    File fileLockFile = new File(inSourceFile.getAbsolutePath() + ".inuse");
    if (CometProperties.getInstance().getUseFileLocking()) {
        if (fileLockFile.exists()) {
            ScreenLog.warning("\tLock file already exists, bail:" + inSourceFile.getAbsolutePath() + ".inuse");
            return true; //acceptable outcome
        } else {
            ScreenLog.out("\tLock file does not exist, create it:" + inSourceFile.getAbsolutePath() + ".inuse");
            StringHelper.touch(fileLockFile);
            fileLock = true;
        }
    } else {
        ScreenLog.fine("\tNot using file locking");
    }

    fis = new FileInputStream(inSourceFile);
    String captured = client.HttpPutHCPContent(new InputStreamEntity(fis, -1), encodedPathURL);

    fis.close();
    if (fileLock) {
        ScreenLog.fine("deleting file lock");
        fileLockFile.delete();
    }
    ScreenLog.out("output from PUT operation: " + captured);
    ScreenLog.out("filename(" + inSourceFile.toString() + ") status code = " + client.getStatusCode() + "\n");

    if (409 == client.getStatusCode()) {
        logger.fine(" Object already exists on HCP, ignore the error for transaction \""
                + inSourceFile.getAbsolutePath() + "\" to \"" + encodedPathURL);
    }
    // If the return code is anything BUT 200 range indicating success, we have to throw an exception.
    else {
        if (2 != client.getStatusCode() / 100)
            eObjectStatus = WriteStatus.WRITE_FAILURE;
        else {
            eObjectStatus = WriteStatus.WRITE_SUCCESS;
        }
        Date d = new Date();
        logger.force("[" + d.toString() + "] PUT \"" + inSourceFile.getAbsolutePath() + "\" to \""
                + encodedPathURL + "\" " + client.getStatusCode());
    }
    ScreenLog.end("Write Object to HCP");
    return eObjectStatus == WriteStatus.WRITE_SUCCESS;
}

From source file:com.navjagpal.fileshare.WebServer.java

private void addFileEntity(final Uri uri, HttpResponse response) throws IOException {
    if (mTransferStartedListener != null) {
        mTransferStartedListener.started(uri);
    }//from  w w w .  j av a  2 s  . c  om

    Cursor c = mContext.getContentResolver().query(uri, null, null, null, null);
    c.moveToFirst();
    int nameIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns.DISPLAY_NAME);
    String name = c.getString(nameIndex);
    int dataIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns._DATA);
    Uri data = Uri.parse(c.getString(dataIndex));

    c = mContext.getContentResolver().query(data, null, null, null, null);
    c.moveToFirst();
    int sizeIndex = c.getColumnIndexOrThrow(OpenableColumns.SIZE);
    int sizeBytes = c.getInt(sizeIndex);
    c.close();

    InputStream input = mContext.getContentResolver().openInputStream(data);

    String contentType = "application/octet-stream";
    if (name.endsWith(".jpg")) {
        contentType = "image/jpg";
    }

    response.addHeader("Content-Type", contentType);
    response.addHeader("Content-Length", "" + sizeBytes);
    response.setEntity(new InputStreamEntity(input, sizeBytes));
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * (non-Javadoc)/*from  ww  w .  j  a  v  a2  s.  c  om*/
 * 
 * @see com.googlecode.sardine.Sardine#put(java.lang.String,
 *      java.io.InputStream, java.lang.String, boolean)
 */
public void put(String url, InputStream dataStream, String contentType, boolean expectContinue)
        throws IOException {
    // A length of -1 means "go until end of stream"
    InputStreamEntity entity = new InputStreamEntity(dataStream, -1);
    this.put(url, entity, contentType, expectContinue);
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * (non-Javadoc)/*  w ww. j  a va 2s  .co m*/
 * 
 * @see com.googlecode.sardine.Sardine#put(java.lang.String,
 *      java.io.InputStream, java.util.Map)
 */
public void put(String url, InputStream dataStream, Map<String, String> headers) throws IOException {
    // A length of -1 means "go until end of stream"
    InputStreamEntity entity = new InputStreamEntity(dataStream, -1);
    this.put(url, entity, headers);
}