Java 类org.springframework.data.domain.Slice 实例源码

项目:spring-data-examples    文件:SimpleUserRepositoryTests.java   
@Test
public void useSliceToLoadContent() {

    repository.deleteAll();

    // int repository with some values that can be ordered
    int totalNumberUsers = 11;
    List<User> source = new ArrayList<User>(totalNumberUsers);

    for (int i = 1; i <= totalNumberUsers; i++) {

        User user = new User();
        user.setLastname(this.user.getLastname());
        user.setUsername(user.getLastname() + "-" + String.format("%03d", i));
        source.add(user);
    }

    repository.save(source);

    Slice<User> users = repository.findByLastnameOrderByUsernameAsc(this.user.getLastname(), new PageRequest(1, 5));

    assertThat(users, contains(source.subList(5, 10).toArray()));
}
项目:nixmash-blog    文件:GeneralController.java   
@RequestMapping(value = "/", method = GET)
public String home(Model model) {
    String springVersion = webUI.parameterizedMessage("home.spring.version", SpringBootVersion.getVersion());
    model.addAttribute("springVersion", springVersion);

    GitHubStats gitHubStats = webUI.getCurrentGitHubStats();
    if (gitHubStats != null) {
        model.addAttribute("showGitHubStats", true);
        model.addAttribute("gitHubStats", gitHubStats);
    }

    if (webUI.isNixMash()) {
        SiteImage siteImage = siteService.getHomeBanner();
        model.addAttribute("siteImage", siteImage);
    }

    Slice<Post> posts = postService.getPublishedPosts(0, 10);
    if (posts.getContent().size() > 0)
        model.addAttribute("posts", posts);

    return HOME_VIEW;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/quicksearch/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getQuickSearchPosts(@PathVariable int pageNumber,
                                  HttpServletRequest request,
                                  CurrentUser currentUser) {
    String search = (String) WebUtils.getSessionAttribute(request, SESSION_QUICKSEARCH_QUERY);
    String result;
    List<PostDoc> postDocs = postDocService.doQuickSearch(search);
    if (postDocs.size() == 0) {
        result = fmService.getNoResultsMessage(search);
    } else {
        Slice<PostDoc> posts = postDocService.doPagedQuickSearch(search, pageNumber, POST_PAGING_SIZE);
        result = populatePostDocStream(posts.getContent(), currentUser);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_QUICKSEARCH_POSTS, posts.getContent());
    }
    return result;
}
项目:oma-riista-web    文件:ListAnnouncementFeature.java   
@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()));
}
项目: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(() -> eventPublisher.publishEvent(
                    new RolloutUpdatedEvent(rollout, EventPublisherHolder.getInstance().getApplicationId())));
        } catch (final RuntimeException e) {
            LOGGER.error("Exception during deletion of actions of rollout {}", rollout, e);
        }
    }
}
项目:hawkbit    文件:JpaSoftwareModuleManagement.java   
@Override
public Slice<SoftwareModule> findAll(final Pageable pageable) {

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

    Specification<JpaSoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
    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);
}
项目:hawkbit    文件:DeploymentManagementTest.java   
@Test
@Description("Test verifies that action-states of an action are found by using id-based search.")
public void findActionStatusByActionId() {
    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 = assignDistributionSet(testDs, testTarget).getActions().get(0);
    final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
            PAGE);
    final ActionStatus expectedActionStatus = ((JpaAction) actions.getContent().get(0)).getActionStatus().get(0);

    // act
    final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);

    assertThat(actionStates.getContent()).hasSize(1);
    assertThat(actionStates.getContent().get(0)).as("Action-status of action").isEqualTo(expectedActionStatus);
}
项目: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);
        }
    }

}
项目:hawkbit    文件:MultiTenancyEntityTest.java   
@Test
@Description(value = "Ensures that multiple targets with same controller-ID can be created for different tenants.")
public void createMultipleTargetsWithSameIdForDifferentTenant() throws Exception {
    // known controller ID for overall tenants same
    final String knownControllerId = "controllerId";

    // known tenant names
    final String tenant = "aTenant";
    final String anotherTenant = "anotherTenant";
    // create targets
    createTargetForTenant(knownControllerId, tenant);
    createTargetForTenant(knownControllerId, anotherTenant);

    // ensure both tenants see their target
    final Slice<Target> findTargetsForTenant = findTargetsForTenant(tenant);
    assertThat(findTargetsForTenant).hasSize(1);
    assertThat(findTargetsForTenant.getContent().get(0).getTenant().toUpperCase()).isEqualTo(tenant.toUpperCase());
    final Slice<Target> findTargetsForAnotherTenant = findTargetsForTenant(anotherTenant);
    assertThat(findTargetsForAnotherTenant).hasSize(1);
    assertThat(findTargetsForAnotherTenant.getContent().get(0).getTenant().toUpperCase())
            .isEqualTo(anotherTenant.toUpperCase());

}
项目: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);
}
项目: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);
}
项目:hawkbit    文件:DistributionTagBeanQuery.java   
@Override
protected List<ProxyTag> loadBeans(final int startIndex, final int count) {
    final Slice<DistributionSetTag> dsTagBeans = getTagManagement()
            .findAll(new OffsetBasedPageRequest(startIndex, count, sort));

    return dsTagBeans.getContent().stream().map(tag -> {
        final ProxyTag proxyTargetTag = new ProxyTag();
        proxyTargetTag.setColour(tag.getColour());
        proxyTargetTag.setDescription(tag.getDescription());
        proxyTargetTag.setName(tag.getName());
        proxyTargetTag.setId(tag.getId());
        final TagIdName tagIdName = new TagIdName(tag.getName(), tag.getId());
        proxyTargetTag.setTagIdName(tagIdName);

        return proxyTargetTag;

    }).collect(Collectors.toList());
}
项目: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());

        proxyActions.add(proxyAction);
    }
    return proxyActions;
}
项目:hawkbit    文件:MgmtDistributionSetTypeResource.java   
@Override
public ResponseEntity<PagedList<MgmtDistributionSetType>> getDistributionSetTypes(
        @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.sanitizeDistributionSetTypeSortParam(sortParam);
    final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);

    final Slice<DistributionSetType> findModuleTypessAll;
    long countModulesAll;
    if (rsqlParam != null) {
        findModuleTypessAll = distributionSetTypeManagement.findByRsql(pageable, rsqlParam);
        countModulesAll = ((Page<DistributionSetType>) findModuleTypessAll).getTotalElements();
    } else {
        findModuleTypessAll = distributionSetTypeManagement.findAll(pageable);
        countModulesAll = distributionSetTypeManagement.count();
    }

    final List<MgmtDistributionSetType> rest = MgmtDistributionSetTypeMapper
            .toListResponse(findModuleTypessAll.getContent());
    return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
