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 Project: cloudbreak   Author: hortonworks   File: ParcelServiceTest.java    License: Apache License 2.0 7 votes vote down vote up
@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 Project: pulsar   Author: apache   File: WorkerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: onos   Author: opennetworkinglab   File: OpenstackFloatingIpWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: pulsar   Author: apache   File: BaseResource.java    License: Apache License 2.0 6 votes vote down vote up
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 #5
Source Project: onos   Author: opennetworkinglab   File: OpenstackRouterWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source Project: onos   Author: opennetworkinglab   File: ApplicationsResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source Project: pulsar   Author: apache   File: NamespacesImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 #8
Source Project: microprofile-jwt-auth   Author: eclipse   File: CookieTokenTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: rapid   Author: ozlerhakan   File: Swarm.java    License: MIT License 6 votes vote down vote up
@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 #10
Source Project: nifi-registry   Author: apache   File: JerseyBundleVersionClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 #11
Source Project: rapid   Author: ozlerhakan   File: Secret.java    License: MIT License 6 votes vote down vote up
@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 #12
Source Project: pulsar   Author: apache   File: SinksImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 #13
Source Project: onos   Author: opennetworkinglab   File: OpenstackVtapNetworkWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source Project: microprofile-jwt-auth   Author: eclipse   File: TokenAsCookieIgnoredTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: OpenIoE   Author: scorelab   File: GETServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
@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 #16
Source Project: onos   Author: opennetworkinglab   File: DeviceKeyWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #17
Source Project: onos   Author: opennetworkinglab   File: NetworkConfigWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #18
Source Project: FHIR   Author: IBM   File: SortingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #19
Source Project: onos   Author: opennetworkinglab   File: HostResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #20
Source Project: onos   Author: opennetworkinglab   File: GroupsResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #21
Source Project: onos   Author: opennetworkinglab   File: VirtualNetworkWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #22
Source Project: onos   Author: opennetworkinglab   File: RestconfWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #23
Source Project: microprofile-lra   Author: eclipse   File: TckParticipantTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #24
Source Project: nifi-registry   Author: apache   File: JerseyFlowSnapshotClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 #25
Source Project: docker-client   Author: spotify   File: DefaultDockerClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 #26
Source Project: onos   Author: opennetworkinglab   File: RestconfWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #27
Source Project: onos   Author: opennetworkinglab   File: OpenstackTelemetryConfigWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #28
Source Project: nifi   Author: apache   File: JerseyProcessGroupClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 #29
Source Project: onos   Author: opennetworkinglab   File: ControlMetricsCollectorResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
private Response baseTest(String jsonFile, String path) {
    final WebTarget wt = target();
    InputStream jsonStream = ControlMetricsCollectorResourceTest.class
            .getResourceAsStream(jsonFile);

    assertThat(jsonStream, notNullValue());

    return wt.path(path)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(jsonStream));
}
 
Example #30
Source Project: raml-java-client-generator   Author: mulesoft-labs   File: Login.java    License: Apache License 2.0 5 votes vote down vote up
public MultiBodyResponse<multi_body.resource.cs.login.model.LoginPOSTResponseBody> post(InputStream body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.post(javax.ws.rs.client.Entity.entity(body, javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE));
    if (response.getStatusInfo().getFamily()!= javax.ws.rs.core.Response.Status.Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new MultiBodyException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    MultiBodyResponse<multi_body.resource.cs.login.model.LoginPOSTResponseBody> apiResponse = new MultiBodyResponse<multi_body.resource.cs.login.model.LoginPOSTResponseBody>(response.readEntity(multi_body.resource.cs.login.model.LoginPOSTResponseBody.class), response.getStringHeaders(), response);
    return apiResponse;
}