play.libs.ws.WSRequest.post() - java examples

Here are the examples of the java api play.libs.ws.WSRequest.post() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5 Examples 7

18 View Complete Implementation : SlackEventController.java
Copyright Apache License 2.0
Author : EskaleraInc
private void handleChannelJoin(String team, JsonNode eventNode, String user) {
    String authToken = DbManager.getInstance().getTeamToken(team);
    if (authToken == null) {
        authToken = SlackSecrets.getInstance().getSlackAppOauthToken();
    }
    Map<String, Object> responseData = new HashMap<String, Object>();
    String channel = getValueFromJson(eventNode, "channel");
    responseData.put("ok", "true");
    responseData.put("channel", channel);
    responseData.put("token", authToken);
    responseData.put("as_user", "false");
    String apiCall = null;
    String leadMessage = null;
    if (user == null || user.equals(SLACK_APP_BOT_USER)) {
        apiCall = "postMessage";
        leadMessage = "The Catalyst *#BiasCorrect Plug-In* has been added to your channel";
    } else {
        responseData.put("user", user);
        apiCall = "postEphemeral";
        leadMessage = "You have been added to a channel which uses the Catalyst *#BiasCorrect Plug-In*";
    }
    responseData.put("text", String.format("%s.\n" + "Studies show that unconscious gender bias fuels the gender gap. " + "This plug-in is designed to help empower its users to become a catalyst for change, " + "by flagging unconscious gender bias in real-time conversations and offering up alternative " + "bias-free words or phrases for users to consider instead. " + "Hit *Authorize* now to help #BiasCorrect the workplace, once and for all. " + "Use the *bias-correct* command for usage information", leadMessage));
    Map<String, Object> attachment = new HashMap<String, Object>();
    attachment.put("fallback", "Darn!  I wish this worked!");
    attachment.put("actions", getInstallLinkActions());
    List<Map<String, Object>> attachments = new LinkedList<Map<String, Object>>();
    attachments.add(attachment);
    responseData.put("attachments", attachments);
    WSRequest request = _wsClient.url(String.format("https://slack.com/api/chat.%s", apiCall)).setContentType("application/json").addHeader("Authorization", String.format("Bearer %s", authToken));
    CompletionStage<JsonNode> jsonPromise = request.post(toJson(responseData)).thenApply(r -> r.getBody(json()));
    extractResponseJson(jsonPromise);
}

17 View Complete Implementation : SlackEventController.java
Copyright Apache License 2.0
Author : EskaleraInc
private void handleHelpRequest(String team, String user, JsonNode eventNode) {
    String authToken = DbManager.getInstance().getTeamToken(team);
    if (authToken == null) {
        authToken = SlackSecrets.getInstance().getSlackAppOauthToken();
    }
    Map<String, Object> responseData = new HashMap<String, Object>();
    String channel = getValueFromJson(eventNode, "channel");
    responseData.put("ok", "true");
    responseData.put("channel", channel);
    responseData.put("token", authToken);
    responseData.put("user", user);
    responseData.put("text", "The BiasCorrect plug-in helps identify and correct unconscious gender bias in day-to-day messages and " + "conversations.\n" + "Examples: 'she is very emotional', or 'she is very dramatic', or " + "'she is a nag', or 'she is very temperamental'.\n" + "Try typing one of these messages and see what happens!");
    WSRequest request = _wsClient.url("https://slack.com/api/chat.postMessage").setContentType("application/json").addHeader("Authorization", String.format("Bearer %s", authToken));
    CompletionStage<JsonNode> jsonPromise = request.post(toJson(responseData)).thenApply(r -> r.getBody(json()));
    JsonNode responseNode = extractResponseJson(jsonPromise);
    Logger.of("play").info(responseNode.toString());
}

