/** * 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")); }
@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")); }
@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")); }
@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")); }
@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")); }
@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(); }
@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")); }
@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")); }
public void connect() throws IOException { ClientConfig configuration = new ClientConfig(); configuration.property(ClientProperties.READ_TIMEOUT, readTimeoutMillis); client = ClientBuilder.newBuilder() .withConfig(configuration) .hostnameVerifier(SSLHelper.newAllValidHostnameVerifier()) .sslContext(SSLHelper.newAllTrustingSSLContext("SSL")) .build(); if(REQUEST_LOGGER.isInfoEnabled()){ java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(REQUEST_LOGGER_NAME); client.register(new LoggingFeature(julLogger, Level.INFO, LoggingFeature.Verbosity.PAYLOAD_TEXT, 65536)); } final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(ElasticMappingSet.MAPPER); client.register(provider); if (username != null) { client.register(HttpAuthenticationFeature.basic(username, password)); } updateClients(); }
@RunAsClient @Test(groups = TEST_GROUP_CDI_PROVIDER, description = "Verify that the injected raw token claim is as expected") public void verifyInjectedRawToken() throws Exception { Reporter.log("Begin verifyInjectedRawToken\n"); String uri = baseURL.toExternalForm() + "/endp/verifyInjectedRawToken"; 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")); }
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; }
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()); }
@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")); }
/** * 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); }
@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); }
@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")); }
/** * 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; }
/** * 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; }
@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")); }
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(); } }
@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); }
@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); }
@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); }
@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")); }
@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")); }
@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")); }
@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")); }
@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); }
@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")); }
/** 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); }
@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")); }
protected static void initClient(ObjectMapper mapper) { JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(mapper); client = ClientBuilder.newBuilder().register(provider).register(MultiPartFeature.class).build(); rootTarget = client.target("http://localhost:" + currentDremioDaemon.getWebServer().getPort()); apiV2 = rootTarget.path(API_LOCATION); publicAPI = rootTarget.path(PUBLIC_API_LOCATION); if (isMultinode()) { masterApiV2 = client.target("http://localhost:" + masterDremioDaemon.getWebServer().getPort()).path(API_LOCATION); masterPublicAPI = client.target("http://localhost:" + masterDremioDaemon.getWebServer().getPort()).path(PUBLIC_API_LOCATION); } else { masterApiV2 = apiV2; masterPublicAPI = publicAPI; } }
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"); }
/** * 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(); } }
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(); } } }
@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; }
@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"); }
@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); }
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); }