Example usage for org.springframework.data.domain Page getTotalElements

List of usage examples for org.springframework.data.domain Page getTotalElements

Introduction

In this page you can find the example usage for org.springframework.data.domain Page getTotalElements.

Prototype

long getTotalElements();

Source Link

Document

Returns the total amount of elements.

Usage

From source file:org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepositoryTests.java

@Test
public void shouldIndexEntity() {
    // given/*from  w w  w . j  a  va2 s .  c  o  m*/
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity = new SampleEntity();
    sampleEntity.setId(documentId);
    sampleEntity.setVersion(System.currentTimeMillis());
    sampleEntity.setMessage("some message");
    // when
    repository.index(sampleEntity);
    // then
    Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
    assertThat(entities.getTotalElements(), equalTo(1L));
}

From source file:org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepositoryTests.java

@Test
public void shouldReturnSimilarEntities() {
    // given/*  w  w  w. ja v a  2s  .co m*/
    String sampleMessage = "So we build a web site or an application and want to add search to it, "
            + "and then it hits us: getting search working is hard. We want our search solution to be fast,"
            + " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, "
            + "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, "
            + "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud.";

    List<SampleEntity> sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30);
    repository.save(sampleEntities);

    // when
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(new PageRequest(0, 5))
            .withFields("message").build();
    Page<SampleEntity> results = repository.searchSimilar(sampleEntities.get(0), searchQuery);

    // then
    assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}

From source file:org.springframework.data.neo4j.aspects.support.FinderTest.java

private void assertPage(Page<Person> page0, int pageNumber, int totalPages, final int totalElements,
        Person... people) {//from   www .j a  v  a2  s .  co m
    assertEquals("content count", people.length, page0.getNumberOfElements());
    assertEquals("page number", pageNumber, page0.getNumber());
    assertEquals("page size", 2, page0.getSize());
    assertEquals("total elements", totalElements, page0.getTotalElements());
    assertEquals("page count", totalPages, page0.getTotalPages());
    assertEquals("next page", pageNumber < totalPages - 1, page0.hasNextPage());
    assertEquals("previous page", pageNumber > 0, page0.hasPreviousPage());
    assertEquals("page content", asList(people), page0.getContent());
}

From source file:piecework.persistence.concrete.SearchRepositoryProvider.java

