Example usage for org.springframework.data.domain PageRequest of

List of usage examples for org.springframework.data.domain PageRequest of

Introduction

In this page you can find the example usage for org.springframework.data.domain PageRequest of.

Prototype

public static PageRequest of(int page, int size) 

Source Link

Document

Creates a new unsorted PageRequest .

Usage

From source file:com._4dconcept.springframework.data.marklogic.repository.support.RepositoryIntegrationTests.java

@Test
public void findAllWithPagination() {
    Page<Person> pageResult = repository.findAll(PageRequest.of(0, 2));
    assertThat(pageResult.getTotalElements(), is(3L));
    assertThat(pageResult.getTotalPages(), is(2));
    assertThat(pageResult.getContent(), hasSize(2));
}

From source file:org.ligoj.app.plugin.security.fortify.FortifyPluginResource.java

/**
 * Find the spaces matching to the given criteria.Look into space key, and space name.
 *
 * @param criteria/*from   w  ww . j  a  v  a2  s .c o m*/
 *            the search criteria.
 * @param node
 *            the node to be tested with given parameters.
 * @return project name.
 */
@GET
@Path("{node}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<FortifyProject> findAllByName(@PathParam("node") final String node,
        @PathParam("criteria") final String criteria) throws IOException {
    return inMemoryPagination
            .newPage(findAll(node, "api/v1/projects?fields=id,name", criteria), PageRequest.of(0, 10))
            .getContent();
}

From source file:com.netflix.genie.web.jpa.services.JpaJobPersistenceServiceImpl.java

/**
 * {@inheritDoc}//from   w  ww .  ja  v  a  2  s  .c o  m
 */
@Override
public long deleteBatchOfJobsCreatedBeforeDate(@NotNull final Instant date, @Min(1) final int maxDeleted,
        @Min(1) final int pageSize) {
    log.info("Attempting to delete batch of jobs (at most {}) created before {} ms from epoch", maxDeleted,
            date.toEpochMilli());
    long jobsDeleted = 0;
    long totalAttemptedDeletions = 0;
    final Pageable page = PageRequest.of(0, pageSize);
    Slice<IdProjection> idProjections;
    do {
        idProjections = this.jobRepository.findByCreatedBefore(date, page);
        if (idProjections.hasContent()) {
            final List<Long> ids = idProjections.getContent().stream().map(IdProjection::getId)
                    .collect(Collectors.toList());

            final long toBeDeleted = ids.size();
            totalAttemptedDeletions += toBeDeleted;

            log.debug("Attempting to delete {} rows from jobs...", toBeDeleted);
            final long deletedJobs = this.jobRepository.deleteByIdIn(ids);
            log.debug("Successfully deleted {} rows from jobs...", deletedJobs);
            if (deletedJobs != toBeDeleted) {
                log.error("Deleted {} job records but expected to delete {}", deletedJobs, toBeDeleted);
            }
            jobsDeleted += deletedJobs;
        }
    } while (idProjections.hasNext() && totalAttemptedDeletions < maxDeleted);

    log.info("Deleted a chunk of {} job records: {} job", totalAttemptedDeletions, jobsDeleted);
    return totalAttemptedDeletions;
}

From source file:info.rmapproject.webapp.service.DataDisplayServiceImpl.java

@Override
public String getResourceLabel(String resourceUri, RMapSearchParams params) throws Exception {
    String preferredLabel = null;
    Integer highestCount = 0;//  w  w w . j a  v  a 2 s  .c  om
    Map<String, Integer> countLabel = new HashMap<String, Integer>();

    int NUM_MATCHES = 1000;
    Pageable pageable = PageRequest.of(0, NUM_MATCHES);
    List<String> labels = searchService.getLabelListForResource(resourceUri, params, pageable);

    for (String label : labels) {
        int count = countLabel.containsKey(label) ? countLabel.get(label) + 1 : 1;
        countLabel.put(label, count);
        if (highestCount < count) {
            highestCount = count;
            preferredLabel = label;
        }
        log.debug("Label count for {} is {}", label, count);
    }

    log.debug("Preferred label for resource uri {} is {}", resourceUri, preferredLabel);

    return preferredLabel;
}

