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:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Retrieves the wanted data described in the {@link StorageDescriptor} from the desired
 * {@link CmrRepositoryDefinition}. This method will try to invoke as less as possible HTTP
 * requests for all descriptors./*from ww  w . j a  v  a2 s.c o  m*/
 * <p>
 * The method will execute the HTTP requests sequentially.
 * <p>
 * It is not guaranteed that amount of returned objects in the list is same as the amount of
 * provided descriptors. If some of the descriptors are pointing to the wrong files or files
 * positions, it can happen that this influences the rest of the descriptor that point to the
 * same file. Thus, a special care needs to be taken that the data in descriptors is correct.
 * 
 * @param <E>
 *            Type of the objects are wanted.
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData} that points to the wanted storage.
 * @param descriptors
 *            Descriptors.
 * @return List of objects in the supplied generic type. Note that if the data described in the
 *         descriptor is not of a supplied generic type, there will be a casting exception
 *         thrown.
 * @throws SerializationException
 *             If {@link SerializationException} occurs.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
@SuppressWarnings("unchecked")
public <E extends DefaultData> List<E> getDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition,
        IStorageData storageData, List<IStorageDescriptor> descriptors)
        throws IOException, SerializationException {
    Map<Integer, List<IStorageDescriptor>> separateFilesGroup = createFilesGroup(descriptors);
    List<E> receivedData = new ArrayList<E>();
    String serverUri = getServerUri(cmrRepositoryDefinition);

    HttpClient httpClient = new DefaultHttpClient();
    for (Map.Entry<Integer, List<IStorageDescriptor>> entry : separateFilesGroup.entrySet()) {
        HttpGet httpGet = new HttpGet(
                serverUri + storageManager.getHttpFileLocation(storageData, entry.getKey()));
        StringBuilder rangeHeader = new StringBuilder("bytes=");

        RangeDescriptor rangeDescriptor = null;
        for (IStorageDescriptor descriptor : entry.getValue()) {
            if (null == rangeDescriptor) {
                rangeDescriptor = new RangeDescriptor(descriptor);
            } else {
                if (rangeDescriptor.getEnd() + 1 == descriptor.getPosition()) {
                    rangeDescriptor.setEnd(descriptor.getPosition() + descriptor.getSize() - 1);
                } else {
                    rangeHeader.append(rangeDescriptor.toString());
                    rangeHeader.append(',');
                    rangeDescriptor = new RangeDescriptor(descriptor);
                }
            }
        }
        rangeHeader.append(rangeDescriptor);

        httpGet.addHeader("Range", rangeHeader.toString());
        ISerializer serializer = null;
        try {
            serializer = serializerQueue.take();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
        InputStream inputStream = null;
        Input input = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (MultipartEntityUtil.isMultipart(entity)) {
                inputStream = entity.getContent();
                @SuppressWarnings("deprecation")
                // all non-deprecated constructors have default modifier
                MultipartStream multipartStream = new MultipartStream(inputStream,
                        MultipartEntityUtil.getBoundary(entity).getBytes());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                boolean nextPart = multipartStream.skipPreamble();
                while (nextPart) {
                    multipartStream.readHeaders();
                    multipartStream.readBodyData(byteArrayOutputStream);
                    input = new Input(byteArrayOutputStream.toByteArray());
                    while (KryoUtil.hasMoreBytes(input)) {
                        Object object = serializer.deserialize(input);
                        E element = (E) object;
                        receivedData.add(element);
                    }
                    nextPart = multipartStream.readBoundary();
                }
            } else {
                // when kryo changes the visibility of optional() method, we can really stream
                input = new Input(EntityUtils.toByteArray(entity));
                while (KryoUtil.hasMoreBytes(input)) {
                    Object object = serializer.deserialize(input);
                    E element = (E) object;
                    receivedData.add(element);
                }
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != input) {
                input.close();
            }
            serializerQueue.add(serializer);
        }
    }
    return receivedData;
}

From source file:rocks.inspectit.ui.rcp.storage.util.DataRetriever.java

