Search in sources :

Example 56 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) {
    // prepare temp file for json stream
    File temp = getAttachmentManager().createTempFile();
    // 
    try (FileOutputStream 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 = PageRequest.of(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 {
        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) 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)

Example 57 with Pageable

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

the class AddNewRoleCompositionTaskExecutor method getItemsToProcess.

/**
 * Returns superior roles, which should be processed
 */
@Override
public Page<IdmRoleDto> getItemsToProcess(Pageable pageable) {
    IdmRoleCompositionDto roleComposition = roleCompositionService.get(roleCompositionId);
    Assert.notNull(roleComposition, "Role composition is required.");
    // 
    List<IdmRoleDto> superiorRoles = roleCompositionService.findAllSuperiorRoles(roleComposition.getSub()).stream().map(composition -> {
        return DtoUtils.getEmbedded(composition, IdmRoleComposition_.superior, IdmRoleDto.class);
    }).collect(Collectors.toList());
    return new PageImpl<>(superiorRoles);
}
Also used : DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) IdmIdentityRole_(eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole_) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) IdmRoleCompositionDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto) IdmRoleCompositionFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleCompositionFilter) Autowired(org.springframework.beans.factory.annotation.Autowired) PersistentType(eu.bcvsolutions.idm.core.eav.api.domain.PersistentType) IdmRoleRequestService(eu.bcvsolutions.idm.core.api.service.IdmRoleRequestService) Lists(com.google.common.collect.Lists) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) Map(java.util.Map) IdmConceptRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmConceptRoleRequestDto) IdmLongRunningTaskFilter(eu.bcvsolutions.idm.core.scheduler.api.dto.filter.IdmLongRunningTaskFilter) Pageable(org.springframework.data.domain.Pageable) IdmIdentityContractDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto) IdmCheckConcurrentExecution(eu.bcvsolutions.idm.core.scheduler.api.domain.IdmCheckConcurrentExecution) IdmIdentityRoleService(eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) ImmutableMap(com.google.common.collect.ImmutableMap) IdmRoleComposition_(eu.bcvsolutions.idm.core.model.entity.IdmRoleComposition_) AbstractSchedulableStatefulExecutor(eu.bcvsolutions.idm.core.scheduler.api.service.AbstractSchedulableStatefulExecutor) IdmRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto) PageRequest(org.springframework.data.domain.PageRequest) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) AcceptedException(eu.bcvsolutions.idm.core.api.exception.AcceptedException) IdmRoleCompositionService(eu.bcvsolutions.idm.core.api.service.IdmRoleCompositionService) UUID(java.util.UUID) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) List(java.util.List) Component(org.springframework.stereotype.Component) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmLongRunningTaskDto(eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) RoleRequestEvent(eu.bcvsolutions.idm.core.model.event.RoleRequestEvent) Optional(java.util.Optional) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) RoleRequestEventType(eu.bcvsolutions.idm.core.model.event.RoleRequestEvent.RoleRequestEventType) PageImpl(org.springframework.data.domain.PageImpl) ConceptRoleRequestOperation(eu.bcvsolutions.idm.core.api.domain.ConceptRoleRequestOperation) Assert(org.springframework.util.Assert) PageImpl(org.springframework.data.domain.PageImpl) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmRoleCompositionDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto)

Example 58 with Pageable

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

the class DefaultSchedulerManager method find.

