Java Code Examples for javax.ws.rs.client.ClientBuilder

The following are top voted examples for showing how to use javax.ws.rs.client.ClientBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 9 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected raw token claim using @Claim(standard) is as expected")
public void verifyInjectedRawTokenStandard() throws Exception {
    Reporter.log("Begin verifyInjectedRawTokenStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedRawTokenStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.raw_token.name(), token)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 2
Project: Pet-Supply-Store   File: RegistryTest.java   Source Code and License 7 votes vote down vote up
/**
 * Test if after registration of service they can be found in registry.
 */
@Test
public void testRegister() {
	 Response response1 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service1/abbaasd")
			 .request(MediaType.APPLICATION_JSON).put(Entity.text(""));
	 Assert.assertTrue(response1.getStatus() == Response.Status.OK.getStatusCode());
	 Response response2 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service1/abbaasd2")
			 .request(MediaType.APPLICATION_JSON).put(Entity.text(""));
	 Assert.assertTrue(response2.getStatus() == Response.Status.OK.getStatusCode());
	 Response response = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service1").request(MediaType.APPLICATION_JSON).get();
	 Assert.assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
	 List<String> list = response.readEntity(new GenericType<List<String>>() { }); 
	 Assert.assertTrue(list != null);
	 Assert.assertTrue(list.size() == 2);
	 Assert.assertTrue(list.get(0).equals("abbaasd"));
	 Assert.assertTrue(list.get(1).equals("abbaasd2"));
}
 
Example 3
Project: radiobrowser4j   File: RadioBrowser.java   Source Code and License 7 votes vote down vote up
/** Custom constructor for mocked unit testing.
 * @param apiUrl the base URL of the API.
 * @param timeout the timeout in milliseconds for connecting
 *                and reading.
 * @param myUserAgent the user agent string to use.
 * */
RadioBrowser(final String apiUrl,
                     final int timeout,
                     final String myUserAgent) {
    if (timeout <= 0) {
        throw new IllegalArgumentException(
                "timeout must be > 0, but is "
                        + timeout);
    }
    this.userAgent = Objects.requireNonNull(myUserAgent,
            "User agent is null");
    Client client = ClientBuilder.newBuilder()
            .register(JacksonFeature.class)
            .build();
    client.property(ClientProperties.CONNECT_TIMEOUT, timeout);
    client.property(ClientProperties.READ_TIMEOUT,    timeout);
    webTarget = client.target(apiUrl);
}
 
Example 4
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected aud claim using @Claim(standard) is as expected")
public void verifyInjectedAudienceStandard() throws Exception {
    Reporter.log("Begin verifyInjectedAudienceStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedAudienceStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    System.out.println(reply);
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 5
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customInteger claim is as expected")
public void verifyInjectedCustomInteger2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomInteger\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomInteger";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 123456789)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 6
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customString claim is as expected")
public void verifyInjectedCustomString2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomString\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomString";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "customStringValue")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 7
Project: microprofile-jwt-auth   File: JsonValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customDouble claim is as expected")
public void verifyInjectedCustomDouble2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomDouble2\n");
    String token2 = TokenUtils.generateTokenString("/Token2.json");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomDouble";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 3.241592653589793)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 8
Project: reactive-components   File: TestRs.java   Source Code and License 6 votes vote down vote up
@Test
public void testGet() throws Exception {
    Server server = createServer();
    server.start();
    WebTarget client1 = ClientBuilder.newClient().target("http://localhost:8384/Hello");
    WebTarget client2 = ClientBuilder.newClient().target("http://localhost:8384/World");
    /*
    Mono<String> get1 = fromCompletionStage(client1.request().rx().get(String.class));
    Mono<String> get2 = fromCompletionStage(client2.request().rx().get(String.class));
    List<String> result = Mono
        .from(get1)
        .concatWith(get2)
        .doOnError(ex -> ex.printStackTrace())
        .collectList()
        .block(Duration.ofMillis(1500));
    String resultSt = result.stream().collect(Collectors.joining(" "));
    org.junit.Assert.assertEquals("Hello World", resultSt);
    */
    server.stop();
}
 
Example 9
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected sub claim using @Claim(standard) is as expected")
public void verifyInjectedSubjectStandard() throws Exception {
    Reporter.log("Begin verifyInjectedSubjectStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedSubjectStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.sub.name(), "24400320")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 10
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected raw token claim is as expected")
public void verifyInjectedOptionalAuthTime() throws Exception {
    Reporter.log("Begin verifyInjectedOptionalAuthTime\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedOptionalAuthTime";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 11
Project: microservices-transactions-tcc   File: CompositeTransactionConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public WebTarget tccCoordinatorClient() {
	Client client = ClientBuilder.newClient();
	client.register(new JacksonJaxbJsonProvider());
	client.register(new TransactionProvider());
	WebTarget target = client.target(tccCoordinatorBaseUrl);
	return target.path("/coordinator");
}
 
Example 12
Project: open-kilda   File: FlowFFRTest.java   Source Code and License 6 votes vote down vote up
private boolean connectSwitch(String switchName, String controller) throws Exception {
    System.out.println("\n==> Connect Switch");

    long current = System.currentTimeMillis();
    Client client = ClientBuilder.newClient(new ClientConfig());
    Response result = client
            .target(trafficEndpoint)
            .path("/reviveswitch")
            .queryParam("switch", switchName)
            .queryParam("controller", "tcp:" + controller + ":6653")
            .request()
            .post(Entity.json(""));

    System.out.println(String.format("===> Response = %s", result.toString()));
    System.out.println(String.format("===> Connect Switch Time: %,.3f", getTimeDuration(current)));

    return result.getStatus() == 200;
}
 
Example 13
Project: servicebuilder   File: StubGenerator.java   Source Code and License 6 votes vote down vote up
public <T> T generateClient(Class<T> resource) {
    Client clientToUse = client != null
            ? client
            : ClientBuilder.newClient();

    MultivaluedMap<String, Object> headerArg = new MultivaluedHashMap<>(headers);

    WebTarget webTarget = clientToUse.target(uri);
    if (apiPath != null) {
        webTarget = webTarget.path(apiPath);
    }
    if(throwExceptionForErrors) {
        webTarget.register(ClientErrorResponseFilter.class);
    }
    webTarget.register(RequestIdClientFilter.class);
    webTarget.register(ClientNameFilter.class);
    if (logging) {
        webTarget.register(ClientLogFilter.class);
    }

    return WebResourceFactory.newResource(resource, webTarget, false, headerArg, cookies, new Form());
}
 
Example 14
Project: microprofile-jwt-auth   File: PrimitiveInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected sub claim is as expected")
public void verifyInjectedSUB() throws Exception {
    Reporter.log("Begin verifyInjectedSUB\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedSUB";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.sub.name(), "24400320")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 15
Project: Pet-Supply-Store   File: RegistryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test if unregistering a service actually removes it from the registry.
 */
@Test
public void testUnregisterSuccess() {
	 Response response1 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service2/abbaasd")
			 .request(MediaType.APPLICATION_JSON).put(Entity.text(""));
	 Assert.assertTrue(response1.getStatus() == Response.Status.OK.getStatusCode());
	 Response response2 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service2/abbaasd")
			 .request(MediaType.APPLICATION_JSON).delete();
	 Assert.assertTrue(response2.getStatus() == Response.Status.OK.getStatusCode());
	 Response response = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service2").request(MediaType.APPLICATION_JSON).get();
	 Assert.assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
	 List<String> list = response.readEntity(new GenericType<List<String>>() { }); 
	 Assert.assertTrue(list != null);
	 Assert.assertTrue(list.size() == 0);
}
 
Example 16
Project: taskana   File: TaskanaProducersTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRollback() throws SQLException, ClassNotFoundException, NamingException {
    Client client = ClientBuilder.newClient();
    client.target("http://127.0.0.1:8090/rest/test").request().post(null);

    Class.forName("org.h2.Driver");
    int resultCount = 0;
    try (Connection conn = DriverManager.getConnection("jdbc:h2:~/data/testdb;AUTO_SERVER=TRUE", "SA", "SA")) {
        ResultSet rs = conn.createStatement().executeQuery("SELECT ID, OWNER FROM TASK");

        while (rs.next()) {
            resultCount++;
        }
    }

    Assert.assertEquals(0, resultCount);
}
 
Example 17
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected sub claim is as expected")
public void verifyInjectedOptionalSubject() throws Exception {
    Reporter.log("Begin verifyInjectedOptionalSubject\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedOptionalSubject";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.sub.name(), "24400320")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 18
Project: open-kilda   File: TopologyHelp.java   Source Code and License 6 votes vote down vote up
/**
 * NB: This method calls TE, not Mininet
 *
 * @return The JSON document of the Topology from the Topology Engine
 */
public static String GetTopology() {
    System.out.println("\n==> Get Topology-Engine Topology");

    long current = System.currentTimeMillis();
    Client client = ClientBuilder.newClient(new ClientConfig());
    Response response = client
            .target(topologyEndpoint)
            .path("/api/v1/topology/network")
            .request()
            .get();

    System.out.println(String.format("===> Response = %s", response.toString()));
    System.out.println(String.format("===> Get Topology-Engine Topology Time: %,.3f", getTimeDuration(current)));
    String result = response.readEntity(String.class);
    System.out.println(String.format("====> Topology-Engine Topology = %s", result));

    return result;
}
 
Example 19
Project: open-kilda   File: TopologyHelp.java   Source Code and License 6 votes vote down vote up
/**
 * NB: This method calls TE, not Mininet
 *
 * @return The JSON document of the Topology from the Topology Engine
 */
public static String ClearTopology() {
    System.out.println("\n==> Clear Topology-Engine Topology");

    long current = System.currentTimeMillis();
    Client client = ClientBuilder.newClient(new ClientConfig());
    Response response = client
            .target(topologyEndpoint)
            .path("/api/v1/topology/clear")
            .request()
            .get();

    System.out.println(String.format("===> Response = %s", response.toString()));
    System.out.println(String.format("===> Clear Topology-Engine Topology Time: %,.3f", getTimeDuration(current)));
    String result = response.readEntity(String.class);
    System.out.println(String.format("====> Topology-Engine Topology = %s", result));
    return result;
}
 
Example 20
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected aud claim is as expected")
public void verifyInjectedAudience() throws Exception {
    Reporter.log("Begin verifyInjectedAudience\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    System.out.println(reply);
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 21
Project: dubbo2   File: RestClient.java   Source Code and License 6 votes vote down vote up
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 22
Project: mid-tier   File: AccountServiceExposureIT.java   Source Code and License 6 votes vote down vote up
@Test
public void testListAccounts() {
    WebTarget target = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/sample");
    Map<String, Object> response = target.path("accounts")
            .queryParam("customer", "1")
            .request()
            .accept("application/hal+json")
            .header("X-Client-Version", "1.0.0")
            .header("X-Service-Generation", "1")
            .header("X-Log-Token", DiagnosticContext.getLogToken())
            .get(Map.class);

    assertNotNull(response.get("_embedded"));
    Map<String, Object> embedded = (Map<String, Object>) response.get("_embedded");
    assertTrue(((List) embedded.get("accounts")).size() >= 2);
}
 
Example 23
Project: mid-tier   File: CustomerServiceExposureIT.java   Source Code and License 6 votes vote down vote up
@Ignore("Ignored because a valid OAuth endpoint is not supplied")
@Test
public void testEventCollections() throws UnsupportedEncodingException {
    WebTarget target = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/sample");
    String accessToken = requestAccessToken("tx-system-update");
    Map<String, Object> response = target.path("customer-events")
            .request()
            .accept("application/hal+json")
            .header("X-Client-Version", "1.0.0")
            .header("X-Service-Generation", "1")
            .header("X-Log-Token", DiagnosticContext.getLogToken())
            .header("Authorization", "Bearer " + accessToken)
            .get(Map.class);

    assertNotNull(response);
    assertNotNull(response.get("_links"));
    assertNotNull(response.get("_embedded"));
    Map<String, Object> embedded = (Map<String, Object>) response.get("_embedded");
    assertTrue(((List) embedded.get("events")).size() >= 2);
}
 
Example 24
Project: servicebuilder   File: ExceptionMapperAddonTest.java   Source Code and License 6 votes vote down vote up
@Test
public void userMessageException() {
    //Given
    when(testService.get()).thenThrow(new UserMessageException("Boooom!", 421));

    //when
    Response response = testServiceRunner.oneShot((clientconfig, uri) ->
            ClientBuilder.newClient(clientconfig).target(uri)
                    .path(TestService.PATH)
                    .request()
                    .get());

    //then
    ProblemResponse actual = response.readEntity(ProblemResponse.class);
    assertThat(actual.detail).isEqualTo("Boooom!");
    assertThat(actual.status).isEqualTo(421);
    assertThat(actual.suggestedUserMessageInDetail).isEqualTo(true);
    assertThat(response.getStatus()).isEqualTo(421);
}
 
Example 25
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected jti claim using @Claim(standard) is as expected")
public void verifyInjectedJTIStandard() throws Exception {
    Reporter.log("Begin verifyInjectedJTIStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedJTIStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.jti.name(), "a-123")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 26
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected raw token claim using @Claim(standard) is as expected")
public void verifyInjectedAuthTimeStandard() throws Exception {
    Reporter.log("Begin verifyInjectedAuthTimeStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedAuthTimeStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 27
Project: microprofile-jwt-auth   File: JsonValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customString claim is as expected from Token2")
public void verifyInjectedCustomString2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomString2\n");
    String token2 = TokenUtils.generateTokenString("/Token2.json");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomString";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "customStringValue2")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 28
Project: microprofile-jwt-auth   File: InvalidTokenTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_JAXRS,
    description = "Validate a request with an incorrect signer fails with HTTP_UNAUTHORIZED")
public void callEchoBadSigner() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    System.out.printf("jwt: %s\n", token);

    String uri = baseURL.toExternalForm() + "/endp/echo";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("input", "hello")
        ;
    Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_UNAUTHORIZED);
    String reply = response.readEntity(String.class);
    System.out.printf("Reply: %s\n", reply);
}
 
Example 29
Project: microprofile-jwt-auth   File: JsonValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customInteger claim is as expected from Token2")
public void verifyInjectedCustomInteger2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomInteger2\n");
    String token2 = TokenUtils.generateTokenString("/Token2.json");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomInteger";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 1234567892)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 30
Project: microprofile-jwt-auth   File: JsonValueInjectionTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customStringArray claim is as expected")
public void verifyInjectedCustomStringArray() throws Exception {
    Reporter.log("Begin verifyInjectedCustomStringArray\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedCustomStringArray";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "value0", "value1", "value2")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 31
Project: mid-tier   File: CustomerServiceExposureIT.java   Source Code and License 5 votes vote down vote up
private String requestAccessToken(final String username) throws UnsupportedEncodingException {
    WebTarget oauth2Service = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/security");
    MultivaluedMap<String, String> request = new MultivaluedHashMap<>();
    request.putSingle("grant_type", "client_credentials");
    String credentials = Base64.getEncoder().encodeToString((username + ":passw0rd").getBytes("UTF-8"));
    Map<String, String> oauthResponse = oauth2Service.path("oauth2/token")
            .request(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .header("Authorization", "Basic " + credentials)
            .header("X-Log-Token", DiagnosticContext.getLogToken())
            .header("X-Service-Generation", "1")
            .header("X-Client-Version", "1.0.0")
            .post(Entity.form(request), Map.class);
    return oauthResponse.get("access_token");
}
 
Example 32
Project: keycloak-jaxrs-client-authfilter   File: Keycloak.java   Source Code and License 5 votes vote down vote up
/**
 * Invoke the token web service with specified parameters.
 */
@Nullable
private AccessTokenResponse callTokenService( @Nonnull final MultivaluedMap<String, String> parameters )
{
  final ClientBuilder builder =
    ClientBuilder.newBuilder().register( JacksonFeature.class );
  final String clientSecret = _config.getClientSecret();
  if ( null != clientSecret )
  {
    builder.register( new BasicAuthFilter( _config.getClientID(), clientSecret ) );
  }
  final Client client = builder.build();
  try
  {
    final WebTarget target = client.
      target( _config.getServerUrl() ).
      path( "/realms/" ).path( _config.getRealm() ).path( "/protocol/openid-connect/token" );
    final Response response = target.
      request( MediaType.APPLICATION_FORM_URLENCODED ).
      accept( MediaType.APPLICATION_JSON ).
      post( Entity.form( parameters ) );
    if ( Response.Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily() )
    {
      return response.readEntity( AccessTokenResponse.class );
    }
    else
    {
      return null;
    }
  }
  finally
  {
    client.close();
  }
}
 
Example 33
Project: launcher-backend   File: MissionControl.java   Source Code and License 5 votes vote down vote up
private <T> T perform(Function<Client, T> request) {
    Client client = null;
    try {
        client = ClientBuilder.newClient();
        return request.apply(client);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
 
Example 34
Project: getting-started-microprofile   File: AuthorService.java   Source Code and License 5 votes vote down vote up
@Retry
@CircuitBreaker
@Fallback(fallbackMethod = "getCachedAuthor")
public Author findAuthor(String id) {
    Author author = ClientBuilder.newClient()
            .target(authorUrl)
            .path("/{id}")
            .resolveTemplate("id", id)
            .request(MediaType.APPLICATION_JSON)
            .get(Author.class);
    authorCache.put(id, author);
    return author;
}
 
Example 35
Project: Architecting-Modern-Java-EE-Applications   File: HelloCloudProcessor.java   Source Code and License 5 votes vote down vote up
@PostConstruct
private void initClient() {
    client = ClientBuilder.newBuilder()
            .connectTimeout(100, TimeUnit.MILLISECONDS)
            .readTimeout(2, TimeUnit.SECONDS)
            .build();
    target = client.target("http://cloud-processor:8080/processor/resources/hello");
}
 
Example 36
Project: http-bench   File: EchoResourceTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // start the server
    server = Server.startServer();

    // create the client
    Client c = ClientBuilder.newClient();
    target = c.target(Server.BASE_URI);
}
 
Example 37
Project: SER316-Dresden   File: HttpRequestService.java   Source Code and License 5 votes vote down vote up
private HttpRequestService() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    JacksonJsonProvider provider = new JacksonJsonProvider();
    provider.setMapper(objectMapper);

    client = ClientBuilder.newClient().register(provider);
}
 
Example 38
Project: athena   File: OnosXosIntegrationManager.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a client web resource builder for the base XOS REST API
 * with an optional additional URI.
 *
 * @return web resource builder
 * @deprecated in Cardinal Release
 */
@Deprecated
private Invocation.Builder getClientBuilder(String uri) {
    String baseUrl = "http://" + xosServerAddress + ":"
            + Integer.toString(xosServerPort);
    Client client = ClientBuilder.newClient();
    client.register(HttpAuthenticationFeature.basic("[email protected]", "letmein"));
    WebTarget wt = client.target(baseUrl
            + XOS_TENANT_BASE_URI + uri);
    return wt.request(JSON_UTF_8.toString());
}
 
Example 39
Project: Pet-Supply-Store   File: RegistryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test if registering fails if service is already registered.
 */
@Test
public void testRegisterFail() {
	 Response response1 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service4/abbaasda")
			 .request(MediaType.APPLICATION_JSON).put(Entity.text(""));
	 Assert.assertTrue(response1.getStatus() == Response.Status.OK.getStatusCode());
	 Response response2 = ClientBuilder.newBuilder().build().target("http://localhost:" 
			 + getTomcatPort() + "/test/rest/services/service4/abbaasda")
			 .request(MediaType.APPLICATION_JSON).put(Entity.text(""));
     Assert.assertTrue(response2.getStatus() == Response.Status.CONFLICT.getStatusCode());
}
 
Example 40
Project: CharmMylynConnector   File: CharmClient.java   Source Code and License 5 votes vote down vote up
public WebTarget buildWebTarget(String path) {

		Client client = ClientBuilder.newClient();

		return client.target(repository.getUrl()).path(path)
				.queryParam("sap-client", repository.getProperty(CharmCorePlugin.SETTING_CLIENT))
				.queryParam("sap-language", repository.getProperty(CharmCorePlugin.SETTING_LANGUAGE))
				.register(new BasicAuthenticator(repository.getCredentials(AuthenticationType.REPOSITORY).getUserName(),
						repository.getCredentials(AuthenticationType.REPOSITORY).getPassword()));

	}