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

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

Introduction

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

Prototype

List<T> getContent();

Source Link

Document

Returns the page content as List .

Usage

From source file:org.openlmis.fulfillment.repository.OrderRepositoryIntegrationTest.java

@Test
public void shouldSort() {
    final Order one = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order two = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order three = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order four = orderRepository.save(generateInstance(OrderStatus.ORDERED));

    two.setCreatedDate(ZonedDateTime.of(2017, 3, 29, 0, 0, 0, 0, ZoneId.systemDefault()));
    four.setCreatedDate(ZonedDateTime.of(2017, 3, 29, 1, 0, 0, 0, ZoneId.systemDefault()));
    one.setCreatedDate(ZonedDateTime.of(2017, 3, 30, 0, 0, 0, 0, ZoneId.systemDefault()));
    three.setCreatedDate(ZonedDateTime.of(2017, 4, 1, 0, 0, 0, 0, ZoneId.systemDefault()));

    orderRepository.save(one);/*from   w  w w  .j  ava  2s .  c om*/
    orderRepository.save(two);
    orderRepository.save(three);
    orderRepository.save(four);

    HashSet<UUID> availableSupplyingFacilities = newHashSet(one.getSupplyingFacilityId(),
            two.getSupplyingFacilityId(), three.getSupplyingFacilityId(), four.getSupplyingFacilityId());

    OrderSearchParams params = new OrderSearchParams();
    params.setStatus(newHashSet(OrderStatus.ORDERED.name()));
    Page<Order> result = orderRepository.searchOrders(params, null,
            new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate")), availableSupplyingFacilities,
            null);

    assertEquals(4, result.getContent().size());
    // They should be returned from the most recent to the least recent
    assertTrue(
            result.getContent().get(0).getCreatedDate().isAfter(result.getContent().get(1).getCreatedDate()));
    assertTrue(
            result.getContent().get(1).getCreatedDate().isAfter(result.getContent().get(2).getCreatedDate()));
    assertTrue(
            result.getContent().get(2).getCreatedDate().isAfter(result.getContent().get(3).getCreatedDate()));
}

From source file:org.jblogcms.core.account.service.AccountServiceImplTest.java

@Test
public void findAllAccounts() throws Exception {
    when(accountRepositoryMock.findAccounts(pageable)).thenReturn(accounts);
    when(accountToolServiceMock.addItemRelationsToItemPage(accounts, CURRENT_ACCOUNT_ID)).thenReturn(accounts);

    Page<Account> testAccounts = accountService.findAccounts(pageable, CURRENT_ACCOUNT_ID);

    verify(accountRepositoryMock, times(1)).findAccounts(pageable);
    verify(accountToolServiceMock, times(1)).addItemRelationsToItemPage(accounts, CURRENT_ACCOUNT_ID);

    Assert.assertEquals(ACCOUNTS_SIZE, testAccounts.getTotalElements());

    Assert.assertEquals(ACCOUNT_1_ID, testAccounts.getContent().get(0).getId());
    Assert.assertEquals(ACCOUNT_1_EMAIL, testAccounts.getContent().get(0).getEmail());
    Assert.assertEquals(ACCOUNT_2_ID, testAccounts.getContent().get(1).getId());
    Assert.assertEquals(ACCOUNT_2_EMAIL, testAccounts.getContent().get(1).getEmail());
    Assert.assertEquals(ACCOUNT_3_ID, testAccounts.getContent().get(2).getId());
    Assert.assertEquals(ACCOUNT_3_EMAIL, testAccounts.getContent().get(2).getEmail());
}

From source file:com.cami.web.controller.DepartementController.java

@RequestMapping(method = RequestMethod.GET)
public String indexAction(final ModelMap model, final WebRequest webRequest) {

    final String code = webRequest.getParameter("code") != null ? webRequest.getParameter("code") : "";
    final String intitule = webRequest.getParameter("intitule") != null ? webRequest.getParameter("intitule")
            : "";

    final Integer page = webRequest.getParameter("page") != null
            ? Integer.valueOf(webRequest.getParameter("page"))
            : 0;//from  w  w  w  .  ja  v  a 2  s .  c om
    final Integer size = webRequest.getParameter("size") != null
            ? Integer.valueOf(webRequest.getParameter("size"))
            : 55;

    boolean deleted = false;
    if (webRequest.getParameter("querydeleted") != null) {
        deleted = webRequest.getParameter("querydeleted").equals("true");
    }

    final Page<Departement> resultPage = iDepartementService.searchDepartements(code, intitule, deleted, page,
            size);

    final Departement departement = new Departement();
    departement.setCode(code);
    departement.setIntitule(intitule);
    model.addAttribute("departement", departement);
    model.addAttribute("page", page);
    model.addAttribute("Totalpage", resultPage.getTotalPages());
    model.addAttribute("size", size);
    model.addAttribute("departements", resultPage.getContent());

    return "departement/index";
}

From source file:nu.yona.server.subscriptions.service.BuddyService.java

