Search in sources :

Example 31 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class DefaultImportManager method executeImportForType.

/**
 * Ensures add new and update existed DTOs by given batch.
 *
 * @param descriptor
 * @param context
 */
private void executeImportForType(ExportDescriptorDto descriptor, ImportContext context) {
    Class<? extends BaseDto> dtoClass = descriptor.getDtoClass();
    Path dtoTypePath = Paths.get(context.getTempDirectory().toString(), dtoClass.getSimpleName());
    try {
        List<BaseDto> dtos;
        try (Stream<Path> paths = Files.walk(dtoTypePath)) {
            dtos = // 
            paths.filter(// 
            Files::isRegularFile).map(path -> {
                BaseDto dto = convertFileToDto(path.toFile(), dtoClass, context);
                Assert.notNull(dto, "DTO cannot be null after conversion from the batch!");
                return dto;
            }).collect(Collectors.toList());
        }
        if (dtos.isEmpty()) {
            return;
        }
        // Sorts all DTOs for this type (maybe it is tree).
        dtos = sortsDTOs(dtoClass, dtos);
        int i = 0;
        for (BaseDto dto : dtos) {
            // Flush Hibernate in batch - performance improving
            if (i % 20 == 0 && i > 0) {
                // Call hard hibernate session flush and clear
                if (getHibernateSession().isOpen()) {
                    getHibernateSession().flush();
                    getHibernateSession().clear();
                }
            }
            i++;
            // Increase counter and update state of import LRT.
            context.getImportTaskExecutor().increaseCounter();
            context.getImportTaskExecutor().updateState();
            BaseDto parentDto = getParentDtoFromBatch(dto, context);
            if (parentDto == null) {
                parentDto = dto;
            }
            BaseDto originalDto = dto;
            try {
                dto = makeAdvancedPairing(dto, context, dtoClass);
                if (dto == null) {
                    // If DTO after advanced pairing is null, then was not found and is optional ->
                    // skip.
                    IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), originalDto, RequestOperationType.ADD, (UUID) parentDto.getId());
                    ResultModel resultModel = new DefaultResultModel(CoreResultCode.IMPORT_DTO_SKIPPED, ImmutableMap.of("dto", originalDto.toString()));
                    dtoLog.setResult(new OperationResultDto.Builder(OperationState.CANCELED).setModel(resultModel).build());
                    importLogService.saveDistinct(dtoLog);
                    continue;
                }
            } catch (ResultCodeException ex) {
                if (context.isDryRun() && ex.getError() != null && ex.getError().getError() != null && CoreResultCode.IMPORT_ADVANCED_PARING_FAILED_NOT_FOUND.name().equals(ex.getError().getError().getStatusEnum())) {
                    // Not found DTO we will mark as skipped in dry run mode.
                    IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), originalDto, RequestOperationType.ADD, (UUID) parentDto.getId());
                    dtoLog.setResult(new OperationResultDto.Builder(OperationState.EXCEPTION).setException(ex).build());
                    importLogService.saveDistinct(dtoLog);
                    continue;
                } else if (ex.getError() != null && ex.getError().getError() != null && CoreResultCode.IMPORT_ADVANCED_PARING_NOT_FOUND_OPTIONAL.name().equals(ex.getError().getError().getStatusEnum())) {
                    // Not found DTO, but optional, we will mark as skipped.
                    IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), originalDto, RequestOperationType.ADD, (UUID) parentDto.getId());
                    dtoLog.setResult(new OperationResultDto.Builder(OperationState.CANCELED).setException(ex).build());
                    importLogService.saveDistinct(dtoLog);
                    continue;
                }
                throw ex;
            }
            Class<? extends BaseDto> serviceDtoClass = dtoClass;
            if (dto instanceof IdmFormInstanceDto) {
                // Form instance is very special here (doesn't have entity in DB).
                IdmFormInstanceDto formInstance = (IdmFormInstanceDto) dto;
                IdmFormDefinitionDto definition = formInstance.getFormDefinition();
                Assert.notNull(definition, "Definition cannot be null for import!");
                CoreEvent<IdmFormInstanceDto> event = new CoreEvent<>(CoreEventType.UPDATE, formInstance);
                // Check if owner exist (UPDATE/ADD)
                @SuppressWarnings("unchecked") Class<? extends BaseDto> ownerType = (Class<? extends BaseDto>) ((IdmFormInstanceDto) dto).getOwnerType();
                UUID ownerId = UUID.fromString((String) ((IdmFormInstanceDto) dto).getOwnerId());
                BaseDto ownerDto = this.getDtoService(ownerType).get(ownerId);
                IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), dto, ownerDto != null ? RequestOperationType.UPDATE : RequestOperationType.ADD, ownerId);
                if (!context.isDryRun()) {
                    formService.publish(event);
                    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);
                continue;
            }
            if (dto.getClass().isAnnotationPresent(Inheritable.class)) {
                serviceDtoClass = dto.getClass().getAnnotation(Inheritable.class).dtoService();
            }
            ReadWriteDtoService<BaseDto, ?> dtoService = getDtoService(serviceDtoClass);
            BaseDto currentDto = dtoService.get(dto.getId());
            if (currentDto != null) {
                // DTO with same ID already exists -> update.
                IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), dto, RequestOperationType.UPDATE, (UUID) parentDto.getId());
                // Resolve excluded fields
                dto = this.excludeFields(dto, currentDto, context);
                if (!context.isDryRun()) {
                    dtoService.save(dto);
                    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);
                continue;
            }
            if (dto instanceof Codeable) {
                // We try to find exists DTO by code.
                currentDto = lookupService.lookupDto(serviceDtoClass, ((Codeable) dto).getCode());
            }
            // Find target DTO by example source DTO (typically by more then one filter field).
            currentDto = findByExample(dto, null, context);
            if (dto instanceof IdmFormDefinitionDto) {
                IdmFormDefinitionDto definition = (IdmFormDefinitionDto) dto;
                // We try to find exists definition by code and type (IdmFormDefinitionDto is
                // not Codeable).
                currentDto = formService.getDefinition(definition.getType(), definition.getCode());
            }
            if (dto instanceof IdmFormAttributeDto) {
                IdmFormAttributeDto attribute = (IdmFormAttributeDto) dto;
                IdmFormDefinitionDto definition = formService.getDefinition(attribute.getFormDefinition());
                if (definition != null) {
                    // We try to find exists attribute definition by code and form definition.
                    currentDto = formService.getAttribute(definition, attribute.getCode());
                } else {
                    currentDto = null;
                }
            }
            if (currentDto != null) {
                // We found current DTO in IdM.
                // Save old and new ID for next DTOs.
                context.getReplacedIDs().put((UUID) dto.getId(), (UUID) currentDto.getId());
                // We have to change the ID in import DTO.
                dto.setId(currentDto.getId());
                // Update current DTO by batch DTO.
                IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), dto, RequestOperationType.UPDATE, (UUID) parentDto.getId());
                if (!context.isDryRun()) {
                    // Resolve excluded fields
                    dto = this.excludeFields(dto, currentDto, context);
                    // Save a DTO.
                    dtoService.save(dto);
                    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);
            } else {
                IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), dto, RequestOperationType.ADD, (UUID) parentDto.getId());
                // No current DTO was found -> create.
                if (!context.isDryRun()) {
                    // Resolve excluded fields
                    dto = this.excludeFields(dto, null, context);
                    // Save new DTO.
                    dtoService.save(dto);
                    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 (IOException | IllegalArgumentException e) {
        throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_IO_FAILED, e);
    }
}
Also used : Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) ResultModel(eu.bcvsolutions.idm.core.api.dto.ResultModel) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) IdmImportLogDto(eu.bcvsolutions.idm.core.api.dto.IdmImportLogDto) UUID(java.util.UUID) Path(java.nio.file.Path) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) IOException(java.io.IOException) CoreEvent(eu.bcvsolutions.idm.core.api.event.CoreEvent)

