Search in sources :

Example 1 with BaseEntityDto

use of org.meveo.api.dto.BaseEntityDto in project meveo by meveo-org.

the class EntityCustomActionService method addFilesToModule.

@Override
public void addFilesToModule(EntityCustomAction entity, MeveoModule module) throws BusinessException {
    BaseEntityDto businessEntityDto = businessEntitySerializer.serialize(entity);
    String businessEntityDtoSerialize = JacksonUtil.toString(businessEntityDto);
    File gitDirectory = GitHelper.getRepositoryDir(currentUser, module.getCode());
    String cetCode = CustomEntityTemplate.getCodeFromAppliesTo(entity.getAppliesTo());
    if (cetCode == null) {
        cetCode = CustomRelationshipTemplate.getCodeFromAppliesTo(entity.getAppliesTo());
    }
    String path = entity.getClass().getAnnotation(ModuleItem.class).path() + "/" + cetCode;
    File newDir = new File(gitDirectory, path);
    newDir.mkdirs();
    File newJsonFile = new File(newDir, entity.getCode() + ".json");
    try {
        MeveoFileUtils.writeAndPreserveCharset(businessEntityDtoSerialize, newJsonFile);
    } catch (IOException e) {
        throw new BusinessException("File cannot be updated or created", e);
    }
    GitRepository gitRepository = gitRepositoryService.findByCode(module.getCode());
    gitClient.commitFiles(gitRepository, Collections.singletonList(newDir), "Add JSON file for custom action " + cetCode + "." + entity.getCode());
}
Also used : ModuleItem(org.meveo.model.ModuleItem) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) GitRepository(org.meveo.model.git.GitRepository) BusinessException(org.meveo.admin.exception.BusinessException) IOException(java.io.IOException) File(java.io.File)

Example 2 with BaseEntityDto

use of org.meveo.api.dto.BaseEntityDto in project meveo by meveo-org.

the class BaseApi method convertDtoToEntityWithChildProcessing.