private boolean processPossiblePendingBuddyResponseMessage(UserDto user, Buddy buddy,
        Page<Message> messagePage) {

    Stream<BuddyConnectResponseMessage> buddyConnectResponseMessages = messagePage.getContent().stream()
            .filter(m -> m instanceof BuddyConnectResponseMessage).map(m -> (BuddyConnectResponseMessage) m);
    Stream<BuddyConnectResponseMessage> messagesFromBuddy = buddyConnectResponseMessages
            .filter(m -> buddy.getUserId().equals(getUserId(m).orElse(null)));
    Optional<BuddyConnectResponseMessage> messageToBeProcessed = messagesFromBuddy.filter(m -> !m.isProcessed())
            .findFirst();//from w ww  .j a  v  a  2  s .  c  o m
    messageToBeProcessed.ifPresent(m -> connectResponseMessageHandler.handleAction_Process(user, m,
            new MessageActionDto(Collections.emptyMap())));
    return messageToBeProcessed.isPresent();
}

From source file:de.hska.ld.content.service.DocumentServiceIntegrationTest.java

@Test
@Transactional/*from   w w  w . ja va 2  s . c o  m*/
public void testPublicFlagForDocumentsPage() {
    // 1. Create a document with testUser
    Document document = documentService.save(newDocument());

    // 2. Switch to user "user"
    User user = userService.findByUsername("user");
    setAuthentication(user);

    // 3. Try to retrieve the document (expected is that the user doesn't see it now)
    Page<Document> documentsPage = documentService.getDocumentsPage(0, Integer.MAX_VALUE, "DESC", "createdAt");
    List<Document> documentList = documentsPage.getContent();
    final Document tempDocument = document;
    List<Document> documentFoundResult = documentList.stream()
            .filter(d -> tempDocument.getTitle().equals(d.getTitle())).collect(Collectors.toList());
    Assert.assertTrue(documentFoundResult.size() == 0);

    // 4. Switch back to the testUser
    setAuthentication(testUser);
    // 5. Make the document public
    document = documentService.setAccessAll(document.getId(), true);

    // 6. Switch back to user
    setAuthentication(user);

    // 7. Try to retrieve the document again (expected is that the user does have access now)
    Page<Document> documentsPage2 = documentService.getDocumentsPage(0, Integer.MAX_VALUE, "DESC", "createdAt");
    Assert.assertTrue(documentsPage2.getTotalElements() > 0);
    List<Document> documentList2 = documentsPage2.getContent();
    final Document tempDocument2 = document;
    List<Document> documentFoundResult2 = documentList2.stream()
            .filter(d -> tempDocument2.getTitle().equals(d.getTitle())).collect(Collectors.toList());
    Assert.assertTrue(documentFoundResult2.size() > 0);
}

From source file:org.jblogcms.core.account.service.AccountServiceImplTest.java

@Test
public void findFavoriteAccounts() throws Exception {
    when(accountRepositoryMock.findFavoriteAccounts(ACCOUNT_ID, pageable)).thenReturn(accounts);
    when(accountToolServiceMock.addItemRelationsToItemPage(accounts, CURRENT_ACCOUNT_ID)).thenReturn(accounts);

    Page<Account> testAccounts = accountService.findFavoriteAccounts(ACCOUNT_ID, pageable, CURRENT_ACCOUNT_ID);

    verify(accountRepositoryMock, times(1)).findFavoriteAccounts(ACCOUNT_ID, pageable);
    verify(accountToolServiceMock, times(1)).addItemRelationsToItemPage(accounts, CURRENT_ACCOUNT_ID);

    Assert.assertEquals(ACCOUNTS_SIZE, testAccounts.getTotalElements());

    Assert.assertEquals(ACCOUNT_1_ID, testAccounts.getContent().get(0).getId());
    Assert.assertEquals(ACCOUNT_1_EMAIL, testAccounts.getContent().get(0).getEmail());
    Assert.assertEquals(ACCOUNT_2_ID, testAccounts.getContent().get(1).getId());
    Assert.assertEquals(ACCOUNT_2_EMAIL, testAccounts.getContent().get(1).getEmail());
    Assert.assertEquals(ACCOUNT_3_ID, testAccounts.getContent().get(2).getId());
    Assert.assertEquals(ACCOUNT_3_EMAIL, testAccounts.getContent().get(2).getEmail());
}

From source file:com.thinkbiganalytics.jobrepo.rest.controller.JobsRestController.java

@GET
@Path("/list")
@ApiOperation("Lists all jobs.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the jobs.", response = SearchResult.class),
        @ApiResponse(code = 400, message = "The sort cannot be empty.", response = RestResponseStatus.class),
        @ApiResponse(code = 404, message = "The start or limit is not a valid integer.", response = RestResponseStatus.class),
        @ApiResponse(code = 500, message = "The sort contains an invalid value.", response = RestResponseStatus.class) })
