Example usage for org.springframework.data.domain Page forEach

List of usage examples for org.springframework.data.domain Page forEach

Introduction

In this page you can find the example usage for org.springframework.data.domain Page forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:nu.yona.server.messaging.entities.MessageSource.java

private void decryptMessagePage(Page<Message> messages) {
    PublicKeyDecryptor decryptor = PublicKeyDecryptor.createInstance(loadPrivateKey());
    messages.forEach(m -> m.decryptMessage(decryptor));
}

From source file:org.obiba.mica.file.search.FileIndexer.java

@Async
@Subscribe//from www  .  j  a va  2 s .  c  om
public void reIndexAll(IndexFilesEvent event) {
    if (indexer.hasIndex(Indexer.ATTACHMENT_DRAFT_INDEX))
        indexer.dropIndex(Indexer.ATTACHMENT_DRAFT_INDEX);
    if (indexer.hasIndex(Indexer.ATTACHMENT_PUBLISHED_INDEX))
        indexer.dropIndex(Indexer.ATTACHMENT_PUBLISHED_INDEX);

    Pageable pageRequest = new PageRequest(0, 100);
    Page<AttachmentState> attachments;

    do {
        attachments = attachmentStateRepository.findAll(pageRequest);
        attachments.forEach(a -> {
            if (FileUtils.isDirectory(a))
                return;

            indexer.index(Indexer.ATTACHMENT_DRAFT_INDEX, a);

            if (a.getPublishedAttachment() != null) {
                indexer.index(Indexer.ATTACHMENT_PUBLISHED_INDEX, a);
            }
        });
    } while ((pageRequest = attachments.nextPageable()) != null);
}

From source file:org.openlmis.fulfillment.AuditLogInitializer.java

private void createSnapshots(PagingAndSortingRepository<?, ?> repository) {
    Pageable pageable = new PageRequest(DEFAULT_PAGE_NUMBER, 2000);

    while (true) {
        Page<?> page = repository.findAll(pageable);

        if (!page.hasContent()) {
            break;
        }//from w ww.j  a  v  a2  s .c o m

        page.forEach(this::createSnapshot);

        pageable = pageable.next();
    }
}

From source file:app.service.CollectionService.java

private void fillExplorers(Collection col) {
    Link link = mLinkRepo.findFirstByUrl(col.getLink().getUrl());
    // ???? 5 ?/*from  w  w w.  j ava2  s.co  m*/
    Page<Collection> linkCols = mColRepo.findByLink(link, new PageRequest(0, 5, mCreateSort));
    List<User> users = new ArrayList<>(linkCols.getContent().size());
    linkCols.forEach(item -> {
        User user = item.getUser();
        user = user.cloneProfile();
        user.setColId(item.getId());
        users.add(user);
    });
    col.setExplorers(users);
}

From source file:de.hska.ld.oidc.listeners.LDToSSSEventListener.java

