Java Code Examples for javax.ws.rs.core.Response#readEntity()

The following examples show how to use javax.ws.rs.core.Response#readEntity() . These examples are extracted from open source projects. 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: syncope   File: SCIMITCase.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void deleteGroup() {
    SCIMGroup group = new SCIMGroup(null, null, UUID.randomUUID().toString());
    Response response = webClient().path("Groups").post(group);
    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());

    group = response.readEntity(SCIMGroup.class);
    assertNotNull(group.getId());

    response = webClient().path("Groups").path(group.getId()).get();
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    response = webClient().path("Groups").path(group.getId()).delete();
    assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());

    response = webClient().path("Groups").path(group.getId()).get();
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
 
Example 2
Source Project: cassandra-reaper   File: BasicSteps.java    License: Apache License 2.0 6 votes vote down vote up
@And("^a second daily repair schedule is added for \"([^\"]*)\" and keyspace \"([^\"]*)\"$")
public void a_second_daily_repair_schedule_is_added_for_and_keyspace(String clusterName, String keyspace)
    throws Throwable {

  synchronized (BasicSteps.class) {
    LOG.info("add second daily repair schedule: {}/{}", clusterName, keyspace);
    Map<String, String> params = Maps.newHashMap();
    params.put("clusterName", clusterName);
    params.put("keyspace", keyspace);
    params.put("owner", TestContext.TEST_USER);
    params.put("intensity", "0.8");
    params.put("scheduleDaysBetween", "1");
    ReaperTestJettyRunner runner = RUNNERS.get(RAND.nextInt(RUNNERS.size()));
    Response response = runner.callReaper("POST", "/repair_schedule", Optional.of(params));
    int responseStatus = response.getStatus();
    assertEquals(Response.Status.CREATED.getStatusCode(), responseStatus);
    // rest command requests should not response with bodies, follow the location to GET that
    Assertions.assertThat(response.readEntity(String.class)).isEmpty();
    // follow to new location (to GET resource)
    response = runner.callReaper("GET", response.getLocation().toString(), Optional.empty());
    String responseData = response.readEntity(String.class);
    Assertions.assertThat(responseData).isNotBlank();
    RepairScheduleStatus schedule = SimpleReaperClient.parseRepairScheduleStatusJSON(responseData);
    testContext.addCurrentScheduleId(schedule.getId());
  }
}
 
Example 3
Source Project: TeaStore   File: CacheManager.java    License: Apache License 2.0 6 votes vote down vote up
private String clearRemoteCacheREST(RESTClient<String> client, Class<?> entityClass) {
	WebTarget target = client.getService().path(client.getApplicationURI())
			.path(client.getEndpointURI());
	if (entityClass != null) {
		target = target.path("class").path(entityClass.getName());
	} else {
		target = target.path("cache");
	}
	Response response = target.request(MediaType.TEXT_PLAIN).delete();
	String message = null;
	if (response.getStatus() == 200) {
		message = response.readEntity(String.class);
	}
	response.close();
	return message;
}
 
Example 4
@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"));
}
 
Example 5
public <T> RestResponse<T>  makeRequest(String path, Class<T> type) {
  Response response = makeGetRequest(path);
  try {
    if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
      return RestResponse.erroneous(
              new KsqlErrorMessage(
                  Errors.ERROR_CODE_UNAUTHORIZED,
                  new AuthenticationException(
                      "Could not authenticate successfully with the supplied credentials."
                  )
              )
      );
    }
    T result = response.readEntity(type);
    return RestResponse.successful(result);
  } finally {
    response.close();
  }
}
 
Example 6
@Test(dependsOnMethods = "multipleRetrieval")
public void multipleRetrievalExcluding() {
    logger.debug("Retrieving test users...");
    String exclude="displayName, externalId, name, addresses, emails";

    Response response=client.searchUsers("displayName co \"Test\"", null, null, null, null, null, exclude);
    assertEquals(response.getStatus(), OK.getStatusCode());

    ListResponse listResponse = response.readEntity(ListResponse.class);
    List<UserResource> list=listResponse.getResources().stream().map(UserResource.class::cast).collect(Collectors.toList());

    //Verify users retrieved do not contain attributes of interest
    for (UserResource usr : list) {
        assertNull(usr.getDisplayName());
        assertNull(usr.getExternalId());
        assertNull(usr.getName());
        assertNull(usr.getAddresses());
        assertNull(usr.getEmails());

        assertNotNull(usr.getSchemas());
        assertNotNull(usr.getId());
    }
    user=list.get(0);

}
 
