org.springframework.data.domain.Slice Java Examples

The following examples show how to use org.springframework.data.domain.Slice. 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: ActionBeanQuery.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a list of {@link ProxyAction}s for presentation layer from slice
 * of {@link Action}s.
 *
 * @param actionBeans
 *            slice of {@link Action}s
 * @return list of {@link ProxyAction}s
 */
private static List<ProxyAction> createProxyActions(final Slice<Action> actionBeans) {
    final List<ProxyAction> proxyActions = new ArrayList<>();
    for (final Action action : actionBeans) {
        final ProxyAction proxyAction = new ProxyAction();
        final String dsNameVersion = action.getDistributionSet().getName() + ":"
                + action.getDistributionSet().getVersion();
        proxyAction.setActive(action.isActive());
        proxyAction.setIsActiveDecoration(buildIsActiveDecoration(action));
        proxyAction.setDsNameVersion(dsNameVersion);
        proxyAction.setAction(action);
        proxyAction.setId(action.getId());
        proxyAction.setLastModifiedAt(action.getLastModifiedAt());
        proxyAction.setRolloutName(action.getRollout() != null ? action.getRollout().getName() : "");
        proxyAction.setStatus(action.getStatus());
        proxyAction.setMaintenanceWindow(
                action.hasMaintenanceSchedule() ? buildMaintenanceWindowDisplayText(action) : "");

        proxyActions.add(proxyAction);
    }
    return proxyActions;
}
 
Example #2
Source File: AutoAssignCheckerTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param set
 *            the expected distribution set
 * @param targets
 *            the targets that should have it
 */
@Step
private void verifyThatTargetsHaveDistributionSetAssignment(final DistributionSet set, final List<Target> targets,
        final int count) {
    final List<Long> targetIds = targets.stream().map(Target::getId).collect(Collectors.toList());

    final Slice<Target> targetsAll = targetManagement.findAll(PAGE);
    assertThat(targetsAll).as("Count of targets").hasSize(count);

    for (final Target target : targetsAll) {
        if (targetIds.contains(target.getId())) {
            assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get())
                    .as("assigned DS").isEqualTo(set);
        }
    }

}
 
Example #3
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void sliceQueryLast() throws NoSuchMethodException {
	queryWithMockResult("findByActionAndSymbolAndPriceLessThanAndPriceGreater"
					+ "ThanEqualAndIdIsNull", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class,
					Pageable.class));

	this.partTreeDatastoreQuery = createQuery(false, true, null);

	Object[] params = new Object[] { "BUY", "abcd", 8.88, 3.33, PageRequest.of(1, 2, Sort.Direction.DESC, "id") };

	prepareSliceResults(2, 2, true);

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	Slice result = (Slice) this.partTreeDatastoreQuery.execute(params);
	assertThat(result.hasNext()).isEqualTo(true);

	verify(this.datastoreTemplate, times(1))
			.query(any(), (Function) any());

	verify(this.datastoreTemplate, times(0))
			.queryKeysOrEntities(isA(KeyQuery.class), any());
}
 
Example #4
Source File: MultiTenancyEntityTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description(value = "Ensures that targtes created by a tenant are not visible by another tenant.")
@WithUser(tenantId = "mytenant", allSpPermissions = true)
public void queryTargetFromDifferentTenantIsNotVisible() throws Exception {
    // create target for another tenant
    final String anotherTenant = "anotherTenant";
    final String controllerAnotherTenant = "anotherController";
    createTargetForTenant(controllerAnotherTenant, anotherTenant);

    // find all targets for current tenant "mytenant"
    final Slice<Target> findTargetsAll = targetManagement.findAll(PAGE);
    // no target has been created for "mytenant"
    assertThat(findTargetsAll).hasSize(0);

    // find all targets for anotherTenant
    final Slice<Target> findTargetsForTenant = findTargetsForTenant(anotherTenant);
    // another tenant should have targets
    assertThat(findTargetsForTenant).hasSize(1);
}
 
Example #5
Source File: UserServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
/**
 * Get user's favorite author page
 *
 * @param page     page number
 * @param pageSize page size
 * @return favorite author page
 */