Example 32 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException 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);
    }
}
Also used : Embedded(eu.bcvsolutions.idm.core.api.domain.Embedded) ImportContext(eu.bcvsolutions.idm.core.api.dto.ImportContext) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) FormService(eu.bcvsolutions.idm.core.eav.api.service.FormService) CoreEvent(eu.bcvsolutions.idm.core.api.event.CoreEvent) IdmImportLogDto(eu.bcvsolutions.idm.core.api.dto.IdmImportLogDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) JsonNode(com.fasterxml.jackson.databind.JsonNode) AbstractLongRunningTaskExecutor(eu.bcvsolutions.idm.core.scheduler.api.service.AbstractLongRunningTaskExecutor) AttachmentConfiguration(eu.bcvsolutions.idm.core.ecm.api.config.AttachmentConfiguration) Path(java.nio.file.Path) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ImmutableMap(com.google.common.collect.ImmutableMap) ImportTaskExecutor(eu.bcvsolutions.idm.core.scheduler.task.impl.ImportTaskExecutor) IdmImportLogFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmImportLogFilter) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) LongRunningFutureTask(eu.bcvsolutions.idm.core.scheduler.api.dto.LongRunningFutureTask) Set(java.util.Set) IdmExportImportService(eu.bcvsolutions.idm.core.api.service.IdmExportImportService) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) FileSystemUtils(org.springframework.util.FileSystemUtils) Sets(com.google.common.collect.Sets) IntrospectionException(java.beans.IntrospectionException) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) Inheritable(eu.bcvsolutions.idm.core.api.domain.Inheritable) Objects(java.util.Objects) EmbeddedDto(eu.bcvsolutions.idm.core.api.dto.EmbeddedDto) List(java.util.List) Stream(java.util.stream.Stream) PropertyDescriptor(java.beans.PropertyDescriptor) CollectionUtils(org.springframework.util.CollectionUtils) Entry(java.util.Map.Entry) Strings(org.apache.logging.log4j.util.Strings) ExportImportType(eu.bcvsolutions.idm.core.api.domain.ExportImportType) ZipUtils(eu.bcvsolutions.idm.core.api.utils.ZipUtils) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) RequestOperationType(eu.bcvsolutions.idm.core.api.domain.RequestOperationType) ExportManager(eu.bcvsolutions.idm.core.api.service.ExportManager) ImportManager(eu.bcvsolutions.idm.core.api.service.ImportManager) IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) AttachableEntity(eu.bcvsolutions.idm.core.ecm.api.entity.AttachableEntity) Session(org.hibernate.Session) MessageFormat(java.text.MessageFormat) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) Lists(com.google.common.collect.Lists) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) IdmImportLogService(eu.bcvsolutions.idm.core.api.service.IdmImportLogService) Service(org.springframework.stereotype.Service) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) EntityUtils(eu.bcvsolutions.idm.core.api.utils.EntityUtils) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmExportImportDto(eu.bcvsolutions.idm.core.api.dto.IdmExportImportDto) Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) Files(java.nio.file.Files) LongRunningTaskManager(eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager) AttachmentManager(eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) IOException(java.io.IOException) EntityManager(javax.persistence.EntityManager) Field(java.lang.reflect.Field) File(java.io.File) BaseFilter(eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) ExportDescriptorDto(eu.bcvsolutions.idm.core.api.dto.ExportDescriptorDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) Paths(java.nio.file.Paths) CoreEventType(eu.bcvsolutions.idm.core.api.event.CoreEvent.CoreEventType) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) ResultModel(eu.bcvsolutions.idm.core.api.dto.ResultModel) InputStream(java.io.InputStream) Transactional(org.springframework.transaction.annotation.Transactional) Assert(org.springframework.util.Assert) Serializable(java.io.Serializable) IntrospectionException(java.beans.IntrospectionException) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) BaseFilter(eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) IdmImportLogDto(eu.bcvsolutions.idm.core.api.dto.IdmImportLogDto) UUID(java.util.UUID) Path(java.nio.file.Path) PropertyDescriptor(java.beans.PropertyDescriptor) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) IOException(java.io.IOException)