@Override
public Page<Task> find(TaskFilter filter, Pageable pageable) {
    try {
        List<Task> tasks = new ArrayList<>();
        // load scheduled tasks
        for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(DEFAULT_GROUP_NAME))) {
            Task task = getTask(jobKey);
            // 
            if (passFilter(task, filter)) {
                tasks.add(task);
            }
        }
        // 
        // pageable is required internally
        Pageable internalPageable;
        if (pageable == null) {
            internalPageable = PageRequest.of(0, Integer.MAX_VALUE);
        } else {
            internalPageable = pageable;
        }
        // apply "naive" sort and pagination
        tasks = tasks.stream().sorted((taskOne, taskTwo) -> {
            Sort sort = internalPageable.getSort();
            if (internalPageable.getSort() == null) {
                return 0;
            }
            int compareAscValue = 0;
            boolean asc = true;
            // "naive" sort implementation
            Order orderForTaskType = sort.getOrderFor(Task.PROPERTY_TASK_TYPE);
            if (orderForTaskType != null) {
                asc = orderForTaskType.isAscending();
                compareAscValue = taskOne.getTaskType().getSimpleName().compareTo(taskTwo.getTaskType().getSimpleName());
            }
            Order orderForDescription = sort.getOrderFor(Task.PROPERTY_DESCRIPTION);
            if (orderForDescription != null) {
                asc = orderForDescription.isAscending();
                compareAscValue = StringUtils.compare(taskOne.getDescription(), taskTwo.getDescription());
            }
            Order orderForInstance = sort.getOrderFor(Task.PROPERTY_INSTANCE_ID);
            if (orderForInstance != null) {
                asc = orderForInstance.isAscending();
                compareAscValue = StringUtils.compare(taskOne.getInstanceId(), taskTwo.getInstanceId());
            }
            // 
            return asc ? compareAscValue : compareAscValue * -1;
        }).collect(Collectors.toList());
        // "naive" pagination
        int first = internalPageable.getPageNumber() * internalPageable.getPageSize();
        int last = internalPageable.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 new PageImpl<>(taskPage, internalPageable, tasks.size());
    } catch (org.quartz.SchedulerException ex) {
        throw new CoreException(ex);
    }
}
Also used : Order(org.springframework.data.domain.Sort.Order) PageImpl(org.springframework.data.domain.PageImpl) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) ArrayList(java.util.ArrayList) JobKey(org.quartz.JobKey) Pageable(org.springframework.data.domain.Pageable) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) Sort(org.springframework.data.domain.Sort)

Example 59 with Pageable

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

the class AbstractSchedulableStatefulExecutor method executeProcess.

/**
 * Process long running task.
 *
 * @return true - completed, false - not complete
 */
private boolean executeProcess() {
    Set<UUID> processedRefs = new HashSet<>();
    // 
    boolean canContinue = true;
    boolean updateStateSucceed = true;
    boolean dryRun = longRunningTaskService.get(this.getLongRunningTaskId()).isDryRun();
    Pageable pageable = PageRequest.of(0, getPageSize(), new Sort(Direction.ASC, BaseEntity.PROPERTY_ID));
    // 
    do {
        Page<DTO> candidates = this.getItemsToProcess(pageable);
        // 
        if (count == null) {
            count = candidates.getTotalElements();
        }
        // 
        for (Iterator<DTO> i = candidates.iterator(); i.hasNext() && canContinue; ) {
            DTO candidate = i.next();
            Assert.notNull(candidate, "DTO candidate is required for LRT processing.");
            Assert.notNull(candidate.getId(), "DTO candidate has to be persisted for LRT processing.");
            // 
            Optional<OperationResult> result = processCandidate(candidate, dryRun);
            if (!result.isPresent() || // executed
            result.get().getState().isSuccessful() || result.get().getState().isRunnable()) {
                // running (e.q. asynchronously)
                if (supportsQueue()) {
                    processedRefs.add(candidate.getId());
                }
            }
            updateStateSucceed = this.updateState();
            canContinue &= updateStateSucceed;
            // flush and clear session - if LRT is wrapped in parent transaction, we need to clear it
            if (getHibernateSession().isOpen()) {
                getHibernateSession().flush();
                getHibernateSession().clear();
            }
        }
        canContinue &= candidates.hasNext();
        pageable = candidates.nextPageable();
    // 
    } while (canContinue);
    // if task doesn't support queue, we can end
    if (!supportsQueue()) {
        return updateStateSucceed;
    }
    // 
    // check task was not canceled or interrupted, then clean history
    // task is not ended yet - running is the correct state in this phase
    IdmLongRunningTaskDto task = longRunningTaskService.get(getLongRunningTaskId());
    OperationState resultState = task.getResultState();
    if (// executed (set manually somehow ... just for sure)
    resultState.isSuccessful() || resultState.isRunnable()) {
        // running is the correct state in this phase
        List<UUID> queueEntityRefs = Lists.newArrayList(this.getProcessedItemRefsFromQueue());
        // processed should remain in history (is not related to whole task is canceled)
        queueEntityRefs.removeAll(processedRefs);
        queueEntityRefs.forEach(entityRef -> this.removeFromProcessedQueue(entityRef));
    }
    // 
    return updateStateSucceed;
}
Also used : IdmLongRunningTaskDto(eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) UUID(java.util.UUID) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) HashSet(java.util.HashSet)