Example 7
Source Project: nifi   File: ITProcessorAccessControl.java    License: Apache License 2.0 6 votes vote down vote up
private ProcessorEntity getRandomProcessor(final NiFiTestUser user) throws Exception {
    final String url = helper.getBaseUrl() + "/flow/process-groups/root";

    // get the processors
    final Response response = user.testGet(url);

    // ensure the response was successful
    assertEquals(200, response.getStatus());

    // unmarshal
    final ProcessGroupFlowEntity flowEntity = response.readEntity(ProcessGroupFlowEntity.class);
    final FlowDTO flowDto = flowEntity.getProcessGroupFlow().getFlow();
    final Set<ProcessorEntity> processors = flowDto.getProcessors();

    // ensure the correct number of processors
    assertFalse(processors.isEmpty());

    // use the first processor as the target
    Iterator<ProcessorEntity> processorIter = processors.iterator();
    assertTrue(processorIter.hasNext());
    return processorIter.next();
}
 
Example 8
Source Project: FHIR   File: BasicServerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the retrieval of a particular version of an observation.
 */
@Test(groups = { "server-basic" }, dependsOnMethods = { "testCreateObservation", "testUpdateObservation" })
public void testVreadObservation() {
    WebTarget target = getWebTarget();

    // Call the 'version read' API to retrieve the original created version of the
    // observation.
    String targetPath = "Observation/" + savedCreatedObservation.getId() + "/_history/"
            + savedCreatedObservation.getMeta().getVersionId().getValue();
    Response response = target.path(targetPath).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
    assertResponse(response, Response.Status.OK.getStatusCode());
    Observation originalObservation = response.readEntity(Observation.class);
    assertNotNull(originalObservation);
    TestUtil.assertResourceEquals(savedCreatedObservation, originalObservation);

    // Now try reading an Observation, passing a bogus version.
    targetPath = "Observation/" + savedCreatedObservation.getId() + "/_history/" + "-44";
    response = target.path(targetPath).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
    assertResponse(response, Response.Status.NOT_FOUND.getStatusCode());
}
 
Example 9
@Test
public void returns500IfARuntimeExceptionIsThrown() {
    when(authnRequestFactory.build(any())).thenThrow(RuntimeException.class);

    RequestGenerationBody requestGenerationBody = new RequestGenerationBody(LevelOfAssurance.LEVEL_2, null);
    Response response = resources.target(GENERATE_REQUEST_RESOURCE_PATH).request().post(Entity.entity(requestGenerationBody, MediaType.APPLICATION_JSON_TYPE));

    ErrorMessage responseEntity = response.readEntity(ErrorMessage.class);
    assertThat(responseEntity.getCode()).isEqualTo(500);
    assertThat(responseEntity.getMessage()).contains("There was an error processing your request. It has been logged (ID");
    assertThat(responseEntity.getDetails()).isNullOrEmpty();
}
 
Example 10
@Test
public void testJwsCompactDetached() throws Exception {
    Jose jose = getJose();
    Response r = client.target("http://localhost:8080/signDetached")
                            .request(MediaType.TEXT_PLAIN)
                            .header("DetachedData", "Hello")
                            .post(Entity.entity(jose.sign("Hello"), MediaType.TEXT_PLAIN));
    String jws = r.readEntity(String.class);
    Assert.assertEquals("Hello", jose.verifyDetached(jws, r.getHeaderString("DetachedData")));
    
    String[] parts = jws.split("\\.");
    Assert.assertEquals(3, parts.length);
    Assert.assertTrue(parts[1].isEmpty());
}
 
Example 11
Source Project: registry   File: SchemaRegistryClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SchemaVersionMergeResult mergeSchemaVersion(Long schemaVersionId, boolean disableCanonicalCheck) throws SchemaNotFoundException, IncompatibleSchemaException {
    Response response = runRetryableBlock((SchemaRegistryTargets targets) -> {
        try {
            WebTarget target = targets.schemasTarget.path(schemaVersionId + "/merge").queryParam("disableCanonicalCheck", disableCanonicalCheck);
            return login.doAction(new PrivilegedAction<Response>() {
                @Override
                public Response run() {
                    return target.request().post(null);
                }
            });
        } catch (LoginException | ProcessingException e) {
            throw new RegistryRetryableException(e);
        }
    });

    int status = response.getStatus();
    if (status == Response.Status.OK.getStatusCode()) {
        String msg = response.readEntity(String.class);
        return readEntity(msg, SchemaVersionMergeResult.class);
    } else if (status == Response.Status.NOT_FOUND.getStatusCode()) {
        throw new SchemaNotFoundException(response.readEntity(String.class));
    } else if (status == Response.Status.BAD_REQUEST.getStatusCode()) {
        throw new IncompatibleSchemaException(response.readEntity(String.class));
    } else {
        throw new RuntimeException(response.readEntity(String.class));
    }
}
 
