Search in sources :

Example 26 with ResultCodeException

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

the class IdentityAnonymousUsernameGenerator method generate.

@Override
public IdmIdentityDto generate(IdmIdentityDto dto, IdmGenerateValueDto valueGenerator) {
    Assert.notNull(dto, "DTO is required.");
    Assert.notNull(valueGenerator, "Value generator is required.");
    // if exists username and configuration doesn't allow regenerate return dto
    if (!valueGenerator.isRegenerateValue() && StringUtils.isNotEmpty(dto.getUsername())) {
        return dto;
    }
    // generator configuration
    int numPartLen = getNumberPartLength(valueGenerator);
    int numPartMax = calcMaxValueForLen(numPartLen);
    String prefix = getPrefixString(valueGenerator);
    // try to generate the new unique username within several attempts
    int attepts = GENERATE_ATTEMPTS;
    do {
        int randomPartVal = generateNumberPart(numPartMax);
        String username = createUsername(prefix, randomPartVal, numPartLen);
        // find at the first attempt OK
        if (!usernameInUse(username)) {
            dto.setUsername(username);
            return dto;
        }
    } while (--attepts != 0);
    // unsuccessful with random generation -> search for empty number slots
    String usernameRoot = createUsername(prefix, null, null);
    IdmIdentityFilter identityFilt = new IdmIdentityFilter();
    identityFilt.setText(usernameRoot);
    Page<IdmIdentityDto> page = null;
    int pageSize = SEARCH_PAGE_SIZE;
    int pageNum = 0;
    do {
        page = identityService.find(identityFilt, PageRequest.of(pageNum, pageSize, Sort.by(IdmIdentity_.username.getName()).ascending()));
        List<IdmIdentityDto> dtos = page.getContent();
        List<String> usernameNumbers = dtos.stream().map(IdmIdentityDto::getUsername).filter(usernameFilterFactory(usernameRoot, numPartLen)).map(name -> name.replace(usernameRoot, "")).collect(Collectors.toList());
        Integer newRandomPartVal = findEmptySlotFromRange(usernameNumbers, 0, usernameNumbers.size() - 1);
        if (newRandomPartVal != null) {
            String username = createUsername(prefix, newRandomPartVal, Integer.valueOf(numPartLen));
            dto.setUsername(username);
            return dto;
        }
        pageNum++;
    } while (pageNum < page.getTotalPages());
    // unable to find empty space by bisect? try min and max values which may still be missing
    // first index
    String username = createUsername(prefix, 0, numPartLen);
    if (!usernameInUse(username)) {
        dto.setUsername(username);
        return dto;
    }
    // last index
    username = createUsername(prefix, numPartMax, numPartLen);
    if (!usernameInUse(username)) {
        dto.setUsername(username);
        return dto;
    }
    // it's over nothing remains to try
    LOG.warn("The anonymous username generator reached the limit of the count of available numbers. Increase nuemric part length in the generator setting.");
    throw new ResultCodeException(CoreResultCode.IDENTITY_UNABLE_GENERATE_UNIQUE_USERNAME);
}
Also used : IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) Random(java.util.Random) StringUtils(org.apache.commons.lang3.StringUtils) PersistentType(eu.bcvsolutions.idm.core.eav.api.domain.PersistentType) BigDecimal(java.math.BigDecimal) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Math(java.lang.Math) Sort(org.springframework.data.domain.Sort) AbstractValueGenerator(eu.bcvsolutions.idm.core.api.generator.AbstractValueGenerator) Description(org.springframework.context.annotation.Description) Predicate(java.util.function.Predicate) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) PageRequest(org.springframework.data.domain.PageRequest) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) List(java.util.List) Component(org.springframework.stereotype.Component) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) IdmIdentity_(eu.bcvsolutions.idm.core.model.entity.IdmIdentity_) Pattern(java.util.regex.Pattern) IdmIdentityService(eu.bcvsolutions.idm.core.api.service.IdmIdentityService) IdmGenerateValueDto(eu.bcvsolutions.idm.core.api.dto.IdmGenerateValueDto) Assert(org.springframework.util.Assert) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Example 27 with ResultCodeException

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

the class CodeListSaveProcessor method process.

