play.libs.ws.WSResponse Java Examples

The following examples show how to use play.libs.ws.WSResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Play26CallFactory.java    From openapi-generator with Apache License 2.0 7 votes vote down vote up
@Override
public void enqueue(final okhttp3.Callback responseCallback) {
    final Call call = this;
    final CompletionStage<WSResponse> promise = executeAsync();

    promise.whenCompleteAsync((v, t) -> {
        if (t != null) {
            if (t instanceof IOException) {
                responseCallback.onFailure(call, (IOException) t);
            } else {
                responseCallback.onFailure(call, new IOException(t));
            }
        } else {
            try {
                responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(v));
            } catch (Exception e) {
                responseCallback.onFailure(call, new IOException(e));
            }
        }
    }, this.executor);
}
 
Example #2
Source File: HomeControllerTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog()
  throws Exception {
    WSClient ws = play.test.WSTestClient.newClient(port);
    WSResponse wsResponse = ws.url(url)
                              .setRequestFilter(new AhcCurlRequestLogger())
                              .addHeader("key", "value")
                              .addQueryParameter("num", "" + 1)
                              .get()
                              .toCompletableFuture()
                              .get();

    log.debug("Thread#" + Thread.currentThread()
                                .getId() + " Request complete: Response code = "
      + wsResponse.getStatus()
      + " | Response: " + wsResponse.getBody() + " | Current Time:"
      + System.currentTimeMillis());
    assert (HttpStatus.SC_OK == wsResponse.getStatus());
}
 
Example #3
Source File: IexQuoteServiceImpl.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
public CompletionStage<Quote> getQuote(String symbol) {
    CompletionStage<WSResponse> request =
            circuitBreaker.callWithCircuitBreakerCS(() ->
                    quoteRequest(symbol)
                            .setRequestTimeout(requestTimeout)
                            .get());

    request.thenAccept(response -> {
        if (response.getStatus() == 200) {
            log.debug(response.toString());
        } else {
            log.info(response.toString());
        }
    });
    return request
            .thenApply(response -> {
                JsonNode json = response.getBody(json());
                IexQuoteResponse iexQuoteResponse = Json.fromJson(json, IexQuoteResponse.class);
                return Quote.builder()
                        .symbol(symbol)
                        .sharePrice(iexQuoteResponse.getLatestPrice())
                        .build();
            });
}
 
Example #4
Source File: AzureResourceManagerClientTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 100000, expected = ExecutionException.class)
@Category({UnitTest.class})
public void getOffice365IsEnabled_ReturnsFalseIfForbidden() throws
        NotAuthorizedException,
        ExternalDependencyException,
        ExecutionException,
        InterruptedException {

    // Arrange
    WSRequest wsRequest = mock(WSRequest.class);
    WSResponse wsResponse = mock(WSResponse.class);

    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();
}
 
Example #5
Source File: AzureResourceManagerClientTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 100000)
@Category({UnitTest.class})
public void getOffice365IsEnabled_ReturnsFalseIfNotAuthorized() throws
        NotAuthorizedException,
        ExternalDependencyException,
        ExecutionException,
        InterruptedException {
    // Arrange
    WSRequest wsRequest = mock(WSRequest.class);
    WSResponse wsResponse = mock(WSResponse.class);

    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();

    // Assert
    Assert.assertFalse(result);
}
 
Example #6
Source File: AzureResourceManagerClientTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    this.wsClient = mock(WSClient.class);
    this.wsRequest = mock(WSRequest.class);
    this.wsResponse = mock(WSResponse.class);
    this.mockUserManagementClient = mock(UserManagementClient.class);
    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);
}
 
