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

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

Introduction

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

Prototype

public static Request Post(final String uri) 

Source Link

Usage

From source file:org.restheart.test.integration.JsonPathConditionsCheckerIT.java

@Test
public void testPostData() throws Exception {
    Response resp;/*from  w  ww.ja v  a  2s  .c  om*/

    // *** test create invalid data
    resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check post invalid data", resp, HttpStatus.SC_BAD_REQUEST);

    // *** test create valid data
    final String VALID_USER = getResourceFile("data/jsonpath-testuser.json");

    resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString(VALID_USER, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check post valid data", resp, HttpStatus.SC_CREATED);

    // *** test update invalid data

    resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{_id: \"a@si.com\", a:1}", halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check update post invalid data", resp, HttpStatus.SC_BAD_REQUEST);
}

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

@When("^\"([^\"]*)\" upload a content$")
public void userUploadContent(String username) throws Throwable {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    Request request = Request.Post(uploadUri).bodyStream(
            new BufferedInputStream(new ZeroedInputStream(_1M), _1M),
            org.apache.http.entity.ContentType.DEFAULT_BINARY);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }/*from   w  w  w  .ja v a  2s.c  om*/
    response = Executor.newInstance(HttpClientBuilder.create().disableAutomaticRetries().build())
            .execute(request).returnResponse();
}

From source file:com.example.app.communication.service.SmsService.java

/**
 * Send an Sms message to the specified phone number with the given content.
 *
 * @param recipient the intended recipient of the message
 * @param content the content of the message
 *
 * @return a Future representing the success of the action.
 *//*from   w ww  .j  a v  a2 s  . c  o  m*/
public Future<Boolean> sendSms(@Nonnull final PhoneNumber recipient, @Nonnull final String content) {
    return _executorConfig.executorService().submit(() -> {
        //All we want is a raw number with a '+' in front -- so we strip the formatting.
        String numberToDial = PAT_PHONE_SEPARATORS.matcher(recipient.toExternalForm()).replaceAll("");

        Gson gson = new GsonBuilder().create();

        TropoRequest request = new TropoRequest();
        request.action = "create";
        request.message = content;
        request.numberToDial = numberToDial;
        request.token = _tropoMessageApiKey;

        try {
            return Request.Post(_tropoEndpoint).addHeader("accept", "application/json")
                    .addHeader("content-type", "application/json")
                    .bodyString(gson.toJson(request), ContentType.APPLICATION_JSON).execute()
                    .handleResponse(httpResponse -> {
                        if (httpResponse.getStatusLine().getStatusCode() != ResponseStatus.OK.getCode()) {
                            _logger.warn("Sms Message sending failed.  Status code: "
                                    + httpResponse.getStatusLine().getStatusCode() + " was returned.");
                            return false;
                        }
                        String responseString = EntityUtils.toString(httpResponse.getEntity());
                        TropoResponse response = gson.fromJson(responseString, TropoResponse.class);
                        if (response.success == null || !response.success) {
                            _logger.warn("Sms Message sending failed. Tropo Response: " + responseString);
                            return false;
                        }
                        return true;
                    });
        } catch (IOException e) {
            _logger.error("Unable to send Sms message request to Tropo.", e);
            return false;
        }
    });
}

From source file:com.ibm.mds.MobileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String question = req.getParameter("questionText");

    if (question == null || question.trim().equals("")) {
        doResp(formartErrJsonMsg(RESP_ERR_COMMAND_NOT_CORRECT, RESP_TXT_COMMAND_NOT_CORRECT), resp);
        return;/*  ww  w.ja  va2 s. co m*/
    }

    // create the { 'question' : {
    // 'questionText:'...',
    // 'evidenceRequest': { 'items': 5} } json as requested by the service
    JSONObject questionJson = new JSONObject();
    questionJson.put("questionText", question);
    JSONObject evidenceRequest = new JSONObject();
    evidenceRequest.put("items", 5);
    questionJson.put("evidenceRequest", evidenceRequest);

    JSONObject postData = new JSONObject();
    postData.put("question", questionJson);

    try {
        Executor executor = Executor.newInstance().auth(username, password);
        URI serviceURI = new URI(baseURL + "/v1/question/travel").normalize();

        String answersJsonStr = executor
                .execute(Request.Post(serviceURI).addHeader("Accept", "application/json")
                        .addHeader("X-SyncTimeout", "30")
                        .bodyString(postData.toString(), ContentType.APPLICATION_JSON))
                .returnContent().asString();

        JSONObject resultObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        JSONArray pipelines = JSONArray.parse(answersJsonStr);
        // the response has two pipelines, lets use the first one
        JSONObject answersJson = (JSONObject) pipelines.get(0);
        JSONArray answers = (JSONArray) ((JSONObject) answersJson.get("question")).get("evidencelist");

        for (int i = 0; i < answers.size(); i++) {
            JSONObject answer = (JSONObject) answers.get(i);
            double p = Double.parseDouble((String) answer.get("value"));
            p = Math.floor(p * 100);
            JSONObject obj = new JSONObject();
            obj.put("confidence", Double.toString(p) + "%");
            obj.put("text", (String) answer.get("text"));
            jsonArray.add(obj);
        }

        resultObject.put("respCode", RESP_SUCCESS);
        resultObject.put("body", jsonArray);

        doResp(resultObject.toString(), resp);

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

}

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

@When("^the user move \"([^\"]*)\" to mailbox \"([^\"]*)\"")
public void moveMessageToMailbox(String message, String mailbox) throws Throwable {
    String username = userStepdefs.lastConnectedUser;
    MessageId messageId = getMessagesMethodStepdefs.getMessageId(message);
    MailboxId mailboxId = mainStepdefs.jmapServer.getProbe(MailboxProbeImpl.class)
            .getMailbox(MailboxConstants.USER_NAMESPACE, userStepdefs.lastConnectedUser, mailbox)
            .getMailboxId();// w ww.j av a2 s .  c  om

    String requestBody = "[" + "  [" + "    \"setMessages\"," + "    {" + "      \"update\": { \""
            + messageId.serialize() + "\" : {" + "        \"mailboxIds\": [\"" + mailboxId.serialize() + "\"]"
            + "      }}" + "    }," + "    \"#0\"" + "  ]" + "]";
    Request.Post(mainStepdefs.baseUri().setPath("/jmap").build())
            .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize())
            .bodyString(requestBody, org.apache.http.entity.ContentType.APPLICATION_JSON).execute()
            .discardContent();
}

