play.libs.ws.WSClient Java Examples

The following examples show how to use play.libs.ws.WSClient. 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: IexQuoteServiceImpl.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
@Inject
IexQuoteServiceImpl(WSClient wsClient,
                    Config config,
                    ActorSystem actorSystem) {
    this.wsClient = wsClient;
    this.hostName = config.getString("quote.iex.hostname");
    this.requestTimeout = Duration.ofMillis(1000); // TODO: Configurable
    int maxFailures = 10;
    Duration callTimeout = this.requestTimeout.minus(this.requestTimeout.dividedBy(10));
    Duration resetTimeout = Duration.ofMillis(1000);
    this.circuitBreaker = new CircuitBreaker(
            actorSystem.getDispatcher(),
            actorSystem.getScheduler(),
            maxFailures,
            callTimeout,
            resetTimeout); // TODO
}
 
Example #2
Source File: HomeControllerTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenASinglePostRequestWhenResponseThenLog() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    WSClient ws = play.test.WSTestClient.newClient(port);
    ws.url(url)
      .setContentType("application/x-www-form-urlencoded")
      .post("key1=value1&key2=value2")
      .thenAccept(r -> {
          log.debug("Thread#" + Thread.currentThread()
                                      .getId() + " Request complete: Response code = "
            + r.getStatus()
            + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis());
          latch.countDown();
      });

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example #3
Source File: HomeControllerTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenASingleGetRequestWhenResponseThenLog() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    WSClient ws = play.test.WSTestClient.newClient(port);
    ws.url(url)
      .setRequestFilter(new AhcCurlRequestLogger())
      .addHeader("key", "value")
      .addQueryParameter("num", "" + 1)
      .get()
      .thenAccept(r -> {
          log.debug("Thread#" + Thread.currentThread()
                                      .getId() + " Request complete: Response code = "
            + r.getStatus()
            + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis());
          latch.countDown();
      });

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example #4
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 #5
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 #6
Source File: AzureResourceManagerClient.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Inject
public AzureResourceManagerClient(final IServicesConfig config,
                                  final WSClient wsClient,
                                  IUserManagementClient userManagementClient) {
    this.wsClient = wsClient;
    this.userManagementClient = userManagementClient;

    IActionsConfig actionsConfig = config.getActionsConfig();
    this.subscriptionId = actionsConfig.getSubscriptionId();
    this.resourceGroup = actionsConfig.getResourceGroup();
    this.armEndpointUrl = actionsConfig.getArmEndpointUrl();
    this.managementApiVersion = actionsConfig.getManagementApiVersion();

    if (StringUtils.isEmpty(this.subscriptionId.trim()) ||
            StringUtils.isEmpty(this.resourceGroup.trim()) ||
            StringUtils.isEmpty(this.armEndpointUrl.trim())) {
        throw new CompletionException(new InvalidConfigurationException("Subscription Id, " +
                "Resource Group, and Arm Endpoint Url must be specified" +
                "in the environment variable configuration for this " +
                "solution in order to use this API."));
    }
}
 
Example #7
Source File: AlarmsByRuleControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    // setup before every test
    try {
        IServicesConfig servicesConfig = new Config().getServicesConfig();
        IStorageClient client = mock(IStorageClient.class);
        IDiagnosticsClient diagnosticsClient = mock(IDiagnosticsClient.class);
        this.wsClient = mock(WSClient.class);
        this.alarms = new Alarms(servicesConfig, client);
        this.rules = new Rules(servicesConfig, wsClient, alarms, diagnosticsClient);
        this.controller = new AlarmsByRuleController(this.alarms, this.rules);
    } catch (Exception ex) {
        log.error("Exception setting up test", ex);
        Assert.fail(ex.getMessage());
    }
}
 
