Example usage for org.springframework.data.domain Pageable getPageNumber

List of usage examples for org.springframework.data.domain Pageable getPageNumber

Introduction

In this page you can find the example usage for org.springframework.data.domain Pageable getPageNumber.

Prototype

int getPageNumber();

Source Link

Document

Returns the page to be returned.

Usage

From source file:org.ngrinder.perftest.controller.PerfTestController.java

/**
 * Get the perf test lists.//  ww  w . j a v a  2  s .  co m
 *
 * @param user        user
 * @param query       query string to search the perf test
 * @param tag         tag
 * @param queryFilter "F" means get only finished, "S" means get only scheduled tests.
 * @param pageable    page
 * @param model       modelMap
 * @return perftest/list
 */
@RequestMapping({ "/list", "/", "" })
public String getAll(User user, @RequestParam(required = false) String query,
        @RequestParam(required = false) String tag, @RequestParam(required = false) String queryFilter,
        @PageableDefaults Pageable pageable, ModelMap model) {
    pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(),
            defaultIfNull(pageable.getSort(), new Sort(Direction.DESC, "lastModifiedDate")));
    Page<PerfTest> tests = perfTestService.getPagedAll(user, query, tag, queryFilter, pageable);
    annotateDateMarker(tests);
    model.addAttribute("tag", tag);
    model.addAttribute("availTags", tagService.getAllTagStrings(user, StringUtils.EMPTY));
    model.addAttribute("testListPage", tests);
    model.addAttribute("queryFilter", queryFilter);
    model.addAttribute("query", query);
    putPageIntoModelMap(model, pageable);
    return "perftest/list";
}

From source file:ei.ne.ke.cassandra.cql3.AstyanaxCql3Repository.java

protected Page<T> doFindAll(ID restrict, Pageable pageable) {
    /*/*from ww  w  .  j  a  v  a 2  s  .  com*/
     * Example #1
     *   pageNumber = 0
     *   pageSize = 25
     *   offset = 0
     *   => start row = 0
     *   => end row = 24 (including)
     *
     * Example #2
     *   pageNumber = 1
     *   pageSize = 25
     *   offset = 0
     *   => start row = 25
     *   => end row = 49 (including)
     *
     * Example #3
     *   pageNumber = 1
     *   pageSize = 25
     *   offset = 10
     *   => start row = 35
     *   => end row = 59 (including)
     */
    try {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int offset = pageable.getOffset();
        int firstRow = pageNumber * pageSize + offset;
        int lastRow = (pageNumber + 1) * pageSize + offset;
        Map<String, ByteBuffer> serializedKeyValues = spec.getSerializedKeyValues(restrict);
        List<String> keysSet = EntitySpecificationUtils.getKeysSet(serializedKeyValues);
        String keysCql = cqlGen.buildLimitedFindAllKeysStatement(keysSet, pageable.getSort(), lastRow);
        PreparedCqlQuery<String, String> preparedStatement = doPreparedCqlRead(keysCql);
        for (String column : keysSet) {
            preparedStatement = preparedStatement.withValue(serializedKeyValues.get(column));
        }
        OperationResult<CqlResult<String, String>> keysResult = preparedStatement.execute();
        LOGGER.debug("attempts: {}, latency: {}ms", keysResult.getAttemptsCount(),
                keysResult.getLatency(TimeUnit.MILLISECONDS));
        CqlResult<String, String> cqlKeysResult = keysResult.getResult();
        Rows<String, String> keysSetRows = cqlKeysResult.getRows();
        List<T> keysAsEnts = Lists.newArrayListWithExpectedSize(lastRow - firstRow + 1);
        for (int i = firstRow; i < keysSetRows.size() && i < lastRow; i++) {
            keysAsEnts.add(spec.map(keysSetRows.getRowByIndex(i).getColumns()));
        }
        List<ID> keys = spec.getKey(keysAsEnts);
        return new PageImpl<T>((List<T>) findAll(keys), pageable, count(restrict));
    } catch (ConnectionException e) {
        throw new DataRetrievalFailureException("Error while executing CQL3 query", e);
    }
}

