Example usage for org.apache.http.util EntityUtils toByteArray

List of usage examples for org.apache.http.util EntityUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toByteArray.

Prototype

public static byte[] toByteArray(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendData(byte[] byteArray, ContentTypeVS contentType, String serverURL, String... headerNames)
        throws IOException {
    log.info("sendData - contentType: " + contentType + " - serverURL: " + serverURL);
    ResponseVS responseVS = null;/*from   w ww .  j a va 2  s . c om*/
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    try {
        httpPost = new HttpPost(serverURL);
        ByteArrayEntity entity = null;
        if (contentType != null)
            entity = new ByteArrayEntity(byteArray, ContentType.create(contentType.getName()));
        else
            entity = new ByteArrayEntity(byteArray);
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        ContentTypeVS responseContentType = null;
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        log.info("------------------------------------------------");
        log.info(response.getStatusLine().toString() + " - contentTypeVS: " + responseContentType
                + " - connManager stats: " + connManager.getTotalStats().toString());
        log.info("------------------------------------------------");
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        if (headerNames != null && headerNames.length > 0) {
            List<String> headerValues = new ArrayList<String>();
            for (String headerName : headerNames) {
                org.apache.http.Header headerValue = response.getFirstHeader(headerName);
                if (headerValue != null)
                    headerValues.add(headerValue.getValue());
            }
            responseVS.setData(headerValues);
        }
    } catch (HttpHostConnectException ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR,
                ContextVS.getInstance().getMessage("hostConnectionErrorMsg", serverURL));
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private Response execute(CloseableHttpClient http, ServerInfo serverInfo, HttpRequestBase request,
        MessageContext context) throws IOException {
    ensureCertsAreLoaded(context);//from ww w  .  j  a  va  2 s.  c o  m
    CloseableHttpResponse response = http.execute(request, serverInfo.httpContext);
    if (response == null) {
        return Response.status(Response.Status.BAD_GATEWAY).build();
    }
    Header[] responseHeaders = response.getAllHeaders();
    ResponseBuilder builder = Response.status(response.getStatusLine().getStatusCode());
    for (Header header : responseHeaders) {
        builder.header(header.getName(), header.getValue());
    }
    String strReply = new String(EntityUtils.toByteArray(response.getEntity()));
    HttpServletRequest servletRequest = context.getHttpServletRequest();
    StringBuffer entireRequestUrl = servletRequest.getRequestURL();
    builder.entity(strReply.replaceAll(serverInfo.url.toExternalForm(),
            entireRequestUrl.substring(0, entireRequestUrl.indexOf(servletRequest.getPathInfo())) + "/"
                    + serverInfo.name + "/"));
    return builder.build();
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private byte[] extractBody(HttpResponse response) throws IOException, UnsupportedEncodingException {
    byte[] content = null;

    HttpEntity responseEntity = response.getEntity();
    long contentLength = responseEntity.getContentLength();

    if (contentLength > 0) {
        content = EntityUtils.toByteArray(responseEntity);
    }//from   w  ww.ja v a2s.  c o  m
    return content;
}

From source file:de.geeksfactory.opacclient.apis.BaseApi.java

/**
 * Downloads a cover to a CoverHolder. You only need to use this if the covers are only
 * available with e.g. Session cookies. Otherwise, it is sufficient to specify the URL of the
 * cover./*from  w w  w .  j  a  va  2s. c  om*/
 *
 * @param item CoverHolder to download the cover for
 */
protected void downloadCover(CoverHolder item) {
    if (item.getCover() == null) {
        return;
    }
    HttpGet httpget = new HttpGet(cleanUrl(item.getCover()));
    HttpResponse response;

    try {
        response = http_client.execute(httpget);

        if (response.getStatusLine().getStatusCode() >= 400) {
            return;
        }
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);

        item.setCoverBitmap(bytes);

    } catch (IOException e) {
        logHttpError(e);
    }
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ??URI???.//from w w w . j  a  va  2s .  c  o  m
 * 
 * @param uri ????URI
 * @return 
 */
public static byte[] getBytes(final String uri) {
    HttpGet request = new HttpGet(uri);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        byte[] result = httpClient.execute(request, new ResponseHandler<byte[]>() {
            @Override
            public byte[] handleResponse(final HttpResponse response) throws IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    return EntityUtils.toByteArray(response.getEntity());
                case HttpStatus.SC_NOT_FOUND:
                    throw new RuntimeException("No Found.");
                default:
                    throw new RuntimeException("Connection Error.");
                }
            }
        });
        return result;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendObjectMap(Map<String, Object> fileMap, String serverURL) throws Exception {
    log.info("sendObjectMap - serverURL: " + serverURL);
    ResponseVS responseVS = null;/*  w w  w  .  j ava 2s.  c o m*/
    if (fileMap == null || fileMap.isEmpty())
        throw new Exception(ContextVS.getInstance().getMessage("requestWithoutFileMapErrorMsg"));
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    ContentTypeVS responseContentType = null;
    try {
        httpPost = new HttpPost(serverURL);
        Set<String> fileNames = fileMap.keySet();
        MultipartEntity reqEntity = new MultipartEntity();
        for (String objectName : fileNames) {
            Object objectToSend = fileMap.get(objectName);
            if (objectToSend instanceof File) {
                File file = (File) objectToSend;
                log.info("sendObjectMap - fileName: " + objectName + " - filePath: " + file.getAbsolutePath());
                FileBody fileBody = new FileBody(file);
                reqEntity.addPart(objectName, fileBody);
            } else if (objectToSend instanceof byte[]) {
                byte[] byteArray = (byte[]) objectToSend;
                reqEntity.addPart(objectName, new ByteArrayBody(byteArray, objectName));
            }
        }
        httpPost.setEntity(reqEntity);
        response = httpClient.execute(httpPost);
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - contentTypeVS: " + responseContentType
                + " - connManager stats: " + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        String statusLine = null;
        if (response != null)
            statusLine = response.getStatusLine().toString();
        log.log(Level.SEVERE, ex.getMessage() + " - StatusLine: " + statusLine, ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:org.restcomm.camelgateway.slee.CamelBaseSbb.java

protected byte[] getResultData(HttpEntity entity) throws IOException {
    return EntityUtils.toByteArray(entity);
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 * /*from  w w  w  .ja v a2  s .  co m*/
 * @param account
 *            The account being synced
 * @param authtoken
 *            The authtoken stored in the AccountManager for this account
 * @param serverSyncState
 *            A token returned from the server on the last sync
 * @param dirtyContacts
 *            A list of the contacts to send to the server
 * @param newIdMap
 *            Map of RawId to ServerId
 * @param explizitPhotoSave
 * @return A list of contacts that we need to update locally. Null if
 *         processing of server-results failed.
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 *             when Authentication was canceled from user
 * @throws SAXException
 * @throws ServerException
 * @throws NetworkErrorException
 * @throws HeaderParseException
 * @throws HeaderCreateException
 */
public static SyncResponse syncContacts(Account account, String authtoken, SyncAnchor serverSyncState,
        List<RawContact> dirtyContacts, List<ContactGroup> dirtyGroups, SecretKey key,
        AccountManager accountManager, Context context, SyncResult syncResult, String pwdSaltHexStr,
        Map<Long, String> newIdMap, Restrictions restr, boolean explizitPhotoSave)
        throws AuthenticationException, OperationCanceledException, AuthenticatorException, ServerException,
        NetworkErrorException, HeaderParseException, HeaderCreateException {
    String clientId = getClientId(accountManager, account);

    SyncPrepErrorStatistic prepError = new SyncPrepErrorStatistic();
    byte[] totBuffer = RequestGenerator.prepareServerRequest(serverSyncState, dirtyContacts, dirtyGroups, key,
            SystemHelper.getPkgVersion(context), clientId, pwdSaltHexStr, newIdMap, prepError, restr,
            explizitPhotoSave);
    syncResult.stats.numSkippedEntries += prepError.getIgnoredRows();
    String currAuthtoken = authtoken;

    SyncResponse syncResponse = null;
    boolean retry;
    int retrycount = 0;
    do {
        retry = false;

        HttpEntity entity = new ByteArrayEntity(totBuffer);

        // Send the updated friends data to the server
        final HttpPost post = new HttpPost(SYNC_URI);
        post.setHeader("Content-Encoding", "application/octect-stream");
        post.setEntity(entity);

        HttpEntity respEntity = null;

        try {
            final HttpResponse resp = getHttpClient(context).execute(post,
                    createHttpContext(account.name, currAuthtoken));

            respEntity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final byte[] response = EntityUtils.toByteArray(respEntity);

                syncResponse = processServerResponse(account, key, accountManager, clientId, response,
                        syncResult);
                if (Log.isLoggable(TAG, Log.INFO)) {
                    Log.i(TAG, "Response-Length: " + response.length);
                }
            } else {
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    currAuthtoken = retryAuthentification(retrycount, accountManager, currAuthtoken,
                            account.name, resp);
                    retry = true;
                } else {
                    throw new ServerException(
                            "Server error in sending dirty contacts: " + resp.getStatusLine());
                }
            }
        } catch (IOException ex) {
            throw new NetworkErrorException(ex);
        } finally {
            consumeContent(respEntity);
        }
        retrycount++;
    } while (retry);

    return syncResponse;
}

From source file:org.bibalex.gallery.model.BAGImage.java

private void updateZoomedBytes() throws BAGException {
    HttpGet getReq = null;//from w  w w. ja v  a2  s. co m
    try {

        ArrayList<NameValuePair> reqParams = (ArrayList<NameValuePair>) this.djatokaParams.clone();

        // Curiously the X and Y coordinates need not be scaled using the level scale ratio
        // long djatokaY = Math.round(this.zoomedY * this.djatokaLevelScaleRatio);
        // long djatokaX = Math.round(this.zoomedX * this.djatokaLevelScaleRatio);

        long djatokaWidth = Math.round(
                (this.zoomedWidth > 0 ? this.zoomedWidth : this.fullWidth) * this.djatokaLevelScaleRatio);

        // make use of view pane height to minimize retrieved image
        if (this.zoomedWidth == this.fullWidth) {
            this.zoomedHeight = this.fullHeight; // To allow the retrieval of the full image
        } else {
            double zoomedPixelRatio = (double) this.zoomedWidth / this.viewPaneWidth;
            if (Math.abs(
                    Math.round((double) this.zoomedHeight / zoomedPixelRatio) - this.viewPaneHeight) > 10) {
                this.zoomedHeight = Math.round(this.viewPaneHeight * zoomedPixelRatio);
            }
        }

        long djatokaHeight = Math.round(
                (this.zoomedHeight > 0 ? this.zoomedHeight : this.fullHeight) * this.djatokaLevelScaleRatio);

        reqParams.add(new BasicNameValuePair("svc.rotate", "" + this.zoomedRotate));

        reqParams.add(new BasicNameValuePair("svc.scale",
                "" + Math.round(this.viewPaneWidth * this.scaleFactor) + ",0"));
        reqParams.add(new BasicNameValuePair("svc.level", "" + this.djatokaLevel));
        reqParams.add(new BasicNameValuePair("svc.region",
                // "" + djatokaY + "," + djatokaX + ","
                "" + this.zoomedY + "," + this.zoomedX + "," + djatokaHeight + "," + djatokaWidth));

        URI serverUri = new URI(this.gallery.getDjatokaServerUrlStr());

        URI reqUri = URIUtils.createURI(serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(),
                serverUri.getPath(), URLEncodedUtils.format(reqParams, "US-ASCII"), null);

        getReq = new HttpGet(reqUri);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting region via URL: " + getReq.getURI());
        }

        HttpResponse response = this.httpclient.execute(getReq);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response from URL: " + getReq.getURI() + " => " + response.getStatusLine());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if ("image/jpeg".equalsIgnoreCase(entity.getContentType().getValue())) {
                this.zoomedBytes = EntityUtils.toByteArray(entity);
            }
        } else {

            throw new BAGException("Cannot retrieve region!");
        }

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        getReq.abort();
        throw ex;

    } catch (URISyntaxException e) {
        throw new BAGException(e);
    } finally {
        // connection kept alive and closed in finalize
    }

}