/**
 * Convert DTO object to an entity. In addition process child DTO object by creating or updating related entities via calls to API.createOrUpdate(). Note: Does not persist the
 * entity passed to the method.Takes about 1ms longer as compared to a regular hardcoded jpa.value=dto.value assignment
 *
 * @param entityToPopulate JPA Entity to populate with data from DTO object
 * @param dto DTO object
 * @param partialUpdate Is this a partial update - fields with null values will be ignored
 *
 * @throws MeveoApiException meveo api exception.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void convertDtoToEntityWithChildProcessing(Object entityToPopulate, Object dto, boolean partialUpdate) throws MeveoApiException {
    String dtoClassName = dto.getClass().getName();
    for (Field dtoField : FieldUtils.getAllFieldsList(dto.getClass())) {
        if (Modifier.isStatic(dtoField.getModifiers())) {
            continue;
        }
        // log.trace("AKK Populate field {}.{}", dtoClassName,
        // dtoField.getName());
        Object dtoValue = null;
        try {
            dtoValue = dtoField.get(dto);
            if (partialUpdate && dtoValue == null) {
                continue;
            }
            // Process custom fields as special case
            if (dtoField.getType().isAssignableFrom(CustomFieldsDto.class)) {
                populateCustomFields((CustomFieldsDto) dtoValue, (ICustomFieldEntity) entityToPopulate, true);
                continue;
            } else if (dtoField.getName().equals("active")) {
                if (dtoValue != null) {
                    FieldUtils.writeField(entityToPopulate, "disabled", !(boolean) dtoValue, true);
                }
                continue;
            }
            Field entityField = FieldUtils.getField(entityToPopulate.getClass(), dtoField.getName(), true);
            if (entityField == null) {
                log.warn("No match found for field {}.{} in entity {}", dtoClassName, dtoField.getName(), entityToPopulate.getClass().getName());
                continue;
            }
            // Null value - clear current field value
            if (dtoValue == null) {
                // clearing them instead of setting them null
                FieldUtils.writeField(entityToPopulate, dtoField.getName(), dtoValue, true);
            // Both DTO object and Entity fields are DTO or JPA type
            // fields and require a conversion
            } else if (ReflectionUtils.isDtoOrEntityType(dtoField.getType()) && ReflectionUtils.isDtoOrEntityType(entityField.getType())) {
                // String entityClassName =
                // dtoValue.getClass().getSimpleName().substring(0,
                // dtoValue.getClass().getSimpleName().lastIndexOf("Dto"));
                // Class entityClass =
                // ReflectionUtils.getClassBySimpleNameAndAnnotation(entityClassName,
                // Entity.class);
                // if (entityClass == null) {
                // entityClass =
                // ReflectionUtils.getClassBySimpleNameAndAnnotation(entityClassName,
                // Embeddable.class);
                // }
                // 
                // if (entityClass == null) {
                // log.debug("Don't know how to process a child DTO entity
                // {}. No JPA entity class matched. Will skip the field
                // {}.{}", dtoValue, dtoClassName,
                // dtoField.getName());
                // continue;
                // }
                Class entityClass = entityField.getType();
                // BaseDto class)
                if (dtoValue instanceof BaseEntityDto) {
                    // reference (e.g. Code) is passed
                    if (BusinessEntity.class.isAssignableFrom(entityClass)) {
                        BusinessEntity valueAsEntity = null;
                        String codeValue = (String) FieldUtils.readField(dtoValue, "code", true);
                        // Find an entity referenced
                        if (isEntityReferenceOnly(dtoValue)) {
                            // log.trace("A lookup for {} with code {} will
                            // be done as reference was passed",
                            // entityClass, codeValue);
                            PersistenceService persistenceService = getPersistenceService(entityClass, true);
                            valueAsEntity = ((BusinessService) persistenceService).findByCode(codeValue);
                            if (valueAsEntity == null) {
                                throw new EntityDoesNotExistsException(entityClass, codeValue);
                            }
                        // Create or update a full entity DTO passed
                        } else {
                            ApiService apiService = ApiUtils.getApiService((BaseEntityDto) dtoValue, true);
                            valueAsEntity = (BusinessEntity) apiService.createOrUpdate((BaseEntityDto) dtoValue);
                        }
                        // Update field with a new entity
                        FieldUtils.writeField(entityToPopulate, dtoField.getName(), valueAsEntity, true);
                    // For non-business entity just Create or update a
                    // full entity DTO passed
                    } else {
                        ApiService apiService = ApiUtils.getApiService((BaseEntityDto) dtoValue, true);
                        IEntity valueAsEntity = (BusinessEntity) apiService.createOrUpdate((BaseEntityDto) dtoValue);
                        // Update field with a new entity
                        FieldUtils.writeField(entityToPopulate, dtoField.getName(), valueAsEntity, true);
                    }
                // Process other embedded DTO entities
                } else {
                    // Use existing or create a new entity
                    Object embededEntity = FieldUtils.readField(entityToPopulate, dtoField.getName(), true);
                    if (embededEntity == null) {
                        embededEntity = entityClass.newInstance();
                    }
                    convertDtoToEntityWithChildProcessing(embededEntity, dtoValue, partialUpdate);
                    FieldUtils.writeField(entityToPopulate, dtoField.getName(), embededEntity, true);
                }
            // DTO field is a simple field (String) representing entity
            // identifier (code) and entity field is a JPA type field
            } else if (!ReflectionUtils.isDtoOrEntityType(dtoField.getType()) && ReflectionUtils.isDtoOrEntityType(entityField.getType())) {
                Class entityClass = entityField.getType();
                // Find an entity referenced
                PersistenceService persistenceService = getPersistenceService(entityClass, true);
                IEntity valueAsEntity = ((BusinessService) persistenceService).findByCode((String) dtoValue);
                if (valueAsEntity == null) {
                    throw new EntityDoesNotExistsException(entityClass, (String) dtoValue);
                }
                // Update field with a new entity
                FieldUtils.writeField(entityToPopulate, dtoField.getName(), valueAsEntity, true);
            // Regular type like String, Integer, etc..
            } else {
                FieldUtils.writeField(entityToPopulate, dtoField.getName(), dtoValue, true);
            }
        } catch (MeveoApiException e) {
            log.error("Failed to read/convert/populate field value {}.{}. Value {}. Processing will stop.", dtoClassName, dtoField.getName(), dtoValue, e);
            throw e;
        } catch (Exception e) {
            log.error("Failed to read/convert/populate field value {}.{}. Value {}", dtoClassName, dtoField.getName(), dtoValue, e);
            continue;
        }
    }
}
Also used : IEntity(org.meveo.model.IEntity) BusinessEntity(org.meveo.model.BusinessEntity) ELException(org.meveo.elresolver.ELException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) PatternSyntaxException(java.util.regex.PatternSyntaxException) BusinessApiException(org.meveo.api.exception.BusinessApiException) MeveoApiException(org.meveo.api.exception.MeveoApiException) MissingParameterException(org.meveo.api.exception.MissingParameterException) AccessDeniedException(java.nio.file.AccessDeniedException) InvalidParameterException(org.meveo.api.exception.InvalidParameterException) IOException(java.io.IOException) ConstraintViolationException(javax.validation.ConstraintViolationException) PersistenceService(org.meveo.service.base.PersistenceService) Field(java.lang.reflect.Field) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) BusinessService(org.meveo.service.base.BusinessService) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) MeveoApiException(org.meveo.api.exception.MeveoApiException)

Example 3 with BaseEntityDto

use of org.meveo.api.dto.BaseEntityDto in project meveo by meveo-org.

the class MeveoModuleApi method getEntityDto.

/**
 * @param moduleItems
 * @param item
 * @return
 * @throws MissingParameterException
 * @throws InvalidParameterException
 * @throws ClassNotFoundException
 * @throws MeveoApiException
 * @throws EntityDoesNotExistsException
 */