17 View Complete Implementation : SlackEventController.java
Copyright Apache License 2.0
Author : EskaleraInc
private void handleUserMessage(JsonNode eventNode, String team, String user) {
    String messageId = getValueFromJson(eventNode, "ts");
    String channel = getValueFromJson(eventNode, "channel");
    String messageText = getValueFromJson(eventNode, "text");
    if (user != null && messageText != null) {
        if (team != null && channel != null) {
            DbManager.getInstance().updateMessageCounts(team, channel);
        }
        Pair<Boolean, String> result = TriggerWordBiasDetector.getInstance().getCorrectedMessage(messageText);
        if (result != null && result.getLeft()) {
            String authToken = DbManager.getInstance().getTeamToken(team);
            if (authToken == null) {
                authToken = SlackSecrets.getInstance().getSlackAppOauthToken();
            }
            String correctedMessage = result.getRight();
            Map<String, Object> attachment = new HashMap<String, Object>();
            attachment.put("fallback", "Darn!  I wish this worked!");
            attachment.put("replacedle", "Before you hit send, think about it...if she was a he, would you have chosen that word?");
            attachment.put("callback_id", messageId);
            attachment.put("attachment_type", "default");
            attachment.put("actions", getActions(messageText));
            List<Map<String, Object>> attachments = new LinkedList<Map<String, Object>>();
            attachments.add(attachment);
            Map<String, Object> responseData = new HashMap<String, Object>();
            responseData.put("ok", "true");
            responseData.put("channel", channel);
            responseData.put("token", authToken);
            responseData.put("user", user);
            responseData.put("as_user", "false");
            responseData.put("text", String.format("Did you mean, \"%s?\"", correctedMessage));
            responseData.put("attachments", attachments);
            WSRequest request = _wsClient.url("https://slack.com/api/chat.postEphemeral").setContentType("application/json").addHeader("Authorization", String.format("Bearer %s", authToken));
            CompletionStage<JsonNode> jsonPromise = request.post(toJson(responseData)).thenApply(r -> r.getBody(json()));
            JsonNode responseNode = extractResponseJson(jsonPromise);
            Logger.of("play").info(responseNode.toString());
        }
    }
}

