Java 类javax.ws.rs.client.WebTarget 实例源码

项目:athena    文件:HostResourceTest.java   
/**
 * 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));
}
项目:athena    文件:IntentsResourceTest.java   
/**
 * 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/"));
}
项目:Stargraph    文件:IndraRanker.java   
@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;
}
项目:javaee8-jaxrs-sample    文件:AuthResourceIT.java   
@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()));
    }

}
项目: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"));
}
项目:athena    文件:NetworkConfigWebResourceTest.java   
/**
 * 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);
}
项目:athena    文件:MulticastRouteResourceTest.java   
/**
 * 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);
}
项目:athena    文件:PortPairGroupResourceTest.java   
/**
 * 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));
}
项目:athena    文件:VirtualNetworkWebResourceTest.java   
/**
 * 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);
}
项目:Pet-Supply-Store    文件:NonBalancedCRUDOperations.java   
/**
 * 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;
}
项目:redirector    文件:RuleNameIntegrationTest.java   
@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());
}
项目:athena    文件:RegionsResourceTest.java   
/**
 * 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);
}
项目:redirector    文件:RuleNameIntegrationTest.java   
@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));
}
项目:sample-acmegifts    文件:DemoData.java   
/** 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();
  }
}
项目:sample-acmegifts    文件:LoginResourceTest.java   
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();
}
项目:Graphene    文件:Coreference.java   
private InternalCoreferenceResponse sendRequest(WebTarget target, InternalCoreferenceRequest request) {

        log.debug("Sending coreference request to {}", target.getUri().toString());

        final Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));

        if (response.hasEntity()) {
            if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {

                return response.readEntity(InternalCoreferenceResponse.class);

            } else {
                log.error(
                        "A request was sent, but the response code was '{}: {}'",
                        response.getStatusInfo().getStatusCode(),
                        response.getStatusInfo().getReasonPhrase());
            }
        } else {
            log.error("The response has no entity.");
        }

        throw new RuntimeException("The response contained no content.");
    }
项目:auto-questions-service    文件:NLPServiceClient.java   
static NLP getNlp(String deckID) {
    Client client = ClientBuilder.newClient();
    String hostIp = "https://nlpstore.experimental.slidewiki.org/nlp/" + deckID;
    WebTarget webTarget = client.target(hostIp);
    NLP nlp = webTarget
            .request(MediaType.APPLICATION_JSON)
            .get(NLP.class);
    if (nlp == null) {
        hostIp = "https://nlpservice.experimental.slidewiki.org/nlp/nlpForDeck/" + deckID;
        webTarget = client.target(hostIp);
        nlp = webTarget
                .queryParam(DBPEDIA_SPOTLIGHT_CONFIDENCE_FOR_SLIDE, SPOTLIGHT_CONFIDENCE_FOR_SLIDE_VALUE)
                .queryParam(DBPEDIA_SPOTLIGHT_CONFIDENCE_FOR_DECK, SPOTLIGHT_CONFIDENCE_FOR_DECK_VALUE)
                .request(MediaType.APPLICATION_JSON)
                .get(NLP.class);
    }
    return nlp;
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected iat claim using @Claim(standard) is as expected")
public void verifyInjectedIssuedAtStandard() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAtStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedIssuedAtStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iat.name(), iatClaim)
        .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    文件:PrimitiveInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customString claim is as expected")
public void verifyInjectedCustomString() 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    文件:ClaimValueInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected iat claim is as expected")
public void verifyInjectedIssuedAt() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAt\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedIssuedAt";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iat.name(), iatClaim)
        .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"));
}
项目:athena    文件:FlowObjectiveResourceTest.java   
/**
 * A base class for testing various objective creation.
 *
 * @param jsonFile json file path
 * @param deviceId device id in string format
 * @param method objective method
 */
private void testObjectiveCreation(String jsonFile, String deviceId, String method) {
    WebTarget wt = target();
    InputStream jsonStream = FlowsResourceTest.class
            .getResourceAsStream(jsonFile);

    StringBuilder sb = new StringBuilder();
    sb.append("flowobjectives");
    sb.append("/");
    sb.append(deviceId);
    sb.append("/");
    sb.append(method);

    Response response = wt.path(sb.toString())
            .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("/" + sb.toString()));
}
项目:athena    文件:PortChainResourceTest.java   
/**
 * Tests creating a port chain with POST.
 */
