Search in sources :

Example 1 with BusinessEntity

use of org.meveo.model.BusinessEntity in project meveo by meveo-org.

the class BaseBean method addToModule.

protected void addToModule(T entity, MeveoModule module) throws BusinessException {
    BusinessEntity businessEntity = (BusinessEntity) entity;
    MeveoModuleItem item = new MeveoModuleItem(businessEntity);
    if (!module.getModuleItems().contains(item)) {
        try {
            meveoModuleService.addModuleItem(item, module);
        } catch (BusinessException e2) {
            throw new BusinessException("Entity cannot be add or remove from the module", e2);
        }
        try {
            if (!org.meveo.commons.utils.StringUtils.isBlank(module.getModuleSource())) {
                module.setModuleSource(JacksonUtil.toString(updateModuleItemDto(module)));
            }
            meveoModuleService.update(module);
            messages.info(businessEntity.getCode() + " added to module " + module.getCode());
        } catch (Exception e) {
            messages.error(businessEntity.getCode() + " not added to module " + module.getCode(), e);
        }
    } else {
        messages.error(new BundleKey("messages", "meveoModule.error.moduleItemExisted"), businessEntity.getCode(), module.getCode());
        return;
    }
}
Also used : BusinessException(org.meveo.admin.exception.BusinessException) MeveoModuleItem(org.meveo.model.module.MeveoModuleItem) BusinessEntity(org.meveo.model.BusinessEntity) BundleKey(org.jboss.seam.international.status.builder.BundleKey) ELException(org.meveo.elresolver.ELException) BusinessException(org.meveo.admin.exception.BusinessException) MeveoApiException(org.meveo.api.exception.MeveoApiException) ConstraintViolationException(org.meveo.admin.exception.ConstraintViolationException)

Example 2 with BusinessEntity

use of org.meveo.model.BusinessEntity in project meveo by meveo-org.

the class CacheBean method getShortRepresentationOfCachedValue.

/**
 * Extract values of cached object to show in a list. In case of list of items, show only the first 10 items, in case of mapped items - only first 2 entries.
 *
 * @param item Item to convert to string
 * @param returnToStringForSimpleObjects true/false
 * @return A string representation of an item. Preferred way is code (id) or id or a value. For lists, separate items by a comma, for maps: key:[items..]
 */
@SuppressWarnings("rawtypes")
public String getShortRepresentationOfCachedValue(Object item, boolean returnToStringForSimpleObjects) {
    if (item instanceof List) {
        StringBuilder builder = new StringBuilder();
        List listObject = (List) item;
        for (int i = 0; i < 10 && i < listObject.size(); i++) {
            builder.append(builder.length() == 0 ? "" : ", ");
            Object listItem = listObject.get(i);
            builder.append(getShortRepresentationOfCachedValue(listItem, false));
        }
        if (listObject.size() > 10) {
            builder.append(", ...");
        }
        return builder.toString();
    } else if (item instanceof Map) {
        StringBuilder builder = new StringBuilder();
        Map mapObject = (Map) item;
        int i = 0;
        for (Object mapEntry : mapObject.entrySet()) {
            builder.append(builder.length() == 0 ? "" : ", ");
            Object key = ((Entry) mapEntry).getKey();
            Object value = ((Entry) mapEntry).getValue();
            if (i > 2) {
                break;
            }
            builder.append(String.format("%s: [%s]", key, getShortRepresentationOfCachedValue(value, false)));
            i++;
        }
        if (mapObject.size() > 2) {
            builder.append(", ...");
        }
        return builder.toString();
    } else if (returnToStringForSimpleObjects) {
        return item.toString();
    } else if (item instanceof BusinessEntity) {
        return String.format("%s (%s)", ((BusinessEntity) item).getCode(), ((BusinessEntity) item).getId());
    } else if (item instanceof IEntity) {
        return ((IEntity) item).getId().toString();
    } else if (item instanceof Long) {
        return item.toString();
    } else {
        Object code = null;
        try {
            code = MethodUtils.invokeExactMethod(item, "getCode");
        } catch (Exception e) {
        // Method does not exist - so just ignore
        }
        Object id = null;
        try {
            id = MethodUtils.invokeExactMethod(item, "getId");
        } catch (Exception e) {
        // Method does not exist - so just ignore
        }
        if (code != null && id != null) {
            return String.format("%s (%s)", code, id);
        } else if (code != null) {
            return code.toString();
        } else if (id != null) {
            return id.toString();
        } else {
            return item.toString();
        }
    }
}
Also used : IEntity(org.meveo.model.IEntity) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) BusinessEntity(org.meveo.model.BusinessEntity) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 3 with BusinessEntity

use of org.meveo.model.BusinessEntity in project meveo by meveo-org.

the class UserBean method getSelectedSecuredEntities.

