Search in sources :

Example 1 with Pageable

use of org.springframework.data.domain.Pageable in project goci by EBISPOT.

the class SolrIndexer method mapAssociations.

Integer mapAssociations() {
    Sort sort = new Sort(new Sort.Order("id"));
    Pageable pager = new PageRequest(0, pageSize, sort);
    Page<Association> associationPage = associationService.findPublishedAssociations(pager);
    associationMapper.map(associationPage.getContent());
    while (associationPage.hasNext()) {
        if (maxPages != -1 && associationPage.getNumber() >= maxPages - 1) {
            break;
        }
        pager = pager.next();
        associationPage = associationService.findPublishedAssociations(pager);
        associationMapper.map(associationPage.getContent());
        if (sysOutLogging) {
            System.out.print(".");
        }
    }
    return (int) associationPage.getTotalElements();
}
Also used : PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) Association(uk.ac.ebi.spot.goci.model.Association) Sort(org.springframework.data.domain.Sort)

Example 2 with Pageable

use of org.springframework.data.domain.Pageable in project goci by EBISPOT.

the class SolrIndexer method mapStudies.

Integer mapStudies() {
    Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "publicationDate"));
    Pageable pager = new PageRequest(0, pageSize, sort);
    Page<Study> studyPage = studyService.findPublishedStudies(pager);
    studyMapper.map(studyPage.getContent());
    while (studyPage.hasNext()) {
        if (maxPages != -1 && studyPage.getNumber() >= maxPages - 1) {
            break;
        }
        pager = pager.next();
        studyPage = studyService.findPublishedStudies(pager);
        studyMapper.map(studyPage.getContent());
        if (sysOutLogging) {
            System.out.print(".");
        }
    }
    return (int) studyPage.getTotalElements();
}
Also used : Study(uk.ac.ebi.spot.goci.model.Study) PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort)

Example 3 with Pageable

use of org.springframework.data.domain.Pageable in project CzechIdMng by bcvsolutions.

the class DefaultWorkflowTaskInstanceService method search.

@Override
public ResourcesWrapper<WorkflowTaskInstanceDto> search(WorkflowFilterDto filter) {
    Pageable pageable = null;
    // get pageable setting from filter - backward compatibility
    if (StringUtils.isNotEmpty(filter.getSortByFields())) {
        Sort sort = null;
        if (filter.isSortAsc()) {
            sort = new Sort(Direction.ASC, filter.getSortByFields());
        } else {
            sort = new Sort(Direction.DESC, filter.getSortByFields());
        }
        pageable = new PageRequest(filter.getPageNumber(), filter.getPageSize(), sort);
    } else {
        pageable = new PageRequest(filter.getPageNumber(), filter.getPageSize());
    }
    filter.setCandidateOrAssigned(securityService.getCurrentId().toString());
    Page<WorkflowTaskInstanceDto> page = this.find(filter, pageable);
    return new ResourcesWrapper<>(page.getContent(), page.getTotalElements(), page.getTotalPages(), filter.getPageNumber(), filter.getPageSize());
}
Also used : PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) WorkflowTaskInstanceDto(eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowTaskInstanceDto) Sort(org.springframework.data.domain.Sort) ResourcesWrapper(eu.bcvsolutions.idm.core.api.rest.domain.ResourcesWrapper)

Example 4 with Pageable

use of org.springframework.data.domain.Pageable in project CzechIdMng by bcvsolutions.

the class SchedulerController method find.