From source file:ru.portal.services.TableServiceImpl.java

@Override
public Page<HashMap<String, String>> findAll(String tableOrViewName, Pageable pageable) {

    List<HashMap<String, String>> result = new ArrayList<>();

    EntityType<?> type = null;//from w w w.  ja  v a2s .c  o  m
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                type = entityType;
                break;
            }
        }
    }

    Long totalRows = 0L;

    if (type != null) {
        Class<?> bindableJavaType = type.getBindableJavaType();

        //count
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(bindableJavaType)));
        totalRows = em.createQuery(countQuery).getSingleResult();

        //select
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
        Root<?> root = cq.from(bindableJavaType);
        //          cq.select(root);
        if (pageable == null) {
            pageable = new PageRequest(0, 50);
        }

        TypedQuery<?> query = em.createQuery(cq);

        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<?> all = query.getResultList();

        List<String> columns = getTableOrViewMetaData(tableOrViewName);

        for (Object object : all) {

            HashMap<String, String> res = new HashMap<>(columns.size());
            Class<? extends Object> clazz = object.getClass();
            for (String fieldName : columns) {
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object fieldValue = field.get(object);
                    res.put(fieldName, fieldValue.toString());
                    //TODO cast data integer long etc
                } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                        | IllegalAccessException ex) {
                    Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            result.add(res);
        }
    }

    PageImpl<HashMap<String, String>> list = new PageImpl<>(result, pageable, totalRows);
    return list;
}

From source file:org.jbb.members.web.base.logic.MemberSearchCriteriaFactory.java

private Pageable includeSortingToPageable(SearchMemberForm form, Pageable pageable) {
    return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
            Direction.fromString(form.getSortDirection()), form.getSortByField());
}

From source file:org.opentestsystem.shared.progman.client.ProgramManagementClient.java

private static Map<String, String> getPageableParams(final Pageable pageable) {
    Map<String, String> params = Maps.newHashMap();
    params.put("page.page", "");
    params.put("page.size", "");
    params.put("page.sort", "");
    params.put("page.sort.dir", "");

    if (pageable != null) {
        params.put("page.page", Integer.toString(pageable.getPageNumber()));
        params.put("page.size", Integer.toString(pageable.getPageSize()));
        if (pageable.getSort() != null && pageable.getSort().iterator().hasNext()) {
            Order firstOrder = pageable.getSort().iterator().next();
            params.put("page.sort", firstOrder.getProperty());
            params.put("page.sort.dir", firstOrder.getDirection().name());
        }/*from   w  ww  .j  a v  a2  s.c  o m*/
    }

    return params;
}

From source file:org.springframework.cloud.dataflow.server.stream.AppDeployerStreamDeployer.java

@Override
public Page<AppStatus> getAppStatuses(Pageable pageable) throws ExecutionException, InterruptedException {

    Iterable<StreamDefinition> streamDefinitions = this.streamDefinitionRepository.findAll();
    Iterable<StreamDeployment> streamDeployments = this.streamDeploymentRepository.findAll();

    List<String> appDeployerStreams = new ArrayList<>();
    for (StreamDeployment streamDeployment : streamDeployments) {
        appDeployerStreams.add(streamDeployment.getStreamName());

    }/*from   w  ww .j a  va 2  s .c  o  m*/

    List<StreamDefinition> appDeployerStreamDefinitions = new ArrayList<>();
    for (StreamDefinition streamDefinition : streamDefinitions) {
        if (appDeployerStreams.contains(streamDefinition.getName())) {
            appDeployerStreamDefinitions.add(streamDefinition);
        }
    }

    // First build a sorted list of deployment id's so that we have a predictable paging order.
    List<String> deploymentIds = appDeployerStreamDefinitions.stream()
            .flatMap(sd -> sd.getAppDefinitions().stream()).flatMap(sad -> {
                String key = DeploymentKey.forStreamAppDefinition(sad);
                String id = this.deploymentIdRepository.findOne(key);
                return id != null ? Stream.of(id) : Stream.empty();
            }).sorted(String::compareTo).collect(Collectors.toList());

    // Running this this inside the FJP will make sure it is used by the parallel stream
    // Skip first items depending on page size, then take page and discard rest.
    List<AppStatus> content = this.forkJoinPool.submit(() -> deploymentIds.stream()
            .skip(pageable.getPageNumber() * pageable.getPageSize()).limit(pageable.getPageSize()).parallel()
            .map(appDeployer::status).collect(Collectors.toList())).get();
    return new PageImpl<>(content, pageable, deploymentIds.size());
}

