Example usage for org.apache.http.client.fluent Request execute

List of usage examples for org.apache.http.client.fluent Request execute

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request execute.

Prototype

public Response execute() throws ClientProtocolException, IOException 

Source Link

Usage

From source file:net.bluemix.droneselfie.UploadPictureServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String id = request.getParameter("id");
    if (id == null)
        return;/*from w  w  w .j a va 2 s . c o m*/
    if (id.equals(""))
        return;

    InputStream inputStream = null;
    Part filePart = request.getPart("my_file");
    if (filePart != null) {
        inputStream = filePart.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.apache.commons.io.IOUtils.copy(inputStream, baos);
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream bistream = new ByteArrayInputStream(bytes);
        String contentType = "image/png";

        java.util.Date date = new java.util.Date();
        String uniqueId = String.valueOf(date.getTime());
        AttachmentDoc document = new AttachmentDoc(id, AttachmentDoc.TYPE_FULL_PICTURE, date);
        DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
        document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, id);
        AttachmentInputStream ais = new AttachmentInputStream(id, bistream, contentType);
        DatabaseUtilities.getSingleton().getDB().createAttachment(id, document.getRevision(), ais);

        javax.websocket.Session ssession;
        ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
        if (ssession != null) {
            for (Session session : ssession.getOpenSessions()) {
                try {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText("fpic?id=" + id);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

        String alchemyUrl = "";
        String apiKey = ConfigUtilities.getSingleton().getAlchemyAPIKey();
        String bluemixAppName = ConfigUtilities.getSingleton().getBluemixAppName();

        /*
        if (bluemixAppName == null) {
           String host = request.getServerName();
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + host +"/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }
        else {
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + bluemixAppName +".mybluemix.net/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }*/

        alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://ar-drone-selfie.mybluemix.net/pic?id="
                + id + "&apikey=1657f33d25d39ff6d226c5547db6190ea8d5af76&outputMode=json";
        System.out.println("alchemyURL: " + alchemyUrl);
        org.apache.http.client.fluent.Request req = Request.Post(alchemyUrl);
        org.apache.http.client.fluent.Response res = req.execute();

        String output = res.returnContent().asString();
        Gson gson = new Gson();

        AlchemyResponse alchemyResponse = gson.fromJson(output, AlchemyResponse.class);

        if (alchemyResponse != null) {
            List<ImageFace> faces = alchemyResponse.getImageFaces();
            if (faces != null) {
                for (int i = 0; i < faces.size(); i++) {
                    ImageFace face = faces.get(i);
                    String sH = face.getHeight();
                    String sPX = face.getPositionX();
                    String sPY = face.getPositionY();
                    String sW = face.getWidth();
                    int height = Integer.parseInt(sH);
                    int positionX = Integer.parseInt(sPX);
                    int positionY = Integer.parseInt(sPY);
                    int width = Integer.parseInt(sW);

                    int fullPictureWidth = 640;
                    int fullPictureHeight = 360;
                    positionX = positionX - width / 2;
                    positionY = positionY - height / 2;
                    height = height * 2;
                    width = width * 2;
                    if (positionX < 0)
                        positionX = 0;
                    if (positionY < 0)
                        positionY = 0;
                    if (positionX + width > fullPictureWidth)
                        width = width - (fullPictureWidth - positionX);
                    if (positionY + height > fullPictureHeight)
                        height = height - (fullPictureHeight - positionY);

                    bistream = new ByteArrayInputStream(bytes);
                    javaxt.io.Image image = new javaxt.io.Image(bistream);
                    image.crop(positionX, positionY, width, height);
                    byte[] croppedImage = image.getByteArray();

                    ByteArrayInputStream bis = new ByteArrayInputStream(croppedImage);

                    date = new java.util.Date();
                    uniqueId = String.valueOf(date.getTime());
                    document = new AttachmentDoc(uniqueId, AttachmentDoc.TYPE_PORTRAIT, date);
                    DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
                    document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, uniqueId);

                    ais = new AttachmentInputStream(uniqueId, bis, contentType);
                    DatabaseUtilities.getSingleton().getDB().createAttachment(uniqueId, document.getRevision(),
                            ais);

                    ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
                    if (ssession != null) {
                        for (Session session : ssession.getOpenSessions()) {
                            try {
                                if (session.isOpen()) {
                                    /*
                                     * In addition to portrait url why don't we send a few meta back to client
                                     */
                                    ImageTag tag = face.getImageTag();
                                    tag.setUrl("pic?id=" + uniqueId);
                                    session.getBasicRemote().sendText(tag.toString());
                                }
                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

public HttpResponse logout() throws IOException {
    HttpResponse response;/*from   w w w  .j  av a2s  .  c o  m*/
    try {
        if (urlConnection != null) {
            closeUrlConnection();
        }
    } finally {
        Request request = Request.Post(url + "/logout?client-app=STUDIO").addHeader(authorisationHeader);
        response = request.execute().returnResponse();
        if (returnStatusCode(response) != HttpServletResponse.SC_OK && authorisationHeader != null) {
            LOGGER.error(messages.getMessage("error.logoutFailed",
                    extractResponseInformationAndConsumeResponse(response)));
        }
    }
    return response;
}

From source file:gate.tagger.tagme.TaggerWatWS.java

protected String retrieveServerResponse(String text) {
    URI uri;//from   ww  w. j  av  a 2 s.co m
    try {
        uri = new URIBuilder(getTagMeServiceUrl().toURI()).setParameter("text", text)
                .setParameter("gcube-token", getApiKey()).setParameter("lang", getLanguageCode()).build();
    } catch (URISyntaxException ex) {
        throw new GateRuntimeException("Could not create URI for the request", ex);
    }

    //System.err.println("DEBUG: WAT URL="+uri);
    Request req = Request.Get(uri);

    Response res = null;
    try {
        res = req.execute();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem executing HTTP request: " + req, ex);
    }
    Content cont = null;
    try {
        cont = res.returnContent();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex);
    }
    String ret = cont.asString();
    logger.debug("WAT server response " + ret);
    return ret;
}

From source file:aiai.ai.station.actors.UploadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;/*from  w  ww . j  ava  2  s .  co m*/
    }
    if (!globals.isStationEnabled) {
        return;
    }

    UploadResourceTask task;
    List<UploadResourceTask> repeat = new ArrayList<>();
    while ((task = poll()) != null) {
        boolean isOk = false;
        try (InputStream is = new FileInputStream(task.file)) {
            log.info("Start uploading result data to server, resultDataFile: {}", task.file);

            final String uri = globals.uploadRestUrl + '/' + task.taskId;
            HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setCharset(StandardCharsets.UTF_8)
                    .addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, task.file.getName()).build();

            Request request = Request.Post(uri).connectTimeout(5000).socketTimeout(5000).body(entity);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            String json = response.returnContent().asString();

            UploadResult result = fromJson(json);
            log.info("'\tresult data was successfully uploaded");
            if (!result.isOk) {
                log.error("Error uploading file, server error: " + result.error);
            }
            isOk = result.isOk;
        } catch (HttpResponseException e) {
            log.error("Error uploading code", e);
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e.toString());
        } catch (IOException e) {
            log.error("IOException", e);
        } catch (Throwable th) {
            log.error("Throwable", th);
        }
        if (!isOk) {
            log.error("'\tTask assigned one more time.");
            repeat.add(task);
        }

    }
    for (UploadResourceTask uploadResourceTask : repeat) {
        add(uploadResourceTask);
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

private String fetchDataSetId() throws IOException {
    if (dataSetName == null || authorisationHeader == null) {
        return null;
    }//from  w w w  . jav a2 s .c  o  m

    String result = null;

    URI uri = null;
    URL localUrl = new URL(url);
    try {
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName, null);
    } catch (URISyntaxException e) {
        throw new ComponentException(e);
    }

    Request request = Request.Get(uri);
    request.addHeader(authorisationHeader);
    HttpResponse response = request.execute().returnResponse();
    String content = extractResponseInformationAndConsumeResponse(response);

    if (returnStatusCode(response) != HttpServletResponse.SC_OK) {
        throw new IOException(content);
    }

    if (content != null && !"".equals(content)) {
        Object object = JsonReader.jsonToJava(content);
        if (object != null && object instanceof Object[]) {
            Object[] array = (Object[]) object;
            if (array.length > 0) {
                @SuppressWarnings("rawtypes")
                JsonObject jo = (JsonObject) array[0];
                result = (String) jo.get("id");
            }
        }
    }

    return result;
}

From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

@When("^\"([^\"]*)\" checks for the availability of the attachment endpoint$")
public void optionDownload(String username) throws Throwable {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    URI target = mainStepdefs.baseUri().setPath("/download/" + ONE_ATTACHMENT_EML_ATTACHEMENT_BLOB_ID).build();
    Request request = Request.Options(target);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }/*from www.  j  ava2  s  .c  o  m*/
    response = request.execute().returnResponse();
}

From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java

private User getProfileWithAccessToken(String accessToken) {
    User result = null;//w  w w . j av a2s .  c  o  m
    String output = null;

    try {
        configureSSL();

        org.apache.http.client.fluent.Request req = Request
                .Get("https://idaas.ng.bluemix.net/idaas/resources/profile.jsp");

        req.addHeader("Authorization", "bearer " + accessToken);

        org.apache.http.client.fluent.Response res = req.execute();

        output = res.returnContent().asString();

        Gson gson = new Gson();
        result = gson.fromJson(output, User.class);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:org.apache.james.jmap.methods.integration.cucumber.UploadStepdefs.java

@When("^\"([^\"]*)\" upload a too big content$")
public void userUploadTooBigContent(String username) throws Throwable {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    Request request = Request.Post(uploadUri).bodyStream(
            new BufferedInputStream(new ZeroedInputStream(_10M), _10M),
            org.apache.http.entity.ContentType.DEFAULT_BINARY);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }//w ww  .jav a2  s .  co m
    response = request.execute().returnResponse();
}

From source file:aiai.ai.station.actors.DownloadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;//from   w ww  .j a v  a2s .  c  om
    }
    if (!globals.isStationEnabled) {
        return;
    }

    DownloadResourceTask task;
    while ((task = poll()) != null) {
        //            if (Boolean.TRUE.equals(preparedMap.get(task.getId()))) {
        //                continue;
        //            }
        AssetFile assetFile = StationResourceUtils.prepareResourceFile(task.targetDir, task.binaryDataType,
                task.id, null);
        if (assetFile.isError) {
            log.warn("Resource can't be downloaded. Asset file initialization was failed, {}", assetFile);
            continue;
        }
        if (assetFile.isContent) {
            log.info("Resource was already downloaded. Asset file: {}", assetFile.file.getPath());
            //                preparedMap.put(task.getId(), true);
            continue;
        }

        try {
            Request request = Request.Get(targetUrl + '/' + task.getBinaryDataType() + '/' + task.getId())
                    .connectTimeout(5000).socketTimeout(5000);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            response.saveContent(assetFile.file);

            //                preparedMap.put(task.getId(), true);
            log.info("Resource #{} was loaded", task.getId());
        } catch (HttpResponseException e) {
            if (e.getStatusCode() == HttpServletResponse.SC_GONE) {
                log.warn("Resource with id {} wasn't found", task.getId());
            } else if (e.getStatusCode() == HttpServletResponse.SC_CONFLICT) {
                log.warn("Resource with id {} is broken and need to be recreated", task.getId());
            } else {
                log.error("HttpResponseException.getStatusCode(): {}", e.getStatusCode());
                log.error("HttpResponseException", e);
            }
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        }
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

public HttpResponse connect() throws IOException {
    String encoding = "UTF-8";

    if ((url == null) || (login == null) || (pass == null)) {
        throw new IOException(
                messages.getMessage("error.loginFailed", "please set the url, email and password"));
    }/* w w  w .j a  v a 2 s .  com*/

    Request request = Request.Post(url + "/login?username=" + URLEncoder.encode(login, encoding) + "&password="
            + URLEncoder.encode(pass, encoding) + "&client-app=studio");
    HttpResponse response = request.execute().returnResponse();
    authorisationHeader = response.getFirstHeader("Authorization");
    if (returnStatusCode(response) != HttpServletResponse.SC_OK && authorisationHeader == null) {
        String moreInformation = extractResponseInformationAndConsumeResponse(response);
        LOGGER.error(messages.getMessage("error.loginFailed", moreInformation));
        throw new IOException(messages.getMessage("error.loginFailed", moreInformation));
    }
    return response;
}