javax.ws.rs.client.WebTarget Java Examples
The following examples show how to use
javax.ws.rs.client.WebTarget.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParcelServiceTest.java From cloudbreak with Apache License 2.0 | 7 votes |
@Test void testFilterParcelsByBlueprintWhenNoManifest() { Client client = mock(Client.class); WebTarget webTarget = mock(WebTarget.class); Invocation.Builder request = mock(Invocation.Builder.class); Response response = mock(Response.class); Blueprint blueprint = new Blueprint(); blueprint.setBlueprintText("bpText"); SupportedServices supportedServices = getSupportedServices("serv1"); when(clusterTemplateGeneratorService.getServicesByBlueprint("bpText")).thenReturn(supportedServices); when(restClientFactory.getOrCreateDefault()).thenReturn(client); when(client.target("http://parcel1.com/manifest.json")).thenReturn(webTarget); when(webTarget.request()).thenReturn(request); when(request.get()).thenReturn(response); when(response.getStatusInfo()).thenReturn(Response.Status.OK); when(response.readEntity(String.class)).thenReturn(null); List<ClouderaManagerProduct> parcels = getParcels("http://parcel1.com/", "http://parcel2.com/"); Set<ClouderaManagerProduct> actual = underTest.filterParcelsByBlueprint(parcels, blueprint); Assertions.assertEquals(2, actual.size()); Assertions.assertEquals(actual, new HashSet<>(parcels)); }
Example #2
Source File: TokenAsCookieIgnoredTest.java From microprofile-jwt-auth with Apache License 2.0 | 6 votes |
@RunAsClient @Test(groups = TEST_GROUP_CONFIG, description = "Validate a request with a valid JWT in a Cookie but no Token Header set fails with " + "HTTP_UNAUTHORIZED") public void noTokenHeaderSetToCookie() throws Exception { String token = TokenUtils.generateTokenString("/Token1.json"); String uri = baseURL.toExternalForm() + "endp/echo"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam("input", "hello"); Response response = echoEndpointTarget .request(TEXT_PLAIN) .cookie("jwt", token) .get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_UNAUTHORIZED); }
Example #3
Source File: OpenstackFloatingIpWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests the results of the REST API POST with creation operation. */ @Test public void testCreateFloatingIpWithCreationOperation() { mockOpenstackRouterAdminService.createFloatingIp(anyObject()); replay(mockOpenstackRouterAdminService); expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes(); replay(mockOpenstackHaService); final WebTarget wt = target(); InputStream jsonStream = OpenstackFloatingIpWebResourceTest.class .getResourceAsStream("openstack-floatingip1.json"); Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); final int status = response.getStatus(); assertThat(status, is(201)); verify(mockOpenstackRouterAdminService); }
Example #4
Source File: WorkerImpl.java From pulsar with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Collection<Metrics>> getMetricsAsync() { WebTarget path = workerStats.path("metrics"); final CompletableFuture<Collection<Metrics>> future = new CompletableFuture<>(); asyncGetRequest(path, new InvocationCallback<Response>() { @Override public void completed(Response response) { if (!response.getStatusInfo().equals(Response.Status.OK)) { future.completeExceptionally(new ClientErrorException(response)); } else { future.complete(response.readEntity( new GenericType<List<Metrics>>() {})); } } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
Example #5
Source File: OpenstackTelemetryConfigWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests the results of the REST API DELETE method without removing config. */ @Test public void testDeleteConfigWithoutModifyOperation() { expect(mockConfigAdminService.getConfig(anyString())).andReturn(null).once(); replay(mockConfigAdminService); final WebTarget wt = target(); Response response = wt.path(PATH + "/test1") .request(MediaType.APPLICATION_JSON_TYPE) .delete(); final int status = response.getStatus(); assertEquals(304, status); verify(mockConfigAdminService); }
Example #6
Source File: JerseyProcessGroupClient.java From nifi with Apache License 2.0 | 6 votes |
@Override public VariableRegistryUpdateRequestEntity getVariableRegistryUpdateRequest( final String processGroupId, final String requestId) throws NiFiClientException, IOException { if (StringUtils.isBlank(processGroupId)) { throw new IllegalArgumentException("Process group id cannot be null or blank"); } if (StringUtils.isBlank(requestId)) { throw new IllegalArgumentException("Request id cannot be null or blank"); } return executeAction("Error getting variable registry update request", () -> { final WebTarget target = processGroupsTarget .path("{processGroupId}/variable-registry/update-requests/{updateId}") .resolveTemplate("processGroupId", processGroupId) .resolveTemplate("updateId", requestId); return getRequestBuilder(target).get(VariableRegistryUpdateRequestEntity.class); }); }
Example #7
Source File: ApplicationsResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests a POST operation. This should attempt to * install the application. */ @Test public void postApplication() { expect(appService.install(isA(InputStream.class))) .andReturn(app4) .once(); replay(appService); ApplicationCodec codec = new ApplicationCodec(); String app4Json = codec.encode(app4, new MockCodecContextWithAppService(appService)) .asText(); WebTarget wt = target(); String response = wt.path("applications").request().post( Entity.entity(app4Json, MediaType.APPLICATION_OCTET_STREAM), String.class); JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result, matchesApp(app4)); verify(appService); }
Example #8
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 6 votes |
@Override public void deleteNode(final String nodeId, final boolean force) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.24"); final WebTarget resource = resource().path("nodes") .path(nodeId) .queryParam("force", String.valueOf(force)); try { request(DELETE, resource, resource.request(APPLICATION_JSON_TYPE)); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new NodeNotFoundException(nodeId); case 503: throw new NonSwarmNodeException("Node " + nodeId + " is not a swarm node", e); default: throw e; } } }
Example #9
Source File: RestconfWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Test handlePostRequest with 'already exists' exception. */ @Test public void testHandlePostRequestAlreadyExists() { ObjectMapper mapper = new ObjectMapper(); ObjectNode ietfSystemSubNode = mapper.createObjectNode(); ietfSystemSubNode.put("contact", "Open Networking Foundation"); ietfSystemSubNode.put("hostname", "host1"); ietfSystemSubNode.put("location", "The moon"); ObjectNode ietfSystemNode = mapper.createObjectNode(); ietfSystemNode.put("ietf-system:system", ietfSystemSubNode); restconfService.runPostOperationOnDataResource( EasyMock.<URI>anyObject(), EasyMock.<ObjectNode>anyObject()); expectLastCall().andThrow(new RestconfException("Requested node already present", null, RestconfError.ErrorTag.DATA_EXISTS, CONFLICT, Optional.of("/" + DATA_IETF_SYSTEM_SYSTEM))); replay(restconfService); WebTarget wt = target(); Response response = wt.path("/" + DATA_IETF_SYSTEM_SYSTEM) .request() .post(Entity.json(ietfSystemNode.toString())); assertEquals(409, response.getStatus()); }
Example #10
Source File: BaseResource.java From pulsar with Apache License 2.0 | 6 votes |
public <T> CompletableFuture<Void> asyncPutRequest(final WebTarget target, Entity<T> entity) { final CompletableFuture<Void> future = new CompletableFuture<>(); try { request(target).async().put(entity, new InvocationCallback<ErrorData>() { @Override public void completed(ErrorData response) { future.complete(null); } @Override public void failed(Throwable throwable) { log.warn("[{}] Failed to perform http put request: {}", target.getUri(), throwable.getMessage()); future.completeExceptionally(getApiException(throwable.getCause())); } }); } catch (PulsarAdminException cae) { future.completeExceptionally(cae); } return future; }
Example #11
Source File: OpenstackRouterWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests the results of the REST API POST with creation operation. */ @Test public void testCreateRouterWithCreationOperation() { mockOpenstackRouterAdminService.createRouter(anyObject()); replay(mockOpenstackRouterAdminService); expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes(); replay(mockOpenstackHaService); final WebTarget wt = target(); InputStream jsonStream = OpenstackRouterWebResourceTest.class .getResourceAsStream("openstack-router.json"); Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); final int status = response.getStatus(); assertThat(status, is(201)); verify(mockOpenstackRouterAdminService); }
Example #12
Source File: TckParticipantTests.java From microprofile-lra with Apache License 2.0 | 6 votes |
/** * Test verifyies {@link java.util.concurrent.CompletionStage} parametrized by * {@link Response} and {@link org.eclipse.microprofile.lra.annotation.ParticipantStatus} as valid * non-JAX-RS participant methods return types * * @throws InterruptedException When Test is interrupted during sleep. */ @Test public void testNonJaxRsCompletionStageResponseAndParticipantStatus() throws InterruptedException { WebTarget resourcePath = tckSuiteTarget.path(ValidLRACSParticipant.ROOT_PATH) .path(ValidLRACSParticipant.ENLIST_WITH_COMPLETE); Response response = resourcePath.request().get(); URI lraId = URI.create(checkStatusReadAndCloseResponse(Response.Status.OK, response, resourcePath)); assertEquals("Non JAX-RS @Complete method with CompletionStage<Response> should have been called", 1, lraMetricService.getMetric(LRAMetricType.Completed, lraId)); assertEquals("Non JAX-RS @Compensate method should have not been called", 0, lraMetricService.getMetric(LRAMetricType.Compensated, lraId)); lraTestService.waitForRecovery(lraId); assertTrue("Non JAX-RS @Status method with CompletionStage<ParticipantStatus> should have been called", lraMetricService.getMetric(LRAMetricType.Status, lraId) >= 1); lraTestService.waitForRecovery(lraId); }
Example #13
Source File: JerseyFlowSnapshotClient.java From nifi-registry with Apache License 2.0 | 6 votes |
@Override public VersionedFlowSnapshot getLatest(final String bucketId, final String flowId) throws NiFiRegistryException, IOException { if (StringUtils.isBlank(bucketId)) { throw new IllegalArgumentException("Bucket Identifier cannot be blank"); } if (StringUtils.isBlank(flowId)) { throw new IllegalArgumentException("Flow Identifier cannot be blank"); } return executeAction("Error retrieving latest snapshot", () -> { final WebTarget target = bucketFlowSnapshotTarget .path("/latest") .resolveTemplate("bucketId", bucketId) .resolveTemplate("flowId", flowId); return getRequestBuilder(target).get(VersionedFlowSnapshot.class); }); }
Example #14
Source File: NamespacesImpl.java From pulsar with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<List<String>> getTopicsAsync(String namespace) { NamespaceName ns = NamespaceName.get(namespace); String action = ns.isV2() ? "topics" : "destinations"; WebTarget path = namespacePath(ns, action); final CompletableFuture<List<String>> future = new CompletableFuture<>(); asyncGetRequest(path, new InvocationCallback<List<String>>() { @Override public void completed(List<String> topics) { future.complete(topics); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
Example #15
Source File: CookieTokenTest.java From microprofile-jwt-auth with Apache License 2.0 | 6 votes |
@RunAsClient @Test(groups = TEST_GROUP_JAXRS, description = "Validate a request with a different Cookie name from the one configured fais with " + "HTTP_UNAUTHORIZED") public void wrongCookieName() throws Exception { String token = TokenUtils.generateTokenString("/Token1.json"); String uri = baseURL.toExternalForm() + "endp/echo"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam("input", "hello"); Response response = echoEndpointTarget .request(TEXT_PLAIN) .cookie("Bearer", token) .get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_UNAUTHORIZED); }
Example #16
Source File: VirtualNetworkWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests removing a virtual network with DELETE request. */ @Test public void testDeleteVirtualNetwork() { mockVnetAdminService.removeVirtualNetwork(anyObject()); expectLastCall(); replay(mockVnetAdminService); WebTarget wt = target() .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); Response response = wt.path("vnets/" + "2") .request(MediaType.APPLICATION_JSON_TYPE) .delete(); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT)); verify(mockVnetAdminService); }
Example #17
Source File: GroupsResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Test the result of a rest api GET with specifying device id and appcookie. */ @Test public void testGroupByDeviceIdAndAppCookie() { setupMockGroups(); expect(mockGroupService.getGroup(anyObject(), anyObject())) .andReturn(group5).anyTimes(); replay(mockGroupService); final WebTarget wt = target(); final String response = wt.path("groups/" + deviceId3 + "/" + "0x111") .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("groups")); final JsonArray jsonFlows = result.get("groups").asArray(); assertThat(jsonFlows, notNullValue()); assertThat(jsonFlows, hasGroup(group5)); }
Example #18
Source File: HostResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests that a fetch of a non-existent object throws an exception. */ @Test public void testBadGet() { expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1"))) .andReturn(null) .anyTimes(); replay(mockHostService); WebTarget wt = target(); try { wt.path("hosts/00:00:11:00:00:01/1").request().get(String.class); fail("Fetch of non-existent host did not throw an exception"); } catch (NotFoundException ex) { assertThat(ex.getMessage(), containsString("HTTP 404 Not Found")); } }
Example #19
Source File: SortingTest.java From FHIR with Apache License 2.0 | 6 votes |
@Test public void testCreatePatient2() throws Exception { WebTarget target = getWebTarget(); // Build a new Patient and then call the 'create' API. Patient patient = TestUtil.readLocalResource("Patient_DavidOrtiz.json"); patient = patient.toBuilder().gender(AdministrativeGender.MALE).build(); Entity<Patient> entity = Entity.entity(patient, FHIRMediaType.APPLICATION_FHIR_JSON); Response response = target.path("Patient").request().post(entity, Response.class); assertResponse(response, Response.Status.CREATED.getStatusCode()); // Get the patient's logical id value. patientId = getLocationLogicalId(response); // Next, call the 'read' API to retrieve the new patient and verify it. response = target.path("Patient/" + patientId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get(); assertResponse(response, Response.Status.OK.getStatusCode()); Patient responsePatient = response.readEntity(Patient.class); TestUtil.assertResourceEquals(patient, responsePatient); }
Example #20
Source File: Swarm.java From rapid with MIT License | 6 votes |
@POST @Path("leave") public Response leaveSwarm(@DefaultValue("false") @QueryParam("force") boolean force) { WebTarget target = resource().path("swarm").path("leave").queryParam("force", force); Response response = postResponse(target); String entity = response.readEntity(String.class); try { if (entity.isEmpty()) { return Response.ok(Json.createObjectBuilder().add("message", "Node left.").build()) .build(); } else { return Response.status(response.getStatus()) .entity(Json.createReader(new StringReader(entity)).read()) .build(); } } finally { response.close(); } }
Example #21
Source File: NetworkConfigWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests the result of the rest api single subject key GET when * there is a config. */ @Test public void testSingleSubjectKeyConfig() { setUpConfigData(); final WebTarget wt = target(); final String response = wt.path("network/configuration/devices").request().get(String.class); final JsonObject result = Json.parse(response).asObject(); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(1)); JsonValue device1 = result.asObject().get("device1"); Assert.assertThat(device1, notNullValue()); JsonValue basic = device1.asObject().get("basic"); Assert.assertThat(basic, notNullValue()); checkBasicAttributes(basic); }
Example #22
Source File: JerseyBundleVersionClient.java From nifi-registry with Apache License 2.0 | 6 votes |
@Override public List<BundleVersionMetadata> getBundleVersions(final String bundleId) throws IOException, NiFiRegistryException { if (StringUtils.isBlank(bundleId)) { throw new IllegalArgumentException("Bundle id cannot be null or blank"); } return executeAction("Error getting extension bundle versions", () -> { final WebTarget target = extensionBundlesTarget .path("{bundleId}/versions") .resolveTemplate("bundleId", bundleId); final BundleVersionMetadata[] bundleVersions = getRequestBuilder(target).get(BundleVersionMetadata[].class); return bundleVersions == null ? Collections.emptyList() : Arrays.asList(bundleVersions); }); }
Example #23
Source File: Secret.java From rapid with MIT License | 6 votes |
@DELETE @Path("{id}") public Response deleteSecret(@PathParam("id") String id) { WebTarget target = resource().path("secrets").path(id); Response response = deleteResponse(target); String entity = response.readEntity(String.class); try { if (entity.isEmpty()) { return Response.ok(Json.createObjectBuilder().add("message", id + " removed.").build()) .build(); } else { return Response.status(response.getStatus()) .entity(Json.createReader(new StringReader(entity)).read()) .build(); } } finally { response.close(); } }
Example #24
Source File: DeviceKeyWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests that a DELETE of a non-existent device key throws an exception. */ @Test public void testDeleteNonExistentDeviceKey() { expect(mockDeviceKeyService.getDeviceKey(anyObject())) .andReturn(null) .anyTimes(); expectLastCall(); replay(mockDeviceKeyService); replay(mockDeviceKeyAdminService); WebTarget wt = target(); try { wt.path("keys/" + "NON_EXISTENT_DEVICE_KEY").request() .delete(String.class); fail("Delete of a non-existent device key did not throw an exception"); } catch (NotFoundException ex) { assertThat(ex.getMessage(), containsString("HTTP 404 Not Found")); } verify(mockDeviceKeyService); verify(mockDeviceKeyAdminService); }
Example #25
Source File: SinksImpl.java From pulsar with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<List<ConnectorDefinition>> getBuiltInSinksAsync() { WebTarget path = sink.path("builtinsinks"); final CompletableFuture<List<ConnectorDefinition>> future = new CompletableFuture<>(); asyncGetRequest(path, new InvocationCallback<Response>() { @Override public void completed(Response response) { if (!response.getStatusInfo().equals(Response.Status.OK)) { future.completeExceptionally(getApiException(response)); } else { future.complete(response.readEntity( new GenericType<List<ConnectorDefinition>>() {})); } } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
Example #26
Source File: GETServiceBean.java From OpenIoE with Apache License 2.0 | 6 votes |
@Override public String get(String server, String path) throws InvalidResponseException { String json = null; Client client = null; try { client = ClientBuilder.newBuilder().build(); WebTarget webResource = client.target(server); webResource = webResource.path(path); Builder builder = webResource.request(MediaType.APPLICATION_JSON); builder.accept(MediaType.APPLICATION_JSON); Response response = builder.get(); if (response.getStatus() == Status.OK.getStatusCode()) { json = response.readEntity(String.class); } else { throw new InvalidResponseException("Response code is not 200."); } } catch (Exception ex) { throw new InvalidResponseException("GET error when calling server: " + server + " path: " + path + ". " + ex.getMessage()); } finally { if(client != null) { client.close(); } } return json; }
Example #27
Source File: OpenstackVtapNetworkWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests the results of the REST API PUT method with modifying the vtap network. */ @Test public void testUpdateVtapNetworkWithoutModifyOperation() { expect(mockVtapService.updateVtapNetwork(anyObject())).andReturn(vtapNetwork).once(); replay(mockVtapService); final WebTarget wt = target(); InputStream jsonStream = OpenstackVtapNetworkWebResourceTest.class .getResourceAsStream("openstack-vtap-config.json"); Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.json(jsonStream)); final int status = response.getStatus(); assertThat(status, is(200)); verify(mockVtapService); }
Example #28
Source File: RestconfWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Test handleGetRequest when an RestconfException is thrown. */ @Test public void testHandleGetRequestRestconfException() { expect(restconfService .runGetOperationOnDataResource(URI.create(getBaseUri() + DATA_IETF_SYSTEM_SYSTEM))) .andThrow(new RestconfException("Suitable error message", RestconfError.ErrorTag.OPERATION_FAILED, INTERNAL_SERVER_ERROR, Optional.of("/" + DATA_IETF_SYSTEM_SYSTEM), Optional.of("More info about the error"))) .anyTimes(); replay(restconfService); WebTarget wt = target(); try { String response = wt.path("/" + DATA_IETF_SYSTEM_SYSTEM).request().get(String.class); fail("Expecting fail as response is RestconfException"); } catch (InternalServerErrorException e) { assertNotNull(e.getResponse()); assertRestconfErrorJson(e.getResponse()); } }
Example #29
Source File: JBossRESTEasyClientITest.java From hawkular-apm with Apache License 2.0 | 5 votes |
@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, "PUT", SAY_HELLO_URL); }
Example #30
Source File: EnvironmentApiClientConfig.java From cloudbreak with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnBean(EnvironmentApiClientParams.class) public WebTarget environmentApiClientWebTarget(EnvironmentApiClientParams environmentApiClientParams) { return new ThreadLocalUserCrnWebTargetBuilder(environmentApiClientParams.getServiceUrl()) .withCertificateValidation(environmentApiClientParams.isCertificateValidation()) .withIgnorePreValidation(environmentApiClientParams.isIgnorePreValidation()) .withDebug(environmentApiClientParams.isRestDebug()) .withClientRequestFilter(apiClientRequestFilter) .withApiRoot(EnvironmentApi.API_ROOT_CONTEXT) .withTracer(clientTracingFeature) .build(); }