下面列出了怎么用javax.ws.rs.client.ClientBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
private static Client getJAXRSClient(boolean skipSSLValidation) throws KeyManagementException, NoSuchAlgorithmException {
ClientBuilder cb = ClientBuilder.newBuilder();
cb.connectTimeout(10, TimeUnit.SECONDS);
Client newClient;
if (skipSSLValidation) {
SSLContext nullSSLContext = SSLContext.getInstance("TLSv1.2");
nullSSLContext.init(null, nullTrustManager, null);
cb.hostnameVerifier(NullHostnameVerifier.INSTANCE)
.sslContext(nullSSLContext);
newClient = cb.build();
} else {
newClient = cb.build();
}
newClient.register(JacksonJsonProvider.class);
return newClient;
}
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected aud claim is as expected")
public void verifyInjectedAudience2() 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();
Reporter.log(reply.toString());
Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
@PostConstruct
private void init() {
try {
InetAddress inetAddress = InetAddress.getByName(
((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
.getServerName());
baseUri = FacesContext.getCurrentInstance().getExternalContext().getRequestScheme() + "://"
+ inetAddress.getHostName() + ":"
+ FacesContext.getCurrentInstance().getExternalContext().getRequestServerPort()
+ "/jakartaee-cafe/rest/coffees";
this.client = ClientBuilder.newClient();
this.getAllCoffees();
} catch (IllegalArgumentException | NullPointerException | WebApplicationException | UnknownHostException ex) {
logger.severe("Processing of HTTP response failed.");
ex.printStackTrace();
}
}
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
description = "Validate specifying the mp.jwt.decrypt.key.location as resource path to a JWKS key")
public void testKeyAsLocation() throws Exception {
Reporter.log("testKeyAsLocation, expect HTTP_OK");
PublicKey publicKey = TokenUtils.readJwkPublicKey("/encryptorPublicKey.jwk");
String kid = "mp-jwt-set";
String token = TokenUtils.encryptClaims(publicKey, kid, "/Token1.json");
String uri = baseURL.toExternalForm() + "jwks/endp/verifyKeyLocationAsJWKSResource";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam("kid", kid);
Response response = echoEndpointTarget.request(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
public void testService() throws Exception
{
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9095/rest/mine/pairs");
Invocation.Builder request = target.request();
request.accept("application/json");
String rtn = request.get().readEntity(String.class);
String expected = "{\"key\":\"key22\",\"value\":\"value22\"}";
Assert.assertTrue("Expected json response", rtn.contains(expected));
target = client.target("http://localhost:9095/rest/mine/pairs");
request = target.request();
request.accept("application/xml");
rtn = request.get().readEntity(String.class);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(rtn.getBytes()));
Assert.assertTrue("Expected xml element",doc.getDocumentElement().getElementsByTagName("pair").getLength() == 23);
}
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
description = "Validate that JWK with iss that matches mp.jwt.verify.issuer returns HTTP_OK")
public void testRequiredIss() throws Exception {
Reporter.log("testRequiredIss, expect HTTP_OK");
String uri = baseURL.toExternalForm() + "endp/verifyIssIsOk";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
;
Response response = echoEndpointTarget.request(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
public void tesSubtractASyncTimeout() throws Exception {
final WebTarget webTarget = ClientBuilder.newClient().target(base.toURI());
final Response response = webTarget
.queryParam("op", "subtract")
.queryParam("x", "50")
.queryParam("y", "34")
.queryParam("async", "true")
.queryParam("delay", "10000")
.queryParam("timeout", "1000")
.request()
.accept(MediaType.MEDIA_TYPE_WILDCARD)
.get();
Assert.assertEquals(500, response.getStatus());
final InputStream is = (InputStream) response.getEntity();
final String responsePayload = IO.slurp(is);
System.out.println(responsePayload);
}
@Test
public void testNonExistentJaxrs20WithPost() throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://168.168.168.168/");
Invocation.Builder builder = target.request();
Entity<String> entity = Entity.entity("entity", MediaType.WILDCARD_TYPE);
Invocation invocation = builder.buildPost(entity);
Future<String> future = invocation.submit(
new GenericType<String>() {
}
);
try {
future.get();
} catch (Exception ex) {
Throwable cause = ex.getCause();
assertTrue(cause instanceof ProcessingException);
}
}
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();
}
}
private Response checkTokenExchange() {
Client httpClient = ClientBuilder.newClient();
WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
.path("/realms")
.path(TEST)
.path("protocol/openid-connect/token");
Response response = exchangeUrl.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-exchanger", "secret"))
.post(Entity.form(
new Form()
.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
.param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user")
));
return response;
}
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected exp claim is as expected")
public void verifyInjectedExpiration() throws Exception {
Reporter.log("Begin verifyInjectedExpiration\n");
String uri = baseURL.toExternalForm() + "endp/verifyInjectedExpiration";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.exp.name(), expClaim)
.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 @Ignore //Easy way to quickly upload an extension when running Application.main()
public void upload2Server() throws IOException {
URL driverClasspath = DriverUploadTest.class.getClassLoader().getResource(FILE_CLASSPATH);
assertThat(driverClasspath).isNotNull();
final WebTarget target = ClientBuilder.newClient()
.target(String.format("http://%s/api/v1/drivers",
"localhost:8080"));
MultipartFormDataOutput multipart = new MultipartFormDataOutput();
multipart.addFormData("fileName", "myExtDir", MediaType.TEXT_PLAIN_TYPE);
multipart.addFormData("file", driverClasspath.openStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE);
GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(multipart) {};
target.request().post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE),Boolean.class);
}
/**
* Returns the concept for the specified concept id.
*
* @param conceptId the concept id
* @return the concept for id
* @throws Exception the exception
*/
public Concept findByConceptId(String conceptId) throws Exception {
Logger.getLogger(getClass()).debug(
"Snomed Client - find concept by concept id " + conceptId);
validateNotEmpty(conceptId, "conceptId");
final Client client = ClientBuilder.newClient();
final WebTarget target = client.target(getUrl() + "/concepts/" + conceptId);
final Response response = target.request(MediaType.APPLICATION_JSON).get();
final String resultString = response.readEntity(String.class);
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
// n/a
} else {
throw new Exception(response.toString());
}
// converting to object
return Utility.getGraphForJson(resultString, Concept.class);
}
@Test
public void testGetPodcast() throws JsonGenerationException,
JsonMappingException, IOException {
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(JacksonFeature.class);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client
.target("http://localhost:8888/demo-rest-spring-jersey-jpa2-hibernate-0.0.1-SNAPSHOT/legacy/podcasts/2");
Builder request = webTarget.request(MediaType.APPLICATION_JSON);
Response response = request.get();
Assert.assertTrue(response.getStatus() == 200);
Podcast podcast = response.readEntity(Podcast.class);
ObjectMapper mapper = new ObjectMapper();
System.out
.print("Received podcast from LEGACY database *************************** "
+ mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(podcast));
}
@Test
public void testSuccess_postMethod_header() throws Exception {
Client client = ClientBuilder.newClient();
try {
AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);
WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
Response response = userInfoTarget.request()
.header(HttpHeaders.AUTHORIZATION, "bearer " + accessTokenResponse.getToken())
.post(Entity.form(new Form()));
testSuccessfulUserInfoResponse(response);
} finally {
client.close();
}
}
@Test
public void shouldGetStreamOfPrices() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(pricesUrl);
AtomicInteger priceCount = new AtomicInteger();
try (SseEventSource source = SseEventSource.target(target).build()) {
source.register(event -> {
Double value = event.readData(Double.class);
System.out.println("Received price: " + value);
priceCount.incrementAndGet();
});
source.open();
Thread.sleep(15 * 1000L);
} catch (InterruptedException ignored) {
}
int count = priceCount.get();
assertTrue(count > 1, "Expected more than 2 prices read from the source, got " + count);
}
WebTarget buildWebClient() throws Exception {
ClientConfig httpConfig = new ClientConfig();
httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
httpConfig.register(MultiPartFeature.class);
ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
.register(JacksonConfigurator.class).register(JacksonFeature.class);
SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
KEYSTORE_TYPE,
CLIENT_KEYSTORE_FILE_PATH,
CLIENT_KEYSTORE_PW,
KEYSTORE_TYPE,
BROKER_TRUSTSTORE_FILE_PATH,
BROKER_TRUSTSTORE_PW);
clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
Client client = clientBuilder.build();
return client.target(brokerUrlTls.toString());
}
@Override
public int getRunningCollectionsCountFromCollector() {
int runningCollections = 0;
try {
Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
WebTarget webResource = client.target(fetchMainUrl + "/manage/ping");
ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
Response clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
String jsonResponse = clientResponse.readEntity(String.class);
PingResponse pingResponse = objectMapper.readValue(jsonResponse, PingResponse.class);
if (pingResponse != null && "RUNNING".equals(pingResponse.getCurrentStatus())) {
runningCollections = Integer.parseInt(pingResponse.getRunningCollectionsCount());
}
} catch (Exception e) {
logger.error("Collector is not reachable");
}
return runningCollections;
}
@Test
@RunAsClient
@InSequence(1)
public void testCreateTicketClient() throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("<ticketDTO>");
sb.append("<price>12.00</price>");
sb.append("</ticketDTO>");
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080").path("tickets");
javax.ws.rs.core.Response response = target.request(MediaType.TEXT_XML)
.post(Entity.entity(sb.toString(), MediaType.TEXT_XML));
Assert.assertEquals(201, response.getStatus());
Assert.assertTrue(response.getHeaders().keySet().contains("Location"));
}
@Test
public void testAddASync() throws Exception {
final WebTarget webTarget = ClientBuilder.newClient().target(base.toURI());
final Response response = webTarget
.queryParam("op", "add")
.queryParam("x", "10")
.queryParam("y", "20")
.queryParam("async", "true")
.queryParam("delay", "2000")
.queryParam("timeout", "10000")
.request()
.accept(MediaType.MEDIA_TYPE_WILDCARD)
.get();
Assert.assertEquals(200, response.getStatus());
final InputStream is = (InputStream) response.getEntity();
final String responsePayload = IO.slurp(is);
Assert.assertEquals("30", responsePayload);
}
private TokenResponse retrieveAccessToken(String code) {
var tokenUrl = this.engine.getOAuthTokenUrl();
LOGGER.info("Trying to retrieve access token from {}", tokenUrl);
var uri =
UriBuilder.fromUri(tokenUrl)
.queryParam("grant_type", "authorization_code")
.queryParam("code", code)
.build();
var client =
ClientBuilder.newClient()
.register(
(ClientRequestFilter)
requestContext -> {
var headers = requestContext.getHeaders();
headers.add(
"Authorization",
"Basic "
+ Base64.getEncoder()
.encodeToString(
(this.engine.getOAuthClientId()
+ ":"
+ this.engine.getOAuthClientSecret())
.getBytes()));
})
.register(
(ClientResponseFilter)
(requestContext, responseContext) -> {
// stupid workaround because some oauth servers incorrectly sends two
// Content-Type
// headers! fix it!
var contentType = responseContext.getHeaders().getFirst("Content-Type");
responseContext.getHeaders().putSingle("Content-Type", contentType);
});
return client.target(uri).request().post(null, TokenResponse.class);
}
private static void getUser(String url) {
System.out.println("Getting user via " + url);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().get();
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 testGetBookWebTargetProvider() {
String address = "http://localhost:" + PORT + "/bookstore/bookheaders";
Client client = ClientBuilder.newClient();
client.register(new BookInfoReader());
BookInfo book = client.target(address).path("simple")
.request("application/xml").get(BookInfo.class);
assertEquals(124L, book.getId());
}
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
JsonMappingException, IOException {
ClientConfig clientConfig = new ClientConfig();
clientConfig.register(JacksonFeature.class);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client
.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");
Builder request = webTarget.request();
request.header("Content-type", MediaType.APPLICATION_JSON);
Response response = request.get();
Assert.assertTrue(response.getStatus() == 200);
List<Podcast> podcasts = response
.readEntity(new GenericType<List<Podcast>>() {
});
ObjectMapper mapper = new ObjectMapper();
System.out.print(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(podcasts));
Assert.assertTrue("At least one podcast is present in the LEGACY",
podcasts.size() > 0);
}
@Override
public String loadLatestTweetsWithCount(String code, int count)
throws AidrException {
Client client = ClientBuilder.newBuilder()
.register(JacksonFeature.class).build();
try {
String constraints = "{\"constraints\":[]}";
WebTarget webResource = client.target(outputAPIMainUrl
+ "/crisis/fetch/channel/filter/" + code + "?count="
+ count);
/*System.out.println("[loadLatestTweetsWithCount] Invoking: "
+ outputAPIMainUrl + "/crisis/fetch/channel/filter/" + code
+ "?count=" + count);
System.out.println("[loadLatestTweetsWithCount] constraints: "
+ constraints);*/
Response clientResponse = webResource.request(
MediaType.APPLICATION_JSON).post(Entity.json(constraints),
Response.class);
String jsonResponse = clientResponse.readEntity(String.class);
if (jsonResponse != null
&& (jsonResponse.startsWith("{") || jsonResponse
.startsWith("["))) {
/*System.out
.println("[loadLatestTweetsWithCount] jsonResponse for collection "
+ code + ": " + jsonResponse);*/
return jsonResponse;
} else {
/*System.out
.println("[loadLatestTweetsWithCount] jsonResponse for collection "
+ code + ": \"\"");*/
return "";
}
} catch (Exception e) {
logger.error("Error while loadLatestTweetsWithCount for collection: "+code, e);
throw new AidrException("Error while loadLatestTweetsWithCount", e);
}
}
private static void getUser(String url) {
System.out.println("Getting user via " + url);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().get();
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();
}
}
public WatcherClient(final String ip, final int port) {
client = ClientBuilder.newBuilder()
.register(ObjectMapperProvider.class)
.register(JacksonFeature.class)
.build();
service = client.target("http://" + ip + ":" + port);
}
@RunAsClient
@Test(groups = TCKConstants.TEST_GROUP_JACC,
description = "Validate a request with MP-JWT PolicyContext.getContext(javax.security.auth.Subject.containe) has a JsonWebToken")
public void getSubjectClass() throws Exception {
String uri = baseURL.toExternalForm() + "endp/getSubjectClass";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
;
Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
String reply = response.readEntity(String.class);
System.out.println(reply);
}
@Before
public void setUp() {
configureBean();
clientBuilder = spy(ClientBuilder.newBuilder());
JerseyClient client = mock(JerseyClient.class);
JerseyWebTarget listTarget = mock(JerseyWebTarget.class);
JerseyInvocation.Builder builder = mock(JerseyInvocation.Builder.class);
getInvocation = mock(JerseyInvocation.class);
JerseyInvocation postInvocation = mock(JerseyInvocation.class);
listResponse = mock(Response.class);
runResponse = mock(Response.class);
doReturn(listTarget).when(client).target(anyString());
doReturn(listTarget).when(listTarget).queryParam("job_id", configBean.jobId);
doReturn(builder).when(listTarget).request(MediaType.APPLICATION_JSON_TYPE);
doReturn(getInvocation).when(builder).buildGet();
doReturn(listResponse).when(getInvocation).invoke();
doReturn(postInvocation).when(builder).buildPost(any());
doReturn(runResponse).when(postInvocation).invoke();
doReturn(builder).when(listTarget).request();
doReturn(postInvocation).when(builder)
.buildPost(Entity.json((
new RunJarJobJson(configBean.jobId, configBean.jarParams))));
doReturn(client).when(clientBuilder).build();
}
protected Client createClient(Level clientLogLevel) {
ClientBuilder builder = ClientBuilder.newBuilder().register(MattermostModelMapperProvider.class)
.register(JacksonFeature.class);
if (clientLogLevel != null) {
builder.register(new LoggingFeature(Logger.getLogger(getClass().getName()), clientLogLevel,
Verbosity.PAYLOAD_ANY, 1000));
}
return builder.build();
}