play.libs.ws.WSRequest

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

18 Examples 7

19 Source : GoogleAnalyticsService.java
with Apache License 2.0
from willowtreeapps

private WSRequest addQueryParameters(WSRequest request, Map<String, String> values) {
    for (var entry : values.entrySet()) {
        // addQueryParmeter will url encode the value
        request.addQueryParameter(entry.getKey(), entry.getValue());
    }
    return request;
}

19 Source : Rules.java
with MIT License
from Azure

private WSRequest prepareRequest(String id) {
    String url = this.storageUrl;
    if (id != null) {
        url = url + "/" + id;
    }
    WSRequest wsRequest = this.wsClient.url(url).addHeader("Content-Type", "application/json");
    return wsRequest;
}

19 Source : DiagnosticsClient.java
with MIT License
from Azure

private WSRequest prepareRequest() {
    String url = this.diagnosticsEndpointUrl + "/diagnosticsevents";
    WSRequest wsRequest = this.wsClient.url(url).addHeader("Content-Type", "application/json");
    return wsRequest;
}

19 Source : EmailActionExecutor.java
with MIT License
from Azure

private WSRequest prepareRequest() {
    WSRequest wsRequest = this.wsClient.url(this.logicAppEndpointUrl).addHeader("Csrf-Token", "no-check").addHeader("Content-Type", "application/json");
    return wsRequest;
}

18 Source : WsRequestBuilder.java
with MIT License
from Azure

public WSRequest prepareRequest(String url) {
    WSRequest wsRequest = this.ws.url(url).addHeader("Content-Type", "application/json").addHeader("Cache-Control", "no-cache").addHeader("Referer", "IotHubManager");
    wsRequest.setRequestTimeout(Duration.ofSeconds(10));
    return wsRequest;
}

18 Source : WsRequestBuilder.java
with MIT License
from Azure

public WSRequest prepareRequest(String url) {
    WSRequest wsRequest = this.ws.url(url).addHeader("Content-Type", "application/json").addHeader("Cache-Control", "no-cache").addHeader("Referer", "Device Telemetry");
    wsRequest.setRequestTimeout(Duration.ofSeconds(10));
    return wsRequest;
}

18 Source : AzureResourceManagerClientTest.java
with MIT License
from Azure

public clreplaced AzureResourceManagerClientTest {

    private final String mockSubscriptionId = "123456abcd";

    private final String mockResourceGroup = "example-name";

    private final String mockArmEndpointUrl = "https://management.azure.com";

    private final String mockApiVersion = "2016-06-01";

    private final String mockUrl = "http://mockurl";

    private WSClient wsClient;

    private WSRequest wsRequest;

    private WSResponse wsResponse;

    private IUserManagementClient mockUserManagementClient;

    private AzureResourceManagerClient client;

    @Before
    public void setUp() {
        this.wsClient = mock(WSClient.clreplaced);
        this.wsRequest = mock(WSRequest.clreplaced);
        this.wsResponse = mock(WSResponse.clreplaced);
        this.mockUserManagementClient = mock(UserManagementClient.clreplaced);
        ActionsConfig actionsConfig = new ActionsConfig(mockArmEndpointUrl, mockApiVersion, mockUrl, mockResourceGroup, mockSubscriptionId);
        ServicesConfig config = new ServicesConfig("http://telemetryurl", "http://storageurl", "http://usermanagementurl", "http://simurl", "template", "mapsKey", actionsConfig);
        this.client = new AzureResourceManagerClient(config, this.wsClient, this.mockUserManagementClient);
    }

    @Test(timeout = 100000)
    @Category({ UnitTest.clreplaced })
    public void getOffice365IsEnabled_ReturnsTrueIfEnabled() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
        // Arrange
        when(mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
        when(this.wsClient.url(any())).thenReturn(this.wsRequest);
        when(this.wsRequest.get()).thenReturn(CompletableFuture.completedFuture(this.wsResponse));
        when(this.wsResponse.getStatus()).thenReturn(HttpStatus.SC_OK);
        // Act
        boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
        // replacedert
        replacedertTrue(result);
    }

    @Test(timeout = 100000)
    @Category({ UnitTest.clreplaced })
    public void getOffice365IsEnabled_ReturnsFalseIfDisabled() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
        // Arrange
        when(this.mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
        when(this.wsClient.url(any())).thenReturn(this.wsRequest);
        when(this.wsRequest.get()).thenReturn(CompletableFuture.completedFuture(this.wsResponse));
        when(this.wsResponse.getStatus()).thenReturn(HttpStatus.SC_NOT_FOUND);
        // Act
        boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
        // replacedert
        replacedert.replacedertFalse(result);
    }

    // If the user is not authorized to access the Auth service with their token, this method should also throw.
    @Test(timeout = 100000, expected = NotAuthorizedException.clreplaced)
    @Category({ UnitTest.clreplaced })
    public void getOffice365IsEnabled_ThrowsIfUserManagementNotAuthorized() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
        // Arrange
        when(mockUserManagementClient.getTokenAsync()).thenThrow(NotAuthorizedException.clreplaced);
        // Act
        this.client.isOffice365EnabledAsync().toCompletableFuture().get();
    }

    // If the Logic App testconnection api returns a 401 Unauthorized, then it means the user has access
    // to make the api call but the application is configured incorrectly and needs the user to sign in
    // with their Outlook email account.
    @Test(timeout = 100000)
    @Category({ UnitTest.clreplaced })
    public void getOffice365IsEnabled_ReturnsFalseIfNotAuthorized() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
        // Arrange
        WSRequest wsRequest = mock(WSRequest.clreplaced);
        WSResponse wsResponse = mock(WSResponse.clreplaced);
        when(mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
        when(wsClient.url(any())).thenReturn(wsRequest);
        when(wsRequest.get()).thenReturn(CompletableFuture.completedFuture(wsResponse));
        when(wsResponse.getStatus()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
        // Act
        boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
        // replacedert
        replacedert.replacedertFalse(result);
    }

    // If the application receives a Forbidden from the Logic App testconnection api,
    // then this method should throw.
    @Test(timeout = 100000, expected = ExecutionException.clreplaced)
    @Category({ UnitTest.clreplaced })
    public void getOffice365IsEnabled_ReturnsFalseIfForbidden() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
        // Arrange
        WSRequest wsRequest = mock(WSRequest.clreplaced);
        WSResponse wsResponse = mock(WSResponse.clreplaced);
        when(mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
        when(wsClient.url(any())).thenReturn(wsRequest);
        when(wsRequest.get()).thenReturn(CompletableFuture.completedFuture(wsResponse));
        when(wsResponse.getStatus()).thenReturn(HttpStatus.SC_FORBIDDEN);
        // Act
        boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
    }
}