Example 60 with Pageable

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

the class DefaultMonitoringManager method getLastResults.

@Override
public Page<IdmMonitoringResultDto> getLastResults(IdmMonitoringResultFilter filter, Pageable pageable, BasePermission... permission) {
    // all instances => last results should be visible on each instance
    IdmMonitoringFilter monitoringFilter = new IdmMonitoringFilter();
    if (filter != null) {
        monitoringFilter.setId(filter.getMonitoring());
    }
    monitoringFilter.setDisabled(Boolean.FALSE);
    // 
    List<IdmMonitoringDto> monitorings = monitoringService.find(monitoringFilter, PageRequest.of(0, Integer.MAX_VALUE, Sort.by(IdmMonitoring_.seq.getName())), PermissionUtils.isEmpty(permission) ? null : IdmBasePermission.AUTOCOMPLETE).getContent();
    // 
    // last results sorted by monitoring order
    List<IdmMonitoringResultDto> results = new ArrayList<>(monitorings.size());
    for (IdmMonitoringDto monitoring : monitorings) {
        MonitoringEvaluator evaluator = getEvaluator(monitoring);
        if (evaluator == null) {
            LOG.debug("Monitoring evaluator for motitoring configuration [{}] not exists.", monitoring.getId());
            continue;
        }
        IdmMonitoringResultDto lastResult = getLastResult(monitoring.getId(), permission);
        if (lastResult == null) {
            continue;
        }
        // filter by level
        NotificationLevel lastResultLevel = lastResult.getLevel();
        List<NotificationLevel> levels = filter == null ? null : filter.getLevels();
        if (CollectionUtils.isNotEmpty(levels) && !levels.contains(lastResultLevel)) {
            continue;
        }
        lastResult.setTrimmed(true);
        results.add(lastResult);
    }
    // 
    // pageable is required internally
    Pageable internalPageable;
    if (pageable == null) {
        internalPageable = PageRequest.of(0, Integer.MAX_VALUE);
    } else {
        internalPageable = pageable;
    }
    // 
    // Sort by level desc
    results.sort((r1, r2) -> {
        return ObjectUtils.compare(r2.getLevel(), r1.getLevel());
    });
    // 
    // "naive" pagination
    int first = internalPageable.getPageNumber() * internalPageable.getPageSize();
    int last = internalPageable.getPageSize() + first;
    List<IdmMonitoringResultDto> page = results.subList(first < results.size() ? first : results.size() > 0 ? results.size() - 1 : 0, last < results.size() ? last : results.size());
    // 
    return new PageImpl<>(page, internalPageable, results.size());
}
Also used : IdmMonitoringFilter(eu.bcvsolutions.idm.core.monitoring.api.dto.filter.IdmMonitoringFilter) PageImpl(org.springframework.data.domain.PageImpl) IdmMonitoringDto(eu.bcvsolutions.idm.core.monitoring.api.dto.IdmMonitoringDto) Pageable(org.springframework.data.domain.Pageable) MonitoringEvaluator(eu.bcvsolutions.idm.core.monitoring.api.service.MonitoringEvaluator) ArrayList(java.util.ArrayList) NotificationLevel(eu.bcvsolutions.idm.core.notification.api.domain.NotificationLevel) IdmMonitoringResultDto(eu.bcvsolutions.idm.core.monitoring.api.dto.IdmMonitoringResultDto)

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