下面列出了javax.ws.rs.client.Client#target ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Calls the manager's public collection REST API.
* @return publiclyListed value of given channel name
*/
@SuppressWarnings("unchecked")
public Boolean getChannelPublicStatus(String channelName) {
String channelCode = parseChannelName(channelName);
Response clientResponse = null;
Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
try {
WebTarget webResource = client.target(managerMainUrl
+ "/public/collection/getChannelPublicFlagStatus?channelCode=" + channelCode);
clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
Map<String, Boolean> collectionMap = new HashMap<String, Boolean>();
if (clientResponse.getStatus() == 200) {
//convert JSON string to Map
collectionMap = clientResponse.readEntity(Map.class);
logger.info("Channel info received from manager: " + collectionMap);
if (collectionMap != null) {
return collectionMap.get(channelCode);
}
} else {
logger.warn("Couldn't contact AIDRFetchManager for publiclyListed status, channel: " + channelName);
}
} catch (Exception e) {
logger.error("Error in querying manager for running collections: " + clientResponse);
}
return true; // Question: should default be true or false?
}
/**
* This test checks that we do not lose track of registered interceptors
* on the original client implementation after we create a new impl with
* the path(...) method - particularly when the path passed in to the
* path(...) method contains a template.
*/
@Test
public void testClientConfigCopiedOnPathCallWithTemplates() {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/");
WebClient webClient = getWebClient(webTarget);
ClientConfiguration clientConfig = WebClient.getConfig(webClient);
clientConfig.setOutInterceptors(Arrays.asList(new MyInterceptor()));
assertTrue("Precondition failed - original WebTarget is missing expected interceptor",
doesClientConfigHaveMyInterceptor(webClient));
WebTarget webTargetAfterPath = webTarget.path("/rest/{key}/").resolveTemplate("key", "myKey");
WebClient webClientAfterPath = getWebClient(webTargetAfterPath);
assertTrue("New WebTarget is missing expected interceptor specified on 'parent' WebTarget's client impl",
doesClientConfigHaveMyInterceptor(webClientAfterPath));
}
@Test
public void testBadUser() {
Client client = ClientBuilder.newClient();
URI uri = OIDCLoginProtocolService.tokenUrl(authServerPage.createUriBuilder()).build("demo");
WebTarget target = client.target(uri);
String header = BasicAuthHelper.createHeader("customer-portal", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "[email protected]")
.param("password", "password");
Response response = target.request()
.header(HttpHeaders.AUTHORIZATION, header)
.post(Entity.form(form));
assertEquals(401, response.getStatus());
response.close();
client.close();
}
@Test
public void testResponse() throws Exception
{
// fill out a query param and execute a get request
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9095/customers");
Response response = target.queryParam("name", "Bill").request().get();
try
{
Assert.assertEquals(200, response.getStatus());
Customer cust = response.readEntity(Customer.class);
Assert.assertEquals("Bill", cust.getName());
}
finally
{
response.close();
client.close();
}
}
@Test
public void testCustomer() throws Exception
{
// fill out a query param and execute a get request
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9095/customers");
try
{
// extract customer directly expecting success
Customer cust = target.queryParam("name", "Bill").request().get(Customer.class);
Assert.assertEquals("Bill", cust.getName());
}
finally
{
client.close();
}
}
@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
public void corsTest() {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(OAuthClient.AUTH_SERVER_ROOT);
URI oidcDiscoveryUri = RealmsResource.wellKnownProviderUrl(builder).build("test", OIDCWellKnownProviderFactory.PROVIDER_ID);
WebTarget oidcDiscoveryTarget = client.target(oidcDiscoveryUri);
Invocation.Builder request = oidcDiscoveryTarget.request();
request.header(Cors.ORIGIN_HEADER, "http://somehost");
Response response = request.get();
assertEquals("http://somehost", response.getHeaders().getFirst(Cors.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testJaxRSClientPUT() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(SAY_HELLO_URL);
Response response = target.request().header("test-header", "test-value").put(Entity.<String> text(SAY_HELLO));
processResponse(response, false, false, false);
}
public Response sendRequest(String url, String requestType) {
Client client = ClientBuilder.newClient();
System.out.println("Testing " + url);
WebTarget target = client.target(url);
Invocation.Builder invoBuild = target.request();
Response response = invoBuild.build(requestType).invoke();
return response;
}
private < E > E getObjectFromEndpoint(Class<E> klass, String extension, MediaType mediaType) {
String port = System.getProperty("liberty.test.port");
String url = "http://localhost:" + port + endpoint + extension;
System.out.println("Getting object from url " + url);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Invocation.Builder invoBuild = target.request();
E object = invoBuild.accept(mediaType).get(klass);
client.close();
return object;
}
public static void delete(String resourceUrl, String id, Class clazz) throws BlockCypherException {
Client client = ClientBuilder.newClient(new ClientConfig());
WebTarget webTarget = client.target(resourceUrl);
delete(webTarget, clazz);
}
private static WebTarget newApiV2Target(Client client, DACDaemon daemon) {
WebTarget rootTarget = client.target("http://localhost:" + daemon.getWebServer().getPort());
return rootTarget.path(API_LOCATION);
}
@Before
public void setUp() throws MalformedURLException {
Client client = ClientBuilder.newClient();
target = client.target(URI.create(new URL(base, "registry/employee").toExternalForm()));
target.register(Employee.class);
}
@Test
public void testDirectGrantHttpChallengeUserDisabled() {
setupBruteForce();
Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
WebTarget grantTarget = httpClient.target(grantUri);
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);
UserRepresentation user = adminClient.realm("test").users().search("[email protected]").get(0);
user.setEnabled(false);
adminClient.realm("test").users().get(user.getId()).update(user);
// user disabled
Response response = grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password"))
.post(Entity.form(form));
assertEquals(401, response.getStatus());
assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
response.close();
user.setEnabled(true);
adminClient.realm("test").users().get(user.getId()).update(user);
// lock the user account
grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "wrongpassword"))
.post(Entity.form(form));
grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "wrongpassword"))
.post(Entity.form(form));
// user is temporarily disabled
response = grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password"))
.post(Entity.form(form));
assertEquals(401, response.getStatus());
assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
response.close();
clearBruteForce();
httpClient.close();
events.clear();
}
@Test
public void runAppAndBasicTest() throws InterruptedException, ExecutionException{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("http://localhost:8080/simple-app/single/ping");
Builder request = resource.request();
request.accept(MediaType.TEXT_PLAIN);
assertFalse(request.get().getHeaders().containsKey("Access-Control-Allow-Origin"));
}
public<T> T post(String url, Object payload,Class<T> type) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}
public String post(String url) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
return request.post(null, String.class);
}
public String getJson(String url) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
return request.get(String.class);
}
public String get(String url) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.TEXT_PLAIN);
return request.get(String.class);
}
public<T> T post(String url, Object payload,Class<T> type) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}