protected BaseEntityDto getEntityDto(Set<MeveoModuleItem> moduleItems, MeveoModuleItem item) throws MissingParameterException, InvalidParameterException, ClassNotFoundException, MeveoApiException, org.meveo.exceptions.EntityDoesNotExistsException {
    BaseEntityDto itemDto = null;
    if (item.getItemClass().equals(CustomFieldTemplate.class.getName())) {
        // we will only add a cft if it's not a field of a cet contained in the module
        if (!StringUtils.isBlank(item.getAppliesTo())) {
            String cetCode = EntityCustomizationUtils.getEntityCode(item.getAppliesTo());
            boolean isCetInModule = moduleItems.stream().filter(moduleItem -> moduleItem.getItemClass().equals(CustomEntityTemplate.class.getName())).anyMatch(moduleItem -> moduleItem.getItemCode().equals(cetCode));
            if (!isCetInModule) {
                itemDto = customFieldTemplateApi.findIgnoreNotFound(item.getItemCode(), item.getAppliesTo());
            }
        } else {
            itemDto = customFieldTemplateApi.findIgnoreNotFound(item.getItemCode(), item.getAppliesTo());
        }
    } else if (item.getItemClass().equals(EntityCustomAction.class.getName())) {
        EntityCustomActionDto entityCustomActionDto = entityCustomActionApi.findIgnoreNotFound(item.getItemCode(), item.getAppliesTo());
        itemDto = entityCustomActionDto;
    } else if (item.getItemClass().equals(CustomEntityInstance.class.getName()) && item.getAppliesTo() != null) {
        try {
            CustomEntityTemplate customEntityTemplate = customEntityTemplateService.findByCode(item.getAppliesTo());
            Map<String, Object> ceiTable;
            try {
                ceiTable = crossStorageService.find(// XXX: Maybe we will need to parameterize this or search in all repositories ?
                repositoryService.findDefaultRepository(), customEntityTemplate, item.getItemCode(), // XXX: Maybe it should also be a parameter
                false);
            } catch (EntityDoesNotExistsException e) {
                ceiTable = null;
            }
            // Map<String, Object> ceiTable = customTableService.findById(SqlConfiguration.DEFAULT_SQL_CONNECTION, item.getAppliesTo(), item.getItemCode());
            CustomEntityInstance customEntityInstance = new CustomEntityInstance();
            customEntityInstance.setUuid((String) ceiTable.get("uuid"));
            customEntityInstance.setCode((String) ceiTable.get("uuid"));
            customEntityInstance.setCetCode(item.getAppliesTo());
            customEntityInstance.setCet(customEntityTemplateService.findByCode(item.getAppliesTo()));
            customFieldInstanceService.setCfValues(customEntityInstance, item.getAppliesTo(), ceiTable);
            itemDto = CustomEntityInstanceDto.toDTO(customEntityInstance, entityToDtoConverter.getCustomFieldsDTO(customEntityInstance, true));
        } catch (BusinessException e) {
            log.error(e.getMessage());
        }
    } else {
        Class clazz = Class.forName(item.getItemClass());
        if (clazz.isAnnotationPresent(VersionedEntity.class)) {
            ApiVersionedService apiService = ApiUtils.getApiVersionedService(item.getItemClass(), true);
            itemDto = apiService.findIgnoreNotFound(item.getItemCode(), item.getValidity() != null ? item.getValidity().getFrom() : null, item.getValidity() != null ? item.getValidity().getTo() : null);
        } else {
            ApiService apiService = ApiUtils.getApiService(clazz, true);
            itemDto = apiService.findIgnoreNotFound(item.getItemCode());
        }
    }
    return itemDto;
}
Also used : CustomRelationshipTemplateService(org.meveo.service.custom.CustomRelationshipTemplateService) Arrays(java.util.Arrays) Reflections(org.reflections.Reflections) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) RepositoryService(org.meveo.service.storage.RepositoryService) StringUtils(org.meveo.commons.utils.StringUtils) MeveoModuleService(org.meveo.service.admin.impl.MeveoModuleService) ScriptInstanceService(org.meveo.service.script.ScriptInstanceService) CustomFieldTemplateDto(org.meveo.api.dto.CustomFieldTemplateDto) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) ScriptInstance(org.meveo.model.scripts.ScriptInstance) TransactionAttributeType(javax.ejb.TransactionAttributeType) Map(java.util.Map) CustomEntityInstanceApi(org.meveo.api.CustomEntityInstanceApi) ValidationException(org.meveo.admin.exception.ValidationException) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) InvocationTargetException(java.lang.reflect.InvocationTargetException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) MeveoApiException(org.meveo.api.exception.MeveoApiException) GitRepository(org.meveo.model.git.GitRepository) MeveoModuleDependency(org.meveo.model.module.MeveoModuleDependency) ScriptInstanceApi(org.meveo.api.ScriptInstanceApi) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration) ZipOutputStream(java.util.zip.ZipOutputStream) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MeveoModuleItem(org.meveo.model.module.MeveoModuleItem) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) VersionedEntity(org.meveo.model.VersionedEntity) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) JacksonUtil(org.meveo.model.persistence.JacksonUtil) CommitEvent(org.meveo.event.qualifier.git.CommitEvent) MeveoModuleItemDto(org.meveo.api.dto.module.MeveoModuleItemDto) InvalidParameterException(org.meveo.api.exception.InvalidParameterException) EJB(javax.ejb.EJB) FileUtils.addToZipFile(org.meveo.commons.utils.FileUtils.addToZipFile) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) ModuleDependencyDto(org.meveo.api.dto.module.ModuleDependencyDto) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) ExportFormat(org.meveo.api.export.ExportFormat) CRC32(java.util.zip.CRC32) ModuleUtil(org.meveo.admin.util.ModuleUtil) SqlConfigurationService(org.meveo.persistence.sql.SqlConfigurationService) MeveoModuleUtils(org.meveo.service.admin.impl.MeveoModuleUtils) LoggerFactory(org.slf4j.LoggerFactory) ApiVersionedService(org.meveo.api.ApiVersionedService) FilesApi(org.meveo.api.admin.FilesApi) GenericTypeReferences(org.meveo.model.typereferences.GenericTypeReferences) Repository(org.meveo.model.storage.Repository) MeveoModuleDto(org.meveo.api.dto.module.MeveoModuleDto) CommitReceived(org.meveo.event.qualifier.git.CommitReceived) Observes(javax.enterprise.event.Observes) MeveoModuleFilters(org.meveo.service.admin.impl.MeveoModuleFilters) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Stateless(javax.ejb.Stateless) FileUtils(org.meveo.commons.utils.FileUtils) ModuleItem(org.meveo.model.ModuleItem) ApiUtils(org.meveo.api.ApiUtils) BusinessApiException(org.meveo.api.exception.BusinessApiException) MeveoModule(org.meveo.model.module.MeveoModule) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) ModuleReleaseDto(org.meveo.api.dto.module.ModuleReleaseDto) Collectors(java.util.stream.Collectors) BaseCrudApi(org.meveo.api.BaseCrudApi) FileNotFoundException(java.io.FileNotFoundException) EJBTransactionRolledbackException(javax.ejb.EJBTransactionRolledbackException) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityInstanceDto(org.meveo.api.dto.CustomEntityInstanceDto) List(java.util.List) EntityCustomizationUtils(org.meveo.util.EntityCustomizationUtils) ModuleRelease(org.meveo.model.module.ModuleRelease) ModuleUninstall(org.meveo.service.admin.impl.ModuleUninstall) MissingParameterException(org.meveo.api.exception.MissingParameterException) FilenameUtils(org.apache.commons.io.FilenameUtils) EntityCustomAction(org.meveo.model.crm.custom.EntityCustomAction) ApiService(org.meveo.api.ApiService) CrossStorageService(org.meveo.persistence.CrossStorageService) CustomEntityTemplateService(org.meveo.service.custom.CustomEntityTemplateService) FileUtils.addDirectoryToZip(org.meveo.commons.utils.FileUtils.addDirectoryToZip) ActionForbiddenException(org.meveo.api.exception.ActionForbiddenException) HashMap(java.util.HashMap) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) BusinessEntityException(org.meveo.admin.exception.BusinessEntityException) EntityCustomActionDto(org.meveo.api.dto.EntityCustomActionDto) HashSet(java.util.HashSet) Inject(javax.inject.Inject) CustomFieldTemplateApi(org.meveo.api.CustomFieldTemplateApi) CollectionUtils(org.apache.commons.collections.CollectionUtils) TransactionAttribute(javax.ejb.TransactionAttribute) CustomModelObject(org.meveo.model.customEntities.CustomModelObject) EntityAlreadyExistsException(org.meveo.api.exception.EntityAlreadyExistsException) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) PersistenceService(org.meveo.service.base.PersistenceService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) ModuleInstallFail(org.meveo.api.exceptions.ModuleInstallFail) GitHelper(org.meveo.service.git.GitHelper) ModuleReleaseItem(org.meveo.model.module.ModuleReleaseItem) IPersistenceService(org.meveo.service.base.local.IPersistenceService) EntityCustomActionApi(org.meveo.api.EntityCustomActionApi) CheckedOutputStream(java.util.zip.CheckedOutputStream) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) DiffEntry(org.eclipse.jgit.diff.DiffEntry) InputStream(java.io.InputStream) ApiVersionedService(org.meveo.api.ApiVersionedService) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) BusinessException(org.meveo.admin.exception.BusinessException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) ApiService(org.meveo.api.ApiService) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) EntityCustomActionDto(org.meveo.api.dto.EntityCustomActionDto) CustomModelObject(org.meveo.model.customEntities.CustomModelObject) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance)

