Search in sources :

Example 36 with Pageable

use of org.springframework.data.domain.Pageable in project openlmis-stockmanagement by OpenLMIS.

the class StockCardService method search.

/**
 * Find stock card page by parameters. Allowed multiple id parameters.
 *
 * @param ids      collection of ids for batch fetch
 * @param pageable pagination and sorting parameters
 * @return page of filtered stock cards.
 */
public Page<StockCardDto> search(@NotNull Collection<UUID> ids, Pageable pageable) {
    OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    Page<StockCard> page;
    if (!authentication.isClientOnly()) {
        UserDto user = authenticationHelper.getCurrentUser();
        LOGGER.info("list of ids:" + ids);
        PermissionStrings.Handler handler = permissionService.getPermissionStrings(user.getId());
        Set<PermissionStringDto> permissionStrings = handler.get();
        LOGGER.info("list of permission strings:" + permissionStrings);
        Set<UUID> facilityIds = new HashSet<>();
        Set<UUID> programIds = new HashSet<>();
        permissionStrings.stream().filter(permissionString -> STOCK_CARDS_VIEW.equalsIgnoreCase(permissionString.getRightName())).forEach(permission -> {
            facilityIds.add(permission.getFacilityId());
            programIds.add(permission.getProgramId());
        });
        LOGGER.info("list of facility ids:" + facilityIds);
        LOGGER.info("list of program ids:" + programIds);
        if (isEmpty(ids)) {
            page = cardRepository.findByFacilityIdInAndProgramIdIn(facilityIds, programIds, pageable);
        } else {
            page = cardRepository.findByFacilityIdInAndProgramIdInAndIdIn(facilityIds, programIds, ids, pageable);
        }
    } else {
        if (isEmpty(ids)) {
            page = cardRepository.findAll(pageable);
        } else {
            page = cardRepository.findByIdIn(ids, pageable);
        }
    }
    return Pagination.getPage(createDtos(page.getContent()), pageable, page.getTotalElements());
}
Also used : FacilityReferenceDataService(org.openlmis.stockmanagement.service.referencedata.FacilityReferenceDataService) StockCard(org.openlmis.stockmanagement.domain.card.StockCard) OrderableReferenceDataService(org.openlmis.stockmanagement.service.referencedata.OrderableReferenceDataService) OrganizationRepository(org.openlmis.stockmanagement.repository.OrganizationRepository) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) CollectionUtils.isEmpty(org.apache.commons.collections4.CollectionUtils.isEmpty) OrderableLotIdentity.identityOf(org.openlmis.stockmanagement.domain.identity.OrderableLotIdentity.identityOf) Collections.singletonList(java.util.Collections.singletonList) StockCardLineItem(org.openlmis.stockmanagement.domain.card.StockCardLineItem) HashSet(java.util.HashSet) OrderableLotIdentity(org.openlmis.stockmanagement.domain.identity.OrderableLotIdentity) Lists(com.google.common.collect.Lists) StockCardDto(org.openlmis.stockmanagement.dto.StockCardDto) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) LotReferenceDataService(org.openlmis.stockmanagement.service.referencedata.LotReferenceDataService) Service(org.springframework.stereotype.Service) PHYSICAL_INVENTORY(org.openlmis.stockmanagement.domain.reason.ReasonCategory.PHYSICAL_INVENTORY) Pageable(org.springframework.data.domain.Pageable) StockCardRepository(org.openlmis.stockmanagement.repository.StockCardRepository) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) STOCK_CARDS_VIEW(org.openlmis.stockmanagement.service.PermissionService.STOCK_CARDS_VIEW) Node(org.openlmis.stockmanagement.domain.sourcedestination.Node) StockEventLineItemDto(org.openlmis.stockmanagement.dto.StockEventLineItemDto) Logger(org.slf4j.Logger) PermissionStrings(org.openlmis.stockmanagement.service.referencedata.PermissionStrings) UserDto(org.openlmis.stockmanagement.dto.referencedata.UserDto) Collection(java.util.Collection) Set(java.util.Set) Pagination(org.openlmis.stockmanagement.web.Pagination) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Page(org.springframework.data.domain.Page) StockEventDto(org.openlmis.stockmanagement.dto.StockEventDto) PermissionStringDto(org.openlmis.stockmanagement.service.referencedata.PermissionStringDto) List(java.util.List) MessageService(org.openlmis.stockmanagement.i18n.MessageService) AuthenticationHelper(org.openlmis.stockmanagement.util.AuthenticationHelper) Message(org.openlmis.stockmanagement.util.Message) FacilityDto(org.openlmis.stockmanagement.dto.referencedata.FacilityDto) StockCardLineItem.createLineItemFrom(org.openlmis.stockmanagement.domain.card.StockCardLineItem.createLineItemFrom) StockCard.createStockCardFrom(org.openlmis.stockmanagement.domain.card.StockCard.createStockCardFrom) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UserDto(org.openlmis.stockmanagement.dto.referencedata.UserDto) PermissionStringDto(org.openlmis.stockmanagement.service.referencedata.PermissionStringDto) StockCard(org.openlmis.stockmanagement.domain.card.StockCard) PermissionStrings(org.openlmis.stockmanagement.service.referencedata.PermissionStrings) UUID(java.util.UUID) HashSet(java.util.HashSet)

