@Transactional(readOnly = true) public Slice<ListAnnouncementDTO> list(final ListAnnouncementRequest request, final Pageable pageRequest) { final ListAnnouncementFilter filter = new ListAnnouncementFilter(occupationRepository); if (!activeUserService.isModeratorOrAdmin()) { filter.withSubscriberPerson(activeUserService.requireActivePerson()); } final Optional<Organisation> maybeOrganisation = resolveOrganisation(request); switch (request.getDirection()) { case SENT: maybeOrganisation.ifPresent(filter::withFromOrganisation); break; case RECEIVED: maybeOrganisation.ifPresent(filter::withSubscriberOrganisation); break; default: throw new IllegalArgumentException("Invalid direction"); } return filter.buildPredicate() .map(predicate -> announcementRepository.findAllAsSlice(predicate, pageRequest)) .map(slice -> transform(pageRequest, slice)) .orElseGet(() -> new SliceImpl<>(emptyList())); }
@Override public <T> Slice<T> findSlice(Query<T> query) { List<T> list = findAllInternal(query); Pageable pageable = query.getPageable(); if (pageable != null) { boolean hasNext = ((pageable.getPageNumber() + 1) * pageable.getPageSize() < total(query)); return new SliceImpl<T>(list, query.getPageable(), hasNext); } else { return new SliceImpl<T>(list); } }
@Override @SuppressWarnings("unchecked") protected Object doExecute(AbstractEbeanQuery query, Object[] values) { ParametersParameterAccessor accessor = new ParametersParameterAccessor(parameters, values); Pageable pageable = accessor.getPageable(); Object createQuery = query.createQuery(values); List<Object> resultList = null; int pageSize = pageable.getPageSize(); if (createQuery instanceof Query) { Query ormQuery = (Query) createQuery; ormQuery.setMaxRows(pageSize + 1); ormQuery.findList(); } else if (createQuery instanceof SqlQuery) { SqlQuery sqlQuery = (SqlQuery) createQuery; sqlQuery.setMaxRows(pageSize + 1); sqlQuery.findList(); } else { throw new InvalidEbeanQueryMethodException("query must be Query or SqlQuery"); } boolean hasNext = resultList != null && resultList.size() > pageSize; return new SliceImpl<Object>(hasNext ? resultList.subList(0, pageSize) : resultList, pageable, hasNext); }
@Override protected Object doExecute(AbstractMybatisQuery query, Object[] values) { MybatisParameters parameters = query.getQueryMethod().getParameters(); Map<String, Object> parameter = new HashMap<String, Object>(); int c = 0; for (MybatisParameter param : parameters.getBindableParameters()) { String name = param.getName(); if (StringUtils.isEmpty(name)) { name = "p" + c; } parameter.put(name, values[param.getIndex()]); c++; } Pageable pageable = (Pageable) values[parameters.getPageableIndex()]; if (parameters.hasSortParameter()) { parameter.put("_sorts", values[parameters.getSortIndex()]); } else { parameter.put("_sorts", pageable.getSort()); } parameter.put("offset", pageable.getOffset()); parameter.put("pageSize", pageable.getPageSize() + 1); parameter.put("offsetEnd", pageable.getOffset() + pageable.getPageSize()); List<Object> resultList = query.getSqlSessionTemplate().selectList(query.getStatementId(), parameter); int pageSize = pageable.getPageSize(); boolean hasNext = resultList.size() > pageSize; return new SliceImpl<Object>(hasNext ? resultList.subList(0, pageSize) : resultList, pageable, hasNext); }
private static <S> Slice<S> toSlice(final List<S> results, final Pageable page) { boolean hasNext = false; if (results.size() > page.getPageSize()) { // Remove the extra element results.remove(results.size() - 1); hasNext = true; } return new SliceImpl<>(results, page, hasNext); }
@Test public void findByCanaryUuids() throws Exception { List<UUID> canaryUuids = Collections.singletonList(UUID.randomUUID()); Slice<EncryptedValue> encryptedValues = new SliceImpl(Collections.singletonList(new EncryptedValue())); when(encryptedValueRepository.findByEncryptionKeyUuidIn(eq(canaryUuids), any())).thenReturn(encryptedValues); assertThat(subject.findByCanaryUuids(canaryUuids), equalTo(encryptedValues)); }
@Before public void beforeEach() { oldUuid = UUID.randomUUID(); UUID activeUuid = UUID.randomUUID(); encryptedValueDataService = mock(EncryptedValueDataService.class); keySet = new EncryptionKeySet(); keySet.add(oldUuid, mock(Key.class)); keySet.add(activeUuid, mock(Key.class)); keySet.setActive(activeUuid); encryptedValue1 = mock(EncryptedValue.class); encryptedValue2 = mock(EncryptedValue.class); encryptedValue3 = mock(EncryptedValue.class); encryptionKeyCanaryMapper = mock(EncryptionKeyCanaryMapper.class); inactiveCanaries = newArrayList(oldUuid); when(encryptedValueDataService.findByCanaryUuids(inactiveCanaries)) .thenReturn(new SliceImpl<>(asList(encryptedValue1, encryptedValue2))) .thenReturn(new SliceImpl<>(asList(encryptedValue3))) .thenReturn(new SliceImpl<>(new ArrayList<>())); final EncryptionKeyRotator encryptionKeyRotator = new EncryptionKeyRotator(encryptedValueDataService, encryptionKeyCanaryMapper, keySet); encryptionKeyRotator.rotate(); }
/** * {@inheritDoc} * <p> * This specific implementation pages by series. * </p> */ @Override @Transactional(readOnly = true) public Slice<Album> findPaginated(int currentPage, Order... orders) { // Adjust the page number: Spring Data counts from 0 currentPage--; if (orders.length > 0) { throw new UnsupportedOperationException("It is not possible to override the order for pages of albums"); } Pageable pageable = new PageRequest(currentPage, configurationService.getConfiguration().getPageSizeForAlbums()); Slice<MetaSeries> metaSlice = metaSeriesRepo.findAll(pageable); // At the very least, there will be that many elements List<Album> albumList = new ArrayList<Album>(metaSlice.getNumberOfElements()); // Add all albums for (MetaSeries meta : metaSlice) { if (meta.getSeries() != null) { LOGGER.debug("Adding all {} albums from {}", meta.getSeries().getAlbums().size(), meta.getSeries().getIdentifyingName()); albumList.addAll(meta.getSeries().getAlbums()); } else { LOGGER.debug("Adding one shot album: {}", meta.getAlbum().getIdentifyingName()); albumList.add(meta.getAlbum()); } } return new SliceImpl<Album>(albumList, pageable, metaSlice.hasNext()); }
/** * <P> * Slices and pages are similar ways to iterate through the result set in blocks, mimicking a cursor. A * {@link org.springframework.data.domain.Slice Slice} is a simpler concept, only requiring to know if further blocks * of data are available. A {@link org.springframework.data.domain.Page Page} requires to know how many blocks of data * are available in total. * </P> * * @param parameters For the query * @param query The query to run * @param queryMethod Holds metadata about the query * @return Query result */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Object executePageSliceQuery(final Object[] parameters, final KeyValueQuery<?> query, final QueryMethod queryMethod) { long totalElements = -1; int indexOfPageRequest = queryMethod.getParameters().getPageableIndex(); Pageable pageRequest = (Pageable) parameters[indexOfPageRequest]; /* TODO Eliminate count call for Slice, retrieve "rows+1" instead to determine if next page exists. */ if (query.getCritieria() == null) { totalElements = this.keyValueOperations.count(queryMethod.getEntityInformation().getJavaType()); } else { totalElements = this.keyValueOperations.count(query, queryMethod.getEntityInformation().getJavaType()); } int requiredRows = pageRequest.getPageSize(); query.setOffset(pageRequest.getOffset()); query.setRows(pageRequest.getPageSize()); Iterable<?> resultSet = this.keyValueOperations.find(query, queryMethod.getEntityInformation().getJavaType()); List<?> content = IterableConverter.toList(resultSet); if (queryMethod.isPageQuery()) { return new PageImpl(content, pageRequest, totalElements); } else { boolean hasNext = totalElements > (query.getOffset() + query.getRows()); if (content.size() > requiredRows) { content = content.subList(0, requiredRows); } return new SliceImpl(content, pageRequest, hasNext); } }
private Slice<T> createSlice(List<T> allResults, Pageable pageable) { Iterator<T> iterator = allResults.iterator(); int processedCount = 0; if (pageable.getOffset() > 0) { processedCount = scanThroughResults(iterator, pageable.getOffset()); if (processedCount < pageable.getOffset()) return new SliceImpl<T>(new ArrayList<T>()); } List<T> results = readPageOfResultsRestrictMaxResultsIfNecessary(iterator, pageable.getPageSize()); // Scan ahead to retrieve the next page count boolean hasMoreResults = scanThroughResults(iterator, 1) > 0; if (getResultsRestrictionIfApplicable() != null && getResultsRestrictionIfApplicable().intValue() <= results.size()) hasMoreResults = false; return new SliceImpl<T>(results, pageable, hasMoreResults); }
private Slice<ListAnnouncementDTO> transform(final Pageable pageRequest, final Slice<Announcement> slice) { return new SliceImpl<>(announcementDTOTransformer.transform(slice.getContent()), pageRequest, slice.hasNext()); }
@Override public Slice<Target> findByFilterOrderByLinkedDistributionSet(final Pageable pageable, final Long orderByDistributionId, final FilterParams filterParams) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class); final Root<JpaTarget> targetRoot = query.from(JpaTarget.class); // select case expression to retrieve the case value as a column to be // able to order based on // this column, installed first,... final Expression<Object> selectCase = cb.selectCase() .when(cb.equal(targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 1) .when(cb.equal(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 2) .otherwise(100); // multiselect statement order by the select case and controllerId query.distinct(true); // build the specifications and then to predicates necessary by the // given filters final Predicate[] specificationsForMultiSelect = specificationsToPredicate(buildSpecificationList(filterParams), targetRoot, query, cb); // if we have some predicates then add it to the where clause of the // multiselect if (specificationsForMultiSelect.length > 0) { query.where(specificationsForMultiSelect); } // add the order to the multi select first based on the selectCase query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(JpaTarget_.id))); // the result is a Object[] due the fact that the selectCase is an extra // column, so it cannot // be mapped directly to a Target entity because the selectCase is not a // attribute of the // Target entity, the the Object array contains the Target on the first // index (case of the // multiselect order) of the array and // the 2nd contains the selectCase int value. final int pageSize = pageable.getPageSize(); final List<JpaTarget> resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) .setMaxResults(pageSize + 1).getResultList(); final boolean hasNext = resultList.size() > pageSize; return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext); }
@Override public Slice<AssignedSoftwareModule> findAllOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( final Pageable pageable, final Long orderByDistributionId, final String searchText, final Long typeId) { final List<AssignedSoftwareModule> resultList = new ArrayList<>(); final int pageSize = pageable.getPageSize(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); // get the assigned software modules final CriteriaQuery<JpaSoftwareModule> assignedQuery = cb.createQuery(JpaSoftwareModule.class); final Root<JpaSoftwareModule> assignedRoot = assignedQuery.from(JpaSoftwareModule.class); assignedQuery.distinct(true); final ListJoin<JpaSoftwareModule, JpaDistributionSet> assignedDsJoin = assignedRoot .join(JpaSoftwareModule_.assignedTo); // build the specifications and then to predicates necessary by the // given filters final Predicate[] specPredicate = specificationsToPredicate(buildSpecificationList(searchText, typeId), assignedRoot, assignedQuery, cb, cb.equal(assignedDsJoin.get(JpaDistributionSet_.id), orderByDistributionId)); // if we have some predicates then add it to the where clause of the // multi select assignedQuery.where(specPredicate); assignedQuery.orderBy(cb.asc(assignedRoot.get(JpaSoftwareModule_.name)), cb.asc(assignedRoot.get(JpaSoftwareModule_.version))); // don't page the assigned query on database, we need all assigned // software modules to filter // them out in the unassigned query final List<JpaSoftwareModule> assignedSoftwareModules = entityManager.createQuery(assignedQuery) .getResultList(); // map result if (pageable.getOffset() < assignedSoftwareModules.size()) { assignedSoftwareModules .subList(pageable.getOffset(), Math.min(assignedSoftwareModules.size(), pageable.getPageSize())) .forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, true))); } if (assignedSoftwareModules.size() >= pageSize) { return new SliceImpl<>(resultList); } // get the unassigned software modules final CriteriaQuery<JpaSoftwareModule> unassignedQuery = cb.createQuery(JpaSoftwareModule.class); unassignedQuery.distinct(true); final Root<JpaSoftwareModule> unassignedRoot = unassignedQuery.from(JpaSoftwareModule.class); Predicate[] unassignedSpec; if (!assignedSoftwareModules.isEmpty()) { unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot, unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id).in( assignedSoftwareModules.stream().map(SoftwareModule::getId).collect(Collectors.toList())))); } else { unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot, unassignedQuery, cb); } unassignedQuery.where(unassignedSpec); unassignedQuery.orderBy(cb.asc(unassignedRoot.get(JpaSoftwareModule_.name)), cb.asc(unassignedRoot.get(JpaSoftwareModule_.version))); final List<JpaSoftwareModule> unassignedSoftwareModules = entityManager.createQuery(unassignedQuery) .setFirstResult(Math.max(0, pageable.getOffset() - assignedSoftwareModules.size())) .setMaxResults(pageSize).getResultList(); // map result unassignedSoftwareModules.forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, false))); return new SliceImpl<>(resultList); }
@Transactional(readOnly = true) @Override public Slice<Tag> findPaginated(int currentPage, Order... orders) { return new SliceImpl<>(repo.findAllWithUsageCounts()); }