Example 4 with BaseEntityDto

use of org.meveo.api.dto.BaseEntityDto in project meveo by meveo-org.

the class MeveoModuleItemInstaller method unpackAndInstallModuleItem.

@SuppressWarnings({ "unchecked" })
@Transactional(TxType.MANDATORY)
public ModuleInstallResult unpackAndInstallModuleItem(MeveoModule meveoModule, MeveoModuleItemDto moduleItemDto, OnDuplicate onDuplicate) throws IllegalArgumentException, MeveoApiException, Exception, BusinessException {
    ModuleInstallResult result = new ModuleInstallResult();
    Class<? extends BaseEntityDto> dtoClass;
    boolean skipped = false;
    MeveoModuleItem moduleItem;
    try {
        dtoClass = (Class<? extends BaseEntityDto>) Class.forName(moduleItemDto.getDtoClassName());
        BaseEntityDto dto = JacksonUtil.convert(moduleItemDto.getDtoData(), dtoClass);
        CustomEntityTemplate customEntityTemplate = null;
        if (dto instanceof CustomEntityInstanceDto) {
            customEntityTemplate = customEntityTemplateService.findByCode(((CustomEntityInstanceDto) dto).getCetCode());
            if (((CustomEntityInstanceDto) dto).getCustomFields() == null) {
                // Comes as pojo, must populate the dto fields
                CustomEntityInstance cei = CEIUtils.pojoToCei(moduleItemDto.getDtoData());
                cei.setCet(customEntityTemplate);
                cei.setCetCode(customEntityTemplate.getCode());
                CustomFieldsDto customFields = entityDtoConverter.getCustomFieldsDTO(cei, true, true);
                ((CustomEntityInstanceDto) dto).setCustomFields(customFields);
            }
        }
        try {
            if (dto instanceof MeveoModuleDto) {
                MeveoModule subModule = meveoModuleService.findByCodeWithFetchEntities(((MeveoModuleDto) dto).getCode());
                result = install(subModule, (MeveoModuleDto) dto, onDuplicate);
                Class<? extends MeveoModule> moduleClazz = MeveoModule.class;
                moduleItem = new MeveoModuleItem(((MeveoModuleDto) dto).getCode(), moduleClazz.getName(), null, null);
                meveoModuleService.addModuleItem(moduleItem, meveoModule);
            } else if (dto instanceof CustomEntityInstanceDto && customEntityTemplate != null && (customEntityTemplate.isStoreAsTable() || customEntityTemplate.storedIn(DBStorageType.NEO4J))) {
                CustomEntityInstance cei = new CustomEntityInstance();
                cei.setUuid(((CustomEntityInstanceDto) dto).getUuid());
                // Use code as a fallback for UUID
                if (cei.getUuid() == null) {
                    cei.setCode(dto.getCode());
                    cei.setUuid(dto.getCode());
                }
                cei.setCetCode(customEntityTemplate.getCode());
                cei.setCet(customEntityTemplate);
                try {
                    meveoModuleApi.populateCustomFields(((CustomEntityInstanceDto) dto).getCustomFields(), cei, true);
                } catch (Exception e) {
                    log.error("Failed to associate custom field instance to an entity: {}", e.getMessage());
                    throw e;
                }
                for (Repository repo : meveoModule.getRepositories()) {
                    crossStorageService.createOrUpdate(repo, cei);
                }
                moduleItem = new MeveoModuleItem(cei.getUuid(), CustomEntityInstance.class.getName(), cei.getCetCode(), null);
                moduleItem.setItemEntity(cei);
                meveoModuleService.addModuleItem(moduleItem, meveoModule);
            } else if (dto instanceof CustomFieldTemplateDto) {
                CustomFieldTemplateDto cftDto = (CustomFieldTemplateDto) dto;
                if (cftDto.getAppliesTo() == null) {
                    return result;
                }
                CustomFieldTemplateDto cft = customFieldTemplateApi.findIgnoreNotFound(cftDto.getCode(), cftDto.getAppliesTo());
                if (cft != null) {
                    switch(onDuplicate) {
                        case OVERWRITE:
                            result.incrNbOverwritten();
                            break;
                        case SKIP:
                            result.setNbSkipped(1);
                            skipped = true;
                            break;
                        case FAIL:
                            throw new EntityAlreadyExistsException(CustomFieldTemplate.class, cft.getAppliesTo() + "." + cft.getCode());
                        default:
                            break;
                    }
                } else {
                    result.incrNbAdded();
                }
                if (!skipped) {
                    customFieldTemplateApi.createOrUpdate((CustomFieldTemplateDto) dto, null);
                    result.addItem(moduleItemDto);
                }
                moduleItem = new MeveoModuleItem(((CustomFieldTemplateDto) dto).getCode(), CustomFieldTemplate.class.getName(), ((CustomFieldTemplateDto) dto).getAppliesTo(), null);
                meveoModuleService.addModuleItem(moduleItem, meveoModule);
            } else if (dto instanceof EntityCustomActionDto) {
                EntityCustomActionDto ecaDto = (EntityCustomActionDto) dto;
                EntityCustomActionDto eca = entityCustomActionApi.findIgnoreNotFound(ecaDto.getCode(), ecaDto.getAppliesTo());
                if (eca != null) {
                    switch(onDuplicate) {
                        case OVERWRITE:
                            result.incrNbOverwritten();
                            break;
                        case SKIP:
                            result.setNbSkipped(1);
                            skipped = true;
                            break;
                        case FAIL:
                            throw new EntityAlreadyExistsException(EntityCustomAction.class, eca.getCode());
                        default:
                            break;
                    }
                } else {
                    result.incrNbAdded();
                }
                if (!skipped) {
                    result.addItem(moduleItemDto);
                    entityCustomActionApi.createOrUpdate((EntityCustomActionDto) dto, null);
                }
                moduleItem = new MeveoModuleItem(((EntityCustomActionDto) dto).getCode(), EntityCustomAction.class.getName(), ((EntityCustomActionDto) dto).getAppliesTo(), null);
                meveoModuleService.addModuleItem(moduleItem, meveoModule);
            } else {
                String moduleItemName = dto.getClass().getSimpleName().substring(0, dto.getClass().getSimpleName().lastIndexOf("Dto"));
                if (checkCetDoesNotExists(moduleItemName, customEntityTemplate)) {
                    Class<?> entityClass = MODULE_ITEM_TYPES.get(moduleItemName);
                    if (entityClass == null) {
                        throw new IllegalArgumentException(moduleItemName + " is not a module item");
                    }
                    log.info("Installing item {} of module with code={}", dto, meveoModule.getCode());
                    Object item = findItem(dto, entityClass);
                    if (item != null) {
                        switch(onDuplicate) {
                            case OVERWRITE:
                                result.incrNbOverwritten();
                                break;
                            case SKIP:
                                result.setNbSkipped(1);
                                skipped = true;
                                break;
                            case FAIL:
                                {
                                    throw new EntityAlreadyExistsException(String.valueOf(item));
                                }
                            default:
                                break;
                        }
                    } else {
                        result.incrNbAdded();
                    }
                    if (!skipped) {
                        createOrUpdateItem(dto, entityClass);
                        result.addItem(moduleItemDto);
                    }
                    DatePeriod validity = null;
                    if (ReflectionUtils.hasField(dto, "validFrom")) {
                        validity = new DatePeriod((Date) FieldUtils.readField(dto, "validFrom", true), (Date) FieldUtils.readField(dto, "validTo", true));
                    }
                    if (ReflectionUtils.hasField(dto, "appliesTo")) {
                        moduleItem = new MeveoModuleItem((String) FieldUtils.readField(dto, "code", true), entityClass.getName(), (String) FieldUtils.readField(dto, "appliesTo", true), validity);
                    } else {
                        moduleItem = new MeveoModuleItem((String) FieldUtils.readField(dto, "code", true), entityClass.getName(), null, validity);
                    }
                    // add cft of cet
                    if (dto instanceof CustomEntityTemplateDto) {
                        // check and add if cft exists to moduleItem
                        addCftToModuleItem((CustomEntityTemplateDto) dto, meveoModule);
                    } else if (dto instanceof CustomRelationshipTemplateDto) {
                        // check and add if cft exists to moduleItem
                        addCftToModuleItem((CustomRelationshipTemplateDto) dto, meveoModule);
                    }
                    meveoModuleService.addModuleItem(moduleItem, meveoModule);
                    if (skipped) {
                        meveoModuleService.loadModuleItem(moduleItem);
                        BaseCrudApi api = (BaseCrudApi) ApiUtils.getApiService(entityClass, true);
                        api.getPersistenceService().enable(moduleItem.getItemEntity());
                    }
                }
            }
            log.info("Item {} installed", dto);
        } catch (IllegalAccessException e) {
            log.error("Failed to access field value in DTO {}", dto, e);
            throw new MeveoApiException("Failed to access field value in DTO: " + e.getMessage());
        } catch (MeveoApiException | BusinessException e) {
            log.error("Failed to transform DTO into a module item. DTO {}", dto, e);
            throw e;
        }
    } catch (ClassNotFoundException e1) {
        throw new BusinessException(e1);
    } catch (Exception e) {
        throw e;
    }
    return result;
}
Also used : MeveoModuleDto(org.meveo.api.dto.module.MeveoModuleDto) EntityAlreadyExistsException(org.meveo.api.exception.EntityAlreadyExistsException) CustomFieldTemplateDto(org.meveo.api.dto.CustomFieldTemplateDto) BaseCrudApi(org.meveo.api.BaseCrudApi) CustomRelationshipTemplateDto(org.meveo.api.dto.CustomRelationshipTemplateDto) BaseEntityDto(org.meveo.api.dto.BaseEntityDto) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) EntityCustomActionDto(org.meveo.api.dto.EntityCustomActionDto) MeveoModule(org.meveo.model.module.MeveoModule) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) CustomEntityInstanceDto(org.meveo.api.dto.CustomEntityInstanceDto) CustomEntityTemplateDto(org.meveo.api.dto.CustomEntityTemplateDto) CustomFieldsDto(org.meveo.api.dto.CustomFieldsDto) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) BusinessApiException(org.meveo.api.exception.BusinessApiException) EJBTransactionRolledbackException(javax.ejb.EJBTransactionRolledbackException) BusinessException(org.meveo.admin.exception.BusinessException) EJBException(javax.ejb.EJBException) MeveoApiException(org.meveo.api.exception.MeveoApiException) ActionForbiddenException(org.meveo.api.exception.ActionForbiddenException) SQLException(java.sql.SQLException) EntityAlreadyExistsException(org.meveo.api.exception.EntityAlreadyExistsException) IOException(java.io.IOException) Repository(org.meveo.model.storage.Repository) MeveoModuleItem(org.meveo.model.module.MeveoModuleItem) DatePeriod(org.meveo.model.DatePeriod) EntityCustomAction(org.meveo.model.crm.custom.EntityCustomAction) MeveoApiException(org.meveo.api.exception.MeveoApiException) Transactional(javax.transaction.Transactional)