@Override
public SearchResponse forms(SearchCriteria criteria, ViewContext context, boolean excludeData)
        throws PieceworkException {
    long time = 0;
    if (LOG.isDebugEnabled())
        time = System.currentTimeMillis();

    Set<String> overseerProcessDefinitionKeys = principal.getProcessDefinitionKeys(AuthorizationRole.OVERSEER);
    Set<String> userProcessDefinitionKeys = principal.getProcessDefinitionKeys(AuthorizationRole.USER);

    Set<String> allProcessDefinitionKeys = Sets.union(overseerProcessDefinitionKeys, userProcessDefinitionKeys);
    Set<piecework.model.Process> allowedProcesses = processes(allProcessDefinitionKeys);

    SearchResponse response = new SearchResponse();

    if (allowedProcesses == null || allowedProcesses.isEmpty())
        return response;

    List<Process> alphabetical = new ArrayList<Process>(allowedProcesses);
    Collections.sort(alphabetical, new Comparator<Process>() {
        @Override//from w  w  w  .j  a va 2s  .  c  om
        public int compare(Process o1, Process o2) {
            if (org.apache.commons.lang.StringUtils.isEmpty(o1.getProcessDefinitionLabel()))
                return 0;
            if (org.apache.commons.lang.StringUtils.isEmpty(o2.getProcessDefinitionLabel()))
                return 1;
            return o1.getProcessDefinitionLabel().compareTo(o2.getProcessDefinitionLabel());
        }
    });

    List<Map<String, String>> metadata = new ArrayList<Map<String, String>>();
    Set<String> pgs = new HashSet<String>();
    for (Process allowedProcess : alphabetical) {
        if (allowedProcess.getProcessDefinitionKey() != null) {
            Process definition = allowedProcess;
            Form form = new Form.Builder().processDefinitionKey(definition.getProcessDefinitionKey())
                    .task(new Task.Builder().processDefinitionKey(definition.getProcessDefinitionKey())
                            .processDefinitionLabel(definition.getProcessDefinitionLabel()).build(context))
                    .build(context);
            Map<String, String> map = new HashMap<String, String>();
            map.put("processDefinitionKey", definition.getProcessDefinitionKey());
            map.put("processDefinitionLabel", definition.getProcessDefinitionLabel());
            map.put("link", form.getLink());
            metadata.add(map);
            if (StringUtils.isNotEmpty(allowedProcess.getProcessGroup())) {
                pgs.add(allowedProcess.getProcessGroup());
            }
        }
    }
    response.setMetadata(metadata);

    // bucket list stuff
    String pg = null;

    // get process group from allowed processes
    if (pgs.size() == 1) {
        pg = pgs.toArray()[0].toString();
    } else {
        // then try to get process group from query
        Map<String, List<String>> contentParameter = criteria.getContentParameters();
        if (contentParameter != null) {
            List<String> vlist = contentParameter.get("pg");
            if (vlist != null && vlist.size() > 0) {
                pg = vlist.get(0);
            }
        }
    }

    if (StringUtils.isNotEmpty(pg) && bucketListRepository != null) {
        BucketList bucketList = bucketListRepository.findOne(pg);
        if (bucketList != null) {
            response.setBucketList(bucketList);
        }
        response.setProcessGroup(pg);
    }

    String processStatus = criteria.getProcessStatus() != null ? sanitizer.sanitize(criteria.getProcessStatus())
            : Constants.ProcessStatuses.OPEN;
    String taskStatus = criteria.getTaskStatus() != null ? sanitizer.sanitize(criteria.getTaskStatus())
            : Constants.TaskStatuses.ALL;

    List<TaskDeployment> taskDeployments = new ArrayList<TaskDeployment>();
    Set<String> userIds = new HashSet<String>();

    List<Facet> facets = FacetFactory.facets(allowedProcesses);
    response.setFacets(facets);

    Map<DataFilterFacet, String> filterFacetParameters = criteria.getFilterFacetParameters();

    if (!excludeData) {
        Query query = new SearchQueryBuilder(criteria).build(allProcessDefinitionKeys, sanitizer);

        int instancePageNumber = 0;
        int instancePageSize = 1000;
        Sort sort = SearchUtility.sort(criteria, sanitizer);
        Pageable pageable = new PageRequest(instancePageNumber, instancePageSize, sort);
        Page<ProcessInstance> page = instanceRepository.findByQuery(query, pageable, true);

        int pageNumber = criteria.getPageNumber() != null ? criteria.getPageNumber().intValue() : 0;
        int pageSize = criteria.getPageSize() != null ? criteria.getPageSize() : 200;
        Pageable taskPageable = new PageRequest(pageNumber, pageSize);
        long total = page.getTotalElements();
        long taskCounter = 0;
        long instanceCounter = 0;
        long start = taskPageable.getOffset();
        long end = taskPageable.getOffset() + taskPageable.getPageSize();

        while (instanceCounter < total && page.hasContent()) {
            // Loop again through the list to get all user ids and build the intermediate object including
            // task, instance, and deployment
            for (ProcessInstance instance : page.getContent()) {
                String processDefinitionKey = instance.getProcessDefinitionKey();
                String processInstanceId = instance.getProcessInstanceId();

                instanceCounter++;

                ProcessDeployment processDeployment = null;

                Map<String, Object> instanceData = new HashMap<String, Object>();

                instanceData.put("processInstanceId", processInstanceId);
                instanceData.put("processInstanceLabel", instance.getProcessInstanceLabel());
                instanceData.put("processDefinitionLabel", instance.getProcessDefinitionLabel());
                instanceData.put("processStatus", instance.getProcessStatus());
                instanceData.put("applicationStatusExplanation", instance.getApplicationStatusExplanation());
                instanceData.put("startTime", instance.getStartTime());
                instanceData.put("lastModifiedTime", instance.getLastModifiedTime());
                instanceData.put("endTime", instance.getEndTime());

                String activation = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, "activation");
                String attachment = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, Attachment.Constants.ROOT_ELEMENT_NAME);
                String cancellation = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, "cancellation");
                String history = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, History.Constants.ROOT_ELEMENT_NAME);
                String restart = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, "restart");
                String suspension = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, "suspension");
                String bucketUrl = context.getApplicationUri(ProcessInstance.Constants.ROOT_ELEMENT_NAME,
                        processDefinitionKey, processInstanceId, "value/Bucket");

                instanceData.put("activation", activation);
                instanceData.put("attachment", attachment);
                instanceData.put("cancellation", cancellation);
                instanceData.put("history", history);
                instanceData.put("restart", restart);
                instanceData.put("suspension", suspension);
                instanceData.put("bucketUrl", bucketUrl);

                Map<String, List<Value>> valueData = instance.getData();
                if (valueData != null && !valueData.isEmpty()) {
                    for (Facet facet : facets) {
                        if (facet instanceof DataSearchFacet) {
                            DataSearchFacet dataSearchFacet = DataSearchFacet.class.cast(facet);
                            String name = dataSearchFacet.getName();
                            String value = ProcessInstanceUtility.firstString(name, valueData);
                            if (StringUtils.isNotEmpty(value))
                                instanceData.put(name, value);
                        }
                    }
                }

                Set<Task> tasks = instance.getTasks();
                if (tasks != null && !tasks.isEmpty()) {
                    for (Task task : tasks) {
                        if (include(task, processStatus, taskStatus, overseerProcessDefinitionKeys,
                                principal)) {
                            if (taskCounter >= start && taskCounter < end) {
                                taskDeployments.add(new TaskDeployment(taskCounter, processDeployment, instance,
                                        task, instanceData));
                                userIds.addAll(task.getAssigneeAndCandidateAssigneeIds());
                            }
                            taskCounter++;
                        }
                    }
                }
            }

            if (total > instanceCounter) {
                instancePageNumber++;
                Pageable nextPage = new PageRequest(instancePageNumber, instancePageSize, sort);
                page = instanceRepository.findByQuery(query, nextPage, false);
            }
        }

        response.setTotal((int) taskCounter);
        response.setPageNumber(taskPageable.getPageNumber());
        response.setPageSize(taskPageable.getPageSize());
    }

    Map<String, User> userMap = identityService.findUsers(userIds);

    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    for (TaskDeployment taskDeployment : taskDeployments) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> instanceData = taskDeployment.getInstanceData();

        if (instanceData != null && !instanceData.isEmpty())
            map.putAll(instanceData);

        Task task = TaskFactory.task(taskDeployment.getTask(), new PassthroughSanitizer(), userMap, context);
        String processDefinitionKey = task.getProcessDefinitionKey();

        if (!include(task, filterFacetParameters))
            continue;

        map.put("itemNumber", taskDeployment.getItemNumber());
        map.put("assignee", task.getAssignee());
        map.put("candidateAssignees", task.getCandidateAssignees());

        map.put("formInstanceId", task.getTaskInstanceId());
        map.put("taskId", task.getTaskInstanceId());
        map.put("taskClaimTime", task.getClaimTime());
        map.put("taskDueDate", task.getDueDate());
        map.put("taskStartTime", task.getStartTime());
        map.put("taskEndTime", task.getEndTime());
        map.put("taskLabel", task.getTaskLabel());
        map.put("taskDescription", task.getTaskDescription());
        map.put("taskStatus", task.getTaskStatus());
        map.put("active", task.isActive());

        String assignment = context != null && task != null && task.getTaskInstanceId() != null
                ? context.getApplicationUri(Task.Constants.ROOT_ELEMENT_NAME, processDefinitionKey,
                        task.getTaskInstanceId(), "assign")
                : null;

        map.put("assignment", assignment);
        map.put("link",
                context != null
                        ? context.getApplicationUri(Form.Constants.ROOT_ELEMENT_NAME, processDefinitionKey)
                                + "?taskId=" + task.getTaskInstanceId()
                        : null);
        data.add(map);
    }
    List<FacetSort> postQuerySortBy = criteria.getPostQuerySortBy();
    if (postQuerySortBy != null && !postQuerySortBy.isEmpty()) {
        Collections.reverse(postQuerySortBy);
        for (FacetSort facetSort : postQuerySortBy) {
            Collections.sort(data, new DataFilterFacetComparator(facetSort.getFacet()));
            if (facetSort.getDirection().equals(Sort.Direction.DESC))
                Collections.reverse(data);
        }
    }

    response.setData(data);

    List<FacetSort> facetSortList = criteria.getSortBy();
    List<String> sortBy = new ArrayList<String>();
    if (facetSortList != null) {
        for (FacetSort facetSort : facetSortList) {
            sortBy.add(facetSort.toString());
        }
    }
    response.setSortBy(sortBy);

    if (LOG.isDebugEnabled())
        LOG.debug("Retrieved forms in " + (System.currentTimeMillis() - time) + " ms");

    if (principal instanceof User)
        response.setCurrentUser(User.class.cast(principal));

    return response;
}