@Override
public EventResult<IdmCodeListDto> process(EntityEvent<IdmCodeListDto> event) {
    IdmCodeListDto codeList = event.getContent();
    // 
    // prevent to change underlying form definition
    IdmCodeListDto originalSource = event.getOriginalSource();
    if (originalSource == null) {
        if (codeList.getFormDefinition() != null) {
            throw new ResultCodeException(CoreResultCode.UNMODIFIABLE_ATTRIBUTE_CHANGE, ImmutableMap.of("name", "formDefinition", "class", codeList.getClass().getSimpleName()));
        }
    } else {
        if (!codeList.getFormDefinition().equals(originalSource.getFormDefinition())) {
            throw new ResultCodeException(CoreResultCode.UNMODIFIABLE_ATTRIBUTE_CHANGE, ImmutableMap.of("name", "formDefinition", "class", codeList.getClass().getSimpleName()));
        }
    }
    codeList = service.saveInternal(codeList);
    event.setContent(codeList);
    // 
    return new DefaultEventResult<>(event, this);
}
Also used : IdmCodeListDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmCodeListDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) DefaultEventResult(eu.bcvsolutions.idm.core.api.event.DefaultEventResult)

Example 28 with ResultCodeException

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

the class DefaultImportManager method makeAdvancedPairing.

/**
 * Make advanced paring
 *
 * @param dto
 * @param context
 * @param dtoClass
 * @return
 */
private BaseDto makeAdvancedPairing(BaseDto dto, ImportContext context, Class<? extends BaseDto> dtoClass) {
    ExportDescriptorDto descriptor = this.getDescriptor(context, dtoClass);
    for (String advancedParingField : descriptor.getAdvancedParingFields()) {
        try {
            Class<? extends AbstractDto> dtoClassField = this.getDtoClassFromField(dtoClass, advancedParingField);
            if (dtoClassField == null) {
                throw new ResultCodeException(CoreResultCode.IMPORT_FIELD_EMBEDDED_ANNOTATION_MISSING, ImmutableMap.of("field", advancedParingField));
            }
            UUID id = this.getFieldUUIDValue(advancedParingField, dto, dtoClass);
            if (id == null) {
                // ID is null -> no relation exists -> continues
                continue;
            }
            // Get service for DTO in field.
            Class<? extends BaseDto> serviceDtoClass = dtoClassField;
            if (dtoClassField.isAnnotationPresent(Inheritable.class)) {
                serviceDtoClass = dto.getClass().getAnnotation(Inheritable.class).dtoService();
            }
            ReadWriteDtoService<BaseDto, ?> dtoServiceForField = getDtoService(serviceDtoClass);
            BaseDto currentFieldDto = dtoServiceForField.get(id);
            if (currentFieldDto != null) {
                // DTO exists -> no change is necessary.
                continue;
            }
            // DTO not found by ID, we will try find it by code.
            if (dto instanceof AbstractDto) {
                Path dtoPath = Paths.get(context.getTempDirectory().toString(), dtoClass.getSimpleName(), MessageFormat.format("{0}.{1}", dto.getId().toString(), ExportManager.EXTENSION_JSON));
                EmbeddedDto embeddedDto = (EmbeddedDto) this.convertFileToDto(dtoPath.toFile(), EmbeddedDto.class, context);
                JsonNode batchFieldDtoAsString = embeddedDto.getEmbedded().get(advancedParingField);
                if (batchFieldDtoAsString == null) {
                    if (descriptor.isOptional()) {
                        return null;
                    } else {
                        Assert.notNull(batchFieldDtoAsString, MessageFormat.format("Embedded map must contains DTO for advanced paring field [{0}]", advancedParingField));
                    }
                }
                BaseDto batchFieldDto;
                try {
                    batchFieldDto = this.convertStringToDto(batchFieldDtoAsString.toString(), dtoClassField, context);
                    String code = null;
                    if (batchFieldDto instanceof Codeable) {
                        code = ((Codeable) batchFieldDto).getCode();
                        if (Strings.isNotEmpty(code)) {
                            currentFieldDto = lookupService.lookupDto(serviceDtoClass, code);
                        }
                    } else if (batchFieldDto != null) {
                        // Find target DTO by example source DTO (typically by more then one filter field).
                        code = batchFieldDto.toString();
                        EmbeddedDto fieldEmbeddedDto = (EmbeddedDto) this.convertStringToDto(batchFieldDtoAsString.toString(), EmbeddedDto.class, context);
                        currentFieldDto = this.findByExample(batchFieldDto, fieldEmbeddedDto, context);
                    }
                    if (currentFieldDto != null) {
                        // DTO for given code exists -> replace ID by this new in given DTO.
                        // 
                        new PropertyDescriptor(advancedParingField, dtoClass).getWriteMethod().invoke(dto, currentFieldDto.getId());
                        // Save old and new ID for next DTOs.
                        context.getReplacedIDs().put(id, (UUID) currentFieldDto.getId());
                        continue;
                    } else {
                        // If is DTO set as optional, we will only skip this DTO.
                        if (descriptor.isOptional()) {
                            throw new ResultCodeException(CoreResultCode.IMPORT_ADVANCED_PARING_NOT_FOUND_OPTIONAL, ImmutableMap.of("field", advancedParingField, "dto", dto.toString(), "notFoundDto", batchFieldDto.toString(), "code", code));
                        }
                        throw new ResultCodeException(CoreResultCode.IMPORT_ADVANCED_PARING_FAILED_NOT_FOUND, ImmutableMap.of("field", advancedParingField, "dto", dto.toString(), "notFoundDto", batchFieldDto.toString(), "code", code));
                    }
                } catch (IOException e) {
                    throw new ResultCodeException(CoreResultCode.IMPORT_CONVERT_TO_DTO_FAILED, ImmutableMap.of("file", "Converted from String.", "dto", dtoClass), e);
                }
            }
            // (skip this DTO).
            if (descriptor.isOptional()) {
                return null;
            }
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
            throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_REFLECTION_FAILED, e);
        }
    }
    return dto;
}
Also used : Path(java.nio.file.Path) Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) PropertyDescriptor(java.beans.PropertyDescriptor) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IntrospectionException(java.beans.IntrospectionException) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExportDescriptorDto(eu.bcvsolutions.idm.core.api.dto.ExportDescriptorDto) EmbeddedDto(eu.bcvsolutions.idm.core.api.dto.EmbeddedDto) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) UUID(java.util.UUID)