Example 5 with BaseEntityDto

use of org.meveo.api.dto.BaseEntityDto in project meveo by meveo-org.

the class BusinessService method addFilesToModule.

public void addFilesToModule(P entity, MeveoModule module) throws BusinessException {
    BaseEntityDto businessEntityDto = getDto(entity);
    String businessEntityDtoSerialize = JacksonUtil.toStringPrettyPrinted(businessEntityDto);
    File gitDirectory = GitHelper.getRepositoryDir(currentUser, module.getCode());
    // + entity.getCode();
    String path = entity.getClass().getAnnotation(ModuleItem.class).path() + "/";
    File newDir = new File(gitDirectory, path);
    newDir.mkdirs();
    File newJsonFile = new File(gitDirectory, path + "/" + entity.getCode() + ".json");
    try {
        MeveoFileUtils.writeAndPreserveCharset(businessEntityDtoSerialize, newJsonFile);
    } catch (IOException e) {
        throw new BusinessException("File cannot be updated or created", e);
    }
    GitRepository gitRepository = gitRepositoryService.findByCode(module.getCode());
    gitClient.commitFiles(gitRepository, Collections.singletonList(newDir), "Add JSON file for entity " + entity.getCode());
}
Also used : BaseEntityDto(org.meveo.api.dto.BaseEntityDto) GitRepository(org.meveo.model.git.GitRepository) BusinessException(org.meveo.admin.exception.BusinessException) IOException(java.io.IOException) File(java.io.File)

