org.springframework.data.domain.SliceImpl Java Examples

The following examples show how to use org.springframework.data.domain.SliceImpl. 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 File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private Slice executeSliceQuery(Object[] parameters) {
	StructuredQuery.Builder builder = getEntityOrProjectionQueryBuilder()
			.setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery query = applyQueryBody(parameters, builder, false, false, null);
	DatastoreResultsIterable<?> resultList = this.datastoreOperations.queryKeysOrEntities(query, this.entityType);

	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);

	Pageable pageable = DatastorePageable.from(paramAccessor.getPageable(), resultList.getCursor(), null);

	EntityQuery.Builder builderNext = newEntityQueryBuilder().setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery queryNext = applyQueryBody(parameters, builderNext, false, true, resultList.getCursor());
	Iterable nextResult = this.datastoreOperations.query(queryNext, x -> x);

	List<Object> result =
					StreamSupport.stream(resultList.spliterator(), false).collect(Collectors.toList());

	return (Slice) this.processRawObjectForProjection(
			new SliceImpl(result, pageable, nextResult.iterator().hasNext()));
}
 
Example #2
Source File: GqlDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private Slice buildSlice(Pageable pageableParam, ParsedQueryWithTagsAndValues parsedQueryWithTagsAndValues,
		Cursor cursor, List resultsList) {
	GqlQuery nextQuery = parsedQueryWithTagsAndValues.bindArgsToGqlQuery(cursor, 1);
	DatastoreResultsIterable<?> next = this.datastoreOperations.queryKeysOrEntities(nextQuery, this.entityType);

	Pageable pageable = DatastorePageable.from(pageableParam, cursor, null);
	return new SliceImpl(resultsList, pageable, next.iterator().hasNext());
}
 
Example #3
Source File: EbeanQueryWrapper.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
<E> Slice<E> findSlice(Pageable pageable) {
    List<E> resultList = null;
    int pageSize = pageable.getPageSize();
    int offset = (int) pageable.getOffset();
    if (queryType == QUERY) {
        resultList = ((Query<E>) queryInstance).setFirstRow(offset).setMaxRows(pageSize + 1).findList();
        boolean hasNext = resultList.size() > pageSize;
        return new SliceImpl<E>(hasNext ? resultList.subList(0, pageSize) : resultList, pageable, hasNext);
    }
    throw new IllegalArgumentException("query not supported!");
}
 
Example #4
Source File: EncryptedValueDataServiceTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void findByCanaryUuids() throws Exception {
  final List<UUID> canaryUuids = Collections.singletonList(UUID.randomUUID());
  final Slice<EncryptedValue> encryptedValues = new SliceImpl(Collections.singletonList(new EncryptedValue()));
  when(encryptedValueRepository.findByEncryptionKeyUuidIn(eq(canaryUuids), any())).thenReturn(encryptedValues);

  assertThat(subject.findByCanaryUuids(canaryUuids), equalTo(encryptedValues));
}
 
Example #5
Source File: EncryptionKeyRotatorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() {
  oldUuid = UUID.randomUUID();
  final UUID activeUuid = UUID.randomUUID();

  encryptedValueDataService = mock(EncryptedValueDataService.class);
  keySet = new EncryptionKeySet();
  keySet.add(new EncryptionKey(mock(InternalEncryptionService.class), oldUuid, mock(Key.class), "key-name"));
  keySet.add(new EncryptionKey(mock(InternalEncryptionService.class), activeUuid, mock(Key.class), "key-name"));
  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();
}
 
Example #6
Source File: HazelcastPartTreeQuery.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * <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.getCriteria() == 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);
    }
}
 
Example #7
Source File: AbstractDynamoDBQuery.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
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);
		}
 
Example #8
Source File: JpaTargetManagement.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@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);
    // 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 of the array and
    // the 2nd contains the selectCase int value.
    final int pageSize = pageable.getPageSize();
    final List<JpaTarget> resultList = entityManager.createQuery(query).setFirstResult((int) pageable.getOffset())
            .setMaxResults(pageSize + 1).getResultList();
    final boolean hasNext = resultList.size() > pageSize;
    return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext);
}
 
Example #9
Source File: JpaSoftwareModuleManagement.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@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((int) 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((int) 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);
}