Search in sources :

Example 1 with EntityDoesNotExistsException

use of org.meveo.api.exception.EntityDoesNotExistsException in project meveo by meveo-org.

the class CustomTableService method fetchField.

public String fetchField(String sqlConnectionCode, Object id, CustomFieldTemplate field, String tableName) {
    log.info("Fetching {} with uuid {}", field.getCode(), id);
    CustomEntityTemplate cet = customFieldsCacheContainerProvider.getCustomEntityTemplate(field.getEntityClazzCetCode());
    Map<String, Object> entityRefValues;
    try {
        entityRefValues = findById(sqlConnectionCode, cet, (String) id);
    } catch (EntityDoesNotExistsException e) {
        return null;
    }
    // We don't want to save the uuid
    entityRefValues.remove("uuid");
    return JacksonUtil.toString(entityRefValues);
}
Also used : EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomModelObject(org.meveo.model.customEntities.CustomModelObject)

Example 2 with EntityDoesNotExistsException

use of org.meveo.api.exception.EntityDoesNotExistsException in project meveo by meveo-org.

the class GenericEntityPickerBean method getCeiListFromCet.

private List<CustomEntityInstance> getCeiListFromCet(CustomEntityTemplate customEntityTemplate) throws BusinessException {
    List<CustomEntityInstance> ceiList = new ArrayList<>();
    List<Map<String, Object>> values;
    try {
        values = crossStorageService.find(// XXX: Maybe we will need to parameterize this or search in all repositories ?
        repositoryService.findDefaultRepository(), customEntityTemplate, new PaginationConfiguration());
    } catch (EntityDoesNotExistsException e) {
        throw new RuntimeException(e);
    }
    if (CollectionUtils.isNotEmpty(values)) {
        for (Map<String, Object> customEntity : values) {
            CustomEntityInstance customEntityInstance = new CustomEntityInstance();
            customEntityInstance.setUuid((String) customEntity.get("uuid"));
            customEntityInstance.setCode((String) customEntity.get("uuid"));
            String fieldName = customFieldTemplateService.getFieldName(customEntityTemplate);
            if (fieldName != null) {
                customEntityInstance.setDescription(fieldName + ": " + customEntity.get(fieldName));
            }
            customEntityInstance.setCet(customEntityTemplate);
            customEntityInstance.setCetCode(customEntityTemplate.getCode());
            customFieldInstanceService.setCfValues(customEntityInstance, customEntityTemplate.getCode(), customEntity);
            ceiList.add(customEntityInstance);
        }
    }
    return ceiList;
}
Also used : EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration)

Example 3 with EntityDoesNotExistsException

use of org.meveo.api.exception.EntityDoesNotExistsException 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 4 with EntityDoesNotExistsException

use of org.meveo.api.exception.EntityDoesNotExistsException in project meveo by meveo-org.

the class BaseCrudApi method importZip.

/**
 * Import data from a zip
 *
 * @param fileName  Name of the file
 * @param file      File to import
 * @param overwrite Whether we should update existing data
 */
