use of eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter in project CzechIdMng by bcvsolutions.
the class AbstractSynchronizationExecutor method findByAttribute.
/**
* Find dto by idm attribute
*
* @param idmAttributeName
* @param value
* @param context
* @return
*/
protected DTO findByAttribute(String idmAttributeName, String value, SynchronizationContext context) {
CorrelationFilter filter = this.getEntityFilter(context);
filter.setProperty(idmAttributeName);
filter.setValue(value);
@SuppressWarnings("unchecked") ReadWriteDtoService<DTO, BaseFilter> service = (ReadWriteDtoService<DTO, BaseFilter>) getService();
List<DTO> entities = service.find((BaseFilter) filter, (Pageable) null).getContent();
if (CollectionUtils.isEmpty(entities)) {
return null;
}
if (entities.size() > 1) {
throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_CORRELATION_TO_MANY_RESULTS, ImmutableMap.of("correlationAttribute", idmAttributeName, "value", value));
}
if (entities.size() == 1) {
return entities.get(0);
}
return null;
}
use of eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter in project CzechIdMng by bcvsolutions.
the class DefaultImportManager method removeRedundant.
/**
* Ensures delete redundant entities in target IdM. Deletes DTOs are within
* golden DTO type (super parent = typically system, role, ...).
*
* @param descriptor
* @param context
*/
private void removeRedundant(ExportDescriptorDto descriptor, ImportContext context) {
Class<? extends BaseDto> dtoClass = descriptor.getDtoClass();
// Does this DTO support the authoritative mode?
boolean supportsAuthoritativeMode = descriptor.isSupportsAuthoritativeMode();
if (!supportsAuthoritativeMode) {
return;
}
String superParentFilterProperty = descriptor.getSuperParentFilterProperty();
Assert.notNull(superParentFilterProperty, "For authoritative mode must be superParentFilterProperty defined!");
// Find super parent (gold) DTO (typically it is DTO for system, role ...)
Class<? extends AbstractDto> superParentDtoClass = getSuperParentDtoClass(descriptor, context);
Assert.notNull(superParentDtoClass, "Supper parent cannot be null here!");
Path superParentDtoTypePath = Paths.get(context.getTempDirectory().toString(), superParentDtoClass.getSimpleName());
try {
// Find all super parent IDs for this DTO type in batch.
Set<UUID> superParentIdsInBatch;
try (Stream<Path> paths = Files.walk(superParentDtoTypePath)) {
superParentIdsInBatch = //
paths.filter(//
Files::isRegularFile).map(path -> {
BaseDto dto = convertFileToDto(path.toFile(), superParentDtoClass, context);
return (UUID) dto.getId();
}).collect(Collectors.toSet());
}
Set<Class<? extends BaseDto>> inheritedClasses = getInheritedClasses(dtoClass, context.getManifest());
// Find all IDs for all children classes
Set<Serializable> childrenIdsInBatch = Sets.newHashSet();
for (Class<? extends BaseDto> inheritedClass : inheritedClasses) {
// Find all IDs for this DTO type in batch.
Path dtoTypePath = Paths.get(context.getTempDirectory().toString(), inheritedClass.getSimpleName());
try (Stream<Path> paths = Files.walk(dtoTypePath)) {
Set<Serializable> childrenIds = //
paths.filter(//
Files::isRegularFile).map(//
path -> convertFileToDto(path.toFile(), inheritedClass, context)).map(dto -> {
// If ID has been replaced, then we need to also replace it.
if (context.getReplacedIDs().containsKey((UUID) dto.getId())) {
return context.getReplacedIDs().get((UUID) dto.getId());
}
return dto.getId();
}).collect(Collectors.toSet());
childrenIdsInBatch.addAll(childrenIds);
}
}
superParentIdsInBatch.forEach(superParentId -> {
try {
Class<? extends BaseDto> serviceDtoClass = dtoClass;
if (dtoClass.isAnnotationPresent(Inheritable.class)) {
serviceDtoClass = dtoClass.getAnnotation(Inheritable.class).dtoService();
}
ReadWriteDtoService<BaseDto, BaseFilter> dtoService = getDtoService(serviceDtoClass);
BaseFilter filterBase = dtoService.getFilterClass().getDeclaredConstructor().newInstance();
// Fill super-parent-property by superParentId (call setter = check if filter is
// implemented).
new PropertyDescriptor(superParentFilterProperty, dtoService.getFilterClass()).getWriteMethod().invoke(filterBase, superParentId);
// Load all IDs in IdM for this parent ID.
List<UUID> childrenIdsInIdM = //
dtoService.find(filterBase, null).getContent().stream().map(//
childDto -> ((AbstractDto) childDto).getId()).collect(Collectors.toList());
// IDs to delete = entities missing in the batch.
Set<UUID> idsToDelete = //
childrenIdsInIdM.stream().filter(//
idmId -> !childrenIdsInBatch.contains(idmId)).collect(Collectors.toSet());
idsToDelete.forEach(id -> {
BaseDto baseDto = dtoService.get(id);
IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), baseDto, RequestOperationType.REMOVE, superParentId);
if (!context.isDryRun()) {
dtoService.delete(baseDto);
dtoLog.setResult(new OperationResultDto(OperationState.EXECUTED));
} else {
dtoLog.setResult(new OperationResultDto.Builder(OperationState.NOT_EXECUTED).setModel(//
new DefaultResultModel(CoreResultCode.IMPORT_EXECUTED_AS_DRYRUN)).build());
}
importLogService.saveDistinct(dtoLog);
});
} catch (ReflectiveOperationException | IllegalArgumentException | IntrospectionException e) {
throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_REFLECTION_FAILED, e);
}
});
} catch (IOException e) {
throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_IO_FAILED, e);
}
}
use of eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter in project CzechIdMng by bcvsolutions.
the class DefaultRequestManager method executeRequestInternal.
@SuppressWarnings("unchecked")
private IdmRequestDto executeRequestInternal(UUID requestId) {
Assert.notNull(requestId, "Role request ID is required!");
IdmRequestDto request = requestService.get(requestId);
Assert.notNull(request, "Role request is required!");
// Validate request
List<IdmRequestItemDto> items = this.findRequestItems(request.getId(), null);
if (items.isEmpty()) {
throw new ResultCodeException(CoreResultCode.REQUEST_CANNOT_BE_EXECUTED_NONE_ITEMS, ImmutableMap.of("request", request.toString()));
}
List<IdmRequestItemDto> sortedItems = items.stream().sorted(Comparator.comparing(IdmRequestItemDto::getCreated)).collect(Collectors.toList());
// Validate items
//
sortedItems.stream().filter(//
item -> !item.getState().isTerminatedState()).filter(//
item -> !(RequestState.CONCEPT == item.getState() || RequestState.APPROVED == item.getState())).forEach(item -> {
//
throw new ResultCodeException(CoreResultCode.REQUEST_ITEM_CANNOT_BE_EXECUTED, ImmutableMap.of("item", item.toString(), "state", item.getState()));
});
//
sortedItems.stream().filter(item -> RequestOperationType.ADD == item.getOperation() || //
RequestOperationType.UPDATE == item.getOperation()).forEach(item -> {
//
// Get DTO service
Requestable dto = null;
try {
Class<? extends Requestable> dtoClass = (Class<? extends Requestable>) Class.forName(item.getOwnerType());
ReadWriteDtoService<Requestable, BaseFilter> dtoService = (ReadWriteDtoService<Requestable, BaseFilter>) getServiceByItem(item, dtoClass);
dto = this.convertItemToDto(item, dtoClass);
dtoService.validateDto((Requestable) dto);
} catch (Exception e) {
throw new RoleRequestException(CoreResultCode.REQUEST_ITEM_IS_NOT_VALID, ImmutableMap.of("dto", dto != null ? dto.toString() : null, "item", item.toString()), e);
}
});
// We have to ensure the referential integrity, because some items (his DTOs)
// could be child of terminated (Disapproved, Cancelled) item (DTO)
//
sortedItems.stream().filter(// We check terminated ADDed items (Executed state could not yet occur)
item -> item.getState().isTerminatedState()).filter(//
item -> RequestOperationType.ADD == item.getOperation()).filter(//
item -> item.getOwnerId() != null).forEach(terminatedItem -> {
// Create predicate - find all DTOs with that UUID value in any fields
ImmutableList<RequestPredicate> predicates = ImmutableList.of(new RequestPredicate(terminatedItem.getOwnerId(), null));
//
sortedItems.stream().filter(//
item -> !item.getState().isTerminatedState()).filter(item -> {
// Is that item child of terminated item?
try {
Class<? extends Requestable> ownerType = (Class<? extends Requestable>) Class.forName(item.getOwnerType());
Requestable requestable = requestManager.convertItemToDto(item, ownerType);
List<Requestable> filteredDtos = requestManager.filterDtosByPredicates(ImmutableList.of(requestable), ownerType, predicates);
return filteredDtos.contains(requestable);
} catch (ClassNotFoundException | IOException e) {
throw new CoreException(e);
}
}).forEach(itemToCancel -> {
// This item could be not executed, because is use in other
// already terminated (added) item.
itemToCancel.setState(RequestState.CANCELED);
itemToCancel.setResult(new OperationResultDto.Builder(OperationState.NOT_EXECUTED).setException(new RoleRequestException(CoreResultCode.REQUEST_ITEM_NOT_EXECUTED_PARENT_CANCELED, ImmutableMap.of("item", itemToCancel.toString(), "terminatedItem", terminatedItem.toString()))).build());
requestItemService.save(itemToCancel);
});
});
// Reload items ... could be changed
items = this.findRequestItems(request.getId(), null);
List<IdmRequestItemDto> sortedItemsResult = items.stream().sorted(Comparator.comparing(IdmRequestItemDto::getCreated)).collect(Collectors.toList());
//
sortedItemsResult.stream().filter(//
item -> !item.getState().isTerminatedState()).forEach(item -> {
try {
this.resolveItem(item);
} catch (ClassNotFoundException | IOException e) {
throw new CoreException(e);
}
});
request.setState(RequestState.EXECUTED);
request.setResult(new OperationResultDto.Builder(OperationState.EXECUTED).build());
return requestService.save(request);
}
use of eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter in project CzechIdMng by bcvsolutions.
the class DefaultRequestManager method resolveItem.
private void resolveItem(IdmRequestItemDto item) throws ClassNotFoundException, IOException {
Assert.notNull(item, "Item is mandatory!");
RequestOperationType type = item.getOperation();
// Get DTO service
@SuppressWarnings("unchecked") Class<? extends Requestable> dtoClass = (Class<? extends Requestable>) Class.forName(item.getOwnerType());
// Get service
@SuppressWarnings("unchecked") ReadWriteDtoService<Requestable, BaseFilter> dtoService = (ReadWriteDtoService<Requestable, BaseFilter>) this.getServiceByItem(item, dtoClass);
// Create or Update DTO
if (RequestOperationType.ADD == type || RequestOperationType.UPDATE == type) {
Requestable dto = this.convertItemToDto(item, dtoClass);
// confidential storage
if (dto instanceof IdmFormValueDto) {
IdmFormValueDto formValueDto = (IdmFormValueDto) dto;
if (formValueDto.isConfidential()) {
formValueDto.setValue(this.getConfidentialPersistentValue(item));
}
}
// Save without check a permissions
dto = dtoService.save(dto);
item.setResult(new OperationResultDto(OperationState.EXECUTED));
item.setState(RequestState.EXECUTED);
requestItemService.save(item);
return;
}
// Delete DTO
if (RequestOperationType.REMOVE == type) {
Assert.notNull(item.getOwnerId(), "Id in item is required for delete!");
Requestable dtoToDelete = dtoService.get(item.getOwnerId());
if (dtoToDelete == null) {
item.setResult(new //
OperationResultDto.Builder(//
OperationState.NOT_EXECUTED).setException(new ResultCodeException(CoreResultCode.NOT_FOUND, //
ImmutableMap.of("entity", item.getOriginalCreatorId()))).build());
requestItemService.save(item);
return;
}
// Delete without check a permissions
dtoService.deleteById(dtoToDelete.getId());
item.setResult(new OperationResultDto(OperationState.EXECUTED));
item.setState(RequestState.EXECUTED);
requestItemService.save(item);
return;
}
}
use of eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter in project CzechIdMng by bcvsolutions.
the class AbstractExportBulkActionTest method executeExportAndImport.
/**
* Provides export and following import operation for supplied dto It accepts a map of methods in order to supply necessary operation between individual steps.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <DTO extends AbstractDto> IdmExportImportDto executeExportAndImport(List<DTO> dtos, Class dtoType, String actionName, Map<String, Consumer<DTO>> execute) {
String batchName = getHelper().createName();
Class<? extends BaseEntity> entityClass = getLookupService().getEntityClass(dtoType);
Set<UUID> ids = dtos.stream().map(AbstractDto::getId).collect(Collectors.toSet());
// Bulk action preparation
IdmBulkActionDto bulkAction = findBulkAction(entityClass, actionName);
bulkAction.setIdentifiers(ids);
bulkAction.getProperties().put(AbstractExportBulkAction.PROPERTY_NAME, batchName);
IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction);
checkResultLrt(processAction, (long) dtos.size(), null, null);
// Export batch is created
IdmExportImportFilter exportImportFilter = new IdmExportImportFilter();
exportImportFilter.setText(batchName);
List<IdmExportImportDto> batches = exportImportService.find(exportImportFilter, null).getContent();
Assert.assertEquals(1, batches.size());
IdmExportImportDto batch = batches.get(0);
Assert.assertEquals(OperationState.EXECUTED, batch.getResult().getState());
Assert.assertNotNull(batch.getData());
// Find export batch as attachment
List<IdmAttachmentDto> attachments = //
attachmentManager.getAttachments(batch.getId(), getLookupService().getEntityClass(IdmExportImportDto.class).getCanonicalName(), //
null).getContent();
Assert.assertEquals(1, attachments.size());
IdmAttachmentDto attachment = attachments.get(0);
// Upload import
IdmExportImportDto importBatch = importManager.uploadImport(attachment.getName(), attachment.getName(), attachmentManager.getAttachmentData(attachment.getId()));
Assert.assertNotNull(importBatch);
Assert.assertEquals(batch.getName(), importBatch.getName());
Assert.assertEquals(ExportImportType.IMPORT, importBatch.getType());
// Get a service corresponding to the DTO type
ReadWriteDtoService<BaseDto, BaseFilter> service = ((ReadWriteDtoService<BaseDto, BaseFilter>) getLookupService().getDtoService(dtoType));
dtos.forEach(dto -> {
// Execute supplied action before original dto deletion
if (execute != null && execute.containsKey(EXECUTE_BEFORE_DTO_DELETE)) {
execute.get(EXECUTE_BEFORE_DTO_DELETE).accept(dto);
}
// Original dto deletion
service.delete(dto);
Assert.assertNull(service.get(dto.getId()));
});
// Execute import
importBatch = importManager.executeImport(importBatch, false);
Assert.assertNotNull(importBatch);
Assert.assertEquals(batch.getName(), importBatch.getName());
Assert.assertEquals(ExportImportType.IMPORT, importBatch.getType());
Assert.assertEquals(OperationState.EXECUTED, importBatch.getResult().getState());
return importBatch;
}
Aggregations