Example 29 with ResultCodeException

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

the class DefaultImportManager method extractZip.

/**
 * Extract ZIP in attachment to the temp directory.
 *
 * @param attachment
 * @return
 */
private Path extractZip(IdmAttachmentDto attachment) {
    File source = Paths.get(attachmentConfiguration.getStoragePath(), attachment.getContentPath()).toFile();
    Path tempDirectory = attachmentManager.createTempDirectory(null);
    try {
        ZipUtils.extract(source, tempDirectory.toString());
    } catch (IOException ex) {
        throw new ResultCodeException(CoreResultCode.IMPORT_ZIP_EXTRACTION_FAILED, ex);
    }
    return tempDirectory;
}
Also used : Path(java.nio.file.Path) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IOException(java.io.IOException) File(java.io.File)

Example 30 with ResultCodeException

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

the class DefaultImportManager method executeImport.

@Override
@Transactional
public IdmExportImportDto executeImport(IdmExportImportDto importBatch, boolean dryRun, BasePermission... permission) {
    Assert.notNull(importBatch, "Batch cannot be null!");
    Assert.notNull(importBatch.getId(), "Id of batch cannot be null!");
    LOG.info("Import [{}, dry-run: {}] starts ...", importBatch.toString(), dryRun);
    // Check permissions (if given) before LRT is executed (dry run updates batch too => permissions have to be evaluated).
    exportImportService.checkAccess(importBatch, permission);
    OperationResult operationResult = importBatch.getResult();
    if (operationResult != null && OperationState.RUNNING == operationResult.getState()) {
        throw new ResultCodeException(CoreResultCode.IMPORT_IS_ALREADY_RUNNING, ImmutableMap.of("batch", importBatch.toString()));
    }
    ImportTaskExecutor lrt = new ImportTaskExecutor(importBatch.getId(), dryRun);
    LongRunningFutureTask<OperationResult> result = longRunningTaskManager.execute(lrt);
    UUID taskId = result.getExecutor().getLongRunningTaskId();
    importBatch.setLongRunningTask(taskId);
    return exportImportService.save(importBatch, permission);
}
Also used : ImportTaskExecutor(eu.bcvsolutions.idm.core.scheduler.task.impl.ImportTaskExecutor) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) UUID(java.util.UUID) Transactional(org.springframework.transaction.annotation.Transactional)

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