public List<ExecutedJob> findJobsList(@QueryParam("sort") @DefaultValue("") String sort,
        @QueryParam("limit") @DefaultValue("10") Integer limit,
        @QueryParam("start") @DefaultValue("1") Integer start, @QueryParam("filter") String filter,
        @Context HttpServletRequest request) {
    this.accessController.checkPermission(AccessController.SERVICES, OperationsAccessControl.ACCESS_OPS);

    return metadataAccess.read(() -> {
        Page<ExecutedJob> page = jobExecutionProvider.findAll(filter, pageRequest(start, limit, sort))
                .map(jobExecution -> JobModelTransform.executedJobSimple(jobExecution));
        return page != null ? page.getContent() : Collections.emptyList();
    });/*from ww w.ja v  a  2  s.co  m*/
}

From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java

@RequestMapping(method = RequestMethod.POST, value = "/etherpad/conversations")
public Callable getConversations(@RequestBody EtherpadDocumentUpdateDto etherpadDocumentUpdateDto) {
    return () -> {
        if (env.getProperty("module.etherpad.apikey").equals(etherpadDocumentUpdateDto.getApiKey())) {
            String sessionId = etherpadDocumentUpdateDto.getAuthorId();
            UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.findBySessionId(sessionId);
            if (userEtherpadInfo == null) {
                return new ResponseEntity<>("sessionID is invalid", HttpStatus.UNAUTHORIZED);
            }//from  w w w  . j av  a 2  s . c o m
            DocumentEtherpadInfo documentEtherpadInfo = documentEtherpadInfoService
                    .findByGroupPadId(etherpadDocumentUpdateDto.getPadId());
            return userService.callAs(userEtherpadInfo.getUser(), () -> {
                // retrieve all conversations the user has access to
                Long documentId = documentEtherpadInfo.getDocument().getId();
                int pageNumber = 0;
                int pageSize = 10;
                String sortDirection = "DESC";
                String sortProperty = "createdAt";
                Page<Document> documentPage = documentService.getDiscussionDocumentsPage(documentId, pageNumber,
                        pageSize, sortDirection, sortProperty);
                System.out.println(documentPage);
                List<Document> documentList = documentPage.getContent();
                List<DocumentInfo> documentInfoList = new ArrayList<DocumentInfo>();
                documentList.forEach(d -> {
                    DocumentInfo documentInfo = new DocumentInfo();
                    documentInfo.setId(d.getId());
                    documentInfo.setTitle(d.getTitle());
                    documentInfoList.add(documentInfo);
                });
                return new ResponseEntity<>(documentInfoList, HttpStatus.OK);
            });
        } else {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    };
}

From source file:org.ow2.proactive.workflow_catalog.rest.service.repository.QueryDslWorkflowRevisionRepositoryIntegrationTest.java

@Test
public void testFindAllWorkflowRevisions4() {
    ListSubQuery<WorkflowRevision> revisionSubQuery = new JPASubQuery()
            .from(QGenericInformation.genericInformation)
            .where(QGenericInformation.genericInformation.key.eq("revisionIndex").and(
                    QGenericInformation.genericInformation.value.eq(Integer.toString(NUMBER_OF_WORKFLOWS))))
            .list(QGenericInformation.genericInformation.workflowRevision);

    BucketMetadata bucket = buckets.get(0);

    Page<WorkflowRevision> result = findAllWorkflowRevisions(bucket, NUMBER_OF_WORKFLOWS,
            Optional.of(QWorkflowRevision.workflowRevision
                    .in(new JPASubQuery().from(QWorkflowRevision.workflowRevision)
                            .where(QWorkflowRevision.workflowRevision.in(revisionSubQuery))
                            .list(QWorkflowRevision.workflowRevision))),
            1);/*from   ww w.j  a  v  a2s . c om*/

    assertThat(result.getContent().get(0).getName())
            .isEqualTo("bucket" + bucket.id + "Name" + Integer.toString(NUMBER_OF_WORKFLOWS));
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Gets schedules by club id./*from ww w.  java 2  s  .  com*/
 *
 * @param id       the id
 * @param response the response
 * @param offset   the offset
 * @param limit    the limit
 * @return the schedules by club id
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs/{id}/schedules", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<ActionSchedule>> getSchedulesByClubId(@PathVariable Long id,
        HttpServletResponse response, @RequestParam(value = "page", required = false) Integer offset,
        @RequestParam(value = "per_page", required = false) Integer limit) throws URISyntaxException {
    log.debug("REST request to get Actions by club id : {}", id);
    Club club = clubRepository.findOne(id);
    if (club == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    List<ActionSchedule> result = null;
    HttpHeaders headers = null;

    if (offset != null && offset == -1) {
        result = actionScheduleRepository.findByClub(club);
        return new ResponseEntity<List<ActionSchedule>>(result, HttpStatus.OK);
    } else {
        Page<ActionSchedule> page = actionScheduleRepository.findByClub(club,
                PaginationUtil.generatePageRequest(offset, limit));
        headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/actionSchedules", offset, limit);
        result = page.getContent();
        return new ResponseEntity<List<ActionSchedule>>(result, headers, HttpStatus.OK);
    }
}