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