项目:hawkbit    文件:MgmtSoftwareModuleResource.java   
@Override
public ResponseEntity<PagedList<MgmtSoftwareModule>> getSoftwareModules(
        @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.sanitizeSoftwareModuleSortParam(sortParam);

    final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);

    final Slice<SoftwareModule> findModulesAll;
    long countModulesAll;
    if (rsqlParam != null) {
        findModulesAll = softwareModuleManagement.findByRsql(pageable, rsqlParam);
        countModulesAll = ((Page<SoftwareModule>) findModulesAll).getTotalElements();
    } else {
        findModulesAll = softwareModuleManagement.findAll(pageable);
        countModulesAll = softwareModuleManagement.count();
    }

    final List<MgmtSoftwareModule> rest = MgmtSoftwareModuleMapper.toResponse(findModulesAll.getContent());
    return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
项目:hawkbit    文件:MgmtDistributionSetResource.java   
@Override
public ResponseEntity<PagedList<MgmtDistributionSet>> getDistributionSets(
        @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.sanitizeDistributionSetSortParam(sortParam);

    final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
    final Slice<DistributionSet> findDsPage;
    final long countModulesAll;
    if (rsqlParam != null) {
        findDsPage = distributionSetManagement.findByRsql(pageable, rsqlParam);
        countModulesAll = ((Page<DistributionSet>) findDsPage).getTotalElements();
    } else {
        findDsPage = distributionSetManagement.findAll(pageable);
        countModulesAll = distributionSetManagement.count();
    }

    final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent());
    return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