Example 12
Source Project: cxf   File: JWTAlgorithmTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testEncryptionProperties() throws Exception {

    URL busFile = JWTAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);

    String address = "https://localhost:" + PORT + "/encryptedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.encryption.properties",
        "org/apache/cxf/systest/jaxrs/security/bob.jwk.properties");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example 13
Source Project: registry   File: SchemaRegistryClient.java    License: Apache License 2.0 5 votes vote down vote up
private void handleDeleteSchemaResponse(Response response) throws SchemaNotFoundException, SchemaLifecycleException {
    String msg = response.readEntity(String.class);
    switch (Response.Status.fromStatusCode(response.getStatus())) {
        case NOT_FOUND:
            throw new SchemaNotFoundException(msg);
        case BAD_REQUEST:
            throw new SchemaLifecycleException(msg);
        case INTERNAL_SERVER_ERROR:
            throw new RuntimeException(msg);
    }
}
 
Example 14
/**
 * Client read request to verify the Client using the
 * <code>code and id_token</code> response types.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "responseTypesCodeIdTokenStep1")
public void responseTypesCodeIdTokenStep2(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri2.substring(registrationClientUri2.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken2);

    Response response = request.get();
    String entity = response.readEntity(String.class);

    showResponse("responseTypesCodeIdTokenStep2", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertNotNull(jsonObj.optJSONArray(RESPONSE_TYPES.toString()));
        Set<String> responseTypes = new HashSet<String>();
        for (int i = 0; i < jsonObj.getJSONArray(RESPONSE_TYPES.toString()).length(); i++) {
            responseTypes.add(jsonObj.getJSONArray(RESPONSE_TYPES.toString()).getString(i));
        }
        assertTrue(responseTypes
                .containsAll(Arrays.asList(ResponseType.CODE.toString(), ResponseType.ID_TOKEN.toString())));
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 15
Source Project: syncope   File: SCIMITCase.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void search() {
    // invalid filter
    Response response = webClient().path("Groups").query("filter", "invalid").get();
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    SCIMError error = response.readEntity(SCIMError.class);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), error.getStatus());
    assertEquals(ErrorType.invalidFilter, error.getScimType());

    // eq
    response = webClient().path("Groups").query("filter", "displayName eq \"additional\"").get();
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertEquals(
            SCIMConstants.APPLICATION_SCIM_JSON,
            StringUtils.substringBefore(response.getHeaderString(HttpHeaders.CONTENT_TYPE), ";"));

    ListResponse<SCIMGroup> groups = response.readEntity(new GenericType<ListResponse<SCIMGroup>>() {
    });
    assertNotNull(groups);
    assertEquals(1, groups.getTotalResults());

    SCIMGroup additional = groups.getResources().get(0);
    assertEquals("additional", additional.getDisplayName());

    // eq via POST
    SCIMSearchRequest request = new SCIMSearchRequest("displayName eq \"additional\"", null, null, null, null);
    response = webClient().path("Groups").path("/.search").post(request);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertEquals(
            SCIMConstants.APPLICATION_SCIM_JSON,
            StringUtils.substringBefore(response.getHeaderString(HttpHeaders.CONTENT_TYPE), ";"));

    groups = response.readEntity(new GenericType<ListResponse<SCIMGroup>>() {
    });
    assertNotNull(groups);
    assertEquals(1, groups.getTotalResults());

    additional = groups.getResources().get(0);
    assertEquals("additional", additional.getDisplayName());

    // gt
    UserTO newUser = userService.create(UserITCase.getUniqueSample("[email protected]")).
            readEntity(new GenericType<ProvisioningResult<UserTO>>() {
            }).getEntity();

    Date value = new Date(newUser.getCreationDate().getTime() - 1000);
    response = webClient().path("Users").query("filter", "meta.created gt \""
            + DATE_FORMAT.get().format(value) + '"').get();
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertEquals(
            SCIMConstants.APPLICATION_SCIM_JSON,
            StringUtils.substringBefore(response.getHeaderString(HttpHeaders.CONTENT_TYPE), ";"));

    ListResponse<SCIMUser> users = response.readEntity(new GenericType<ListResponse<SCIMUser>>() {
    });
    assertNotNull(users);
    assertEquals(1, users.getTotalResults());

    SCIMUser newSCIMUser = users.getResources().get(0);
    assertEquals(newUser.getUsername(), newSCIMUser.getUserName());
}
 
Example 16
Source Project: choerodon-starters   File: JobApi.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Get a list of jobs in a pipeline.
 * <p>
 * GET /projects/:id/pipelines/:pipeline_id/jobs
 *
 * @param projectId  the project ID to get the list of pipeline for
 * @param pipelineId the pipeline ID to get the list of jobs for
 * @return a list containing the jobs for the specified project ID and pipeline ID
 * @throws GitLabApiException if any exception occurs during execution
 */
