Java 类javax.ws.rs.client.ClientBuilder 实例源码
项目:Pet-Supply-Store
文件:RegistryTest.java
/**
* 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"));
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:ProviderInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:ProviderInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:JsonValueInjectionTest.java
@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"));
}
项目:reactive-components
文件:TestRs.java
@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();
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:ProviderInjectionTest.java
@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"));
}
项目:dremio-oss
文件:ElasticConnectionPool.java
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();
}
项目:microprofile-jwt-auth
文件:PrimitiveInjectionTest.java
@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"));
}
项目:open-kilda
文件:FlowFFRTest.java
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;
}
项目:servicebuilder
文件:StubGenerator.java
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());
}
项目:microprofile-jwt-auth
文件:PrimitiveInjectionTest.java
@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"));
}
项目:Pet-Supply-Store
文件:RegistryTest.java
/**
* 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);
}
项目:taskana
文件:TaskanaProducersTest.java
@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);
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:open-kilda
文件:TopologyHelp.java
/**
* 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;
}
项目:open-kilda
文件:TopologyHelp.java
/**
* 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;
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:dubbo2
文件:RestClient.java
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();
}
}
项目:mid-tier
文件:AccountServiceExposureIT.java
@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);
}
项目:mid-tier
文件:CustomerServiceExposureIT.java
@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);
}
项目:servicebuilder
文件:ExceptionMapperAddonTest.java
@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);
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:ClaimValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:JsonValueInjectionTest.java
@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"));
}
项目:microprofile-jwt-auth
文件:InvalidTokenTest.java
@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);
}
项目:microprofile-jwt-auth
文件:JsonValueInjectionTest.java
@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"));
}
项目:radiobrowser4j
文件:RadioBrowser.java
/** 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);
}
项目:microprofile-jwt-auth
文件:JsonValueInjectionTest.java
@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"));
}
项目:dremio-oss
文件:BaseTestServer.java
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;
}
}
项目:mid-tier
文件:CustomerServiceExposureIT.java
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");
}
项目:keycloak-jaxrs-client-authfilter
文件:Keycloak.java
/**
* 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();
}
}
项目:launcher-backend
文件:MissionControl.java
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();
}
}
}
项目:getting-started-microprofile
文件:AuthorService.java
@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;
}
项目:Architecting-Modern-Java-EE-Applications
文件:HelloCloudProcessor.java
@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");
}
项目:http-bench
文件:EchoResourceTest.java
@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);
}
项目:SER316-Dresden
文件:HttpRequestService.java
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);
}