项目:hawkbit    文件:MgmtTargetResourceTest.java   
@Test
@Description("Ensures that a post request for creating one target within a list works.")
public void createTargetsSingleEntryListReturnsSuccessful() throws Exception {
    final String knownName = "someName";
    final String knownControllerId = "controllerId1";
    final String knownDescription = "someDescription";
    final String createTargetsJson = getCreateTargetsListJsonString(knownControllerId, knownName, knownDescription);

    mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson)
            .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().is2xxSuccessful());

    final Slice<Target> findTargetsAll = targetManagement.findAll(new PageRequest(0, 100));
    final Target target = findTargetsAll.getContent().get(0);
    assertThat(targetManagement.count()).isEqualTo(1);
    assertThat(target.getControllerId()).isEqualTo(knownControllerId);
    assertThat(target.getName()).isEqualTo(knownName);
    assertThat(target.getDescription()).isEqualTo(knownDescription);
}
项目:demyo    文件:AlbumController.java   
@Override
@RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
public String index(@RequestParam(value = "page", required = false) Integer currentPage,
        @RequestParam(value = "startsWith", required = false) Character startsWith, Model model,
        HttpServletRequest request) {
    currentPage = getCurrentPage(currentPage, startsWith);

    Long bindingId = getLongParam(request, REQUEST_PARAM_BINDING);
    Predicate filter = null;
    if (bindingId != null) {
        filter = QAlbum.album.binding.id.eq(bindingId);
    }

    Slice<Album> entities = service.findPaginated(currentPage, filter);

    model.addAttribute("albumList", entities);

    return "albums/index";
}
项目:nixmash-blog    文件:PostServiceTests.java   
@Test
public void findAllWithPaging() {
    Slice<Post> posts = postService.getPosts(0, 3);
    assertEquals(posts.getSize(), 3);
    ZonedDateTime firstPostDate = posts.getContent().get(0).getPostDate();
    ZonedDateTime secondPostDate = posts.getContent().get(1).getPostDate();

    // firstPostDate is higher (more recent) than secondPostDate with [sort: postDate: DESC]
    assertTrue(firstPostDate.compareTo(secondPostDate) > 0);
}
项目:nixmash-blog    文件:PostServiceTests.java   
@Test
public void findPostsByTagId() {
    Slice<Post> posts = postService.getPublishedPostsByTagId(1, 0, 3);

    // posts are retrieved for tagId #1 as all 5 H2 posts have tagId #1
    assertEquals(posts.getSize(), 3);
}
项目:nixmash-blog    文件:GeneralController.java   
@RequestMapping(value = "/dev/banner", method = GET)
public String homeBannerDisplay(Model model, @RequestParam(value = "id") long siteImageId) {
    String springVersion = webUI.parameterizedMessage("home.spring.version", SpringBootVersion.getVersion());
    model.addAttribute("springVersion", springVersion);
        SiteImage siteImage = siteService.getHomeBanner(siteImageId);
        model.addAttribute("siteImage", siteImage);

    Slice<Post> posts = postService.getPublishedPosts(0, 10);
    if (posts.getContent().size() > 0)
        model.addAttribute("posts", posts);

    return HOME_VIEW;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/titles/page/{pageNumber}", produces = "text/html;charset=UTF-8")
    public String getPostTitles(@PathVariable Integer pageNumber, HttpServletRequest request, CurrentUser currentUser) {
//        Slice<Post> posts = postService.getPublishedPosts(pageNumber, TITLE_PAGING_SIZE);
        Slice<Post> posts = postService.getPagedPostsByPostType(PostType.POST, pageNumber, TITLE_PAGING_SIZE);
        String result = populatePostStream(posts.getContent(), currentUser, TITLE_TEMPLATE);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_POSTTITLES, posts.getContent());
        return result;
    }
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/links/page/{pageNumber}", produces = "text/html;charset=UTF-8")
public String getLinks(@PathVariable Integer pageNumber, HttpServletRequest request, CurrentUser currentUser) {
    Slice<Post> posts = postService.getPagedPostsByPostType(PostType.LINK, pageNumber, POST_PAGING_SIZE);
    String result;
    if (applicationSettings.getTitleStreamDisplay())
        result = populatePostStream(posts.getContent(), currentUser, TITLE_TEMPLATE);
    else
        result = populatePostStream(posts.getContent(), currentUser);
    if (StringUtils.isEmpty(result)) {
        result = fmService.getNoLinksMessage();
    }
    WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_JUSTLINKS, posts.getContent());
    return result;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/titles/tag/{tagid}/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getPostTitlesByTagId(@PathVariable long tagid,
                                   @PathVariable int pageNumber,
                                   HttpServletRequest request,
                                   CurrentUser currentUser) {
    Slice<Post> posts = postService.getPublishedPostsByTagId(tagid, pageNumber, TITLE_PAGING_SIZE);
    String result = populatePostStream(posts.getContent(), currentUser, TITLE_TEMPLATE);
    WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_TAGPOSTTITLES, posts.getContent());
    return result;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/page/{pageNumber}", produces = "text/html;charset=UTF-8")
    public String getPosts(@PathVariable Integer pageNumber, HttpServletRequest request, CurrentUser currentUser) {
//        Slice<Post> posts = postService.getPublishedPosts(pageNumber, POST_PAGING_SIZE);
        boolean titleDisplay = applicationSettings.getTitleStreamDisplay();
        int pagingSize = titleDisplay ? TITLE_PAGING_SIZE : POST_PAGING_SIZE;
        Slice<Post> posts = postService.getPagedPostsByPostType(PostType.POST, pageNumber, TITLE_PAGING_SIZE);
        String template = titleDisplay ? "title" : null;
        String result = populatePostStream(posts.getContent(), currentUser, template);
        WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_POSTS, posts.getContent());
        return result;
    }
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/tag/{tagid}/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getPostsByTagId(@PathVariable long tagid,
                              @PathVariable int pageNumber,
                              HttpServletRequest request,
                              CurrentUser currentUser) {
    String template = applicationSettings.getTitleStreamDisplay() ? "title" : null;
    Slice<Post> posts = postService.getPublishedPostsByTagId(tagid, pageNumber, POST_PAGING_SIZE);
    String result = populatePostStream(posts.getContent(), currentUser, template);
    WebUtils.setSessionAttribute(request, SESSION_ATTRIBUTE_TAGGEDPOSTS, posts.getContent());
    return result;
}
项目:nixmash-blog    文件:PostsRestController.java   
@RequestMapping(value = "/search/page/{pageNumber}",
        produces = "text/html;charset=UTF-8")