@Override
public Slice<?> getFavoriteAuthor(Integer page, Integer pageSize) {
    if (pageSize > BIG_SIZE.getValue()) {
        pageSize = BIG_SIZE.getValue();
    }
    User user = UserUtils.getUser();
    if (user == null) {
        return null;
    }
    if (user.getFavoriteMid() == null) {
        return null;
    }
    ArrayList<Long> mids = user.getFavoriteMid();
    ArrayList<HashMap<String, Long>> mapsList = new ArrayList<>();
    for (Long mid : mids) {
        HashMap<String, Long> temp = new HashMap<>(1);
        temp.put("mid", mid);
        mapsList.add(temp);
    }
    UserServiceImpl.logger.info(user.getName());
    Slice<Author> authors = authorRepository.getFavoriteAuthor(mapsList, PageRequest.of(page, pageSize));
    authorUtil.getInterval(authors.getContent());
    return authors;
}
 
Example #6
Source File: DatastoreIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testSlice() {
	List<TestEntity> results = new ArrayList<>();
	Slice<TestEntity> slice = this.testEntityRepository.findEntitiesWithCustomQuerySlice("red",
			PageRequest.of(0, 1));

	assertThat(slice.hasNext()).isTrue();
	assertThat(slice).hasSize(1);
	results.addAll(slice.getContent());

	slice = this.testEntityRepository.findEntitiesWithCustomQuerySlice("red",
			slice.getPageable().next());

	assertThat(slice.hasNext()).isTrue();
	assertThat(slice).hasSize(1);
	results.addAll(slice.getContent());

	slice = this.testEntityRepository.findEntitiesWithCustomQuerySlice("red",
			slice.getPageable().next());

	assertThat(slice.hasNext()).isFalse();
	assertThat(slice).hasSize(1);
	results.addAll(slice.getContent());

	assertThat(results).containsExactlyInAnyOrder(this.testEntityA, this.testEntityC, this.testEntityD);
}
 
Example #7
Source File: JpaRolloutManagement.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
private void deleteScheduledActions(final JpaRollout rollout, final Slice<JpaAction> scheduledActions) {
    final boolean hasScheduledActions = scheduledActions.getNumberOfElements() > 0;

    if (hasScheduledActions) {
        try {
            final Iterable<JpaAction> iterable = scheduledActions::iterator;
            final List<Long> actionIds = StreamSupport.stream(iterable.spliterator(), false).map(Action::getId)
                    .collect(Collectors.toList());
            actionRepository.deleteByIdIn(actionIds);
            afterCommit.afterCommit(() -> eventPublisherHolder.getEventPublisher()
                    .publishEvent(new RolloutUpdatedEvent(rollout, eventPublisherHolder.getApplicationId())));
        } catch (final RuntimeException e) {
            LOGGER.error("Exception during deletion of actions of rollout {}", rollout, e);
        }
    }
}
 
Example #8
Source File: MultiTenancyEntityTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description(value = "Ensures that targets created from a different tenant cannot be deleted from other tenants")
@WithUser(tenantId = "mytenant", allSpPermissions = true)
public void deleteTargetFromOtherTenantIsNotPossible() throws Exception {
    // create target for another tenant
    final String anotherTenant = "anotherTenant";
    final String controllerAnotherTenant = "anotherController";
    final Target createTargetForTenant = createTargetForTenant(controllerAnotherTenant, anotherTenant);

    // ensure target cannot be deleted by 'mytenant'
    try {
        targetManagement.delete(Arrays.asList(createTargetForTenant.getId()));
        fail("mytenant should not have been able to delete target of anotherTenant");
    } catch (final EntityNotFoundException ex) {
        // ok
    }

    Slice<Target> targetsForAnotherTenant = findTargetsForTenant(anotherTenant);
    assertThat(targetsForAnotherTenant).hasSize(1);

    // ensure another tenant can delete the target
    deleteTargetsForTenant(anotherTenant, Arrays.asList(createTargetForTenant.getId()));
    targetsForAnotherTenant = findTargetsForTenant(anotherTenant);
    assertThat(targetsForAnotherTenant).hasSize(0);
}
 
Example #9
Source File: MgmtTargetResource.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ResponseEntity<PagedList<MgmtTarget>> getTargets(
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {

    final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
    final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
    final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);

    final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
    final Slice<Target> findTargetsAll;
    final long countTargetsAll;
    if (rsqlParam != null) {
        final Page<Target> findTargetPage = this.targetManagement.findByRsql(pageable, rsqlParam);
        countTargetsAll = findTargetPage.getTotalElements();
        findTargetsAll = findTargetPage;
    } else {
        findTargetsAll = this.targetManagement.findAll(pageable);
        countTargetsAll = this.targetManagement.count();
    }

    final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
    return ResponseEntity.ok(new PagedList<>(rest, countTargetsAll));
}
 