@Test
public void testPost() {

    expect(portChainService.createPortChain(anyObject()))
    .andReturn(true).anyTimes();
    replay(portChainService);

    WebTarget wt = target();
    InputStream jsonStream = PortChainResourceTest.class.getResourceAsStream("post-PortChain.json");

    Response response = wt.path("port_chains")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(jsonStream));
    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));
}
项目:microprofile-jwt-auth    文件:JsonValueInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    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();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
项目: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    文件:JsonValueInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected iat claim is as expected")
public void verifyInjectedIssuedAt() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAt\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedIssuedAt";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iat.name(), iatClaim)
        .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"));
}
项目:oscm    文件:BillingPluginTest.java   
@Test
public void testConnection() throws Exception {

    // given
    String testConnectionUrl = "http://localhost:8680/oscm-file-billing/rest/ping";
    Mockito.doReturn(testConnectionUrl).when(properties)
            .getConfigProperty(BillingPlugin.TEST_CONNECTION_URL);

    // when
    billingPlugin.testConnection();

    // then
    verify(properties, times(1)).getConfigProperty(anyString());
    verify(restDao, times(1)).createWebResource(testConnectionUrl);
    verify(restDao, times(1)).getTextResponse(any(WebTarget.class));
}
项目:athena    文件:VirtualNetworkWebResourceTest.java   
/**
 * Tests adding of new virtual device using POST via JSON stream.
 */
@Test
public void testPostVirtualDevice() {
    NetworkId networkId = networkId3;
    DeviceId deviceId = devId2;
    expect(mockVnetAdminService.createVirtualDevice(networkId, deviceId)).andReturn(vdev2);
    expectLastCall();

    replay(mockVnetAdminService);

    WebTarget wt = target();
    InputStream jsonStream = VirtualNetworkWebResourceTest.class
            .getResourceAsStream("post-virtual-device.json");
    String reqLocation = "vnets/" + networkId.toString() + "/devices";
    Response response = wt.path(reqLocation).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("/" + reqLocation + "/" + vdev2.id().toString()));

    verify(mockVnetAdminService);
}
项目:microprofile-jwt-auth    文件:ProviderInjectionTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected jti claim is as expected")
public void verifyInjectedJTI() throws Exception {
    Reporter.log("Begin verifyInjectedJTI\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedJTI";
    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"));
}
项目:athena    文件:MetersResourceTest.java   
/**
 * Tests the results of a rest api GET for a device.
 */
@Test
public void testMeterSingleDevice() {
    setupMockMeters();

    final Set<Meter> meters1 = new HashSet<>();
    meters1.add(meter1);
    meters1.add(meter2);

    expect(mockMeterService.getMeters(anyObject())).andReturn(meters1).anyTimes();
    replay(mockMeterService);
    replay(mockDeviceService);

    final WebTarget wt = target();
    final String response = wt.path("meters/" + deviceId1.toString()).request().get(String.class);
    final JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    assertThat(result.names(), hasSize(1));
    assertThat(result.names().get(0), is("meters"));
    final JsonArray jsonMeters = result.get("meters").asArray();
    assertThat(jsonMeters, notNullValue());
    assertThat(jsonMeters, hasMeter(meter1));
    assertThat(jsonMeters, hasMeter(meter2));
}
项目:microprofile-jwt-auth    文件:RequiredClaimsTest.java   
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
        description = "Verify that the token sub claim is as expected")
public void verifySubClaim() throws Exception {
    Reporter.log("Begin verifySubClaim");
    String uri = baseURL.toExternalForm() + "/endp/verifySUB";
    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"));
}
项目:athena    文件:PortPairGroupResourceTest.java   
/**
 * Tests the result of a rest api GET for port pair group id.
 */
@Test
public void testGetPortPairGroupId() {

    final Set<PortPairGroup> portPairGroups = new HashSet<>();
    portPairGroups.add(portPairGroup1);

    expect(portPairGroupService.exists(anyObject())).andReturn(true).anyTimes();
    expect(portPairGroupService.getPortPairGroup(anyObject())).andReturn(portPairGroup1).anyTimes();
    replay(portPairGroupService);

    final WebTarget wt = target();
    final String response = wt.path("port_pair_groups/4512d643-24fc-4fae-af4b-321c5e2eb3d1")
            .request().get(String.class);
    final JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());
}
项目:mid-tier    文件:CustomerServiceExposureIT.java   
@Test
public void testGetCustomer() {
    WebTarget target = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/sample");
    Map<String, Object> response = target.path("customers/9999999999")
            .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);

    assertEquals("Ole", response.get("firstName"));
    assertEquals("Bent", response.get("middleName"));
    assertEquals("Pedersen", response.get("sirname"));
    assertEquals("9999999999", response.get("number"));
}
项目:holon-jaxrs    文件:TestSwaggerResteasyAutoConfiguration.java   
@Test
public void testSwaggerJson() {
    Client client = new ResteasyClientBuilder().build();
    WebTarget target = client.target("http://localhost:" + port + "/docs");
    Response response = target.request().get();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertNotNull(response.readEntity(String.class));
    Assert.assertEquals("application/json", response.getMediaType().toString());
}
项目:cloudkarafka-broker    文件:CloudKarafkaAdminService.java   
/**
 * Check if Broker Instance exists
 *
 * @param brokerName
 * @return
 * @throws CloudKarafkaServiceException
 */