Example #8
Source File: Global.java    From pfe-samples with MIT License 6 votes vote down vote up
@Override
protected void configure() {
    bind(OAuth.Configuration.class).toProvider(new Provider<OAuth.Configuration>() {
        @Override
        public OAuth.Configuration get() {
            return new OAuth.Configuration(
                    "https://accounts.google.com/o/oauth2/auth",
                    "https://accounts.google.com/o/oauth2/token",
                    "1079303020045-4kie53crgo06su51pi3dnbm90thc2q33.apps.googleusercontent.com",
                    "9-PoA1ZwynHJlE4Y3VY8fONX",
                    "https://www.googleapis.com/auth/plus.login",
                    controllers.routes.Items.list().url()
            );
        }
    });
    bind(WSClient.class).toProvider(new Provider<WSClient>() {
        @Override
        public WSClient get() {
            return injector.getInstance(Service.class).ws;
        }
    });
}
 
Example #9
Source File: Rules.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Inject
public Rules(
    final IServicesConfig servicesConfig,
    final WSClient wsClient,
    final IAlarms alarmsService,
    final IDiagnosticsClient diagnosticsClient) {

    this.storageUrl = servicesConfig.getKeyValueStorageUrl() + "/collections/rules/values";
    this.wsClient = wsClient;
    this.alarmsService = alarmsService;
    this.diagnosticsClient = diagnosticsClient;
}
 
Example #10
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 #11
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 #12
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 #13
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 #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: TimeSeriesClientTest.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws InvalidConfigurationException {
    this.wsClient = mock(WSClient.class);
    this.servicesConfig = new ServicesConfig(
        "http://localhost:9022/v1",
        "http://localhost:9001/v1",
        mock(MessagesConfig.class),
        mock(AlarmsConfig.class),
        mock(ActionsConfig.class),
        mock(DiagnosticsConfig.class));
    this.timeSeriesClient = new TimeSeriesClient(this.servicesConfig, this.wsClient);
}
 
Example #17
Source File: DiagnosticsClient.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Inject
public DiagnosticsClient(final WSClient wsClient, final IServicesConfig servicesConfig) {
    this.wsClient = wsClient;
    this.diagnosticsEndpointUrl = servicesConfig.getDiagnosticsConfig().getApiUrl();
    if(this.diagnosticsEndpointUrl == null || this.diagnosticsEndpointUrl.length() == 0) {
        this.log.error("No diagnostics url given, cannot write to diagnostics");
        this.canWriteToDiagnostics = false;
    } else {
        this.canWriteToDiagnostics = true;
    }
    this.diagnosticsMaxLogRetries = servicesConfig.getDiagnosticsConfig().getMaxLogRetries();
}
 
Example #18
Source File: EmailActionExecutor.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
@Inject
public EmailActionExecutor(final IServicesConfig serviceConfig, final WSClient wsClient) throws ResourceNotFoundException {
    ActionsConfig actionsConfig = serviceConfig.getActionsConfig();
    this.logicAppEndpointUrl = actionsConfig.getLogicAppEndpointUrl();
    this.solutionWebsiteUrl = actionsConfig.getSolutionWebsiteUrl();
    this.templatePath = actionsConfig.getTemplateFolder();
    this.wsClient = wsClient;
    this.emailTemplate = loadEmailTemplate(String.format("/resources/%s/%s",
        this.templatePath, EMAIL_TEMPLATE_FILE_NAME));
}
 