/**
 * Finds scheduled tasks
 *
 * @return all tasks
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@PreAuthorize("hasAuthority('" + CoreGroupPermission.SCHEDULER_READ + "')")
@ApiOperation(value = "Search scheduled tasks", nickname = "searchSchedulerTasks", tags = { SchedulerController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = CoreGroupPermission.SCHEDULER_READ, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = CoreGroupPermission.SCHEDULER_READ, description = "") }) })
@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "string", paramType = "query", value = "Results page you want to retrieve (0..N)"), @ApiImplicitParam(name = "size", dataType = "string", paramType = "query", value = "Number of records per page."), @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "Sorting criteria in the format: property(,asc|desc). " + "Default sort order is ascending. " + "Multiple sort criteria are supported.") })
public Resources<Task> find(@RequestParam(required = false) MultiValueMap<String, Object> parameters, @PageableDefault Pageable pageable) {
    String text = getParameterConverter().toString(parameters, DataFilter.PARAMETER_TEXT);
    List<Task> tasks = schedulerService.getAllTasks().stream().filter(task -> {
        // filter - like name or description only
        return StringUtils.isEmpty(text) || task.getTaskType().getSimpleName().toLowerCase().contains(text.toLowerCase()) || (task.getDescription() != null && task.getDescription().toLowerCase().contains(text.toLowerCase()));
    }).sorted((taskOne, taskTwo) -> {
        Sort sort = pageable.getSort();
        if (pageable.getSort() == null) {
            return 0;
        }
        int compareAscValue = 0;
        boolean asc = true;
        // "naive" sort implementation
        if (sort.getOrderFor(PROPERTY_TASK_TYPE) != null) {
            asc = sort.getOrderFor(PROPERTY_TASK_TYPE).isAscending();
            compareAscValue = taskOne.getTaskType().getSimpleName().compareTo(taskTwo.getTaskType().getSimpleName());
        }
        if (sort.getOrderFor(PROPERTY_DESCRIPTION) != null) {
            asc = sort.getOrderFor(PROPERTY_DESCRIPTION).isAscending();
            compareAscValue = taskOne.getDescription().compareTo(taskTwo.getDescription());
        }
        if (sort.getOrderFor(PROPERTY_INSTANCE_ID) != null) {
            asc = sort.getOrderFor(PROPERTY_INSTANCE_ID).isAscending();
            compareAscValue = taskOne.getInstanceId().compareTo(taskTwo.getInstanceId());
        }
        return asc ? compareAscValue : compareAscValue * -1;
    }).collect(Collectors.toList());
    // "naive" pagination
    int first = pageable.getPageNumber() * pageable.getPageSize();
    int last = pageable.getPageSize() + first;
    List<Task> taskPage = tasks.subList(first < tasks.size() ? first : tasks.size() > 0 ? tasks.size() - 1 : 0, last < tasks.size() ? last : tasks.size());
    // 
    return pageToResources(new PageImpl(taskPage, pageable, tasks.size()), Task.class);
}
Also used : PagedResourcesAssembler(org.springframework.data.web.PagedResourcesAssembler) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) DependentTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.DependentTaskTrigger) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) SimpleTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.SimpleTaskTrigger) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) Valid(javax.validation.Valid) RequestBody(org.springframework.web.bind.annotation.RequestBody) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) ApiOperation(io.swagger.annotations.ApiOperation) DataFilter(eu.bcvsolutions.idm.core.api.dto.filter.DataFilter) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) SwaggerConfig(eu.bcvsolutions.idm.core.api.config.swagger.SwaggerConfig) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) AuthorizationScope(io.swagger.annotations.AuthorizationScope) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) Api(io.swagger.annotations.Api) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) MultiValueMap(org.springframework.util.MultiValueMap) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) SchedulerManager(eu.bcvsolutions.idm.core.scheduler.api.service.SchedulerManager) Page(org.springframework.data.domain.Page) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) ParameterConverter(eu.bcvsolutions.idm.core.api.utils.ParameterConverter) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) BaseController(eu.bcvsolutions.idm.core.api.rest.BaseController) AbstractTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.AbstractTaskTrigger) CronTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.CronTaskTrigger) PageableDefault(org.springframework.data.web.PageableDefault) Resources(org.springframework.hateoas.Resources) ResponseEntity(org.springframework.http.ResponseEntity) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) PageImpl(org.springframework.data.domain.PageImpl) Authorization(io.swagger.annotations.Authorization) PageImpl(org.springframework.data.domain.PageImpl) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) Sort(org.springframework.data.domain.Sort) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with Pageable

use of org.springframework.data.domain.Pageable in project CzechIdMng by bcvsolutions.

the class IdentityReportExecutor method generateData.

@Override
protected IdmAttachmentDto generateData(RptReportDto report) {
    File temp = null;
    FileOutputStream outputStream = null;
    try {
        // prepare temp file for json stream
        temp = getAttachmentManager().createTempFile();
        outputStream = new FileOutputStream(temp);
        // write into json stream
        JsonGenerator jGenerator = getMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8);
        try {
            // json will be array of identities
            jGenerator.writeStartArray();
            // form instance has useful methods to transform form values
            IdmFormInstanceDto formInstance = new IdmFormInstanceDto(report, getFormDefinition(), report.getFilter());
            // initialize filter by given form - transform to multi value map
            // => form attribute defined above will be automaticaly mapped to identity filter
            IdmIdentityFilter filter = new IdmIdentityFilter(formInstance.toMultiValueMap());
            // report extends long running task - show progress by count and counter lrt attributes
            counter = 0L;
            // find a first page of identities
            Pageable pageable = new PageRequest(0, 100, new Sort(Direction.ASC, IdmIdentity_.username.getName()));
            do {
                Page<IdmIdentityDto> identities = identityService.find(filter, pageable, IdmBasePermission.READ);
                if (count == null) {
                    // report extends long running task - show progress by count and counter lrt attributes
                    count = identities.getTotalElements();
                }
                boolean canContinue = true;
                for (Iterator<IdmIdentityDto> i = identities.iterator(); i.hasNext() && canContinue; ) {
                    // write single identity into json
                    getMapper().writeValue(jGenerator, i.next());
                    // 
                    // supports cancel report generating (report extends long running task)
                    ++counter;
                    canContinue = updateState();
                }
                // iterate while next page of identities is available
                pageable = identities.hasNext() && canContinue ? identities.nextPageable() : null;
            } while (pageable != null);
            // 
            // close array of identities
            jGenerator.writeEndArray();
        } finally {
            // close json stream
            jGenerator.close();
        }
        // save create temp file with array of identities in json as attachment
        return createAttachment(report, new FileInputStream(temp));
    } catch (IOException ex) {
        throw new ReportGenerateException(report.getName(), ex);
    } finally {
        // just for sure - jGenerator should close stream itself
        IOUtils.closeQuietly(outputStream);
        FileUtils.deleteQuietly(temp);
    }
}
Also used : IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) IOException(java.io.IOException) ReportGenerateException(eu.bcvsolutions.idm.rpt.api.exception.ReportGenerateException) FileInputStream(java.io.FileInputStream) PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) FileOutputStream(java.io.FileOutputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) Sort(org.springframework.data.domain.Sort) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) File(java.io.File)

Aggregations

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