public boolean brokerInstanceExists(final String brokerName) throws CloudKarafkaServiceException {
    final String target = String.format("%s/%s", brokerConfig.getCloudkarafkaApiUrl(), "instances");
    final WebTarget webTarget = client.target(target);

    // call create broker instances API
    final CloudKarafkaInstance[] response = webTarget.request(MediaType.APPLICATION_JSON)
            .get(CloudKarafkaInstance[].class);

    // filter brokers list to find the one with the given id
    final CloudKarafkaInstance inst = Arrays.stream(response).filter(x -> x.getId().equals(brokerName)).findAny().orElse(null);

    return inst != null;
}
项目:athena    文件:BadRequestTest.java   
/**
 * Tests the response for a request with a bad method.
 */
@Test
public void badMethod() {
    WebTarget wt = target();
    try {
        wt.path("hosts").request().delete(String.class);
        fail("Fetch of non-existent URL did not throw an exception");
    } catch (NotAllowedException ex) {
        assertThat(ex.getMessage(),
                containsString("HTTP 405 Method Not Allowed"));
    }
}
项目:syndesis    文件:ExternalVerifierService.java   
@Override
public List<Result> verify(String connectorId, Map<String, String> options) {
    final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider();
    resteasyJacksonProvider.setMapper(MAPPER);

    final ResteasyProviderFactory providerFactory = ResteasyProviderFactory.newInstance();
    providerFactory.register(resteasyJacksonProvider);
    final Configuration configuration = new LocalResteasyProviderFactory(providerFactory);

    Client client = ClientBuilder.newClient(configuration);
    WebTarget target = client.target(String.format("http://%s/api/v1/verifier/%s", config.getService(), connectorId));
    return target.request(MediaType.APPLICATION_JSON).post(Entity.entity(options, MediaType.APPLICATION_JSON),
                                                           new GenericType<List<Result>>(){});
}
项目:fuzzy.ai-java    文件:FuzzyAIClient.java   
public Feedback feedback(String evaluationId, Map<String, Double> metricMap) {
    String url = String.format("%1$s/evaluation/%2$s/feedback", root, evaluationId);

    WebTarget webTarget = client.target(url);

    Response response = webTarget
            .request(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + key)
            .header("User-Agent", "fuzzy.ai-java/" + version)
            .post(Entity.json(metricMap));

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> responseMap = response.readEntity(Map.class);

    String id = (String) responseMap.get("id");

    String status = (String) responseMap.get("status");

    ZonedDateTime dateTime = ZonedDateTime.parse((String) responseMap.get("createdAt"));

    @SuppressWarnings("unchecked")
    Map<String, Double> map = (Map<String, Double>) responseMap.get("data");

    String log = (String) responseMap.get("evaluationLog");

    return new Feedback(id, status, dateTime, map, log);
}
项目:redirector    文件:WhitelistNegativeIntegrationTests.java   
@Test
public void testWhitelistDeleteError() {
    Whitelisted whitelisted = new Whitelisted();
    WebTarget webTarget = HttpTestServerHelper.target().path(WHITELISTED_SERVICE_PATH).path(SERVICE_NAME);
    ValidationState error = ServiceHelper.post(webTarget, whitelisted, MediaType.APPLICATION_JSON, ValidationState.class);

    Assert.assertEquals(1, error.getErrors().size());
    Assert.assertEquals(ValidationState.ErrorType.WhitelistDeleteError, error.getErrors().keySet().iterator().next());
}
项目:mid-tier    文件:CustomerServiceExposureIT.java   
@Test
public void testGetCustomerUsingSpecificContentTypeWithParameters() {
    WebTarget target = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/sample");
    Map<String, Object> response = target.path("customers").path("8888888888")
            .request()
            .accept("application/hal+json;concept=customer;v=1")
            .header("X-Client-Version", "1.0.0")
            .header("X-Service-Generation", "1")
            .header("X-Log-Token", DiagnosticContext.getLogToken())
            .get(Map.class);
    assertEquals("Georg", response.get("firstName"));
    assertEquals("B", response.get("middleName"));
    assertEquals("Jensen", response.get("sirname"));
    assertEquals("8888888888", response.get("number"));
}