private void checkIfDocumentsHaveAnAttachedEpisode(DocumentReadListEvent event) {
    Page<Document> documentPage = (Page<Document>) event.getSource();
    List<DocumentListItemDto> documentListItemDtoList = new ArrayList<>();

    documentPage.forEach(doc -> {
        Long documentId = doc.getId();
        DocumentSSSInfo documentSSSInfo = documentSSSInfoService.getDocumentSSSInfoById(documentId);
        DocumentListItemDto documentListItemDto = new DocumentListItemDto(doc);
        if (documentSSSInfo != null) {
            documentListItemDto.setHasConnectedEpisode(true);
        }/* www  . ja  v  a  2s.co  m*/
        documentListItemDtoList.add(documentListItemDto);
    });

    try {
        Field pageableField = PageImpl.class.getSuperclass().getDeclaredField("pageable");
        pageableField.setAccessible(true);
        Pageable pageable = (Pageable) pageableField.get(documentPage);
        Page<DocumentListItemDto> documentListItemDtoPage = new PageImpl<DocumentListItemDto>(
                documentListItemDtoList, pageable, documentPage.getTotalElements());
        event.setResultDocument(documentListItemDtoPage);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:io.leishvl.core.test.CitationRepositoryTests.java

@Test
public void readsFirstPageCorrectly() {
    repository.deleteAll();/*from  w  w  w  . ja  va2 s .co m*/

    // save a couple of citations
    ImmutableList.of(citation0, citation1).stream().forEach(citation -> repository.save(citation));

    // fetch all citations
    pw.println("Citations found with findAll():");
    pw.println("-------------------------------");
    repository.findAll().stream().forEach(pw::println);
    pw.println();

    // fetch a citations within a given namespace
    pw.println("Citation found with findByNamespace('citations'):");
    pw.println("--------------------------------");
    final Page<Citation> citations = repository.findByNamespaceValue("citations",
            new PageRequest(0, 20, Sort.Direction.ASC, "pubmed.medlineCitation.pmid.value"));
    assertThat("first page", citations.isFirst(), equalTo(true));
    pw.println("Total elements=" + citations.getTotalElements() + ", Total pages=" + citations.getTotalPages());
    citations.forEach(pw::println);

    // fetch an individual citation
    pw.println("Citation found with findByLeishvlId('lvl-ci-pm-CIT_0'):");
    pw.println("--------------------------------");
    pw.println(repository.findByLeishvlId("lvl-ci-pm-CIT_0"));
}

From source file:app.service.CollectionService.java

private List<Collection> getFromPage(Page<Collection> colPage, boolean withUser) {
    List<Collection> collections = new ArrayList<>(colPage.getContent().size());
    // set user field null, because what we find is just for one user
    // otherwise, when we need to change the data but not want to apply to the database, do like follow
    colPage.forEach(item -> {
        Collection col = new Collection(null, item.getLink(), item.getDescription(), item.getImage());
        if (withUser) {
            col.setUser(item.getUser().cloneProfile());
        }/*from w  w  w .  ja  va  2  s .  c  om*/
        col.setId(item.getId());
        col.setCreateDate(item.getCreateDate());
        col.setUpdateDate(item.getUpdateDate());
        collections.add(col);
    });
    return collections;
}

From source file:com.example.ekanban.service.ProductService.java

public Page<ProductDto> findPageBySubCategory(SubCategory subCategory, Pageable pageable) {
    logger.debug("findPageBySubCategory()");
    Page<Product> page = productRepository.findBySubCategory(subCategory, pageable);
    page.forEach(p -> {
        Hibernate.initialize(p.getSectionList());
        Hibernate.initialize(p.getSupplierList());
    });//ww w . j a  va  2 s. c  om
    return page.map(converter);
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/database/{databaseName}/dpContributions/{childOf}", method = RequestMethod.GET)
@ResponseBody/*w  ww  .j  a  v a 2s .  co m*/
PagedResources<Resource<BrowsingContributionResource>> dpContributions(
        @RequestParam(value = "page", defaultValue = "0") int page,
        @RequestParam(value = "size", defaultValue = "20") int size,
        @PathVariable("databaseName") String databaseName, @PathVariable("childOf") Long dpId,
        HttpServletRequest hsr, HttpSession session) {
    registerDb(hsr, session, databaseName);

    PageRequest p = new PageRequest(page, size, new Sort("startTime"));

    Optional<DiscoursePart> parent = discoursePartRepository.findOne(dpId);
    if (parent.isPresent()) {
        Page<BrowsingContributionResource> lbcr = discoursePartContributionRepository
                .findByDiscoursePartSorted(parent.get(), p).map(dpc -> dpc.getContribution())
                .map(c -> new BrowsingContributionResource(c, annoService));
        lbcr.forEach(bcr -> {
            if (bcr.getDiscourseParts().size() > 1) {
                bcr._getDiscourseParts().forEach((dpId2, dpName2) -> {
                    if (dpId2 != dpId) {
                        bcr.add(makeLink("/browsing/database/" + databaseName + "/dpContributions/" + dpId2,
                                "Also in:" + dpName2));
                    }
                });
            }
        });
        PagedResources<Resource<BrowsingContributionResource>> response = praContributionAssembler
                .toResource(lbcr);

        //response.add(makeLink("/browsing/subDiscourseParts{?page,size,repoType,annoType}", "search"));
        response.add(
                makeLink("/browsing/database/" + databaseName + "/usersInDiscoursePart/" + dpId, "show users"));
        return response;
    } else {
        return null;
    }
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/database/{databaseName}/subDiscourseParts/{childOf}", method = RequestMethod.GET)
@ResponseBody/*from w  w  w.  j  a va2s .  c  o m*/
PagedResources<Resource<BrowsingDiscoursePartResource>> subDiscourseParts(
        @RequestParam(value = "page", defaultValue = "0") int page,
        @RequestParam(value = "size", defaultValue = "20") int size,
        @PathVariable("databaseName") String databaseName, @PathVariable("childOf") Long dpId,
        HttpServletRequest hsr, HttpSession session) {
    registerDb(hsr, session, databaseName);

    PageRequest p = new PageRequest(page, size, new Sort("startTime"));

    Optional<DiscoursePart> parent = discoursePartRepository.findOne(dpId);
    if (parent.isPresent()) {
        Page<BrowsingDiscoursePartResource> repoResources = discoursePartRelationRepository
                .findAllTargetsBySource(parent.get(), p)
                /*.map(dpr -> dpr.getTarget())*/.map(dp -> new BrowsingDiscoursePartResource(dp, annoService));

        repoResources
                .forEach(bdp -> bdp.fillInUserInteractions(discoursePartInteractionRepository, annoService));
        repoResources.forEach(bcr -> {
            if (bcr.getContainingDiscourseParts().size() > 1) {
                bcr._getContainingDiscourseParts().forEach((childDpId, childDpName) -> {
                    bcr.add(makeLink("/browsing/database/" + databaseName + "/subDiscourseParts/" + childDpId,
                            "Contained in: " + childDpName));
                });
            }
            //if (bcr.getContributionCount() > 0) {
            Link check3 = makeBratExportNameLink(
                    "/browsing/action/database/" + databaseName + "/exportBratItem", "chk:Export to BRAT",
                    parent.get().getName(), Long.toString(bcr._getDpId()));
            bcr.add(check3);
            //} 
            //Link check = makeLink1Arg("/browsing/action/exportLightside","chk:Export to Lightside: no annotations", "parentDpId", Long.toString(bcr._getDpId()));
            //Link check2 = makeLink2Arg("/browsing/action/exportLightside","chk:Export to Lightside: with annotations", "withAnnotations", "true", "parentDpId", Long.toString(bcr._getDpId()));
            Link check = makeLightsideExportNameLink(
                    "/browsing/action/database/" + databaseName + "/exportLightside", false,
                    "chk:Export to Lightside, no annotations", bcr.getName(), Long.toString(bcr._getDpId()));
            Link check2 = makeLightsideExportNameLink(
                    "/browsing/action/database/" + databaseName + "/exportLightside", true,
                    "chk:Export to Lightside, with annotations", bcr.getName(), Long.toString(bcr._getDpId()));
            bcr.add(check);
            bcr.add(check2);

        });
        PagedResources<Resource<BrowsingDiscoursePartResource>> response = praDiscoursePartAssembler
                .toResource(repoResources);

        /*
         * Disabling exportBrat link overall -- instead add for each thread item as a checkbox
         *
        long threadcount = 0L;
        for (BrowsingDiscoursePartResource bdpr: repoResources) {
           threadcount += bdpr.getContributionCount();
        }
                
        if (threadcount > 0) {
           response.add(makeLink1Arg("/browsing/action/exportBrat", "Export these all to BRAT", "parentDpId", dpId.toString()));
        }
         */
        response.add(
                makeLink("/browsing/database/" + databaseName + "/usersInDiscoursePart/" + dpId, "show users"));

        return response;
    } else {
        logger.info("subdiscourseParts(" + dpId + ") : isPresent==false");
        return null;
    }
}