From source file:siddur.solidtrust.autoscout.AutoscoutController.java

@RequestMapping(value = "/daysForSale")
public String daysForSale(@RequestParam(value = "id", required = false) String id,
        @RequestParam(value = "brand", required = false) String brand,
        @RequestParam(value = "model", required = false) String _model,
        @RequestParam(value = "build", required = false) String build,
        @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageIndex,
        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, Model model)
        throws Exception {
    if (!StringUtils.isEmpty(brand)) {
        Pageable pageable = new PageRequest(pageIndex - 1, pageSize);
        Page<ScoutCar> page = mService.timeOnSale(pageable, brand, _model, build);
        model.addAttribute("page", page);

        model.addAttribute("brand", brand);
        model.addAttribute("model", _model);
        model.addAttribute("build", build);

        if (page.getTotalElements() > 0) {
            int avg = mService.averageTimeOnSale(brand, _model, build);
            model.addAttribute("avg", avg);
        }//from  w  w  w. ja v a  2 s  .c o m
    }
    return "autoscout/daysForSale";
}

From source file:siddur.solidtrust.marktplaats.MarktplaatsController.java

@RequestMapping(value = "/daysForSale")
public String timeForSale(@RequestParam(value = "brand", required = false) String brand,
        @RequestParam(value = "model", required = false) String _model,
        @RequestParam(value = "build", required = false) String build,
        @RequestParam(value = "fuelType", required = false) String fuelType,
        @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageIndex,
        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, Model model)
        throws Exception {
    if (!StringUtils.isEmpty(brand)) {
        Pageable pageable = new PageRequest(pageIndex - 1, pageSize);
        Page<MarktplaatsCar> page = mService.timeOnSale(pageable, brand, _model, build, fuelType);
        model.addAttribute("page", page);

        model.addAttribute("brand", brand);
        model.addAttribute("model", _model);
        model.addAttribute("build", build);
        model.addAttribute("fuelType", fuelType);

        if (page.getTotalElements() > 0) {
            int avg = mService.averageTimeOnSale(brand, _model, build, fuelType);
            model.addAttribute("avg", avg);
        }/*from  ww  w.  j  av  a2 s  .  co  m*/
    }
    return "marktplaats/daysForSale";
}

From source file:siddur.solidtrust.marktplaats.MarktplaatsController.java

@RequestMapping(value = "/stadagen")
public String stadagen(@RequestParam(value = "id", required = false) String id,
        @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageIndex,
        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, Model model)
        throws Exception {
    if (!StringUtils.isEmpty(id)) {
        model.addAttribute("id", id);

        AzureCar entity = azureService.findByLicensePlate(id);
        if (entity != null) {
            String brand = entity.getBrand();
            String _model = entity.getType();

            @SuppressWarnings("deprecation")
            String build = (entity.getDateOfBuild().getYear() + 1900) + "";

            Pageable pageable = new PageRequest(pageIndex - 1, pageSize);
            Page<MarktplaatsCar> page = mService.timeOnSaleByLucene(pageable, brand, _model, build);
            model.addAttribute("page", page);

            if (page.getTotalElements() > 0) {
                int avg = mService.averageTimeOnSaleByLucene(brand, _model, build);
                model.addAttribute("avg", avg);
            }/*from  w  ww.j  a va 2s .co  m*/
        }
    }
    return "marktplaats/stadagen";
}