public List<Job> getJobsForPipeline(int projectId, int pipelineId) throws GitLabApiException {
    Response response = get(Status.OK, getDefaultPerPageParam(),
            "projects", projectId, "pipelines", pipelineId, "jobs");
    return (response.readEntity(new GenericType<List<Job>>() {
    }));
}
 
Example 17
Source Project: choerodon-starters   File: CommitsApi.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Get a list of repository commits in a project.
 * <p>
 * GET /projects/:id/repository/commits
 *
 * @param projectId the project ID to get the list of commits for
 * @param ref       the name of a repository branch or tag or if not given the default branch
 * @param since     only commits after or on this date will be returned
 * @param until     only commits before or on this date will be returned
 * @param path      the path to file of a project
 * @return a list containing the commits for the specified project ID
 * @throws GitLabApiException GitLabApiException if any exception occurs during execution
 */
public List<Commit> getCommits(int projectId, String ref, Date since, Date until, String path) throws GitLabApiException {
    Form formData = new GitLabApiForm()
            .withParam(PER_PAGE_PARAM, getDefaultPerPage())
            .withParam("ref_name", ref)
            .withParam("since", ISO8601.toString(since, false))
            .withParam("until", ISO8601.toString(until, false))
            .withParam("path", (path == null ? null : urlEncode(path)));
    Response response = get(Response.Status.OK, formData.asMap(), "projects", projectId, "repository", "commits");
    return (response.readEntity(new GenericType<List<Commit>>() {
    }));
}
 
Example 18
Source Project: gitlab4j-api   File: MilestonesApi.java    License: MIT License 3 votes vote down vote up
/**
 * Get a list of group milestones that have the specified state.
 *
 * <pre><code>GitLab Endpoint: GET /groups/:id/milestones</code></pre>
 *
 * @param groupIdOrPath the group in the form of an Integer(ID), String(path), or Group instance
 * @param state the milestone state
 * @return the milestones associated with the specified group and state
 * @throws GitLabApiException if any exception occurs
 */
public List<Milestone> getGroupMilestones(Object groupIdOrPath, MilestoneState state) throws GitLabApiException {
    Form formData = new GitLabApiForm().withParam("state", state).withParam(PER_PAGE_PARAM, getDefaultPerPage());
    Response response = get(Response.Status.OK, formData.asMap(),
            "groups", getGroupIdOrPath(groupIdOrPath), "milestones");
    return (response.readEntity(new GenericType<List<Milestone>>() {}));
}
 
Example 19
Source Project: gitlab4j-api   File: RunnersApi.java    License: MIT License 3 votes vote down vote up
/**
 * Enable an available specific runner in the project.
 *
 * <pre><code>GitLab Endpoint: POST /projects/:id/runners</code></pre>
 *
 * @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
 * @param runnerId  The ID of a runner
 * @return Runner instance of the Runner enabled
 * @throws GitLabApiException if any exception occurs
 */
public Runner enableRunner(Object projectIdOrPath, Integer runnerId) throws GitLabApiException {
    GitLabApiForm formData = new GitLabApiForm().withParam("runner_id", runnerId, true);
    Response response = post(Response.Status.CREATED, formData.asMap(),
            "projects", getProjectIdOrPath(projectIdOrPath), "runners");
    return (response.readEntity(Runner.class));
}
 
Example 20
Source Project: gitlab4j-api   File: UserApi.java    License: MIT License 2 votes vote down vote up
/**
 * Add an email to the current user's emails.
 *
 * <pre><code>GitLab Endpoint: POST /user/:id/emails</code></pre>
 *
 * @param email the email address to add
 * @return the Email instance for the added email
 * @throws GitLabApiException if any exception occurs
 */
public Email addEmail(String email) throws GitLabApiException {
    GitLabApiForm formData = new GitLabApiForm().withParam("email", email, true);
    Response response = post(Response.Status.CREATED, formData, "user", "emails");
    return (response.readEntity(Email.class));
}