Example 37 with Pageable

use of org.springframework.data.domain.Pageable in project thingsboard by thingsboard.

the class JpaAuditLogDao method findAuditLogs.

private List<AuditLog> findAuditLogs(UUID tenantId, EntityId entityId, CustomerId customerId, UserId userId, TimePageLink pageLink) {
    Specification<AuditLogEntity> timeSearchSpec = JpaAbstractSearchTimeDao.getTimeSearchPageSpec(pageLink, "id");
    Specification<AuditLogEntity> fieldsSpec = getEntityFieldsSpec(tenantId, entityId, customerId, userId);
    Sort.Direction sortDirection = pageLink.isAscOrder() ? Sort.Direction.ASC : Sort.Direction.DESC;
    Pageable pageable = new PageRequest(0, pageLink.getLimit(), sortDirection, ID_PROPERTY);
    return DaoUtil.convertDataList(auditLogRepository.findAll(where(timeSearchSpec).and(fieldsSpec), pageable).getContent());
}
Also used : PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) AuditLogEntity(org.thingsboard.server.dao.model.sql.AuditLogEntity)

Example 38 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-commons by spring-projects.

the class PageableHandlerMethodArgumentResolver method resolveArgument.

/*
	 * (non-Javadoc)
	 * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest, org.springframework.web.bind.support.WebDataBinderFactory)
	 */
@Override
public Pageable resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) {
    assertPageableUniqueness(methodParameter);
    Optional<Pageable> defaultOrFallback = getDefaultFromAnnotationOrFallback(methodParameter).toOptional();
    String pageString = webRequest.getParameter(getParameterNameToUse(pageParameterName, methodParameter));
    String pageSizeString = webRequest.getParameter(getParameterNameToUse(sizeParameterName, methodParameter));
    Optional<Integer> page = parseAndApplyBoundaries(pageString, Integer.MAX_VALUE, true);
    Optional<Integer> pageSize = parseAndApplyBoundaries(pageSizeString, maxPageSize, false);
    if (!(page.isPresent() && pageSize.isPresent()) && !defaultOrFallback.isPresent()) {
        return Pageable.unpaged();
    }
    int p = page.orElseGet(() -> defaultOrFallback.map(Pageable::getPageNumber).orElseThrow(IllegalStateException::new));
    int ps = pageSize.orElseGet(() -> defaultOrFallback.map(Pageable::getPageSize).orElseThrow(IllegalStateException::new));
    // Limit lower bound
    ps = ps < 1 ? defaultOrFallback.map(Pageable::getPageSize).orElseThrow(IllegalStateException::new) : ps;
    // Limit upper bound
    ps = ps > maxPageSize ? maxPageSize : ps;
    Sort sort = sortResolver.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
    return PageRequest.of(p, ps, sort.isSorted() ? sort : defaultOrFallback.map(Pageable::getSort).orElseGet(Sort::unsorted));
}
Also used : Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort)