/**
 * Retrieves the wanted data described in the {@link StorageDescriptor} from the desired
 * {@link CmrRepositoryDefinition}. This method will try to invoke as less as possible HTTP
 * requests for all descriptors.//from w  w w . j ava 2  s  .co m
 * <p>
 * The method will execute the HTTP requests sequentially.
 * <p>
 * It is not guaranteed that amount of returned objects in the list is same as the amount of
 * provided descriptors. If some of the descriptors are pointing to the wrong files or files
 * positions, it can happen that this influences the rest of the descriptor that point to the
 * same file. Thus, a special care needs to be taken that the data in descriptors is correct.
 *
 * @param <E>
 *            Type of the objects are wanted.
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData} that points to the wanted storage.
 * @param descriptors
 *            Descriptors.
 * @return List of objects in the supplied generic type. Note that if the data described in the
 *         descriptor is not of a supplied generic type, there will be a casting exception
 *         thrown.
 * @throws SerializationException
 *             If {@link SerializationException} occurs.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
@SuppressWarnings("unchecked")
public <E extends DefaultData> List<E> getDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition,
        IStorageData storageData, List<IStorageDescriptor> descriptors)
        throws IOException, SerializationException {
    Map<Integer, List<IStorageDescriptor>> separateFilesGroup = createFilesGroup(descriptors);
    List<E> receivedData = new ArrayList<>();
    String serverUri = getServerUri(cmrRepositoryDefinition);

    HttpClient httpClient = new DefaultHttpClient();
    for (Map.Entry<Integer, List<IStorageDescriptor>> entry : separateFilesGroup.entrySet()) {
        HttpGet httpGet = new HttpGet(
                serverUri + storageManager.getHttpFileLocation(storageData, entry.getKey()));
        StringBuilder rangeHeader = new StringBuilder("bytes=");

        RangeDescriptor rangeDescriptor = null;
        for (IStorageDescriptor descriptor : entry.getValue()) {
            if (null == rangeDescriptor) {
                rangeDescriptor = new RangeDescriptor(descriptor);
            } else {
                if ((rangeDescriptor.getEnd() + 1) == descriptor.getPosition()) {
                    rangeDescriptor.setEnd((descriptor.getPosition() + descriptor.getSize()) - 1);
                } else {
                    rangeHeader.append(rangeDescriptor.toString());
                    rangeHeader.append(',');
                    rangeDescriptor = new RangeDescriptor(descriptor);
                }
            }
        }
        rangeHeader.append(rangeDescriptor);

        httpGet.addHeader("Range", rangeHeader.toString());
        ISerializer serializer = null;
        try {
            serializer = serializerQueue.take();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
        InputStream inputStream = null;
        Input input = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (MultipartEntityUtil.isMultipart(entity)) {
                inputStream = entity.getContent();
                @SuppressWarnings("deprecation")
                // all non-deprecated constructors have default modifier
                MultipartStream multipartStream = new MultipartStream(inputStream,
                        MultipartEntityUtil.getBoundary(entity).getBytes());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                boolean nextPart = multipartStream.skipPreamble();
                while (nextPart) {
                    multipartStream.readHeaders();
                    multipartStream.readBodyData(byteArrayOutputStream);
                    input = new Input(byteArrayOutputStream.toByteArray());
                    while (KryoUtil.hasMoreBytes(input)) {
                        Object object = serializer.deserialize(input);
                        E element = (E) object;
                        receivedData.add(element);
                    }
                    nextPart = multipartStream.readBoundary();
                }
            } else {
                // when kryo changes the visibility of optional() method, we can really stream
                input = new Input(EntityUtils.toByteArray(entity));
                while (KryoUtil.hasMoreBytes(input)) {
                    Object object = serializer.deserialize(input);
                    E element = (E) object;
                    receivedData.add(element);
                }
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != input) {
                input.close();
            }
            serializerQueue.add(serializer);
        }
    }
    return receivedData;
}

From source file:com.bamobile.fdtks.util.Tools.java

public static Bitmap getBitmapFromURL(Context context, String imageUrl, int width, int height) {
    if (imageUrl != null && imageUrl.length() > 0) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(imageUrl.replace(" ", "%20"));
        try {//w  w w.j a v a 2  s.  c o  m
            HttpResponse response = client.execute(get);
            byte[] content = EntityUtils.toByteArray(response.getEntity());
            //get the dimensions of the image
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(content, 0, content.length, opts);

            // get the image and scale it appropriately
            opts.inJustDecodeBounds = false;
            opts.inSampleSize = Math.max(opts.outWidth / width, opts.outHeight / height);

            Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length, opts);
            if (bitmap == null) {
                return null;
            }

            int scaledWidth = bitmap.getWidth();
            int scaledHeight = bitmap.getHeight();

            if (scaledWidth < scaledHeight) {
                float scale = width / (float) scaledWidth;

                scaledWidth = width;
                scaledHeight = (int) Math.ceil(scaledHeight * scale);
                if (scaledHeight < height) {
                    scale = height / (float) scaledHeight;

                    scaledHeight = height;
                    scaledWidth = (int) Math.ceil(scaledWidth * scale);
                }
            } else {
                float scale = height / (float) scaledHeight;

                scaledHeight = height;
                scaledWidth = (int) Math.ceil(scaledWidth * scale);

                if (scaledWidth < width) {
                    scale = width / (float) scaledWidth;

                    scaledWidth = width;
                    scaledHeight = (int) Math.ceil(scaledHeight * scale);
                }
            }

            Bitmap bmp = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false);

            bitmap.recycle();
            bitmap = null;

            return bmp;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.corebase.android.framework.http.client.AsyncHttpResponseHandler.java

protected byte[] getByteArrayAndSendMessage(Context context, HttpResponse response) {
    StatusLine status = response.getStatusLine();
    byte[] responseBody = null;
    try {//from w ww  . j  ava 2s  . co m
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            // pcgroup?1MNULL
            long length = entity.getContentLength();
            if (length >= MAX) {
                return null;
            }
        }
        responseBody = EntityUtils.toByteArray(entity);

    } catch (IOException e) {
        sendFailureMessage(context, e, (String) null);
        return null;
    }

    Log.v("Http StatusCode", status.getStatusCode() + "");
    if (status.getStatusCode() >= 300) {
        sendFailureMessage(context, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                (String) null);
        return null;
    }
    if (null == responseBody) {
        // ????
        sendSuccessMessage(context, SUCCESS_STATUS_CODE, null);
        return null;
    }
    return responseBody;
}

From source file:org.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u/*w ww. ja  v  a  2 s.co m*/
 * @param data
 * @param headers
 * @return
 */
