org.springframework.data.domain.SliceImpl#org.springframework.data.domain.Slice源码实例Demo

下面列出了org.springframework.data.domain.SliceImpl#org.springframework.data.domain.Slice 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hawkbit   文件: AutoAssignCheckerTest.java
/**
 * @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);
        }
    }

}
 
源代码2 项目: hawkbit   文件: MultiTenancyEntityTest.java
@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);
}
 
源代码3 项目: hawkbit   文件: MgmtTargetResource.java
@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));
}
 
源代码4 项目: hawkbit   文件: DeploymentManagementTest.java
@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);
}
 
源代码5 项目: biliob_backend   文件: UserServiceImpl.java
/**
 * 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;
}
 
@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());
}
 
源代码7 项目: hawkbit   文件: ActionBeanQuery.java
/**
 * 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;
}
 
@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);
}
 
源代码9 项目: hawkbit   文件: JpaRolloutManagement.java
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);
        }
    }
}
 
源代码10 项目: hawkbit   文件: MultiTenancyEntityTest.java
@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);
}
 
源代码11 项目: hawkbit   文件: RolloutManagementTest.java
@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()));
}
 
源代码12 项目: hawkbit   文件: RolloutManagementTest.java
@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()));
}
 
源代码13 项目: hawkbit   文件: BaseSwModuleBeanQuery.java
@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());
}
 
源代码14 项目: quarkus   文件: MovieResource.java
@GET
@Path("/title/titleLengthOrder/page/{size}/{num}")
public String orderByTitleLengthSlice(@PathParam("size") int pageSize, @PathParam("num") int pageNum) {
    Slice<Movie> slice = movieRepository.findByDurationGreaterThan(1,
            PageRequest.of(pageNum, pageSize, Sort.Direction.ASC, "title"));
    return slice.hasNext() + " / " + slice.getNumberOfElements();
}
 
源代码15 项目: biliob_backend   文件: MySlice.java
public MySlice(Slice<T> slice) {
    this.content = slice.getContent();
    this.number = slice.getNumber();
    this.size = slice.getSize();
    this.last = slice.isLast();
    this.first = slice.isFirst();
    this.numberOfElements = slice.getNumberOfElements();
}
 
源代码16 项目: hawkbit   文件: RSQLActionFieldsTest.java
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);
    }
 
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);
		}
 
源代码18 项目: biliob_backend   文件: VideoRepository.java
/**
 * 获得视频分页
 *
 * @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);
 
源代码19 项目: ignite   文件: IgniteSpringDataQueriesSelfTest.java
/** */
@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);
    }
}
 
源代码20 项目: hawkbit   文件: MgmtTargetResourceTest.java
/**
 * 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();
}
 
源代码21 项目: hawkbit   文件: RolloutManagementTest.java
@Step("Finish one action of the rollout group and delete four targets")
private void finishActionAndDeleteTargetsOfSecondRunningGroup(final Rollout createdRollout) {
    final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
            createdRollout.getId(), Status.RUNNING);
    final List<JpaAction> runningActions = runningActionsSlice.getContent();
    finishAction(runningActions.get(0));
    targetManagement.delete(
            Arrays.asList(runningActions.get(1).getTarget().getId(), runningActions.get(2).getTarget().getId(),
                    runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));

}
 
源代码22 项目: hawkbit   文件: TargetManagementSearchTest.java
@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]));

}
 
源代码23 项目: biliob_backend   文件: QuestionServiceImpl.java
/**
 * 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);
}
 
源代码24 项目: hawkbit   文件: JpaTargetManagement.java
@Override
public Slice<Target> findByTargetFilterQuery(final Pageable pageable, final long targetFilterQueryId) {
    final TargetFilterQuery targetFilterQuery = targetFilterQueryRepository.findById(targetFilterQueryId)
            .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));

    return findTargetsBySpec(
            RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer, database),
            pageable);
}
 
源代码25 项目: biliob_backend   文件: AuthorServiceImpl.java
/**
 * 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);
}
 
源代码26 项目: hawkbit   文件: MgmtTargetResource.java
@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));
}
 
源代码27 项目: biliob_backend   文件: UserServiceImpl.java
/**
 * 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;
    }
}
 
源代码28 项目: biliob_backend   文件: EventServiceImpl.java
/**
 * 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);
}
 
源代码29 项目: hawkbit   文件: JpaSoftwareModuleManagement.java
@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);
}
 
源代码30 项目: ignite   文件: IgniteRepositoryQuery.java
/**
 * @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;
}