Example 39 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-commons by spring-projects.

the class PagedResourcesAssemblerArgumentResolver method findMatchingPageableParameter.

/**
 * Returns finds the {@link MethodParameter} for a {@link Pageable} instance matching the given
 * {@link MethodParameter} requesting a {@link PagedResourcesAssembler}.
 *
 * @param parameter must not be {@literal null}.
 * @return
 */
@Nullable
private static MethodParameter findMatchingPageableParameter(MethodParameter parameter) {
    MethodParameters parameters = new MethodParameters(parameter.getMethod());
    List<MethodParameter> pageableParameters = parameters.getParametersOfType(Pageable.class);
    Qualifier assemblerQualifier = parameter.getParameterAnnotation(Qualifier.class);
    if (pageableParameters.isEmpty()) {
        return null;
    }
    if (pageableParameters.size() == 1) {
        MethodParameter pageableParameter = pageableParameters.get(0);
        MethodParameter matchingParameter = returnIfQualifiersMatch(pageableParameter, assemblerQualifier);
        if (matchingParameter == null) {
            LOGGER.info(SUPERFLOUS_QUALIFIER, PagedResourcesAssembler.class.getSimpleName(), Pageable.class.getName());
        }
        return pageableParameter;
    }
    if (assemblerQualifier == null) {
        throw new IllegalStateException(PARAMETER_AMBIGUITY);
    }
    for (MethodParameter pageableParameter : pageableParameters) {
        MethodParameter matchingParameter = returnIfQualifiersMatch(pageableParameter, assemblerQualifier);
        if (matchingParameter != null) {
            return matchingParameter;
        }
    }
    throw new IllegalStateException(PARAMETER_AMBIGUITY);
}
Also used : Pageable(org.springframework.data.domain.Pageable) Qualifier(org.springframework.beans.factory.annotation.Qualifier) MethodParameters(org.springframework.hateoas.core.MethodParameters) MethodParameter(org.springframework.core.MethodParameter) Nullable(org.springframework.lang.Nullable)

Example 40 with Pageable

use of org.springframework.data.domain.Pageable in project spring-data-commons by spring-projects.

the class RepositoryFactorySupportUnitTests method createsRepositoryInstanceWithCustomIntermediateRepository.

@Test
public void createsRepositoryInstanceWithCustomIntermediateRepository() {
    CustomRepository repository = factory.getRepository(CustomRepository.class);
    Pageable pageable = PageRequest.of(0, 10);
    when(backingRepo.findAll(pageable)).thenReturn(new PageImpl<>(Collections.emptyList()));
    repository.findAll(pageable);
    verify(backingRepo, times(1)).findAll(pageable);
}
Also used : Pageable(org.springframework.data.domain.Pageable) Test(org.junit.Test)

Aggregations

Pageable (org.springframework.data.domain.Pageable)185 PageRequest (org.springframework.data.domain.PageRequest)88 Sort (org.springframework.data.domain.Sort)81 Test (org.junit.Test)39 PageImpl (org.springframework.data.domain.PageImpl)28 ArrayList (java.util.ArrayList)18 Collectors (java.util.stream.Collectors)17 List (java.util.List)15 Page (org.springframework.data.domain.Page)15 Autowired (org.springframework.beans.factory.annotation.Autowired)14 GetMapping (org.springframework.web.bind.annotation.GetMapping)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 Test (org.junit.jupiter.api.Test)11 UUID (java.util.UUID)10 ApiOperation (io.swagger.annotations.ApiOperation)9 Calendar (java.util.Calendar)9 java.util (java.util)8 Lists (com.google.common.collect.Lists)7 Map (java.util.Map)7 Transactional (org.springframework.transaction.annotation.Transactional)6