From source file:org.springframework.cloud.dataflow.server.stream.SkipperStreamDeployer.java

@Override
public Page<AppStatus> getAppStatuses(Pageable pageable) {
    List<String> skipperStreams = new ArrayList<>();
    Iterable<StreamDefinition> streamDefinitions = this.streamDefinitionRepository.findAll();
    for (StreamDefinition streamDefinition : streamDefinitions) {
        skipperStreams.add(streamDefinition.getName());
    }/*  w w  w .j a v a2s.  c  o  m*/

    List<AppStatus> allStatuses = getStreamsStatuses(skipperStreams);

    List<AppStatus> pagedStatuses = allStatuses.stream().skip(pageable.getPageNumber() * pageable.getPageSize())
            .limit(pageable.getPageSize()).parallel().collect(Collectors.toList());

    return new PageImpl<>(pagedStatuses, pageable, allStatuses.size());
}

From source file:org.springframework.xd.dirt.util.PagingUtility.java

/**
 * Get the paged data of the given list.
 *
 * @param pageable the paging information, must not be null
 * @param list the list of content to paginate, must not be null
 * @return the paginated implementation of the given list of <T>
 * @throws PageNotFoundException in case an invalid page is requested
 *///from w w  w. j av a  2 s .c  om
public Page<T> getPagedData(Pageable pageable, List<T> list) throws PageNotFoundException {

    Assert.notNull(pageable, "Pagination info can't be null.");
    Assert.notNull(list, "The provided list must not be null.");

    final int offset = pageable.getOffset();
    final int to = Math.min(list.size(), offset + pageable.getPageSize());

    if (offset > to) {
        throw new PageNotFoundException(String.format("Page %s does not exist.", pageable.getPageNumber()));
    }

    if (CollectionUtils.isEmpty(list)) {
        return new PageImpl<T>(list);
    }

    Collections.sort(list);

    final List<T> data = list.subList(offset, to);
    return new PageImpl<T>(data, pageable, list.size());
}

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/* w  w  w  . j  a  v  a  2  s  .c o m*/
        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.AutoscoutService.java

public Page<ScoutCar> timeOnSale(Pageable pageable, String brand, String model, String build) {
    String baseJpql = "from AutoscoutNl m where m.dateRegisted is not null and m.repetition is null";
    if (!StringUtils.isEmpty(brand)) {
        baseJpql += " and m.brand = '" + brand + "'";
    }/*  w  w  w .  j a va2 s  .  c o  m*/
    if (!StringUtils.isEmpty(model)) {
        baseJpql += " and m.model = '" + model + "'";
    }
    if (!StringUtils.isEmpty(build)) {
        baseJpql += " and m.build = '" + build + "'";
    }

    long count = em.createQuery("select count(m) " + baseJpql, Long.class).getSingleResult();

    String jpql = selectSQL + baseJpql;
    log4j.info(jpql);

    List<Object[]> list = em.createQuery(jpql, Object[].class)
            .setFirstResult(pageable.getPageSize() * pageable.getPageNumber())
            .setMaxResults(pageable.getPageSize()).getResultList();
    List<ScoutCar> results = ScoutCar.toScoutCarList(list, true);
    Page<ScoutCar> page = new PageImpl<ScoutCar>(results, pageable, (int) count);
    return page;
}