本文整理汇总了Java中javax.ws.rs.client.WebTarget类的典型用法代码示例。如果您正苦于以下问题:Java WebTarget类的具体用法?Java WebTarget怎么用?Java WebTarget使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebTarget类属于javax.ws.rs.client包,在下文中一共展示了WebTarget类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testPost
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests creating an intent with POST.
*/
@Test
public void testPost() {
ApplicationId testId = new DefaultApplicationId(2, "myApp");
expect(mockCoreService.getAppId("myApp"))
.andReturn(testId);
replay(mockCoreService);
mockIntentService.submit(anyObject());
expectLastCall();
replay(mockIntentService);
InputStream jsonStream = IntentsResourceTest.class
.getResourceAsStream("post-intent.json");
WebTarget wt = target();
Response response = wt.path("intents")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertThat(location, Matchers.startsWith("/intents/myApp/"));
}
示例2: testSingleHostByMacAndVlanFetch
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests fetch of one host by mac and vlan.
*/
@Test
public void testSingleHostByMacAndVlanFetch() {
final ProviderId pid = new ProviderId("of", "foo");
final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01");
final Set<IpAddress> ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::"));
final Host host1 =
new DefaultHost(pid, HostId.hostId(mac1), valueOf(1), vlanId((short) 1),
new HostLocation(DeviceId.deviceId("1"), portNumber(11), 1),
ips1);
hosts.add(host1);
expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1")))
.andReturn(host1)
.anyTimes();
replay(mockHostService);
WebTarget wt = target();
String response = wt.path("hosts/00:00:11:00:00:01/1").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, matchesHost(host1));
}
示例3: doScore
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
@Override
Scores doScore(Scores inputScores, Rankable target) {
List<TextPair> pairs = inputScores.stream()
.map(score -> new TextPair(score.getRankableView().getValue(), target.getValue()))
.collect(Collectors.toList());
RelatednessRequest request = new RelatednessRequest()
.corpus(params.getCorpus())
.language(params.getLanguage())
.scoreFunction(params.getScoreFunction())
.model(params.getRankingModel().name())
.pairs(pairs);
WebTarget webTarget = client.target(params.getUrl());
RelatednessResponse response = webTarget.request()
.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE), RelatednessResponse.class);
Scores rescored = new Scores(inputScores.size());
response.getPairs().forEach(p -> rescored.addAll(find(inputScores, p.t1, p.score)));
rescored.sort(true);
return rescored;
}
示例4: testAuthWithUser
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
@Test
public void testAuthWithUser() throws MalformedURLException {
LOG.log(Level.INFO, "base url @{0}", base);
//get an authentication
final WebTarget targetAuth = client.target(URI.create(new URL(base, "api/auth/login").toExternalForm()));
String token;
try (Response resAuth = targetAuth.request().post(form(new Form().param("username", "user").param("password", "password")))) {
assertEquals(200, resAuth.getStatus());
token = (String) resAuth.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
LOG.log(Level.INFO, "resAuth.getHeaders().getFirst(\"Bearer\"):{0}", token);
assertTrue(token != null);
}
client.register(new JwtTokenAuthentication(token.substring(AUTHORIZATION_PREFIX.length())));
final WebTarget targetUser = client.target(URI.create(new URL(base, "api/auth/userinfo").toExternalForm()));
try (Response resUser = targetUser.request().accept(MediaType.APPLICATION_JSON_TYPE).get()) {
assertEquals(200, resUser.getStatus());
final UserInfo userInfo = resUser.readEntity(UserInfo.class);
LOG.log(Level.INFO, "get user info @{0}", userInfo);
assertTrue("user".equals(userInfo.getName()));
}
}
示例5: verifyInjectedCustomString2
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
@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"));
}
示例6: testSingleSubjectSingleConfig
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests the result of the rest api single subject single config GET when
* there is a config.
*/
@Test
public void testSingleSubjectSingleConfig() {
setUpConfigData();
final WebTarget wt = target();
final String response =
wt.path("network/configuration/devices/device1/basic")
.request()
.get(String.class);
final JsonObject result = Json.parse(response).asObject();
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.names(), hasSize(2));
checkBasicAttributes(result);
}
示例7: testMcastRoutePost
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests creating a Mcast route with POST.
*/
@Test
public void testMcastRoutePost() {
mockMulticastRouteService.add(anyObject());
expectLastCall();
replay(mockMulticastRouteService);
WebTarget wt = target();
InputStream jsonStream = MulticastRouteResourceTest.class
.getResourceAsStream("mcastroute.json");
Response response = wt.path("mcast/")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
verify(mockMulticastRouteService);
}
示例8: testDelete
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests deleting a port pair group.
*/
@Test
public void testDelete() {
expect(portPairGroupService.removePortPairGroup(anyObject()))
.andReturn(true).anyTimes();
replay(portPairGroupService);
WebTarget wt = target();
String location = "port_pair_groups/4512d643-24fc-4fae-af4b-321c5e2eb3d1";
Response deleteResponse = wt.path(location)
.request(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_PLAIN_TYPE)
.delete();
assertThat(deleteResponse.getStatus(),
is(HttpURLConnection.HTTP_NO_CONTENT));
}
示例9: testPostVirtualLinkNullJsonStream
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests adding of a null virtual link using POST via JSON stream.
*/
@Test
public void testPostVirtualLinkNullJsonStream() {
NetworkId networkId = networkId3;
replay(mockVnetAdminService);
WebTarget wt = target();
try {
String reqLocation = "vnets/" + networkId.toString() + "/links";
wt.path(reqLocation)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(null), String.class);
fail("POST of null virtual link did not throw an exception");
} catch (BadRequestException ex) {
assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request"));
}
verify(mockVnetAdminService);
}
示例10: getEntityWithProperty
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Returns an Entity of the relevant type by using a unique non-primary-key property.
* Example: Get user with user name.
* Note that the AbstractCRUDEndpoint does not offer this feature by default.
* @param client The REST client to use.
* @param propertyURI Name of the property. E.g., "name".
* @param propertyValue Value of the property, e.g., "user1".
* @param <T> Type of entity to handle.
* @throws NotFoundException If 404 was returned.
* @throws TimeoutException If 408 was returned.
* @return The entity; null if it does not exist.
*/
public static <T> T getEntityWithProperty(RESTClient<T> client, String propertyURI,
String propertyValue) throws NotFoundException, TimeoutException {
WebTarget target = client.getService().path(client.getApplicationURI())
.path(client.getEndpointURI()).path(propertyURI).path(propertyValue);
Response response = target.request(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException();
} else if (response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
throw new TimeoutException();
}
T entity = null;
try {
entity = response.readEntity(client.getEntityClass());
} catch (NullPointerException | ProcessingException e) {
//This happens if no entity was found
}
if (response != null) {
response.close();
}
return entity;
}
示例11: testServerIsMissedError
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
@Test
public void testServerIsMissedError() throws InstantiationException, IllegalAccessException {
IfExpressionBuilder builder = new IfExpressionBuilder();
IfExpression expression = builder.
withRuleName("testServerIsMissedError").
withExpression(newSingleParamExpression(Equals.class, "param1", "value1")).build();
// now trying to post rule with invalid name
WebTarget webTarget = HttpTestServerHelper.target().path(RULES_SERVICE_PATH).path(SERVICE_NAME).path(expression.getId());
ValidationState error = ServiceHelper.post(webTarget, expression, MediaType.APPLICATION_JSON, ValidationState.class, true);
// should get error ValidationState.ErrorType.InvalidRuleName
Assert.assertEquals(1, error.getErrors().size());
Assert.assertEquals(ValidationState.ErrorType.ServerIsMissed, error.getErrors().keySet().iterator().next());
}
示例12: testAddDevicesPost
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/**
* Tests adding a set of devices in region with POST.
*/
@Test
public void testAddDevicesPost() {
mockRegionAdminService.addDevices(anyObject(), anyObject());
expectLastCall();
replay(mockRegionAdminService);
WebTarget wt = target();
InputStream jsonStream = RegionsResourceTest.class
.getResourceAsStream("region-deviceIds.json");
Response response = wt.path("regions/" +
region1.id().toString() + "/devices")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
verify(mockRegionAdminService);
}
示例13: testTemplateDependsOnTemplateError
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
@Test
public void testTemplateDependsOnTemplateError() throws InstantiationException, IllegalAccessException {
IfExpressionBuilder builder = new IfExpressionBuilder();
IfExpression expression = builder.
withRuleName("testTemplateDependsOnTemplateError").
withTemplateName("template").
withExpression(newSingleParamExpression(Equals.class, "param1", "value1")).
withExpression(newSingleParamExpression(Matches.class, "param2", "value2")).
withExpression(newSingleParamExpression(NotEqual.class, "param3", "value3")).
withExpression(newSingleParamExpression(LessThan.class, "param4", "4")).
withReturnStatement(newSimpleServerForFlavor("1.1")).build();
// now trying to post rule with invalid name
WebTarget webTarget = HttpTestServerHelper.target().path(TEMPLATES_RULE_SERVICE_PATH).path(SERVICE_NAME).path(expression.getId());
ValidationState error = ServiceHelper.post(webTarget, expression, MediaType.APPLICATION_JSON, ValidationState.class, true);
// should get error ValidationState.ErrorType.InvalidRuleName
Assert.assertEquals(2, error.getErrors().size());
Assert.assertTrue(error.getErrors().containsKey(ValidationState.ErrorType.TemplateDependsOnTemplate));
}
示例14: makeConnection
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
/** Make an HTTP connection to the specified URL and pass in the specified payload. */
private static Response makeConnection(
String method, String urlString, String payload, String jwt)
throws IOException, GeneralSecurityException {
// Setup connection
System.out.println("Creating connection - Method: " + method + ", URL: " + urlString);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(urlString);
Invocation.Builder invoBuild = target.request(MediaType.APPLICATION_JSON_TYPE);
if (jwt != null) {
invoBuild.header("Authorization", jwt);
}
if (payload != null) {
System.out.println("Request Payload: " + payload);
Entity<String> data = Entity.entity(payload, MediaType.APPLICATION_JSON_TYPE);
return invoBuild.build(method, data).invoke();
} else {
return invoBuild.build(method).invoke();
}
}
示例15: processRequest
import javax.ws.rs.client.WebTarget; //导入依赖的package包/类
public static Response processRequest(
String url, String method, String payload, String authHeader) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Builder builder = target.request();
builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
if (authHeader != null) {
builder.header(HttpHeaders.AUTHORIZATION, authHeader);
}
return (payload != null)
? builder.build(method, Entity.json(payload)).invoke()
: builder.build(method).invoke();
}