From source file:org.eclipse.hawkbit.ddi.rest.resource.DdiDeploymentBaseTest.java

@Test
@Description("Multiple uploads of deployment status feedback to the server.")
public void multipleDeplomentActionFeedback() throws Exception {
    final Target savedTarget1 = testdataFactory.createTarget("4712");
    testdataFactory.createTarget("4713");
    testdataFactory.createTarget("4714");

    final DistributionSet ds1 = testdataFactory.createDistributionSet("1", true);
    final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
    final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);

    final List<Target> toAssign = new ArrayList<>();
    toAssign.add(savedTarget1);//from  w  ww  .j a v  a  2 s.  c o  m

    final Long actionId1 = assignDistributionSet(ds1.getId(), "4712").getActions().get(0);
    final Long actionId2 = assignDistributionSet(ds2.getId(), "4712").getActions().get(0);
    final Long actionId3 = assignDistributionSet(ds3.getId(), "4712").getActions().get(0);

    Target myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(3);
    assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
    assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId())).isNotPresent();
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.UNKNOWN))
            .hasSize(2);

    // action1 done

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + actionId1 + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(actionId1.toString(), "closed"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(2);
    assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
    assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds1);

    Iterable<ActionStatus> actionStatusMessages = deploymentManagement
            .findActionStatusAll(PageRequest.of(0, 100, Direction.DESC, "id")).getContent();
    assertThat(actionStatusMessages).hasSize(4);
    assertThat(actionStatusMessages.iterator().next().getStatus()).isEqualTo(Status.FINISHED);

    // action2 done
    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + actionId2 + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(actionId2.toString(), "closed"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();

    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
    assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds2);
    actionStatusMessages = deploymentManagement
            .findActionStatusAll(PageRequest.of(0, 100, Direction.DESC, "id")).getContent();
    assertThat(actionStatusMessages).hasSize(5);
    assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));

    // action3 done
    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + actionId3 + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(actionId3.toString(), "closed"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
    assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
    assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
    actionStatusMessages = deploymentManagement
            .findActionStatusAll(PageRequest.of(0, 100, Direction.DESC, "id")).getContent();
    assertThat(actionStatusMessages).hasSize(6);
    assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));

}

From source file:org.eclipse.hawkbit.ddi.rest.resource.DdiDeploymentBaseTest.java

@Test
@Description("Verfies that an update action is correctly set to error if the controller provides error feedback.")
public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception {
    DistributionSet ds = testdataFactory.createDistributionSet("");
    final Target savedTarget = testdataFactory.createTarget("4712");

    final List<Target> toAssign = new ArrayList<>();
    toAssign.add(savedTarget);/*from ww  w .  j  av  a2s.  com*/

    assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus())
            .isEqualTo(TargetUpdateStatus.UNKNOWN);
    assignDistributionSet(ds, toAssign);
    final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
            .get(0);

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed",
                            "failure", "error message"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    Target myT = targetManagement.getByControllerID("4712").get();
    assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus())
            .isEqualTo(TargetUpdateStatus.ERROR);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(0);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
    assertThat(deploymentManagement.countActionsByTarget(myT.getControllerId())).isEqualTo(1);
    final Iterable<ActionStatus> actionStatusMessages = deploymentManagement
            .findActionStatusAll(PageRequest.of(0, 100, Direction.DESC, "id")).getContent();
    assertThat(actionStatusMessages).hasSize(2);
    assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));

    // redo
    ds = distributionSetManagement.getWithDetails(ds.getId()).get();
    assignDistributionSet(ds, Arrays.asList(targetManagement.getByControllerID("4712").get()));
    final Action action2 = deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())
            .getContent().get(0);

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback",
            tenantAware.getCurrentTenant()).content(
                    JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed", "success"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());

    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(1);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
    assertThat(deploymentManagement.findInActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(2);
    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
    assertThat(deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.ERROR));
    assertThat(deploymentManagement.findActionStatusByAction(PAGE, action2.getId()).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.FINISHED));

}