public String getFullSearchPosts(@PathVariable int pageNumber,
                                 HttpServletRequest request,
                                 CurrentUser currentUser) {
    PostQueryDTO postQueryDTO =
            (PostQueryDTO) WebUtils.getSessionAttribute(request, SESSION_POSTQUERYDTO);
    String result = null;
    List<PostDoc> postDocs = null;
    if (postQueryDTO != null) {
        try {
            postDocs = postDocService.doFullSearch(postQueryDTO);
        } catch (UncategorizedSolrException ex) {
            logger.info(MessageFormat.format("Bad Query: {0}", postQueryDTO.getQuery()));
            return fmService.getNoResultsMessage(postQueryDTO.getQuery());
        }

        if (postDocs.size() == 0) {
            result = fmService.getNoResultsMessage(postQueryDTO.getQuery());
        } else {
            Slice<PostDoc> postDocSlice =
                    postDocService.doPagedFullSearch(postQueryDTO, pageNumber, POST_PAGING_SIZE);
            result = populatePostDocStream(postDocSlice.getContent(), currentUser);
            WebUtils.setSessionAttribute(request,
                    SESSION_ATTRIBUTE_FULLSEARCH_POSTS, postDocSlice.getContent());
        }
    }
    return result;
}
项目:spring-data-snowdrop    文件:SnowdropTemplate.java   
@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);
    }
}
项目:spring-data-mybatis    文件:UserRepositoryFinderTests.java   
@Test
public void executesQueryToSlice() {

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

    assertThat(slice.getContent(), hasItem(dave));
    assertThat(slice.hasNext(), is(true));
}
项目:oma-riista-web    文件:BaseRepositoryImpl.java   
@Override
public Slice<T> findAllAsSlice(final Predicate predicate, final Pageable page) {
    final JPQLQuery<T> query = createQuery(predicate)
            .select(path)
            .offset(page.getOffset())
            .limit(page.getPageSize() + 1);
    return toSlice(querydsl.applySorting(page.getSort(), query).fetch(), page);
}
项目:oma-riista-web    文件:BaseRepositoryImpl.java   
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);
}
项目:oma-riista-web    文件:AnnouncementApiResource.java   
@CacheControl(policy = CachePolicy.NO_CACHE)
@RequestMapping(method = RequestMethod.GET)
public Slice<ListAnnouncementDTO> listAnnouncements(@RequestParam final OrganisationType organisationType,
                                                    @RequestParam final String officialCode,
                                                    @RequestParam final ListAnnouncementRequest.Direction direction,
                                                    Pageable pageRequest) {
    final ListAnnouncementRequest request = new ListAnnouncementRequest();
    request.setOrganisationType(organisationType);
    request.setOfficialCode(officialCode);
    request.setDirection(direction);

    return listAnnouncementFeature.list(request, pageRequest);
}
项目:oma-riista-web    文件:AccountApiResource.java   
@RequestMapping(
        method = RequestMethod.GET,
        value = "announcements")