18 Source : WsRequestBuilder.java
with MIT License
from Azure

public WSRequest prepareRequest(String url) {
    WSRequest wsRequest = this.ws.url(url).addHeader("Content-Type", "application/json").addHeader("Cache-Control", "no-cache").addHeader("Referer", "Config");
    wsRequest.setRequestTimeout(Duration.ofSeconds(10));
    return wsRequest;
}

18 Source : AzureResourceManagerClient.java
with MIT License
from Azure

/**
 * Prepares a WSRequest to the Azure management APIs with an application token
 * Uses the default audience from the User Management service. If the User Management
 * service returns a 401 or 403 unauthorized exception, then the user deploying the application
 * did not have owner permissions in order to replacedign the application owner permission to access
 * the Azure Management APIs.
 *
 * @param url
 * @return WSRequest for the Azure Management service
 * @throws ExternalDependencyException
 * @throws NotAuthorizedException
 */
private WSRequest createRequest(String url) throws ExternalDependencyException, NotAuthorizedException {
    WSRequest request = this.wsClient.url(url);
    try {
        String token = this.userManagementClient.getTokenAsync().toCompletableFuture().get().toString();
        request.addHeader("Authorization", "Bearer " + token);
    } catch (InterruptedException | ExecutionException e) {
        String message = "Unable to get application token.";
        log.error(message);
        throw new ExternalDependencyException(message);
    } catch (CompletionException e) {
        if (e.getCause() instanceof NotAuthorizedException) {
            String message = "Unable to get application token. The application is not authorized " + "and has not been replacedigned owner permissions for the subscription.";
            throw new NotAuthorizedException(message);
        }
    }
    return request;
}

18 Source : AzureResourceManagerClient.java
with MIT License
from Azure

@Override
public CompletionStage<Boolean> isOffice365EnabledAsync() throws ExternalDependencyException, NotAuthorizedException {
    String logicAppTestConnectionUri = String.format("%ssubscriptions/%s/resourceGroups/%s" + "/providers/Microsoft.Web/connections/" + "office365-connector/extensions/proxy/" + "testconnection?api-version=%s", this.armEndpointUrl, this.subscriptionId, this.resourceGroup, this.managementApiVersion);
    // Gets token from auth service and adds to header
    WSRequest request = this.createRequest(logicAppTestConnectionUri);
    return request.get().handle((response, error) -> {
        // If the call to testconnection fails with a 403, it means the application was not
        // replacedigned the correct permissions to make the request. This can happen if the person doing
        // the deployment is not an owner, or if there was an issue at deployment time.
        if (response.getStatus() == HttpStatus.SC_FORBIDDEN) {
            String message = String.format("The application is not authorized and has not been " + "replacedigned owner permissions for the subscription. Go to the Azure portal and " + "replacedign the application as an owner in order to retrieve the token.");
            log.error(message);
            throw new CompletionException(new NotAuthorizedException(message));
        }
        WsResponseHelper.checkError(error, "Failed to check status of Office365 Logic App Connector.");
        // The testconnection call may return a 401, which means the user has not yet configured
        // the O365 Logic App by signing in with the sender email address.
        if (response.getStatus() != Http.Status.OK) {
            log.debug(String.format("Office365 Logic App Connector is not set up."));
            return false;
        }
        return true;
    });
}