From source file:org.eclipse.hawkbit.ddi.rest.resource.DdiDeploymentBaseTest.java

@Test
@Description("Verfies that the controller can provided as much feedback entries as necessry as long as it is in the configured limites.")
public void rootRsSingleDeplomentActionFeedback() throws Exception {
    final DistributionSet ds = testdataFactory.createDistributionSet("");

    final Target savedTarget = testdataFactory.createTarget("4712");

    final List<Target> toAssign = Arrays.asList(savedTarget);

    Target myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
    assignDistributionSet(ds, toAssign);
    final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
            .get(0);//from w w  w.j  a v  a 2 s  .com

    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(targetManagement.findByInstalledDistributionSet(PAGE, ds.getId())).hasSize(0);
    assertThat(targetManagement.findByAssignedDistributionSet(PAGE, ds.getId())).hasSize(1);

    // Now valid Feedback
    for (int i = 0; i < 4; i++) {
        mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
                tenantAware.getCurrentTenant())
                        .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"))
                        .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    }

    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(0);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(5,
            new ActionStatusCondition(Status.RUNNING));

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(0);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(5,
            new ActionStatusCondition(Status.RUNNING));

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(0);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(6,
            new ActionStatusCondition(Status.RUNNING));

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.PENDING))
            .hasSize(1);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(0);

    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(7,
            new ActionStatusCondition(Status.RUNNING));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.CANCELED));

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(6,
            new ActionStatusCondition(Status.RUNNING));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.WARNING));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.CANCELED));

    mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
            tenantAware.getCurrentTenant())
                    .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed"))
                    .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
    myT = targetManagement.getByControllerID("4712").get();
    assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
    assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.ERROR)).hasSize(0);
    assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.IN_SYNC))
            .hasSize(1);

    assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(7,
            new ActionStatusCondition(Status.RUNNING));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.WARNING));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.CANCELED));
    assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
            new ActionStatusCondition(Status.FINISHED));

    assertThat(targetManagement.findByInstalledDistributionSet(PAGE, ds.getId())).hasSize(1);
    assertThat(targetManagement.findByAssignedDistributionSet(PAGE, ds.getId())).hasSize(1);
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtDistributionSetResourceTest.java