public void importZip(String fileName, InputStream file, boolean overwrite) throws EntityDoesNotExistsException {
    Path fileImport = null;
    try {
        fileImport = Files.createTempDirectory(fileName);
        FileUtils.unzipFile(fileImport.toString(), file);
        buildFileList(fileImport.toFile(), overwrite);
    } catch (EntityDoesNotExistsException e) {
        throw new EntityDoesNotExistsException(e.getMessage());
    } catch (Exception e) {
        log.error("Error import zip file {}", fileName, e);
    }
    if (fileImport != null) {
        try {
            org.apache.commons.io.FileUtils.deleteDirectory(fileImport.toFile());
        } catch (IOException e) {
            log.error("Can't delete temp folder {}", fileImport, e);
        }
    }
}
Also used : Path(java.nio.file.Path) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) IOException(java.io.IOException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) IOException(java.io.IOException) BusinessException(org.meveo.admin.exception.BusinessException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MeveoApiException(org.meveo.api.exception.MeveoApiException)

Example 5 with EntityDoesNotExistsException

use of org.meveo.api.exception.EntityDoesNotExistsException in project meveo by meveo-org.

the class CalendarApi method update.

public void update(CalendarDto postData) throws MeveoApiException, BusinessException {
    if (StringUtils.isBlank(postData.getCode())) {
        missingParameters.add("code");
    }
    if (StringUtils.isBlank(postData.getCalendarType())) {
        missingParameters.add("calendarType");
    }
    handleMissingParametersAndValidate(postData);
    Calendar calendar = calendarService.findByCode(postData.getCode());
    if (calendar == null) {
        throw new EntityDoesNotExistsException(Calendar.class, postData.getCode());
    }
    calendar.setCode(StringUtils.isBlank(postData.getUpdatedCode()) ? postData.getCode() : postData.getUpdatedCode());
    calendar.setDescription(postData.getDescription());
    if (calendar instanceof CalendarYearly) {
        if (postData.getDays() != null && postData.getDays().size() > 0) {
            List<DayInYear> days = new ArrayList<DayInYear>();
            for (DayInYearDto d : postData.getDays()) {
                DayInYear dayInYear = dayInYearService.findByMonthAndDay(d.getMonth(), d.getDay());
                if (dayInYear != null) {
                    days.add(dayInYear);
                }
            }
            ((CalendarYearly) calendar).setDays(days);
        }
    } else if (calendar instanceof CalendarYearly) {
        if (postData.getHours() != null && postData.getHours().size() > 0) {
            List<HourInDay> hours = new ArrayList<HourInDay>();
            for (HourInDayDto d : postData.getHours()) {
                HourInDay hourInDay = hourInDayService.findByHourAndMin(d.getHour(), d.getMin());
                if (hourInDay != null) {
                    hours.add(hourInDay);
                }
            }
            ((CalendarDaily) calendar).setHours(hours);
        }
    } else if (calendar instanceof CalendarPeriod) {
        ((CalendarPeriod) calendar).setPeriodLength(postData.getPeriodLength());
        ((CalendarPeriod) calendar).setNbPeriods(postData.getNbPeriods());
        if (!StringUtils.isBlank(postData.getPeriodUnit())) {
            ((CalendarPeriod) calendar).setPeriodUnit(postData.getPeriodUnit().getUnitValue());
        }
    } else if (calendar instanceof CalendarInterval) {
        CalendarInterval calendarInterval = (CalendarInterval) calendar;
        calendarInterval.setIntervalType(postData.getIntervalType());
        calendarInterval.getIntervals().clear();
        if (postData.getIntervals() != null && postData.getIntervals().size() > 0) {
            for (CalendarDateIntervalDto interval : postData.getIntervals()) {
                calendarInterval.getIntervals().add(new CalendarDateInterval(calendarInterval, interval.getIntervalBegin(), interval.getIntervalEnd()));
            }
        }
    } else if (calendar instanceof CalendarJoin) {
        if (StringUtils.isBlank(postData.getJoinCalendar1Code())) {
            missingParameters.add("joinCalendar1Code");
        }
        if (StringUtils.isBlank(postData.getJoinCalendar2Code())) {
            missingParameters.add("joinCalendar2Code");
        }
        handleMissingParameters();
        Calendar cal1 = calendarService.findByCode(postData.getJoinCalendar1Code());
        Calendar cal2 = calendarService.findByCode(postData.getJoinCalendar2Code());
        if (cal1 == null) {
            throw new InvalidParameterException("joinCalendar1Code", postData.getJoinCalendar1Code());
        }
        if (cal2 == null) {
            throw new InvalidParameterException("joinCalendar2Code", postData.getJoinCalendar2Code());
        }
        CalendarJoin calendarJoin = (CalendarJoin) calendar;
        // Join type is expressed as Calendar type in DTO
        calendarJoin.setJoinType(CalendarJoinTypeEnum.valueOf(postData.getCalendarType().name()));
        calendarJoin.setJoinCalendar1(cal1);
        calendarJoin.setJoinCalendar2(cal2);
    }
    calendarService.update(calendar);
}
Also used : DayInYearDto(org.meveo.api.dto.DayInYearDto) DayInYear(org.meveo.model.catalog.DayInYear) CalendarInterval(org.meveo.model.catalog.CalendarInterval) Calendar(org.meveo.model.catalog.Calendar) ArrayList(java.util.ArrayList) HourInDay(org.meveo.model.catalog.HourInDay) HourInDayDto(org.meveo.api.dto.HourInDayDto) CalendarDateInterval(org.meveo.model.catalog.CalendarDateInterval) CalendarJoin(org.meveo.model.catalog.CalendarJoin) InvalidParameterException(org.meveo.api.exception.InvalidParameterException) CalendarDateIntervalDto(org.meveo.api.dto.CalendarDateIntervalDto) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) CalendarYearly(org.meveo.model.catalog.CalendarYearly) CalendarPeriod(org.meveo.model.catalog.CalendarPeriod) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)178 BusinessException (org.meveo.admin.exception.BusinessException)40 ArrayList (java.util.ArrayList)27 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)25 MeveoApiException (org.meveo.api.exception.MeveoApiException)24 CustomEntityTemplate (org.meveo.model.customEntities.CustomEntityTemplate)24 CustomEntityInstance (org.meveo.model.customEntities.CustomEntityInstance)22 InvalidParameterException (org.meveo.api.exception.InvalidParameterException)20 IOException (java.io.IOException)18 BusinessApiException (org.meveo.api.exception.BusinessApiException)18 HashSet (java.util.HashSet)17 ELException (org.meveo.elresolver.ELException)16 ScriptInstance (org.meveo.model.scripts.ScriptInstance)16 HashMap (java.util.HashMap)15 Map (java.util.Map)13 ActionForbiddenException (org.meveo.api.exception.ActionForbiddenException)13 List (java.util.List)12 MeveoModule (org.meveo.model.module.MeveoModule)12 Collection (java.util.Collection)10 Language (org.meveo.model.billing.Language)10