public List<DetailedSecuredEntity> getSelectedSecuredEntities() {
    List<DetailedSecuredEntity> detailedSecuredEntities = new ArrayList<>();
    DetailedSecuredEntity detailedSecuredEntity = null;
    BusinessEntity businessEntity = null;
    if (entity != null && entity.getSecuredEntities() != null) {
        for (SecuredEntity securedEntity : entity.getSecuredEntities()) {
            detailedSecuredEntity = new DetailedSecuredEntity(securedEntity);
            businessEntity = securedBusinessEntityService.getEntityByCode(securedEntity.getEntityClass(), securedEntity.getCode());
            detailedSecuredEntity.setDescription(businessEntity.getDescription());
            detailedSecuredEntities.add(detailedSecuredEntity);
        }
    }
    return detailedSecuredEntities;
}
Also used : DetailedSecuredEntity(org.meveo.model.admin.DetailedSecuredEntity) SecuredEntity(org.meveo.model.admin.SecuredEntity) DetailedSecuredEntity(org.meveo.model.admin.DetailedSecuredEntity) ArrayList(java.util.ArrayList) BusinessEntity(org.meveo.model.BusinessEntity)

Example 4 with BusinessEntity

use of org.meveo.model.BusinessEntity 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 5 with BusinessEntity

use of org.meveo.model.BusinessEntity in project meveo by meveo-org.

the class JSONSchemaGenerator method processorOf.

private CustomTemplateProcessor processorOf(CustomRelationshipTemplate relationshipTemplate) {
    return new CustomTemplateProcessor() {

        @Override
        String code() {
            return relationshipTemplate.getCode();
        }

        @Override
        Map<String, CustomFieldTemplate> fields() {
            return cache.getCustomFieldTemplates(relationshipTemplate.getAppliesTo());
        }

        @Override
        CustomTemplateProcessor parentTemplate() {
            return null;
        }

        @Override
        ObjectSchema.Builder createJsonSchemaBuilder(String schemaLocation, Set<String> allRefs) {
            RelationSchema.Builder result = RelationSchema.builder().requiresRelation(true).id(relationshipTemplate.getCode()).title(relationshipTemplate.getName()).description(relationshipTemplate.getDescription()).storages(buildDBStorageType(relationshipTemplate.getAvailableStorages())).schemaLocation(schemaLocation);
            CustomEntityTemplate node;
            node = relationshipTemplate.getStartNode();
            if (node != null) {
                result.source(createReference(node));
                allRefs.add(node.getCode());
            }
            node = relationshipTemplate.getEndNode();
            if (node != null) {
                result.target(createReference(node));
                allRefs.add(node.getCode());
            }
            return result;
        }

        @Override
        ObjectSchema.Builder toRootJsonSchema(ObjectSchema original, Map<String, Schema> dependencies) {
            RootRelationSchema.Builder builder = RootRelationSchema.builder().copyOf((RelationSchema) original).specificationVersion(JSON_SCHEMA_VERSION);
            dependencies.forEach(builder::addDefinition);
            return builder;
        }

        private ReferenceSchema createReference(CustomEntityTemplate node) {
            ReferenceSchema.Builder r = ReferenceSchema.builder().refValue(DEFINITIONS_PREFIX + node.getCode());
            return r.build();
        }

        @SuppressWarnings("unused")
        private ReferenceViewSchema createReference_obsolete(CustomEntityTemplate node, String nodeKeys) {
            List<String> actualKeys;
            if (nodeKeys != null) {
                actualKeys = Arrays.asList(nodeKeys.split(","));
            } else {
                actualKeys = processorOf(node).fields().values().stream().filter(CustomFieldTemplate::isUnique).map(BusinessEntity::getCode).collect(Collectors.toList());
            }
            ReferenceViewSchema.Builder r = ReferenceViewSchema.builder().refValue(DEFINITIONS_PREFIX + node.getCode());
            actualKeys.forEach(p -> r.addRefProperty(p.trim()));
            return r.build();
        }
    };
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) BusinessEntity(org.meveo.model.BusinessEntity) RootRelationSchema(org.meveo.json.schema.RootRelationSchema) ReferenceSchema(org.everit.json.schema.ReferenceSchema) CombinedObjectSchema(org.everit.json.schema.CombinedObjectSchema) RootObjectSchema(org.meveo.json.schema.RootObjectSchema) ObjectSchema(org.everit.json.schema.ObjectSchema) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) RootRelationSchema(org.meveo.json.schema.RootRelationSchema) RelationSchema(org.everit.json.schema.RelationSchema) HashMap(java.util.HashMap) Map(java.util.Map) ReferenceViewSchema(org.everit.json.schema.ReferenceViewSchema)

Aggregations

BusinessEntity (org.meveo.model.BusinessEntity)41 ArrayList (java.util.ArrayList)13 BusinessException (org.meveo.admin.exception.BusinessException)11 IOException (java.io.IOException)10 HashMap (java.util.HashMap)10 Map (java.util.Map)10 List (java.util.List)9 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)9 InvalidParameterException (org.meveo.api.exception.InvalidParameterException)8 NoResultException (javax.persistence.NoResultException)6 NonUniqueResultException (javax.persistence.NonUniqueResultException)6 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)6 MeveoModuleItem (org.meveo.model.module.MeveoModuleItem)6 Collection (java.util.Collection)5 Date (java.util.Date)5 MeveoApiException (org.meveo.api.exception.MeveoApiException)5 Field (java.lang.reflect.Field)4 Set (java.util.Set)4 ELException (org.meveo.elresolver.ELException)4 CustomEntityTemplate (org.meveo.model.customEntities.CustomEntityTemplate)4