@Test
@Description("Ensures that the metadata creation through API is reflected by the repository.")
public void createMetadata() throws Exception {
    final DistributionSet testDS = testdataFactory.createDistributionSet("one");

    final String knownKey1 = "knownKey1";
    final String knownKey2 = "knownKey2";

    final String knownValue1 = "knownValue1";
    final String knownValue2 = "knownValue2";

    final JSONArray metaData1 = new JSONArray();
    metaData1.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
    metaData1.put(new JSONObject().put("key", knownKey2).put("value", knownValue2));

    mvc.perform(//from w w w  .java 2s  .c  om
            post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId()).accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_JSON).content(metaData1.toString()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("[0]key", equalTo(knownKey1)))
            .andExpect(jsonPath("[0]value", equalTo(knownValue1)))
            .andExpect(jsonPath("[1]key", equalTo(knownKey2)))
            .andExpect(jsonPath("[1]value", equalTo(knownValue2)));

    final DistributionSetMetadata metaKey1 = distributionSetManagement
            .getMetaDataByDistributionSetId(testDS.getId(), knownKey1).get();
    final DistributionSetMetadata metaKey2 = distributionSetManagement
            .getMetaDataByDistributionSetId(testDS.getId(), knownKey2).get();

    assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
    assertThat(metaKey2.getValue()).isEqualTo(knownValue2);

    // verify quota enforcement
    final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerDistributionSet();

    final JSONArray metaData2 = new JSONArray();
    for (int i = 0; i < maxMetaData - metaData1.length() + 1; ++i) {
        metaData2.put(new JSONObject().put("key", knownKey1 + i).put("value", knownValue1 + i));
    }

    mvc.perform(
            post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId()).accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_JSON).content(metaData2.toString()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden());

    // verify that the number of meta data entries has not changed
    // (we cannot use the PAGE constant here as it tries to sort by ID)
    assertThat(distributionSetManagement
            .findMetaDataByDistributionSetId(PageRequest.of(0, Integer.MAX_VALUE), testDS.getId())
            .getTotalElements()).isEqualTo(metaData1.length());

}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verfies the successful creation of metadata and the enforcement of the meta data quota.")
public void createMetadata() throws Exception {

    final String knownKey1 = "knownKey1";
    final String knownValue1 = "knownValue1";
    final String knownKey2 = "knownKey2";
    final String knownValue2 = "knownValue1";

    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    final JSONArray metaData1 = new JSONArray();
    metaData1.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
    metaData1.put(new JSONObject().put("key", knownKey2).put("value", knownValue2).put("targetVisible", true));

    mvc.perform(post("/rest/v1/softwaremodules/{swId}/metadata", sm.getId()).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON).content(metaData1.toString()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("[0]key", equalTo(knownKey1)))
            .andExpect(jsonPath("[0]value", equalTo(knownValue1)))
            .andExpect(jsonPath("[0]targetVisible", equalTo(false)))
            .andExpect(jsonPath("[1]key", equalTo(knownKey2)))
            .andExpect(jsonPath("[1]value", equalTo(knownValue2)))
            .andExpect(jsonPath("[1]targetVisible", equalTo(true)));

    final SoftwareModuleMetadata metaKey1 = softwareModuleManagement
            .getMetaDataBySoftwareModuleId(sm.getId(), knownKey1).get();
    final SoftwareModuleMetadata metaKey2 = softwareModuleManagement
            .getMetaDataBySoftwareModuleId(sm.getId(), knownKey2).get();

    assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
    assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2);

    // verify quota enforcement
    final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerSoftwareModule();

    final JSONArray metaData2 = new JSONArray();
    for (int i = 0; i < maxMetaData - metaData1.length() + 1; ++i) {
        metaData2.put(new JSONObject().put("key", knownKey1 + i).put("value", knownValue1 + i));
    }// w  ww. ja  v  a 2  s.co  m

    mvc.perform(post("/rest/v1/softwaremodules/{swId}/metadata", sm.getId()).accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON).content(metaData2.toString()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden());

    // verify that the number of meta data entries has not changed
    // (we cannot use the PAGE constant here as it tries to sort by ID)
    assertThat(softwareModuleManagement
            .findMetaDataBySoftwareModuleId(PageRequest.of(0, Integer.MAX_VALUE), sm.getId())
            .getTotalElements()).isEqualTo(metaData1.length());

}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtTargetResourceTest.java

@Test
@Description("Ensures that a post request for creating one target within a list works.")
public void createTargetsSingleEntryListReturnsSuccessful() throws Exception {
    final String knownName = "someName";
    final String knownControllerId = "controllerId1";
    final String knownDescription = "someDescription";
    final String createTargetsJson = getCreateTargetsListJsonString(knownControllerId, knownName,
            knownDescription);/*from w  ww  .j  a  v  a  2s  .c  o m*/

    mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson)
            .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().is2xxSuccessful());

    final Slice<Target> findTargetsAll = targetManagement.findAll(PageRequest.of(0, 100));
    final Target target = findTargetsAll.getContent().get(0);
    assertThat(targetManagement.count()).isEqualTo(1);
    assertThat(target.getControllerId()).isEqualTo(knownControllerId);
    assertThat(target.getName()).isEqualTo(knownName);
    assertThat(target.getDescription()).isEqualTo(knownDescription);
}