16 Source : SlackAuthController.java
with Apache License 2.0
from EskaleraInc

/**
 * Handle all oauth requests from Slack.
 */
public Result handle() {
    String requestCode = request().getQueryString("code");
    // send a get request to Slack with the code to get token for authed user
    WSRequest request = _wsClient.url("https://slack.com/api/oauth.access").addQueryParameter("code", requestCode).addQueryParameter("client_id", SlackSecrets.getInstance().getClientId()).addQueryParameter("client_secret", SlackSecrets.getInstance().getClientSecret());
    CompletionStage<JsonNode> jsonPromise = request.get().thenApply(r -> r.getBody(json()));
    JsonNode responseNode = extractResponseJson(jsonPromise);
    String teamId = getValueFromJson(responseNode, "team_id");
    String userId = getValueFromJson(responseNode, "user_id");
    String userToken = getValueFromJson(responseNode, "access_token");
    if (teamId != null && userId != null && userToken != null) {
        DbManager.getInstance().addTeamToken(teamId, userToken);
        DbManager.getInstance().addUserToken(teamId, userId, userToken);
    } else {
        Logger.of("play").info("*** Invalid Auth Access request from Slack");
    }
    return found(System.getenv("APP_INSTALL_LANDING_PAGE"));
}

16 Source : HttpRequestHelper.java
with MIT License
from Azure

public static void checkStatusCode(WSResponse response, WSRequest request) throws ResourceNotFoundException, ConflictingResourceException, ExternalDependencyException {
    if (response.getStatus() == 200) {
        return;
    }
    log.info(String.format("Config returns %s for request %s", response.getStatus(), request.getUrl().toString()));
    switch(response.getStatus()) {
        case 404:
            throw new ResourceNotFoundException(String.format("%s, request URL = %s,", response.getBody(), request.getUrl()));
        case 409:
            throw new ConflictingResourceException(String.format("%s, request URL = %s,", response.getBody(), request.getUrl()));
        default:
            throw new ExternalDependencyException(String.format("WS-request failed, status code = %s, content = %s, request URL = %s", response.getStatus(), response.getBody(), request.getUrl()));
    }
}

14 Source : SlackEventController.java
with Apache License 2.0
from 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);
}

14 Source : SlackEventController.java
with Apache License 2.0
from 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());
}

14 Source : AzureResourceManagerClientTest.java
with MIT License
from Azure

// If the Logic App testconnection api returns a 401 Unauthorized, then it means the user has access
// to make the api call but the application is configured incorrectly and needs the user to sign in
// with their Outlook email account.
@Test(timeout = 100000)
@Category({ UnitTest.clreplaced })
public void getOffice365IsEnabled_ReturnsFalseIfNotAuthorized() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
    // Arrange
    WSRequest wsRequest = mock(WSRequest.clreplaced);
    WSResponse wsResponse = mock(WSResponse.clreplaced);
    when(mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
    when(wsClient.url(any())).thenReturn(wsRequest);
    when(wsRequest.get()).thenReturn(CompletableFuture.completedFuture(wsResponse));
    when(wsResponse.getStatus()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
    // Act
    boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
    // replacedert
    replacedert.replacedertFalse(result);
}

14 Source : AzureResourceManagerClientTest.java
with MIT License
from Azure

// If the application receives a Forbidden from the Logic App testconnection api,
// then this method should throw.
@Test(timeout = 100000, expected = ExecutionException.clreplaced)
@Category({ UnitTest.clreplaced })
public void getOffice365IsEnabled_ReturnsFalseIfForbidden() throws NotAuthorizedException, ExternalDependencyException, ExecutionException, InterruptedException {
    // Arrange
    WSRequest wsRequest = mock(WSRequest.clreplaced);
    WSResponse wsResponse = mock(WSResponse.clreplaced);
    when(mockUserManagementClient.getTokenAsync()).thenReturn(CompletableFuture.completedFuture("foo"));
    when(wsClient.url(any())).thenReturn(wsRequest);
    when(wsRequest.get()).thenReturn(CompletableFuture.completedFuture(wsResponse));
    when(wsResponse.getStatus()).thenReturn(HttpStatus.SC_FORBIDDEN);
    // Act
    boolean result = this.client.isOffice365EnabledAsync().toCompletableFuture().get();
}

10 Source : SlackEventController.java
with Apache License 2.0
from 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());
        }
    }
}

6 Source : SlackUserActionController.java
with Apache License 2.0
from 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();
}