Example #19
Source File: HomeControllerTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenMultipleRequestsWhenResponseThenLog() throws Exception {
    CountDownLatch latch = new CountDownLatch(100);
    WSClient ws = play.test.WSTestClient.newClient(port);
    IntStream.range(0, 100)
             .parallel()
             .forEach(num ->
               ws.url(url)
                 .setRequestFilter(new AhcCurlRequestLogger())
                 .addHeader("key", "value")
                 .addQueryParameter("num", "" + num)
                 .get()
                 .thenAccept(r -> {
                     log.debug(
                       "Thread#" + num + " Request complete: Response code = " + r.getStatus()
                         + " | Response: " + r.getBody() + " | Current Time:"
                         + System.currentTimeMillis());
                     latch.countDown();
                 })
             );

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example #20
Source File: Play26CallFactory.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public PlayWSCall(WSClient wsClient, Executor executor, List<WSRequestFilter> filters, Request request) {
    this.wsClient = wsClient;
    this.request = request;
    this.filters = filters;
    this.timeout = new AsyncTimeout();

    if (executor != null) {
        this.executor = executor;
    }
}
 
Example #21
Source File: Play26CallFactory.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public Play26CallFactory(WSClient wsClient, Map<String, String> extraHeaders,
    Map<String, String> extraCookies,
    List<Pair> extraQueryParams) {
    this.wsClient = wsClient;

    this.extraHeaders.putAll(extraHeaders);
    this.extraCookies.putAll(extraCookies);
    this.extraQueryParams.addAll(extraQueryParams);
}
 
Example #22
Source File: HomeControllerTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenLongResponseWhenTimeoutThenHandle() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    WSClient ws = play.test.WSTestClient.newClient(port);
    Futures futures = app.injector()
                         .instanceOf(Futures.class);
    CompletionStage<Result> f = futures.timeout(
      ws.url(url)
        .setRequestTimeout(Duration.of(1, SECONDS))
        .get()
        .thenApply(result -> {
            try {
                Thread.sleep(2000L);
                return Results.ok();
            } catch (InterruptedException e) {
                return Results.status(
                  SERVICE_UNAVAILABLE);
            }
        }), 1L, TimeUnit.SECONDS
    );
    CompletionStage<Object> res = f.handleAsync((result, e) -> {
        if (e != null) {
            log.error("Exception thrown", e);
            latch.countDown();
            return e.getCause();
        } else {
            return result;
        }
    });
    res.thenAccept(result -> assertEquals(TimeoutException.class, result));

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example #23
Source File: HomeControllerTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenMultigigabyteResponseConsumeWithStreams() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ActorSystem system = ActorSystem.create();
    final ActorMaterializer materializer = ActorMaterializer.create(system);
    final Path path = Files.createTempFile("tmp_", ".out");

    WSClient ws = play.test.WSTestClient.newClient(port);
    log.info("Starting test server on url: " + url);
    ws.url(url)
      .stream()
      .thenAccept(
        response -> {
            try {
                OutputStream outputStream = java.nio.file.Files.newOutputStream(path);
                Sink<ByteString, CompletionStage<Done>> outputWriter =
                  Sink.foreach(bytes -> {
                      log.info("Reponse: " + bytes.utf8String());
                      outputStream.write(bytes.toArray());
                  });

                response.getBodyAsSource()
                        .runWith(outputWriter, materializer);

            } catch (IOException e) {
                log.error("An error happened while opening the output stream", e);
            }
        })
      .whenComplete((value, error) -> latch.countDown());

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example #24
Source File: SocialNetwork.java    From pfe-samples with MIT License 4 votes vote down vote up
public SocialNetwork(WSClient ws) {
    this.ws = ws;
}
 
Example #25
Source File: UserManagementClient.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
@Inject
public UserManagementClient(final IServicesConfig config, final WSClient wsClient) {
    this.wsClient = wsClient;
    this.userManagementServiceUrl = config.getUserManagementApiUrl();
}
 
Example #26
Source File: OAuth.java    From pfe-samples with MIT License 4 votes vote down vote up
@Inject
public OAuth(WSClient ws, Configuration configuration) {
    this.ws = ws;
    this.configuration = configuration;
}
 
Example #27
Source File: MaxmindProvider.java    From play-geolocation-module.edulify.com with Apache License 2.0 4 votes vote down vote up
@Inject
public MaxmindProvider(WSClient ws, Configuration configuration) {
  this.ws = ws;
  this.configuration = configuration;
  this.license = this.configuration.getString("geolocation.maxmind.license");
}
 
Example #28
Source File: FreegeoipProvider.java    From play-geolocation-module.edulify.com with Apache License 2.0 4 votes vote down vote up
@Inject
public FreegeoipProvider(WSClient ws) {
  this.ws = ws;
}
 
Example #29
Source File: WsRequestBuilder.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
@Inject
public WsRequestBuilder(WSClient ws) {
    this.ws = ws;
}
 
Example #30
Source File: UserManagementClient.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
@Inject
public UserManagementClient(final IClientAuthConfig config, final WSClient wsClient) {
    this.userManagementServiceUrl = config.getAuthServiceUrl();
    this.wsClient = wsClient;
}