Example #10
Source File: DeploymentManagementTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Test verifies that actions of a target are found by using id-based search.")
public void findActionByTargetId() {
    final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
            new ArrayList<DistributionSetTag>());
    final List<Target> testTarget = testdataFactory.createTargets(1);
    // one action with one action status is generated
    final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));

    // act
    final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
            PAGE);
    final Long count = deploymentManagement.countActionsByTarget(testTarget.get(0).getControllerId());

    assertThat(count).as("One Action for target").isEqualTo(1L).isEqualTo(actions.getContent().size());
    assertThat(actions.getContent().get(0).getId()).as("Action of target").isEqualTo(actionId);
}
 
Example #11
Source File: JpaSoftwareModuleManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Slice<SoftwareModule> findByType(final Pageable pageable, final long typeId) {
    throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);

    final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(2);

    specList.add(SoftwareModuleSpecification.equalType(typeId));
    specList.add(SoftwareModuleSpecification.isDeletedFalse());

    return convertSmPage(findByCriteriaAPI(pageable, specList), pageable);
}
 
Example #12
Source File: TargetManagementSearchTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.")
public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() {

    final List<Target> notAssigned = testdataFactory.createTargets(3, "not", "first description");
    List<Target> targAssigned = testdataFactory.createTargets(3, "assigned", "first description");
    List<Target> targInstalled = testdataFactory.createTargets(3, "installed", "first description");

    final DistributionSet ds = testdataFactory.createDistributionSet("a");

    targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity().stream().map(Action::getTarget)
            .collect(Collectors.toList());
    targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity().stream().map(Action::getTarget)
            .collect(Collectors.toList());
    targInstalled = testdataFactory
            .sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
            .stream().map(Action::getTarget).collect(Collectors.toList());

    final Slice<Target> result = targetManagement.findByFilterOrderByLinkedDistributionSet(PAGE, ds.getId(),
            new FilterParams(null, null, null, null, Boolean.FALSE, new String[0]));

    final Comparator<TenantAwareBaseEntity> byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId());

    assertThat(result.getNumberOfElements()).isEqualTo(9);
    final List<Target> expected = new ArrayList<>();
    Collections.sort(targInstalled, byId);
    Collections.sort(targAssigned, byId);
    Collections.sort(notAssigned, byId);
    expected.addAll(targInstalled);
    expected.addAll(targAssigned);
    expected.addAll(notAssigned);

    assertThat(result.getContent()).usingElementComparator(controllerIdComparator())
            .containsExactly(expected.toArray(new Target[0]));

}
 
Example #13
Source File: UserRepositoryFinderTests.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void executesQueryToSlice() {

	Slice<User> slice = userRepository.findSliceByLastname("Matthews", PageRequest.of(0, 1, ASC, "firstname"));

	assertThat(slice.getContent(), hasItem(dave));
	assertThat(slice.hasNext(), is(true));
}
 
Example #14
Source File: IgniteRepositoryQuery.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param mtd Method.
 * @param isFieldQry Is field query.
 * @return Return strategy type.
 */
private ReturnStrategy calcReturnType(Method mtd, boolean isFieldQry) {
    Class<?> returnType = mtd.getReturnType();

    if (returnType == Slice.class) {
        if (isFieldQry) {
            if (hasAssignableGenericReturnTypeFrom(ArrayList.class, mtd))
                return ReturnStrategy.SLICE_OF_LISTS;
        }
        else if (hasAssignableGenericReturnTypeFrom(Cache.Entry.class, mtd))
            return ReturnStrategy.SLICE_OF_CACHE_ENTRIES;
        return ReturnStrategy.SLICE_OF_VALUES;
    }
    else if (returnType == Page.class)
        return ReturnStrategy.PAGE_OF_VALUES;
    else if (returnType == Stream.class)
        return ReturnStrategy.STREAM_OF_VALUES;
    else if (Cache.Entry.class.isAssignableFrom(returnType))
        return ReturnStrategy.CACHE_ENTRY;
    else if (Iterable.class.isAssignableFrom(returnType)) {
        if (isFieldQry) {
            if (hasAssignableGenericReturnTypeFrom(ArrayList.class, mtd))
                return ReturnStrategy.LIST_OF_LISTS;
        }
        else if (hasAssignableGenericReturnTypeFrom(Cache.Entry.class, mtd))
            return ReturnStrategy.LIST_OF_CACHE_ENTRIES;
        return ReturnStrategy.LIST_OF_VALUES;
    }
    else
        return ReturnStrategy.ONE_VALUE;
}
 