From source file:com.qwazr.graph.test.FullTest.java

@Test
public void test100PutProductNodes() throws IOException {
    for (int i = 0; i < PRODUCT_NUMBER; i++) {
        GraphNode node = new GraphNode();
        node.properties = new HashMap<String, Object>();
        node.properties.put("type", "product");
        node.properties.put("name", "product" + i);
        HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE + "/node/p" + i)
                .bodyString(JsonMapper.MAPPER.writeValueAsString(node), ContentType.APPLICATION_JSON)
                .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }//from   w  ww. j av  a 2s.c o m
}

From source file:info.losd.galen.scheduler.Scheduler.java

@Scheduled(fixedDelay = 500)
public void processTasks() {
    List<Task> tasks = repo.findTasksToBeRun();
    LOG.debug("There are {} tasks waiting", tasks.size());

    tasks.forEach(task -> {//  w  w  w . j  ava  2  s.c  o  m
        LOG.debug("processing: {}", task.toString());

        Map<String, String> headers = new HashMap<>();
        task.getHeaders().forEach(header -> {
            headers.put(header.getHeader(), header.getValue());
        });

        SchedulerHealthcheck healthcheckRequest = new SchedulerHealthcheck();
        healthcheckRequest.setHeaders(headers);
        healthcheckRequest.setMethod(task.getMethod());
        healthcheckRequest.setTag(task.getName());
        healthcheckRequest.setUrl(task.getUrl());

        try {
            String body = mapper.writeValueAsString(healthcheckRequest);

            HttpResponse response = Request.Post("http://127.0.0.1:8080/healthchecks")
                    .bodyString(body, ContentType.APPLICATION_JSON).execute().returnResponse();

            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                task.setLastUpdated(Instant.now());
                repo.save(task);
                LOG.debug("processed:  {}", task.getId());
            } else {
                LOG.error("task: {}, status code: {}, reason: {}\nbody: {}", task.getId(),
                        status.getStatusCode(), status.getReasonPhrase(),
                        IOUtils.toString(response.getEntity().getContent()));
            }
        } catch (Exception e) {
            LOG.error("Problem processing task {}", task.getId(), e);
        }
    });
}

From source file:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java

@Override
public TypedNamedEntity getAllTypes(Document document, NamedEntity ne,
        List<ExtendedTypedNamedEntity> surfaceForms) {
    TypedNamedEntity tne = new TypedNamedEntity(ne.getStartPosition(), ne.getLength(), ne.getUris(),
            new HashSet<String>());
    for (ExtendedTypedNamedEntity surfaceForm : surfaceForms) {
        tne.getTypes().addAll(surfaceForm.getUris());
    }/*from   w ww . j a v  a  2s . co m*/

    try {
        // request FOX
        Response response = Request.Post(FOX_SERVICE).addHeader("Content-type", "application/json")
                .addHeader("Accept-Charset", "UTF-8")
                .body(new StringEntity(new JSONObject().put("input", document.getText()).put("type", "text")
                        .put("task", "ner").put("output", "JSON-LD").toString(), ContentType.APPLICATION_JSON))
                .execute();

        HttpResponse httpResponse = response.returnResponse();
        HttpEntity entry = httpResponse.getEntity();

        String content = IOUtils.toString(entry.getContent(), "UTF-8");
        EntityUtils.consume(entry);

        // parse results
        JSONObject outObj = new JSONObject(content);
        if (outObj.has("@graph")) {

            JSONArray graph = outObj.getJSONArray("@graph");
            for (int i = 0; i < graph.length(); i++) {
                parseType(graph.getJSONObject(i), tne, surfaceForms);
            }
        } else {
            parseType(outObj, tne, surfaceForms);
        }
    } catch (Exception e) {
        LOGGER.error("Got an exception while communicating with the FOX web service.", e);
    }
    return tne;
}

From source file:com.enitalk.controllers.youtube.BotAware.java

public JsonNode getBotCommandsByTag(JsonNode dest, String tag) throws IOException, ExecutionException {
    String auth = botAuth();// w ww.j  av a 2 s.c  o  m
    ObjectNode j = jackson.createObjectNode();
    j.set("dest", dest);
    j.put("tag", tag);

    String tagResponse = Request.Post(env.getProperty("bot.commands.by.tag"))
            .addHeader("Authorization", "Bearer " + auth).bodyString(j.toString(), ContentType.APPLICATION_JSON)
            .socketTimeout(20000).connectTimeout(5000).execute().returnContent().asString();

    logger.info("Command by tag find response {}", tagResponse);
    return jackson.readTree(tagResponse);
}

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  ww .j  av a  2s. co  m

    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;
}