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());
}
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;
}
}
}
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;
}
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;
}
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());
}
Aggregations