use of org.meveo.elresolver.ELException in project meveo by meveo-org.
the class ReportExtractService method evaluateStringExpression.
private String evaluateStringExpression(String expression, ReportExtract re) throws BusinessException, ELException {
if (!expression.startsWith("#{")) {
return expression;
}
String result = null;
if (StringUtils.isBlank(expression)) {
return result;
}
Map<Object, Object> userMap = new HashMap<>();
userMap.put("re", re);
Object res = MeveoValueExpressionWrapper.evaluateExpression(expression, userMap, String.class);
try {
result = (String) res;
} catch (Exception e) {
throw new BusinessException("Expression " + expression + " do not evaluate to String but " + res);
}
return result;
}
use of org.meveo.elresolver.ELException in project meveo by meveo-org.
the class CustomEntityInstanceBean method executeCustomAction.
/**
* Execute custom action on an entity
*
* @param entity Entity to execute action on
* @param action Action to execute
* @param encodedParameters Additional parameters encoded in URL like style
* param=value&param=value
* @return A script execution result value from Script.RESULT_GUI_OUTCOME
* variable
*/
public String executeCustomAction(ICustomFieldEntity entity, EntityCustomAction action, String encodedParameters) {
try {
action = entityActionScriptService.findByCode(action.getCode());
Map<String, Object> context = CustomScriptService.parseParameters(encodedParameters);
context.put(Script.CONTEXT_ACTION, action.getCode());
if (overrideParams != null && !overrideParams.isEmpty()) {
overrideParams.forEach(entry -> {
context.put(entry.getKey(), entry.getValue());
});
} else {
Map<Object, Object> elContext = new HashMap<>(context);
elContext.put("entity", entity);
action.getScriptParameters().forEach((key, value) -> {
try {
context.put(key, MeveoValueExpressionWrapper.evaluateExpression(value, elContext, Object.class));
} catch (ELException e) {
log.error("Failed to evaluate el for custom action", e);
}
});
}
Map<String, Object> result = scriptInstanceService.execute((IEntity) entity, repository, action.getScript().getCode(), context);
// Display a message accordingly on what is set in result
if (result.containsKey(Script.RESULT_GUI_MESSAGE_KEY)) {
messages.info(new BundleKey("messages", (String) result.get(Script.RESULT_GUI_MESSAGE_KEY)));
} else if (result.containsKey(Script.RESULT_GUI_MESSAGE)) {
messages.info((String) result.get(Script.RESULT_GUI_MESSAGE));
} else {
messages.info(new BundleKey("messages", "scriptInstance.actionExecutionSuccessfull"), action.getLabel());
}
if (result.containsKey(Script.RESULT_GUI_OUTCOME)) {
return (String) result.get(Script.RESULT_GUI_OUTCOME);
}
} catch (BusinessException e) {
log.error("Failed to execute a script {} on entity {}", action.getCode(), entity, e);
messages.error(new BundleKey("messages", "scriptInstance.actionExecutionFailed"), action.getLabel(), e.getMessage());
}
return null;
}
use of org.meveo.elresolver.ELException in project meveo by meveo-org.
the class CustomEntityInstanceBean method setAction.
/**
* @param action the action to set
*/
public void setAction(EntityCustomAction action) {
if (action == null) {
return;
}
if (action == this.action) {
return;
}
this.action = action;
Map<Object, Object> elContext = new HashMap<>();
elContext.put("entity", entity);
overrideParams.clear();
this.action.getScriptParameters().forEach((key, value) -> {
try {
overrideParams.add(new KeyValuePair(key, MeveoValueExpressionWrapper.evaluateExpression(value, elContext, Object.class)));
} catch (ELException e) {
log.error("Failed to evaluate el for custom action", e);
}
});
PrimeFaces.current().ajax().update("formId:buttons:executeDialog");
}
use of org.meveo.elresolver.ELException in project meveo by meveo-org.
the class EntityCustomActionApi method execute.
@SuppressWarnings("rawtypes")
public String execute(String actionCode, String appliesTo, String entityCode) throws MeveoApiException, InvalidScriptException, ElementNotFoundException, InvalidPermissionException, BusinessException {
EntityCustomAction action = entityCustomActionService.findByCodeAndAppliesTo(actionCode, appliesTo);
if (action == null) {
throw new EntityDoesNotExistsException(EntityCustomAction.class, actionCode + "/" + appliesTo);
}
Set<Class<?>> cfClasses = ReflectionUtils.getClassesAnnotatedWith(CustomFieldEntity.class, "org.meveo.model");
Class entityClass = null;
for (Class<?> clazz : cfClasses) {
if (appliesTo.equals(clazz.getAnnotation(CustomFieldEntity.class).cftCodePrefix())) {
entityClass = clazz;
break;
}
}
IEntity entity = (IEntity) entityCustomActionService.findByEntityClassAndCode(entityClass, entityCode);
Map<String, Object> context = new HashMap<String, Object>();
Map<Object, Object> elContext = new HashMap<>(context);
elContext.put("entity", entity);
action.getScriptParameters().forEach((key, value) -> {
try {
context.put(key, MeveoValueExpressionWrapper.evaluateExpression(value, elContext, Object.class));
} catch (ELException e) {
log.error("Failed to evaluate el for custom action", e);
}
});
Map<String, Object> result = scriptInstanceService.execute(entity, repository, action.getScript().getCode(), context);
if (result.containsKey(Script.RESULT_GUI_OUTCOME)) {
return (String) result.get(Script.RESULT_GUI_OUTCOME);
}
return null;
}
use of org.meveo.elresolver.ELException in project meveo by meveo-org.
the class Neo4jService method addSourceNodeUniqueCrt.
/**
* Persist a source node of an unique relationship.
* If a relationship that targets the target node exists, then we merge the fields of the start in parameter to
* the fields of the source node of the relationship.
* If such a relation does not exists, we create the source node with it fields.
*
* @param neo4JConfiguration Neo4J coordinates
* @param crtCode Code of the unique relation
* @param startNodeValues Values to assign to the start node
* @param endNodeValues Filters on the target node values
*/
@JpaAmpNewTx
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public PersistenceActionResult addSourceNodeUniqueCrt(String neo4JConfiguration, String crtCode, Map<String, Object> startNodeValues, Map<String, Object> endNodeValues) throws BusinessException, ELException {
// Get relationship template
final CustomRelationshipTemplate customRelationshipTemplate = customFieldsCache.getCustomRelationshipTemplate(crtCode);
final CustomEntityTemplate endNode = customRelationshipTemplate.getEndNode();
// Extract unique fields values for the start node
Map<String, CustomFieldTemplate> endNodeCfts = customFieldTemplateService.findByAppliesTo(endNode.getAppliesTo());
Map<String, CustomFieldTemplate> startNodeCfts = customFieldTemplateService.findByAppliesTo(customRelationshipTemplate.getStartNode().getAppliesTo());
final Map<String, Object> endNodeUniqueFields = new HashMap<>();
Map<String, Object> endNodeConvertedValues = validateAndConvertCustomFields(endNodeCfts, endNodeValues, endNodeUniqueFields, true);
Map<String, Object> startNodeConvertedValues = validateAndConvertCustomFields(startNodeCfts, startNodeValues, null, true);
// Map the variables declared in the statement
Map<String, Object> valuesMap = new HashMap<>();
final String cetCode = customRelationshipTemplate.getStartNode().getCode();
valuesMap.put("cetCode", cetCode);
valuesMap.put("crtCode", crtCode);
valuesMap.put("endCetcode", customRelationshipTemplate.getEndNode().getCode());
// Prepare the key maps for unique fields and start node fields
final String uniqueFieldStatements = neo4jDao.getFieldsString(endNodeConvertedValues.keySet());
final String startNodeValuesStatements = neo4jDao.getFieldsString(startNodeConvertedValues.keySet());
// No unique fields has been found
if (endNodeUniqueFields.isEmpty()) {
// If no unique fields are provided / defined, retrieve the meveo_uuid of the target node using unicity rules
Set<String> ids = endNode.getNeo4JStorageConfiguration().getUniqueConstraints().stream().filter(uniqueConstraint -> uniqueConstraint.getTrustScore() == 100).filter(uniqueConstraint -> isApplicableConstraint(endNodeValues, uniqueConstraint)).sorted(Neo4jService.CONSTRAINT_COMPARATOR).map(uniqueConstraint -> neo4jDao.executeUniqueConstraint(neo4JConfiguration, uniqueConstraint, endNodeValues, endNode.getCode())).findFirst().orElse(Set.of());
if (ids.isEmpty()) {
log.error("At least one unique field must be provided for target entity [code = {}, fields = {}]. " + "Unique fields are : {}", customRelationshipTemplate.getEndNode().getCode(), endNodeValues, endNodeUniqueFields);
throw new BusinessException("Unique field must be provided");
}
if (ids.size() > 1) {
throw new BusinessException(String.format("Multiple targets for unique relationship %s : %s.", crtCode, ids));
}
String id = ids.iterator().next();
endNodeValues.put("meveo_uuid", id);
endNodeUniqueFields.put("meveo_uuid", id);
}
// Assign the keys names
valuesMap.put(FIELD_KEYS, uniqueFieldStatements);
valuesMap.put(FIELDS, startNodeValuesStatements);
// Create the substitutor
StrSubstitutor sub = new StrSubstitutor(valuesMap);
// Values of the keys defined in valuesMap
Map<String, Object> parametersValues = new HashMap<>();
parametersValues.putAll(startNodeConvertedValues);
parametersValues.putAll(endNodeConvertedValues);
final Transaction transaction = crossStorageTransaction.getNeo4jTransaction(neo4JConfiguration);
// Try to find the id of the source node
String findStartNodeStatement = getStatement(sub, Neo4JRequests.findStartNodeId);
final StatementResult run = transaction.run(findStartNodeStatement, parametersValues);
Neo4jEntity startNode = null;
try {
try {
/* Update the source node with the found id */
// Alias to use in queries
final String startNodeAlias = "startNode";
// Retrieve ID of the node
final Record idRecord = run.single();
final Value id = idRecord.get(0);
parametersValues.put(NODE_ID, id);
// Create statement
CustomEntityTemplate startCet = customRelationshipTemplate.getStartNode();
List<String> additionalLabels = getAdditionalLabels(startCet);
final Map<String, Object> updatableValues = valuesMap.entrySet().stream().filter(s -> startNodeCfts.get(s.getKey()).isAllowEdit()).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
StringBuffer statement = neo4jDao.appendAdditionalLabels(Neo4JRequests.updateNodeWithId, additionalLabels, startNodeAlias, updatableValues);
statement = neo4jDao.appendReturnStatement(statement, startNodeAlias, valuesMap);
String updateStatement = getStatement(sub, statement);
// Execute query
final StatementResult result = transaction.run(updateStatement, parametersValues);
// Fire node update event
startNode = new Neo4jEntity(result.single().get(startNodeAlias).asNode(), neo4JConfiguration);
} catch (NoSuchRecordException e) {
/* Create the source node */
addCetNode(neo4JConfiguration, customRelationshipTemplate.getStartNode(), startNodeValues, null);
}
transaction.success();
} catch (Exception e) {
transaction.failure();
log.error("Transaction for persisting entity with code {} and fields {} was rolled back", cetCode, startNodeValues, e);
throw new BusinessException(e);
}
if (startNode != null) {
nodeUpdatedEvent.fire(startNode);
return new PersistenceActionResult(startNode.get("meveo_uuid").asString());
} else {
return null;
}
}
Aggregations