Search in sources :

Example 1 with ELException

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;
}
Also used : BusinessException(org.meveo.admin.exception.BusinessException) HashMap(java.util.HashMap) ELException(org.meveo.elresolver.ELException) IOException(java.io.IOException) BusinessException(org.meveo.admin.exception.BusinessException)

Example 2 with ELException

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&amp;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;
}
Also used : BusinessException(org.meveo.admin.exception.BusinessException) HashMap(java.util.HashMap) ELException(org.meveo.elresolver.ELException) BundleKey(org.jboss.seam.international.status.builder.BundleKey)

Example 3 with ELException

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");
}
Also used : KeyValuePair(org.meveo.model.util.KeyValuePair) HashMap(java.util.HashMap) ELException(org.meveo.elresolver.ELException)

Example 4 with ELException

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;
}
Also used : EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) IEntity(org.meveo.model.IEntity) HashMap(java.util.HashMap) ELException(org.meveo.elresolver.ELException) EntityCustomAction(org.meveo.model.crm.custom.EntityCustomAction)

Example 5 with ELException

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;
    }
}
Also used : CustomRelationshipTemplateService(org.meveo.service.custom.CustomRelationshipTemplateService) CrossStorageTransaction(org.meveo.persistence.CrossStorageTransaction) CustomPersistenceService(org.meveo.persistence.CustomPersistenceService) Date(java.util.Date) ELException(org.meveo.elresolver.ELException) LoggerFactory(org.slf4j.LoggerFactory) RepositoryService(org.meveo.service.storage.RepositoryService) StringUtils(org.meveo.commons.utils.StringUtils) ScriptInstanceService(org.meveo.service.script.ScriptInstanceService) CustomEntityTemplateUniqueConstraint(org.meveo.model.crm.CustomEntityTemplateUniqueConstraint) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) Future(java.util.concurrent.Future) Repository(org.meveo.model.storage.Repository) Matcher(java.util.regex.Matcher) TransactionAttributeType(javax.ejb.TransactionAttributeType) MeveoJpa(org.meveo.jpa.MeveoJpa) Asynchronous(javax.ejb.Asynchronous) CustomFieldValue(org.meveo.model.crm.custom.CustomFieldValue) Map(java.util.Map) CETUtils(org.meveo.api.CETUtils) AsyncResult(javax.ejb.AsyncResult) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) Value(org.neo4j.driver.v1.Value) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApplicationProvider(org.meveo.util.ApplicationProvider) ElementNotFoundException(org.meveo.admin.exception.ElementNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) Neo4jRelationship(org.meveo.persistence.neo4j.graph.Neo4jRelationship) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Instant(java.time.Instant) Transaction(org.neo4j.driver.v1.Transaction) Collectors(java.util.stream.Collectors) Entity(javax.ws.rs.client.Entity) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) Node(org.neo4j.driver.v1.types.Node) List(java.util.List) Response(javax.ws.rs.core.Response) CustomFieldStorageTypeEnum(org.meveo.model.crm.custom.CustomFieldStorageTypeEnum) HttpURLConnection(org.apache.commons.httpclient.util.HttpURLConnection) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Entry(java.util.Map.Entry) CustomFieldsCacheContainerProvider(org.meveo.cache.CustomFieldsCacheContainerProvider) Optional(java.util.Optional) CustomEntityTemplateUtils(org.meveo.service.custom.CustomEntityTemplateUtils) Pattern(java.util.regex.Pattern) StatementResult(org.neo4j.driver.v1.StatementResult) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException) BusinessEntity(org.meveo.model.BusinessEntity) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) NODE_ID(org.meveo.persistence.neo4j.base.Neo4jDao.NODE_ID) EntityReferenceWrapper(org.meveo.model.crm.EntityReferenceWrapper) BasicAuthentication(org.jboss.resteasy.client.jaxrs.BasicAuthentication) PersistenceActionResult(org.meveo.persistence.PersistenceActionResult) HashMap(java.util.HashMap) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Updated(org.meveo.event.qualifier.Updated) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Record(org.neo4j.driver.v1.Record) HashSet(java.util.HashSet) Inject(javax.inject.Inject) JacksonUtil(org.meveo.model.persistence.JacksonUtil) Removed(org.meveo.event.qualifier.Removed) Provider(org.meveo.model.crm.Provider) CustomFieldTemplateService(org.meveo.service.crm.impl.CustomFieldTemplateService) MeveoValueExpressionWrapper(org.meveo.service.base.MeveoValueExpressionWrapper) TransactionAttribute(javax.ejb.TransactionAttribute) Neo4jDao(org.meveo.persistence.neo4j.base.Neo4jDao) Event(javax.enterprise.event.Event) InvalidCustomFieldException(org.meveo.exceptions.InvalidCustomFieldException) Logger(org.slf4j.Logger) DBStorageType(org.meveo.model.persistence.DBStorageType) Created(org.meveo.event.qualifier.Created) EntityManagerWrapper(org.meveo.jpa.EntityManagerWrapper) CustomFieldTypeEnum(org.meveo.model.crm.custom.CustomFieldTypeEnum) Neo4jEntity(org.meveo.persistence.neo4j.graph.Neo4jEntity) CustomFieldIndexTypeEnum(org.meveo.model.crm.custom.CustomFieldIndexTypeEnum) InternalNode(org.neo4j.driver.internal.InternalNode) Relationship(org.neo4j.driver.v1.types.Relationship) Comparator(java.util.Comparator) Collections(java.util.Collections) EntityRef(org.meveo.persistence.scheduler.EntityRef) Values(org.neo4j.driver.v1.Values) StatementResult(org.neo4j.driver.v1.StatementResult) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ELException(org.meveo.elresolver.ELException) PatternSyntaxException(java.util.regex.PatternSyntaxException) ElementNotFoundException(org.meveo.admin.exception.ElementNotFoundException) BusinessException(org.meveo.admin.exception.BusinessException) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) InvalidCustomFieldException(org.meveo.exceptions.InvalidCustomFieldException) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) BusinessException(org.meveo.admin.exception.BusinessException) CrossStorageTransaction(org.meveo.persistence.CrossStorageTransaction) Transaction(org.neo4j.driver.v1.Transaction) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) CustomFieldValue(org.meveo.model.crm.custom.CustomFieldValue) Value(org.neo4j.driver.v1.Value) Neo4jEntity(org.meveo.persistence.neo4j.graph.Neo4jEntity) Record(org.neo4j.driver.v1.Record) PersistenceActionResult(org.meveo.persistence.PersistenceActionResult) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) TransactionAttribute(javax.ejb.TransactionAttribute)

Aggregations

ELException (org.meveo.elresolver.ELException)26 BusinessException (org.meveo.admin.exception.BusinessException)23 HashMap (java.util.HashMap)17 BundleKey (org.jboss.seam.international.status.builder.BundleKey)10 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 IOException (java.io.IOException)8 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)8 Collection (java.util.Collection)7 HashSet (java.util.HashSet)7 List (java.util.List)7 Collectors (java.util.stream.Collectors)7 Inject (javax.inject.Inject)7 Repository (org.meveo.model.storage.Repository)7 Set (java.util.Set)6 ActionMethod (org.meveo.admin.web.interceptor.ActionMethod)6 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)6 Neo4jDao (org.meveo.persistence.neo4j.base.Neo4jDao)6 EntityRef (org.meveo.persistence.scheduler.EntityRef)6 Collections (java.util.Collections)5