當前位置: 首頁>>代碼示例>>Java>>正文


Java WebTarget類代碼示例

本文整理匯總了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/"));
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:26,代碼來源:IntentsResourceTest.java

示例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));
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:26,代碼來源:HostResourceTest.java

示例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;
}
 
開發者ID:Lambda-3,項目名稱:Stargraph,代碼行數:24,代碼來源:IndraRanker.java

示例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()));
    }

}
 
開發者ID:hantsy,項目名稱:javaee8-jaxrs-sample,代碼行數:26,代碼來源:AuthResourceIT.java

示例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"));
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:19,代碼來源:ProviderInjectionTest.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:21,代碼來源:NetworkConfigWebResourceTest.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:21,代碼來源:MulticastRouteResourceTest.java

示例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));
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:20,代碼來源:PortPairGroupResourceTest.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:22,代碼來源:VirtualNetworkWebResourceTest.java

示例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;
}
 
開發者ID:DescartesResearch,項目名稱:Pet-Supply-Store,代碼行數:34,代碼來源:NonBalancedCRUDOperations.java

示例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());
}
 
開發者ID:Comcast,項目名稱:redirector,代碼行數:17,代碼來源:RuleNameIntegrationTest.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:22,代碼來源:RegionsResourceTest.java

示例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));
}
 
開發者ID:Comcast,項目名稱:redirector,代碼行數:23,代碼來源:RuleNameIntegrationTest.java

示例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();
  }
}
 
開發者ID:OpenLiberty,項目名稱:sample-acmegifts,代碼行數:25,代碼來源:DemoData.java

示例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();
}
 
開發者ID:OpenLiberty,項目名稱:sample-acmegifts,代碼行數:14,代碼來源:LoginResourceTest.java


注:本文中的javax.ws.rs.client.WebTarget類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。