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);
}
}
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);
}
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);
}
}
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;
}
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());
}
Aggregations