Example #7
Source File: StatusService.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
private StatusResultServiceModel PingSimulationService(String serviceName, String serviceURL) {
    StatusResultServiceModel result = new StatusResultServiceModel(false, serviceName + " check failed");

    try {
        WSResponse response = this.wsRequestBuilder
            .prepareRequest(serviceURL + "/status")
            .get()
            .toCompletableFuture()
            .get();

        if (response.getStatus() != HttpStatus.SC_OK) {
            result.setMessage("Status code: " + response.getStatus() + ", Response: " + response.getBody());
        } else {
            result.setIsHealthy(response.asJson().findPath("").asText().startsWith("OK:"));
            result.setMessage(response.asJson().findPath("").asText());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return result;
}
 
Example #8
Source File: StatusService.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
private StatusResultServiceModel PingService(String serviceName, String serviceURL) {
    StatusResultServiceModel result = new StatusResultServiceModel(false, serviceName + " check failed");

    try {
        WSResponse response = this.wsRequestBuilder
            .prepareRequest(serviceURL + "/status")
            .get()
            .toCompletableFuture()
            .get();

        if (response.getStatus() != HttpStatus.SC_OK) {
            result.setMessage("Status code: " + response.getStatus() + ", Response: " + response.getBody());
        } else {
            ObjectMapper mapper = new ObjectMapper();
            StatusServiceModel data = mapper.readValue(response.getBody(), StatusServiceModel.class);
            result.setStatusResultServiceModel(data.getStatus());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return result;
}
 
Example #9
Source File: StatusService.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
private StatusResultServiceModel PingService(String serviceName, String serviceURL) {
    StatusResultServiceModel result = new StatusResultServiceModel(false, serviceName + " check failed");

    try {
        WSResponse response = this.wsRequestBuilder
            .prepareRequest(serviceURL + "/status")
            .get()
            .toCompletableFuture()
            .get();

        if (response.getStatus() != HttpStatus.SC_OK) {
            result.setMessage("Status code: " + response.getStatus() + ", Response: " + response.getBody());
        } else {
            ObjectMapper mapper = new ObjectMapper();
            StatusServiceModel data = mapper.readValue(response.getBody(), StatusServiceModel.class);
            result.setStatusResultServiceModel(data.getStatus());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return result;
}
 
Example #10
Source File: StatusService.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
private StatusResultServiceModel PingService(String serviceName, String serviceURL) {
    StatusResultServiceModel result = new StatusResultServiceModel(false, serviceName + " check failed");

    try {
        WSResponse response = this.wsRequestBuilder
            .prepareRequest(serviceURL + "/status")
            .get()
            .toCompletableFuture()
            .get();

        if (response.getStatus() != HttpStatus.SC_OK) {
            result.setMessage("Status code: " + response.getStatus() + ", Response: " + response.getBody());
        } else {
            ObjectMapper mapper = new ObjectMapper();
            StatusServiceModel data = mapper.readValue(response.getBody(), StatusServiceModel.class);
            result.setStatusResultServiceModel(data.getStatus());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return result;
}
 
Example #11
Source File: HttpRequestHelper.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
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()));
    }
}
 
Example #12
Source File: Play26CallFactory.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
CompletionStage<WSResponse> executeAsync() {
    try {
        HttpUrl url = request.url();
        wsRequest = wsClient.url(url.scheme()+ "://" + url.host() + ":" + url.port() + url.encodedPath());
        url.queryParameterNames().forEach(queryParam -> {
            wsRequest.addQueryParameter(queryParam, url.queryParameter(queryParam));
        });
        addHeaders(wsRequest);
        addCookies(wsRequest);
        if (request.body() != null) {
            addBody(wsRequest);
        }
        filters.stream().forEach(f -> wsRequest.setRequestFilter(f));

        return wsRequest.execute(request.method());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #13
Source File: HttpUtil.java    From pay with Apache License 2.0 5 votes vote down vote up
/**
 * 进行get访问
 * @param url
 * @return
 */
public static String doGet(String url){
    return ws.url(url).get().map(new F.Function<WSResponse, String>() {
        @Override
        public String apply(WSResponse wsResponse) throws Throwable {
            return wsResponse.getBody();
        }
    }).get(HTTP_TIME_OUT);
}
 
Example #14
Source File: PlayFrameworkTest.java    From hypersistence-optimizer with Apache License 2.0 5 votes vote down vote up
@Test
public void testSavePost() throws Exception {
    // Tests using a scoped WSClient to talk to the server through a port.
    try (WSClient ws = WSTestClient.newClient(this.testServer.getRunningHttpPort().getAsInt())) {
        CompletionStage<WSResponse> stage = ws.url("/").get();
        WSResponse response = stage.toCompletableFuture().get();
        String body = response.getBody();
        assertThat(body, containsString("Save Post"));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: BasicHttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unauthorizedWhenEnabledAndNoCredentialsProvided() throws Exception {
    try (WSClient wsClient = WS.newClient(testServer.port())) {
        final WSResponse response = wsClient
                .url(URI)
                .get().toCompletableFuture().get();
        assertThat(response.getStatus()).isEqualTo(Http.Status.UNAUTHORIZED);
        assertThat(response.getHeader(Http.HeaderNames.WWW_AUTHENTICATE)).contains(REALM);
    }
}
 
Example #16
Source File: BasicHttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unauthorizedWhenEnabledAndWrongCredentialsProvided() throws Exception {
    try (WSClient wsClient = WS.newClient(testServer.port())) {
        final WSResponse response = wsClient
                .url(URI)
                .setAuth(USERNAME, "wrong", WSAuthScheme.BASIC)
                .get().toCompletableFuture().get();
        assertThat(response.getStatus()).isEqualTo(Http.Status.UNAUTHORIZED);
        assertThat(response.getHeader(Http.HeaderNames.WWW_AUTHENTICATE)).isNull();
    }
}
 
Example #17
Source File: BasicHttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void authorizedWhenEnabledAndCredentialsProvided() throws Exception {
    try (WSClient wsClient = WS.newClient(testServer.port())) {
        final WSResponse response = wsClient
                .url(URI)
                .setAuth(USERNAME, PASSWORD, WSAuthScheme.BASIC)
                .get().toCompletableFuture().get();
        assertThat(response.getStatus()).isEqualTo(Http.Status.OK);
    }
}
 
Example #18
Source File: HttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unauthorizedWhenEnabled() throws Exception {
    final TestServer testServer = testServer(true);
    running(testServer, () -> {
        try (WSClient wsClient = WS.newClient(testServer.port())) {
            final WSResponse response = wsClient
                    .url(URI)
                    .get().toCompletableFuture().get();
            assertThat(response.getStatus()).isEqualTo(Http.Status.UNAUTHORIZED);
            assertThat(response.getHeader(Http.HeaderNames.WWW_AUTHENTICATE).equals(AUTHENTICATE_HEADER_CONTENT));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
 
Example #19
Source File: HttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allowsAccessWhenDisabled() throws Exception {
    final TestServer testServer = testServer(false);
    running(testServer, () -> {
        try (WSClient wsClient = WS.newClient(testServer.port())) {
            final WSResponse response = wsClient
                    .url(URI)
                    .get().toCompletableFuture().get();
            assertThat(response.getStatus()).isEqualTo(Http.Status.OK);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
 
Example #20
Source File: HttpUtil.java    From pay with Apache License 2.0 5 votes vote down vote up
public static String doPost(String url, String data){
    return ws.url(url).post(data).map(new F.Function<WSResponse, String>() {
        @Override
        public String apply(WSResponse wsResponse) throws Throwable {
            return wsResponse.getBody();
        }
    }).get(HTTP_TIME_OUT);
}
 
Example #21
Source File: WsResponseHelper.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/****
 * Helper method that checks if the response from an external service is a success.
 *
 * @param message message to log if non-success status code
 * @throws CompletionException
 */
public static void checkSuccessStatusCode(WSResponse response, String message) {
    if (response != null) {
        if (response.getStatus() != Http.Status.OK) {
            log.error(message);
            throw new CompletionException(new ExternalDependencyException(message));
        }
    }
}
 
Example #22
Source File: HttpUtil.java    From pay with Apache License 2.0 5 votes vote down vote up
/**
 * 发送String型的json格式字符串
 * @param url
 * @param jsonData
 * @return string型的json字符串
 */
public static String doPostAsJson(String url, String jsonData){
    return ws.url(url).post(jsonData).map(new F.Function<WSResponse, JsonNode>() {
        @Override
        public JsonNode apply(WSResponse wsResponse) throws Throwable {
            return wsResponse.asJson();
        }
    }).get(HTTP_TIME_OUT).toString();
}
 
Example #23
Source File: HttpUtil.java    From pay with Apache License 2.0 5 votes vote down vote up
/**
 * 发送String型的xml格式字符串
 * @param url
 * @param xmlData
 * @return
 */
public static Document doPostAsXml(String url, String xmlData){
     return ws.url(url).post(xmlData).map(new F.Function<WSResponse, Document>() {
         @Override
         public Document apply(WSResponse wsResponse) throws Throwable {
             return wsResponse.asXml();
         }
     }).get(HTTP_TIME_OUT);
}
 
Example #24
Source File: Play26CallFactory.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private Response toWSResponse(final WSResponse r) {
    final Response.Builder builder = new Response.Builder();
    builder.request(request)
           .code(r.getStatus())
           .body(new ResponseBody() {

               @Override
               public MediaType contentType() {
                  return r.getSingleHeader("Content-Type")
                          .map(MediaType::parse)
                          .orElse(null);
               }

               @Override
               public long contentLength() {
                   return r.asByteArray().length;
               }

               @Override
               public BufferedSource source() {
                   return new Buffer().write(r.asByteArray());
               }
           });

    for (Map.Entry<String, List<String>> entry : r.getAllHeaders().entrySet()) {
        for (String value : entry.getValue()) {
            builder.addHeader(entry.getKey(), value);
        }
    }
    for (final WSCookie cookie : r.getCookies()) {
        builder.addHeader("Cookie", String.format("%s=%s", cookie.getName(), cookie.getValue()));
    }

    builder.message(r.getStatusText());
    builder.protocol(Protocol.HTTP_1_1);
    return builder.build();
}
 
Example #25
Source File: WsResponseHelper.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/***
 * Helper method that throws if the status code returned by a service is
 * an unauthorized exception (401 or 403).
 *
 * @param response
 * @throws CompletionException
 */
public static void checkUnauthorizedStatus(WSResponse response) throws CompletionException {
    if (response != null) {
        // If the error is 403 or 401, the user who did the deployment is not authorized
        // to assign the role for the application to have Contributor access.
        if (response.getStatus() == HttpStatus.SC_FORBIDDEN ||
                response.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
            String message = String.format("The application is not authorized and has not been " +
                    "assigned Contributor permissions for the subscription. Go to the Azure portal and " +
                    "assign the application as a Contributor in order to retrieve the token.");
            log.error(message);
            throw new CompletionException(new NotAuthorizedException(message));
        }
    }
}
 
Example #26
Source File: SocialNetwork.java    From pfe-samples with MIT License 4 votes vote down vote up
public F.Promise<WSResponse> share(String content, String token) {
    return ws.url(SHARING_ENDPOINT)
            .setQueryParameter("access_token", token)
            .setContentType(Http.MimeTypes.FORM)
            .post(URL.encode(Scala.varargs(URL.param("content", content))));
}