public HttpResponseBean post(String u, InputStream data, Map<String, String> headers) {
    if (headers == null)
        headers = new HashMap<String, String>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        for (String h : headers.keySet()) {
            post.setHeader(h, headers.get(h));
        }
        HttpEntity request = new InputStreamEntity(data, -1);
        post.setEntity(request);
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);

        HttpResponse resp = null;
        try {
            resp = client.execute(host, post, context);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Map<String, String> rh = new HashMap<String, String>();
        for (Header h : resp.getAllHeaders()) {
            rh.put(h.getName(), h.getValue());
        }
        try {
            HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh,
                    EntityUtils.toByteArray(resp.getEntity()));
            printIfError(u, r);
            return r;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:org.zalando.stups.tokens.AccessTokenRefresher.java

private AccessToken createToken(final AccessTokenConfiguration tokenConfig) {
    try {//from w  w w  .  j  ava2  s .c  om

        // collect credentials
        final ClientCredentials clientCredentials = configuration.getClientCredentialsProvider().get();
        final UserCredentials userCredentials = configuration.getUserCredentialsProvider().get();

        // prepare basic auth credentials
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(configuration.getAccessTokenUri().getHost(),
                        configuration.getAccessTokenUri().getPort()),
                new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

        // create a new client that targets our host with basic auth enabled
        final CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider).build();
        final HttpHost host = new HttpHost(configuration.getAccessTokenUri().getHost(),
                configuration.getAccessTokenUri().getPort(), configuration.getAccessTokenUri().getScheme());
        final HttpPost request = new HttpPost(configuration.getAccessTokenUri());

        // prepare the request body

        final List<NameValuePair> values = new ArrayList<NameValuePair>() {

            {
                add(new BasicNameValuePair("grant_type", "password"));
                add(new BasicNameValuePair("username", userCredentials.getUsername()));
                add(new BasicNameValuePair("password", userCredentials.getPassword()));
                add(new BasicNameValuePair("scope", joinScopes(tokenConfig.getScopes())));
            }
        };
        request.setEntity(new UrlEncodedFormEntity(values));

        // enable basic auth for the request
        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        final HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // execute!
        final CloseableHttpResponse response = client.execute(host, request, localContext);
        try {

            // success status code?
            final int status = response.getStatusLine().getStatusCode();
            if (status < 200 || status >= 300) {
                throw AccessTokenEndpointException.from(response);
            }

            // get json response
            final HttpEntity entity = response.getEntity();
            final AccessTokenResponse accessTokenResponse = OBJECT_MAPPER
                    .readValue(EntityUtils.toByteArray(entity), AccessTokenResponse.class);

            // create new access token object
            final Date validUntil = new Date(
                    System.currentTimeMillis() + (accessTokenResponse.expiresInSeconds * 1000));

            return new AccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getTokenType(),
                    accessTokenResponse.getExpiresInSeconds(), validUntil);
        } finally {
            response.close();
        }
    } catch (Throwable t) {
        throw new AccessTokenEndpointException(t.getMessage(), t);
    }
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