Example 33 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class DefaultIdmRoleTreeNodeService method save.

/**
 * Publish {@link RoleTreeNodeEvent} only.
 *
 * @see {@link RoleTreeNodeSaveProcessor}
 */
@Override
@Transactional(noRollbackFor = AcceptedException.class)
public IdmRoleTreeNodeDto save(IdmRoleTreeNodeDto roleTreeNode, BasePermission... permission) {
    Assert.notNull(roleTreeNode, "Automatic role is required.");
    checkAccess(toEntity(roleTreeNode, null), permission);
    // 
    LOG.debug("Saving automatic role [{}] - [{}] - [{}]", roleTreeNode.getRole(), roleTreeNode.getTreeNode(), roleTreeNode.getRecursionType());
    // FIXME: this should be in save processor ... can be skipped by publishing raw create event
    if (isNew(roleTreeNode)) {
        // create
        EventContext<IdmRoleTreeNodeDto> context = entityEventManager.process(new RoleTreeNodeEvent(RoleTreeNodeEventType.CREATE, roleTreeNode));
        if (context.isSuspended()) {
            throw new AcceptedException(String.valueOf(context.getContent().getId()));
        }
        return context.getContent();
    }
    throw new ResultCodeException(CoreResultCode.METHOD_NOT_ALLOWED, "Automatic role update is not supported");
}
Also used : IdmRoleTreeNodeDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleTreeNodeDto) RoleTreeNodeEvent(eu.bcvsolutions.idm.core.model.event.RoleTreeNodeEvent) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) AcceptedException(eu.bcvsolutions.idm.core.api.exception.AcceptedException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 34 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class DefaultIdmScriptService method findScripts.

/**
 * Return list of {@link IdmScriptType} from resources.
 * {@link IdmScriptType} are found by configured locations and by priority - last one wins.
 * So default location should be configured first, then external, etc.
 *
 * @return <code, script>
 */
private Map<String, IdmScriptType> findScripts() {
    // last script with the same is used
    // => last location has the highest priority
    Map<String, IdmScriptType> scripts = new HashMap<>();
    // 
    for (String location : configurationService.getValues(SCRIPT_FOLDER)) {
        location = location + configurationService.getValue(SCRIPT_FILE_SUFIX, DEFAULT_SCRIPT_FILE_SUFIX);
        Map<String, IdmScriptType> locationScripts = new HashMap<>();
        try {
            Resource[] resources = applicationContext.getResources(location);
            LOG.debug("Found [{}] resources on location [{}]", resources == null ? 0 : resources.length, location);
            // 
            if (ArrayUtils.isEmpty(resources)) {
                continue;
            }
            // 
            for (Resource resource : resources) {
                try {
                    IdmScriptType scriptType = readType(location, resource.getInputStream());
                    // log error, if script with the same code was found twice in one resource
                    if (locationScripts.containsKey(scriptType.getCode())) {
                        LOG.error("More scripts with code [{}], category [{}] found on the same location [{}].", scriptType.getCode(), scriptType.getCategory(), location);
                    }
                    // last one wins
                    locationScripts.put(scriptType.getCode(), scriptType);
                } catch (IOException ex) {
                    LOG.error("Failed get input stream from, file name [{}].", resource.getFilename(), ex);
                }
            }
            scripts.putAll(locationScripts);
        } catch (IOException ex) {
            throw new ResultCodeException(CoreResultCode.DEPLOY_ERROR, ImmutableMap.of("path", location), ex);
        }
    }
    return scripts;
}
Also used : IdmScriptType(eu.bcvsolutions.idm.core.model.jaxb.IdmScriptType) HashMap(java.util.HashMap) Resource(org.springframework.core.io.Resource) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IOException(java.io.IOException)

Example 35 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException 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);
}
Also used : DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) IdmRequestItemDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestItemDto) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) FormService(eu.bcvsolutions.idm.core.eav.api.service.FormService) SecurityService(eu.bcvsolutions.idm.core.security.api.service.SecurityService) Map(java.util.Map) IdmRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestDto) PageRequest(org.springframework.data.domain.PageRequest) Page(org.springframework.data.domain.Page) IntrospectionException(java.beans.IntrospectionException) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) PropertyDescriptor(java.beans.PropertyDescriptor) Builder(eu.bcvsolutions.idm.core.api.dto.OperationResultDto.Builder) Lazy(org.springframework.context.annotation.Lazy) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) RequestOperationType(eu.bcvsolutions.idm.core.api.domain.RequestOperationType) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Introspector(java.beans.Introspector) Strings(com.google.common.base.Strings) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) Lists(com.google.common.collect.Lists) BaseEntity(eu.bcvsolutions.idm.core.api.entity.BaseEntity) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) Service(org.springframework.stereotype.Service) WorkflowProcessInstanceService(eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessInstanceService) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) Requestable(eu.bcvsolutions.idm.core.api.domain.Requestable) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) IOException(java.io.IOException) Field(java.lang.reflect.Field) BaseFilter(eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmRequestItemService(eu.bcvsolutions.idm.core.api.service.IdmRequestItemService) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) FormValueService(eu.bcvsolutions.idm.core.eav.api.service.FormValueService) RequestEventType(eu.bcvsolutions.idm.core.model.event.RequestEvent.RequestEventType) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) Embedded(eu.bcvsolutions.idm.core.api.domain.Embedded) RequestEvent(eu.bcvsolutions.idm.core.model.event.RequestEvent) RequestState(eu.bcvsolutions.idm.core.api.domain.RequestState) RoleRequestException(eu.bcvsolutions.idm.core.api.exception.RoleRequestException) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Pageable(org.springframework.data.domain.Pageable) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) RequestManager(eu.bcvsolutions.idm.core.api.service.RequestManager) AcceptedException(eu.bcvsolutions.idm.core.api.exception.AcceptedException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) ExceptionUtils(eu.bcvsolutions.idm.core.api.utils.ExceptionUtils) Modifier(java.lang.reflect.Modifier) Entry(java.util.Map.Entry) Identifiable(eu.bcvsolutions.idm.core.api.domain.Identifiable) RoleRequestApprovalProcessor(eu.bcvsolutions.idm.core.model.event.processor.role.RoleRequestApprovalProcessor) PageImpl(org.springframework.data.domain.PageImpl) IdmRequestService(eu.bcvsolutions.idm.core.api.service.IdmRequestService) FormableEntity(eu.bcvsolutions.idm.core.eav.api.entity.FormableEntity) IdmRequestItem(eu.bcvsolutions.idm.core.model.entity.IdmRequestItem) HashMap(java.util.HashMap) MessageFormat(java.text.MessageFormat) ConfidentialStorage(eu.bcvsolutions.idm.core.api.service.ConfidentialStorage) ReadDtoService(eu.bcvsolutions.idm.core.api.service.ReadDtoService) RequestFilterPredicate(eu.bcvsolutions.idm.core.api.domain.RequestFilterPredicate) ImmutableList(com.google.common.collect.ImmutableList) CollectionUtils(org.apache.commons.collections.CollectionUtils) Propagation(org.springframework.transaction.annotation.Propagation) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) EntityUtils(eu.bcvsolutions.idm.core.api.utils.EntityUtils) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Niceable(eu.bcvsolutions.idm.core.api.domain.Niceable) IdmRequestItemFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRequestItemFilter) EntityEvent(eu.bcvsolutions.idm.core.api.event.EntityEvent) Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) IdmRequestAttributeValueDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestAttributeValueDto) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IdmRequestItemChangesDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestItemChangesDto) MethodDescriptor(java.beans.MethodDescriptor) ApplicationContext(org.springframework.context.ApplicationContext) ConfigurationMap(eu.bcvsolutions.idm.core.api.domain.ConfigurationMap) IdmRequestItemAttributeDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestItemAttributeDto) Comparator(java.util.Comparator) IdmRequestFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRequestFilter) Transactional(org.springframework.transaction.annotation.Transactional) Assert(org.springframework.util.Assert) RoleRequestException(eu.bcvsolutions.idm.core.api.exception.RoleRequestException) Builder(eu.bcvsolutions.idm.core.api.dto.OperationResultDto.Builder) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Builder(eu.bcvsolutions.idm.core.api.dto.OperationResultDto.Builder) OperationResultDto(eu.bcvsolutions.idm.core.api.dto.OperationResultDto) IdmRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestDto) IOException(java.io.IOException) BaseFilter(eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) IOException(java.io.IOException) RoleRequestException(eu.bcvsolutions.idm.core.api.exception.RoleRequestException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) AcceptedException(eu.bcvsolutions.idm.core.api.exception.AcceptedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IdmRequestItemDto(eu.bcvsolutions.idm.core.api.dto.IdmRequestItemDto) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) Requestable(eu.bcvsolutions.idm.core.api.domain.Requestable) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Aggregations

ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)430 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)107 ApiOperation (io.swagger.annotations.ApiOperation)104 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)101 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)99 UUID (java.util.UUID)90 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)89 Test (org.junit.Test)70 Transactional (org.springframework.transaction.annotation.Transactional)54 SysSystemDto (eu.bcvsolutions.idm.acc.dto.SysSystemDto)53 IdmFormDefinitionDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto)53 IdmRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleDto)49 IOException (java.io.IOException)48 GuardedString (eu.bcvsolutions.idm.core.security.api.domain.GuardedString)47 ResponseEntity (org.springframework.http.ResponseEntity)43 AbstractIntegrationTest (eu.bcvsolutions.idm.test.api.AbstractIntegrationTest)38 ArrayList (java.util.ArrayList)33 HashMap (java.util.HashMap)31 IdmPasswordPolicyDto (eu.bcvsolutions.idm.core.api.dto.IdmPasswordPolicyDto)27 OperationResult (eu.bcvsolutions.idm.core.api.entity.OperationResult)26