public Slice<ListAnnouncementDTO> myAnnouncements(
        @PageableDefault(size = 500, sort = "id", direction = Sort.Direction.ASC) Pageable pageRequest) {
    final ListAnnouncementRequest request = new ListAnnouncementRequest();
    request.setDirection(ListAnnouncementRequest.Direction.RECEIVED);
    return listAnnouncementFeature.list(request, pageRequest);
}
项目:credhub    文件:EncryptionKeyRotator.java   
public void rotate() {
  final long start = System.currentTimeMillis();
  logger.info("Starting encryption key rotation.");
  int rotatedRecordCount = 0;

  final long startingNotRotatedRecordCount = encryptedValueDataService
      .countAllByCanaryUuid(keySet.getActive().getUuid());

  List<UUID> inactiveCanaries = keySet.getInactiveUuids();
  Slice<EncryptedValue> valuesEncryptedByOldKey = encryptedValueDataService
      .findByCanaryUuids(inactiveCanaries);
  while (valuesEncryptedByOldKey.hasContent()) {
    for (EncryptedValue value : valuesEncryptedByOldKey.getContent()) {
      try {
        encryptedValueDataService.rotate(value);
        rotatedRecordCount++;
      } catch (KeyNotFoundException e) {
        logger.error("key not found for value, unable to rotate");
      }
    }
    valuesEncryptedByOldKey = encryptedValueDataService.findByCanaryUuids(inactiveCanaries);
  }

  final long finish = System.currentTimeMillis();
  final long duration = finish - start;
  final long endingNotRotatedRecordCount = startingNotRotatedRecordCount - rotatedRecordCount;

  if (rotatedRecordCount == 0 && endingNotRotatedRecordCount == 0) {
    logger.info("Found no records in need of encryption key rotation.");
  } else {
    logger.info("Finished encryption key rotation in " + duration + " milliseconds. Details:");
    logger.info("  Successfully rotated " + rotatedRecordCount + " item(s)");
    logger.info("  Skipped " + endingNotRotatedRecordCount
        + " item(s) due to missing master encryption key(s).");
  }

  encryptionKeyCanaryMapper.delete(inactiveCanaries);
}
项目:credhub    文件:EncryptedValueDataServiceTest.java   
@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));
}
项目:hawkbit    文件:JpaRolloutManagement.java   
@Override
public Slice<Rollout> findByFiltersWithDetailedStatus(final Pageable pageable, final String searchText,
        final boolean deleted) {
    final Slice<JpaRollout> findAll = findByCriteriaAPI(pageable,
            Arrays.asList(JpaRolloutHelper.likeNameOrDescription(searchText, deleted)));
    setRolloutStatusDetails(findAll);
    return JpaRolloutHelper.convertPage(findAll, pageable);
}
项目:hawkbit    文件:JpaRolloutManagement.java   
private void setRolloutStatusDetails(final Slice<JpaRollout> rollouts) {
    final List<Long> rolloutIds = rollouts.getContent().stream().map(Rollout::getId).collect(Collectors.toList());
    final Map<Long, List<TotalTargetCountActionStatus>> allStatesForRollout = getStatusCountItemForRollout(
            rolloutIds);

    if (allStatesForRollout != null) {
        rollouts.forEach(rollout -> {
            final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(
                    allStatesForRollout.get(rollout.getId()), rollout.getTotalTargets());
            rollout.setTotalTargetCountStatus(totalTargetCountStatus);
        });
    }
}
项目: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), pageable);
}
项目:hawkbit    文件:JpaTargetManagement.java   
private Slice<Target> findByCriteriaAPI(final Pageable pageable, final List<Specification<JpaTarget>> specList) {
    if (CollectionUtils.isEmpty(specList)) {
        return convertPage(criteriaNoCountDao.findAll(pageable, JpaTarget.class), pageable);
    }
    return convertPage(
            criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, JpaTarget.class),
            pageable);
}
项目:hawkbit    文件:JpaSoftwareModuleManagement.java   
@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);
}