protected static byte[] readBytes(HttpResponse response) {
    byte[] body = new byte[0];
    if (response.getEntity() != null) {
        try {/*from  w  ww  . j av  a  2 s . c  o m*/
            body = EntityUtils.toByteArray(response.getEntity());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return body;
}

From source file:com.suning.mobile.ebuy.lottery.network.util.Caller.java

/**
 * /*from  ww  w .  j a va  2s.co  m*/
 * @Description:
 * @Author 12050514 wangwt
 * @Date 2013-1-7
 */
private NetworkBean get(List<NameValuePair> list, String action, boolean withCache) {

    NetworkBean subean = new NetworkBean();
    list.add(new BasicNameValuePair("dcode", mApplication.getDeviceId()));
    list.add(new BasicNameValuePair("versionCode", String.valueOf(mApplication.getVersionCode())));
    String tempUrl = getTempUrl();
    String result = null;
    String url = tempUrl + action + "?" + URLEncodedUtils.format(list, LotteryApiConfig.ENCODE);
    if (mRequestCache != null && withCache) {
        result = mRequestCache.get(url);
    }

    if (result != null) {
        Log.d(TAG, "Caller.get [cached] " + url);
        subean = parseStringToSuBean(subean, result);
    } else {
        HttpGet request = new HttpGet(url);
        // request.addHeader("Accept-Encoding", "gzip");
        LogUtil.d("http url", request.getURI().toString());
        try {
            mClient.setCookieStore(SuningEBuyApplication.getInstance().getCookieStore());
            HttpResponse response = mClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header header = entity.getContentEncoding();
                    if (header != null) {
                        String contentEncoding = header.getValue();
                        if (contentEncoding != null) {
                            if (contentEncoding.contains("gzip")) {
                                entity = new GzipDecompressingEntity(entity);
                            }
                        }
                    }
                    String charset = EntityUtils.getContentCharSet(entity) == null ? LotteryApiConfig.ENCODE
                            : EntityUtils.getContentCharSet(entity);

                    result = new String(EntityUtils.toByteArray(entity), charset);
                    subean = parseStringToSuBean(subean, result);
                }
            } else {
                subean.setResult(2);
                subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror));
            }
        } catch (ClientProtocolException e) {
            LogUtil.logException(e);
            subean.setResult(2);
            subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror));
        } catch (IOException e) {
            LogUtil.logException(e);
            subean.setResult(2);
            subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror));
        } catch (NullPointerException e) {
            LogUtil.logException(e);
        } finally {
            if (mRequestCache != null && withCache && subean.getResult() == 0) {
                // 
                mRequestCache.put(url, result);
            }
        }
    }
    if (result != null) {
        LogUtil.d("http result", result);
    }

    return subean;
}

From source file:org.jupnp.transport.impl.apache.StreamClientImpl.java

protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
    return new ResponseHandler<StreamResponseMessage>() {
        public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {

            StatusLine statusLine = httpResponse.getStatusLine();
            if (log.isLoggable(Level.FINE))
                log.fine("Received HTTP response: " + statusLine);

            // Status
            UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());

            // Message
            StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);

            // Headers
            responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));

            // Body
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null || entity.getContentLength() == 0) {
                log.fine("HTTP response message has no entity");
                return responseMessage;
            }/*from www  .  ja va  2 s  .c  o m*/

            byte data[] = EntityUtils.toByteArray(entity);
            if (data != null) {
                if (responseMessage.isContentTypeMissingOrText()) {
                    log.fine("HTTP response message contains text entity");
                    responseMessage.setBodyCharacters(data);
                } else {
                    log.fine("HTTP response message contains binary entity");
                    responseMessage.setBody(UpnpMessage.BodyType.BYTES, data);
                }
            } else {
                log.fine("HTTP response message has no entity");
            }

            return responseMessage;
        }
    };
}

From source file:com.flipkart.phantom.runtime.impl.server.netty.handler.http.RoutingHttpChannelHandler.java

/**
 * Writes the specified TaskResult data to the channel output. Only the raw output data is written and rest of the TaskResult fields are ignored 
 * @param ctx the ChannelHandlerContext//  www .j  a  v  a  2  s  . com
 * @param event the ChannelEvent
 * @throws Exception in case of any errors
 */
private void writeCommandExecutionResponse(ChannelHandlerContext ctx, ChannelEvent event, HttpResponse response)
        throws Exception {
    // Don't write anything if the response is null
    if (response == null) {
        // write empty response
        event.getChannel().write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT))
                .addListener(ChannelFutureListener.CLOSE);
        return;
    }
    org.jboss.netty.handler.codec.http.HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.getStatusLine().getStatusCode()));
    // write headers
    for (Header header : response.getAllHeaders()) {
        if (!RoutingHttpChannelHandler.REMOVE_HEADERS.contains(header.getName())) {
            httpResponse.setHeader(header.getName(), header.getValue());
        }
    }

    // write entity
    HttpEntity responseEntity = response.getEntity();
    byte[] responseData = EntityUtils.toByteArray(responseEntity);
    httpResponse.setContent(ChannelBuffers.copiedBuffer(responseData));
    // write response
    event.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
}