Example #15
Source File: RolloutManagementTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Step("Finish three actions of the rollout group and delete two targets")
private void finishActionAndDeleteTargetsOfFirstRunningGroup(final Rollout createdRollout) {
    // finish group one by finishing targets and deleting targets
    final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
            createdRollout.getId(), Status.RUNNING);
    final List<JpaAction> runningActions = runningActionsSlice.getContent();
    finishAction(runningActions.get(0));
    finishAction(runningActions.get(1));
    finishAction(runningActions.get(2));
    targetManagement.delete(
            Arrays.asList(runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
 
Example #16
Source File: RolloutManagementTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Step("Delete all targets of the rollout group")
private void deleteAllTargetsFromThirdGroup(final Rollout createdRollout) {
    final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
            createdRollout.getId(), Status.SCHEDULED);
    final List<JpaAction> runningActions = runningActionsSlice.getContent();
    targetManagement.delete(Arrays.asList(runningActions.get(0).getTarget().getId(),
            runningActions.get(1).getTarget().getId(), runningActions.get(2).getTarget().getId(),
            runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
 
Example #17
Source File: IgniteSpringDataQueriesSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testSliceOfLists() {
    Slice<List> lists = repo2.querySliceOfList("^[a-z]+$", new PageRequest(0, 3));

    assertEquals(3, lists.getSize());

    for (List list : lists) {
        assertEquals(2, list.size());

        assertTrue(list.get(0) instanceof Integer);
    }
}
 
Example #18
Source File: QuestionServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * get a slice of handled question
 *
 * @param page     page number
 * @param pagesize page size
 * @return a slice of questions
 */
@Override
public ResponseEntity getHandledQuestion(Integer page, Integer pagesize) {
    if (pagesize > PageSizeEnum.BIG_SIZE.getValue()) {
        return new ResponseEntity<>(new Result(PARAM_ERROR), HttpStatus.FORBIDDEN);
    }
    Slice<Question> questions =
            questionRepository.getHandledQuestions(PageRequest.of(page, pagesize));
    logger.info("获取已处理问题");
    return new ResponseEntity<>(questions, HttpStatus.OK);
}
 
Example #19
Source File: BaseSwModuleBeanQuery.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected List<ProxyBaseSoftwareModuleItem> loadBeans(final int startIndex, final int count) {
    final Slice<SoftwareModule> swModuleBeans;

    if (type == null && StringUtils.isEmpty(searchText)) {
        swModuleBeans = getSoftwareManagementService().findAll(new OffsetBasedPageRequest(startIndex, count, sort));
    } else {
        swModuleBeans = getSoftwareManagementService()
                .findByTextAndType(new OffsetBasedPageRequest(startIndex, count, sort), searchText, type);
    }

    return swModuleBeans.getContent().stream().map(this::getProxyBean).collect(Collectors.toList());
}
 
Example #20
Source File: RSQLActionFieldsTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) {

        final Slice<Action> findEnitity = deploymentManagement.findActionsByTarget(rsqlParam, target.getControllerId(),
                PageRequest.of(0, 100));
        final long countAllEntities = deploymentManagement.countActionsByTarget(rsqlParam, target.getControllerId());
        assertThat(findEnitity).isNotNull();
        assertThat(countAllEntities).isEqualTo(expectedEntities);
    }
 
Example #21
Source File: IgniteSpringDataQueriesSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testSliceOfCacheEntries() {
    Slice<Cache.Entry<Integer, Person>> slice = repo2.findBySecondNameIsNot("lastName18", PageRequest.of(3, 4));

    assertEquals(4, slice.getSize());

    for (Cache.Entry<Integer, Person> entry : slice)
        assertFalse("lastName18".equals(entry.getValue().getSecondName()));
}
 
Example #22
Source File: MgmtTargetResource.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ResponseEntity<PagedList<MgmtAction>> getActionHistory(@PathVariable("targetId") final String targetId,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
        @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {

    findTargetWithExceptionIfNotFound(targetId);

    final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
    final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
    final Sort sorting = PagingUtility.sanitizeActionSortParam(sortParam);
    final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);

    final Slice<Action> activeActions;
    final Long totalActionCount;
    if (rsqlParam != null) {
        activeActions = this.deploymentManagement.findActionsByTarget(rsqlParam, targetId, pageable);
        totalActionCount = this.deploymentManagement.countActionsByTarget(rsqlParam, targetId);
    } else {
        activeActions = this.deploymentManagement.findActionsByTarget(targetId, pageable);
        totalActionCount = this.deploymentManagement.countActionsByTarget(targetId);
    }

    return ResponseEntity.ok(
            new PagedList<>(MgmtTargetMapper.toResponse(targetId, activeActions.getContent()), totalActionCount));
}
 
Example #23
Source File: AuthorServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * get a list of author's fans decrease rate.
 *
 * @return list of author rate of fans decrease.
 */
@Override
public ResponseEntity listFansDecreaseRate() {
    Slice<Author> slice = respository
            .listTopIncreaseRate(PageRequest.of(0, 20, new Sort(Sort.Direction.ASC, "cRate")));
    AuthorServiceImpl.logger.info("获得掉粉榜");
    return new ResponseEntity<>(slice, HttpStatus.OK);
}
 
Example #24
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 #25
Source File: MgmtTargetResourceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * helper method to create a target and start an action on it.
 *
 * @return The targetid of the created target.
 */
private Target createTargetAndStartAction() {
    // prepare test
    final DistributionSet dsA = testdataFactory.createDistributionSet("");
    final Target tA = testdataFactory.createTarget("target-id-A");
    // assign a distribution set so we get an active update action
    assignDistributionSet(dsA, Arrays.asList(tA));
    // verify active action
    final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE);
    assertThat(actionsByTarget.getContent()).hasSize(1);
    return targetManagement.getByControllerID(tA.getControllerId()).get();
}
 
Example #26
Source File: JpaSoftwareModuleManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Slice<SoftwareModule> findByTextAndType(final Pageable pageable, final String searchText,
        final Long typeId) {

    final List<Specification<JpaSoftwareModule>> specList = new ArrayList<>(4);

    Specification<JpaSoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
    specList.add(spec);

    if (!StringUtils.isEmpty(searchText)) {
        spec = SoftwareModuleSpecification.likeNameOrVersion(searchText);
        specList.add(spec);
    }

    if (null != typeId) {
        throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);

        spec = SoftwareModuleSpecification.equalType(typeId);
        specList.add(spec);
    }

    spec = (root, query, cb) -> {
        if (!query.getResultType().isAssignableFrom(Long.class)) {
            root.fetch(JpaSoftwareModule_.type);
        }
        return cb.conjunction();
    };

    specList.add(spec);

    return convertSmPage(findByCriteriaAPI(pageable, specList), pageable);
}
 
Example #27
Source File: UserServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * slice the user record
 *
 * @param page     page number
 * @param pagesize page size
 * @return the slice of user record
 */
@Override
public MySlice<UserRecord> sliceUserRecord(Integer page, Integer pagesize) {
    pagesize = DataReducer.limitPagesize(pagesize);
    User user = UserUtils.getUser();
    if (user != null) {
        String userName = user.getName();
        Slice<UserRecord> slice =
                userRecordRepository.findByUserNameOrderByDatetimeDesc(
                        userName, PageRequest.of(page, pagesize));
        return new MySlice<>(slice);
    } else {
        return null;
    }
}
 
Example #28
Source File: VideoRepository.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * 获得视频分页
 *
 * @param pageable 分页
 * @return 返回视频的分页信息
 */
@Query(
        value = "{data:{$ne:null}}",
        fields =
                "{ 'pic' : 1, 'mid' : 1, 'author' : 1, 'authorName' : 1, 'bvid': 1, 'channel' : 1, 'title' : 1, 'aid' : 1, 'focus':1}"
)
Slice<Video> findAllByAid(Pageable pageable);
 
Example #29
Source File: EventServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
/**
 * Get the data of important events.
 *
 * @param page     page number
 * @param pagesize page size
 * @return a slice of events
 */
@Override
public MySlice<Event> pageEvent(Integer page, Integer pagesize) {
    if (pagesize > PageSizeEnum.BIG_SIZE.getValue()) {
        return null;
    }
    Slice<Event> e =
            eventRepository.findAll(
                    PageRequest.of(page, pagesize, new Sort(Sort.Direction.DESC, "datetime")));
    logger.info("获取事件");
    return new MySlice<>(e);
}
 
Example #30
Source File: IgniteSpringDataQueriesSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testSliceOfLists() {
    Slice<List> lists = repo2.querySliceOfList("^[a-z]+$", new PageRequest(0, 3));

    assertEquals(3, lists.getSize());

    for (List list : lists) {
        assertEquals(2, list.size());

        assertTrue(list.get(0) instanceof Integer);
    }
}