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.xdi.oxauth.service.net.HttpService.java

public byte[] getResponseContent(HttpResponse httpResponse) throws IOException {
    if ((httpResponse == null) || (httpResponse.getStatusLine().getStatusCode() != HttpResponseCodes.SC_OK)) {
        return null;
    }// www  .j a v a  2 s  .co  m

    HttpEntity entity = httpResponse.getEntity();
    byte[] responseBytes = new byte[0];
    if (entity != null) {
        responseBytes = EntityUtils.toByteArray(entity);
    }

    // Consume response content
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    return responseBytes;
}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {/*from w w w  . ja  va2 s. co  m*/
        JsonNode event = jackson.readTree(msg.getBody());
        String ii = event.path("ii").asText();
        logger.info("Check youtube came {}", ii);

        List<String> videos = jackson.convertValue(event.path("yt"), List.class);
        List<String> parts = new ArrayList<>();
        videos.stream().forEach((String link) -> {
            parts.add(StringUtils.substringAfterLast(link, "/"));
        });

        Credential credential = flow.loadCredential("yt");
        YouTube youtube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                credential).setApplicationName("enitalk").build();
        boolean refreshed = credential.refreshToken();
        logger.info("Yt refreshed {}", refreshed);

        HttpResponse rs = youtube.videos().list("processingDetails").setId(StringUtils.join(parts, ','))
                .executeUnparsed();
        InputStream is = rs.getContent();
        byte[] b = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        JsonNode listTree = jackson.readTree(b);
        logger.info("List tree {}", listTree);

        List<JsonNode> items = listTree.path("items").findParents("id");
        long finished = items.stream().filter((JsonNode j) -> {
            return j.at("/processingDetails/processingStatus").asText().equals("succeeded");
        }).count();

        Query q = Query.query(Criteria.where("ii").is(ii));
        if (finished == parts.size()) {
            logger.info("Processing finished {}", ii);

            //send notification and email
            ObjectNode tree = (ObjectNode) jackson
                    .readTree(new ClassPathResource("emails/videoUploaded.json").getInputStream());
            tree.put("To", event.at("/student/email").asText());
            //                String text = tree.path("HtmlBody").asText() + StringUtils.join(videos, "\n");

            StringWriter writer = new StringWriter(29 * 1024);
            Template t = engine.getTemplate("video.html");
            VelocityContext context = new VelocityContext();
            context.put("video", videos.iterator().next());
            t.merge(context, writer);

            tree.put("HtmlBody", writer.toString());

            //make chat and attach it
            String chatTxt = makeChat(event);
            if (StringUtils.isNotBlank(chatTxt)) {
                ArrayNode attachments = jackson.createArrayNode();
                ObjectNode a = attachments.addObject();
                a.put("Name", "chat.txt");
                a.put("ContentType", "text/plain");
                a.put("Content", chatTxt.getBytes("UTF-8"));

                tree.set("Attachments", attachments);
            } else {
                logger.info("No chat available for {}", event.path("ii").asText());
            }

            logger.info("Sending video and chat {} to student", ii);

            org.apache.http.HttpResponse response = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r = EntityUtils.toByteArray(response.getEntity());
            JsonNode emailResp = jackson.readTree(r);

            Update u = new Update().set("video", 4);
            if (StringUtils.isNotBlank(chatTxt)) {
                u.set("chat", chatTxt);
            }

            u.set("student.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("student.uploader.rs", jackson.convertValue(emailResp, HashMap.class));

            tree.put("To", event.at("/teacher/email").asText());
            logger.info("Sending video and chat {} to teacher", ii);

            org.apache.http.HttpResponse response2 = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r2 = EntityUtils.toByteArray(response2.getEntity());
            JsonNode emailResp2 = jackson.readTree(r2);

            u.set("teacher.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("teacher.uploader.rs", jackson.convertValue(emailResp2, HashMap.class));
            u.set("f", 1);

            mongo.updateFirst(q, u, "events");

            //                JsonNode dest = event.at("/student/dest");
            //
            //                ArrayNode msgs = jackson.createArrayNode();
            //                ObjectNode o = msgs.addObject();
            //                o.set("dest", dest);
            //                ObjectNode m = jackson.createObjectNode();
            //                o.set("message", m);
            //                m.put("text", "0x1f3a5 We have uploaded your lesson to Youtube. It is available to you and the teacher only. \n"
            //                        + "Please, do not share it with anyone\n Also, we sent the video link and the text chat to your email.");
            //
            //                ArrayNode buttons = jackson.createArrayNode();
            //                m.set("buttons", buttons);
            //                m.put("buttonsPerRow", 1);
            //
            //                if (videos.size() == 1) {
            //                    botController.makeButtonHref(buttons, "Watch on Youtube", videos.get(0));
            //                } else {
            //                    AtomicInteger cc = new AtomicInteger(1);
            //                    videos.stream().forEach((String y) -> {
            //                        botController.makeButtonHref(buttons, "Watch on Youtube, part " + cc.getAndIncrement(), y);
            //                    });
            //                }
            //
            //                botController.sendMessages(msgs);
            //
            //                sendFeedback(dest, event);

        } else {
            logger.info("{} parts only finished for {}", finished, ii);
            mongo.updateFirst(q,
                    new Update().inc("check", 1).set("checkDate", new DateTime().plusMinutes(12).toDate()),
                    "events");
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java

@Override
protected String doInBackground(String... urls) {
    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering doInBackground()");

    byte[] result = null;
    HttpPost post = new HttpPost(urls[0]);

    try {//from   w  ww  .j  a va  2  s  .  c o  m
        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Prepare for httpPostData");
        // prepare for httpPost data
        String boundary = "b0undaryFP";

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: build the data");
        // build the data
        byte[] bytes = null;
        byte[] imageBytes = null;

        if (isImage) {
            // Get the byte[] of the media we want to upload
            imageBytes = getImageByteArray(mediaPath);
            imageBytes = resizeImage(imageBytes, maxWidth, maxHeight);
        }

        //all the stuff that comes before the media bytes
        ByteArrayOutputStream preMedia = new ByteArrayOutputStream();
        for (@SuppressWarnings("unchecked")
        Iterator<String> keys = uploadParams.keys(); keys.hasNext();) {
            String key = keys.next();
            String value = uploadParams.getString(key);
            preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());
            preMedia.write(("Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@".replaceFirst("%@", key)
                    .replaceFirst("%@", value)).getBytes());
        }
        preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());
        preMedia.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n\r\n").getBytes());

        //all the stuff that comes after the media bytes
        ByteArrayOutputStream postMedia = new ByteArrayOutputStream();
        postMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Set content-type and content of http post");
        // Set content-type and content of http post
        post.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

        if (isImage && imageBytes != null)
            bytes = createHeaderByteArrayImage(preMedia.toByteArray(), postMedia.toByteArray(), imageBytes);
        else
            bytes = createHeaderByteArrayFile(preMedia.toByteArray(), postMedia.toByteArray(), mediaPath);

        preMedia.close();
        postMedia.close();

        if (isVideo) {
            if (bytes.length > maxDuration * 1000 * 1000) {
                status = "FILE_TOO_BIG";
                return null;
            }
        }

        if (bytes == null) {
            status = "ERROR_CREATING_HEADER";
            return null;
        }

        ByteArrayEntity entity = new ByteArrayEntity(bytes) {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                if (outstream == null) {
                    throw new IllegalArgumentException("Output stream may not be null");
                }

                InputStream instream = new ByteArrayInputStream(this.content);

                try {
                    byte[] tmp = new byte[512];
                    int total = (int) this.content.length;
                    int progress = 0;
                    int increment = 0;
                    int l;
                    int percent;

                    while ((l = instream.read(tmp)) != -1) {
                        progress = progress + l;
                        percent = Math.round(((float) progress / (float) total) * 100);

                        if (percent > increment) {
                            increment += 10;
                            // update percentage here !!
                        }
                        double percentage = (double) percent / 100.0;
                        GoogleCloudStorageUploadExtension.context
                                .dispatchStatusEventAsync("FILE_UPLOAD_PROGRESS", "" + percentage);

                        outstream.write(tmp, 0, l);
                    }

                    outstream.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    instream.close();
                }
            }
        };
        post.setEntity(entity);

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: execute post.");

        // execute post.
        HttpResponse httpResponse = client.execute(post);
        StatusLine statusResponse = httpResponse.getStatusLine();
        if (statusResponse.getStatusCode() == HttpURLConnection.HTTP_OK) {
            result = EntityUtils.toByteArray(httpResponse.getEntity());
            response = new String(result, "UTF-8");
            Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: got a response: " + response);
            status = "FILE_UPLOAD_DONE";
        } else {
            status = "FILE_UPLOAD_ERROR";
            Log.d(TAG,
                    "[UploadToGoogleCloudStorageAsyncTask] ~~~ ERR: status code: " + statusResponse.toString());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (IOException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (Exception e) {
        e.printStackTrace();
        status = "UNKNOWN_ERROR";
    }

    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting doInBackground()");
    return response;
}

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

public static Bitmap getBitmapFromURL(String imageUrl) {
    try {/*from w  w w  .j a v a  2  s  .  c  o m*/
        if (imageUrl != null && imageUrl.length() > 0) {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(addImageToUrl(
                    "http://fdtrcksarg-bamobile.rhcloud.com/webresources/entities.camion/getImage", imageUrl));
            try {
                HttpResponse response = client.execute(get);
                byte[] content = EntityUtils.toByteArray(response.getEntity());
                Bitmap bmp = Tools.decodeByteArray(content, 0, content.length);
                return bmp;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception ex) {
        Log.e("Tools.getBitmapFromURL", ex.getMessage(), ex);
    }
    return null;
}

From source file:org.jsnap.request.HttpRequest.java

protected byte[] read() throws CommunicationException {
    // This function gets called only for the client's reads. Server's
    // reads are performed by the RequestHandler.doServiceImpl() method.
    HttpEntity entity = response.getEntity();
    response = null; // Response has been read/consumed.
    try {/*from w  w w  . jav a 2  s  . com*/
        return EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        throw new CommunicationException(e);
    }
}

From source file:com.cellbots.logger.localServer.LocalHttpServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from w  ww . j  a v a2s .c  om

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    // Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    // Log.w(TAG, "*** Request LINE: " +
    // request.getRequestLine().toString());
    // Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Return sensor readings
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        response.setStatusCode(HttpStatus.SC_OK);
        EntityTemplate body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write(serverListener.getLoggerStatus());
                writer.flush();
            }
        });
        body.setContentType(contentType);
        response.setEntity(body);
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}

From source file:org.dvbviewer.controller.io.ServerRequest.java

/**
 * Gets the rS bytes.//  www . j  a v  a 2  s .  c  o m
 *
 * @param request the request
 * @return the rS bytes
 * @throws AuthenticationException the authentication exception
 * @throws URISyntaxException the URI syntax exception
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @author RayBa
 * @date 13.04.2012
 */
public static byte[] getRSBytes(String request) throws Exception {
    byte[] result = null;
    result = EntityUtils.toByteArray(getRSEntity(request));
    return result;
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java

private Response getBinary(String url, String version, boolean getChecksum, String expectedChecksum)
        throws IOException {
    log.info("Proxy file: {}", url);
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
        byte[] data = EntityUtils.toByteArray(response.getEntity());

        // validate checksum
        if (expectedChecksum != null) {
            String remoteChecksum = DigestUtils.sha256Hex(data);
            if (!StringUtils.equals(expectedChecksum, remoteChecksum)) {
                log.warn("Reject file: {} - checksum comparison failed - expected: {}, actual: {}", url,
                        expectedChecksum, remoteChecksum);
                return Response.status(Response.Status.NOT_FOUND).build();
            }//from w w w .ja v a2s  .  c  o  m
        }

        if (getChecksum) {
            return Response.ok(DigestUtils.sha1Hex(data)).type(MediaType.TEXT_PLAIN).build();
        } else {
            return Response.ok(data).type(MediaType.APPLICATION_OCTET_STREAM)
                    .header(CONTENT_LENGTH,
                            response.containsHeader(CONTENT_LENGTH)
                                    ? response.getFirstHeader(CONTENT_LENGTH).getValue()
                                    : null)
                    .build();
        }
    } else {
        EntityUtils.consumeQuietly(response.getEntity());
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java

static HttpResponse toReturnValue(org.apache.http.HttpResponse response, String charset) throws IOException {
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setStatusCode(response.getStatusLine().getStatusCode());
    Map<String, String> responseHeaders = new HashMap<String, String>();
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header.getValue());
    }// www . j  av a 2 s  .  c  o m
    httpResponse.setHeaders(responseHeaders);
    if (response.getEntity() != null) {
        httpResponse.setBody(EntityUtils.toByteArray(response.getEntity()));
    }
    httpResponse.setCharset(charset);
    return httpResponse;
}

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

public byte[] getObject(String namespace, String objName) throws IOException, HttpException, AmpliException {
    String storageUrl = "http://" + this.host + ":" + this.port + nsRoot;

    HttpGet method = HttpClientUtil.makeHttpGet(
            storageUrl + "/" + HttpClientUtil.encodeURL(namespace) + "/" + HttpClientUtil.encodeURL(objName));

    HttpResponse response = null;/*from   w w w.ja v  a2  s . c o  m*/
    try {
        response = client.execute(method);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new AmpliException("Namespace: " + namespace + " did not have object " + objName,
                    response.getAllHeaders(), response.getStatusLine());
        }

    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }

    return null;
}