Aggregations

BaseEntityDto (org.meveo.api.dto.BaseEntityDto)13 IOException (java.io.IOException)10 BusinessException (org.meveo.admin.exception.BusinessException)8 MeveoApiException (org.meveo.api.exception.MeveoApiException)7 MeveoModuleItem (org.meveo.model.module.MeveoModuleItem)6 MeveoModuleDto (org.meveo.api.dto.module.MeveoModuleDto)5 MeveoModuleItemDto (org.meveo.api.dto.module.MeveoModuleItemDto)5 BusinessApiException (org.meveo.api.exception.BusinessApiException)5 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)5 File (java.io.File)4 EJBTransactionRolledbackException (javax.ejb.EJBTransactionRolledbackException)4 CustomFieldTemplateDto (org.meveo.api.dto.CustomFieldTemplateDto)4 ActionForbiddenException (org.meveo.api.exception.ActionForbiddenException)4 EntityAlreadyExistsException (org.meveo.api.exception.EntityAlreadyExistsException)4 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)4 GitRepository (org.meveo.model.git.GitRepository)4 ArrayList (java.util.ArrayList)3 CustomEntityTemplateDto (org.meveo.api.dto.CustomEntityTemplateDto)3 EntityCustomActionDto (org.meveo.api.dto.EntityCustomActionDto)3 InvalidParameterException (org.meveo.api.exception.InvalidParameterException)3