14 View Complete Implementation : SlackUserActionController.java
Copyright Apache License 2.0
Author : EskaleraInc
public Result handle() {
    Map<String, String[]> formData = request().body().asFormUrlEncoded();
    String[] payloadEntries = formData.get("payload");
    if (payloadEntries != null && payloadEntries.length == 1) {
        String payload = payloadEntries[0];
        try {
            JsonNode payloadNode = OBJECT_MAPPER.readTree(payload);
            String messageID = getValueFromJson(payloadNode, "callback_id");
            String triggerId = getValueFromJson(payloadNode, "trigger_id");
            if (messageID != null && triggerId != null) {
                JsonNode actionsNode = payloadNode.path("actions");
                if (actionsNode.isArray()) {
                    int numActions = 0;
                    SlackAction action = null;
                    for (JsonNode actionNode : actionsNode) {
                        if (numActions < 1) {
                            action = OBJECT_MAPPER.convertValue(actionNode, SlackAction.clreplaced);
                            numActions++;
                        }
                    }
                    if (action != null && numActions == 1) {
                        JsonNode userNode = payloadNode.path("user");
                        String userId = userNode.path("id").textValue();
                        String userName = userNode.path("name").textValue();
                        JsonNode teamNode = payloadNode.path("team");
                        String teamId = teamNode.path("id").textValue();
                        JsonNode channelNode = payloadNode.path("channel");
                        String channelId = channelNode.path("id").textValue();
                        String answer = action.getValue();
                        String originalMessage = action.getName();
                        String updateUrl = null;
                        String updateMessage = null;
                        String userToken = DbManager.getInstance().getUserToken(teamId, userId);
                        Map<String, String> responseData = new HashMap<String, String>();
                        responseData.put("trigger_id", triggerId);
                        responseData.put("channel", channelId);
                        boolean addUserToken = false;
                        if (answer.equals("no")) {
                            DbManager.getInstance().updateIgnoredMessageCounts(teamId, channelId);
                        } else if (answer.equals("learn_more")) {
                            DbManager.getInstance().updateLearnMoreMessageCounts(teamId, channelId);
                            updateUrl = "https://slack.com/api/chat.postEphemeral";
                            updateMessage = "*Before you hit send, think about it...if she was a he, would you " + "have chosen that word?*\n" + "Unconscious gender bias negatively impacts women’s advancement in the workplace.  " + "Discover tools for overcoming it at <https://catalyst.org/topics/unconscious-bias/>";
                            responseData.put("user", userId);
                            responseData.put("as_user", String.valueOf(Boolean.TRUE));
                        } else if (answer.equals("yes")) {
                            addUserToken = true;
                            String correctedMessage = TriggerWordBiasDetector.getInstance().correctMessage(originalMessage);
                            if (userToken == null) {
                                updateMessage = String.format("%s has replaced \"%s\" with \"%s\"", userName, originalMessage, correctedMessage);
                                updateUrl = "https://slack.com/api/chat.postMessage";
                            } else {
                                updateMessage = correctedMessage;
                                updateUrl = "https://slack.com/api/chat.update";
                                responseData.put("ts", messageID);
                            }
                            DbManager.getInstance().updateCorrectedMessageCounts(teamId, channelId);
                        }
                        if (updateMessage != null && updateUrl != null) {
                            if (userToken == null) {
                                userToken = DbManager.getInstance().getTeamToken(teamId);
                                if (userToken == null) {
                                    userToken = SlackSecrets.getInstance().getSlackAppOauthToken();
                                }
                            }
                            if (addUserToken) {
                                responseData.put("token", userToken);
                            }
                            responseData.put("text", updateMessage);
                            WSRequest request = _wsClient.url(updateUrl).setContentType("application/json").addHeader("Authorization", String.format("Bearer %s", userToken));
                            CompletionStage<JsonNode> jsonPromise = request.post(toJson(responseData)).thenApply(r -> r.getBody(json()));
                            JsonNode responseNode = extractResponseJson(jsonPromise);
                            Logger.of("play").info(responseNode.toString());
                        }
                    }
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return noContent();
}

12 View Complete Implementation : LoginController.java
Copyright GNU General Public License v2.0
Author : nazareno
@Transactional
public CompletionStage<Result> loginGoogle() {
    Request request = request();
    DadosLogin payload = formFactory.form(DadosLogin.clreplaced).bindFromRequest().get();
    final String accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
    final String peopleApiUrl = "https://www.googleapis.com/plus/v1/people/me/openIdConnect";
    WSRequest requisicaoDeToken = ws.url(accessTokenUrl).setContentType("application/x-www-form-urlencoded");
    StringBuilder builder = new StringBuilder().append(CLIENT_ID_KEY + "=" + payload.getClientId() + "&").append(REDIRECT_URI_KEY + "=" + payload.getRedirectUri() + "&").append(CLIENT_SECRET + "=" + googleSecret + "&").append(CODE_KEY + "=" + payload.getCode() + "&").append(GRANT_TYPE_KEY + "=" + AUTH_CODE);
    return requisicaoDeToken.post(builder.toString()).thenComposeAsync(respostaComToken -> {
        JsonNode jsonComToken = respostaComToken.asJson();
        if (!jsonComToken.has("access_token")) {
            return CompletableFuture.supplyAsync(() -> {
                return internalServerError(jsonComToken);
            });
        }
        String accessToken = jsonComToken.get("access_token").asText();
        WSRequest requisicaoDePerfil = ws.url(peopleApiUrl).setContentType("text/plain").setHeader(AuthUtils.AUTH_HEADER_KEY, String.format("Bearer %s", accessToken));
        return requisicaoDePerfil.get().thenApply(respostaComEmail -> {
            JsonNode jsonComEmail = respostaComEmail.asJson();
            try {
                String urlDaFoto = jsonComEmail.get("picture").asText();
                return processUser(request, ProvedorDeLogin.GOOGLE, jsonComEmail.get("sub").asText(), jsonComEmail.get("email").asText(), jsonComEmail.get("name").asText(), urlDaFoto.substring(0, urlDaFoto.indexOf("?")));
            } catch (Exception e) {
                return internalServerError(e.getMessage());
            }
        });
    });
}