Example usage for org.apache.commons.jexl3 JexlBuilder JexlBuilder

List of usage examples for org.apache.commons.jexl3 JexlBuilder JexlBuilder

Introduction

In this page you can find the example usage for org.apache.commons.jexl3 JexlBuilder JexlBuilder.

Prototype

JexlBuilder

Source Link

Usage

From source file:com.epam.dlab.core.parser.ConditionEvaluate.java

/** Instantiate the engine to evaluate condition. 
 * @param columnNames the list of column names.
 * @param condition condition for filtering data.
 * @throws InitializationException//w w w  .j  a va2s  .  c  o  m
 */
public ConditionEvaluate(List<String> columnNames, String condition) throws InitializationException {
    //Replace : to . in column names
    List<String> colNames = new ArrayList<>(columnNames.size());
    for (int i = 0; i < columnNames.size(); i++) {
        String name = columnNames.get(i);
        if (name.indexOf(':') > -1 && condition.indexOf(name) > -1) {
            String newName = StringUtils.replaceChars(name, ':', '.');
            colNames.add(newName);
            condition = StringUtils.replace(condition, name, newName);
        } else {
            colNames.add(name);
        }
    }

    try {
        JexlEngine engine = new JexlBuilder().strict(true).silent(false).debug(true).create();
        expression = (Script) engine.createExpression(condition);
        jexlContext = new MapContext();
    } catch (Exception e) {
        throw new InitializationException(
                "Cannot initialize JEXL engine for condition: " + condition + ". " + e.getLocalizedMessage(),
                e);
    }

    // Create mapping of columns for evaluations. 
    List<String> names = new ArrayList<>();
    List<Integer> indexes = new ArrayList<>();
    for (List<String> variableList : expression.getVariables()) {
        String columnName = StringUtils.join(variableList, '.');
        int index = getColumnIndex(colNames, columnName);
        if (index == -1) {
            throw new InitializationException("Unknow source column name \"" + columnName + "\" in condition: "
                    + expression.getSourceText() + ". Known column names: "
                    + StringUtils.join(columnNames, ", ") + ".");
        }
        names.add(columnName);
        indexes.add(index);
    }

    this.columnNames = new String[names.size()];
    this.columnIndexes = new int[indexes.size()];
    for (int i = 0; i < indexes.size(); i++) {
        this.columnNames[i] = names.get(i);
        this.columnIndexes[i] = indexes.get(i);
    }
}

From source file:datainstiller.data.DataAliasesConverter.java

@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    DataAliases aliases = new DataAliases();
    String nodeName;//www  . j  av  a2  s .co  m
    String value;
    Object objValue = null;
    JxltEngine jxlt = new JexlBuilder().strict(true).silent(false).create().createJxltEngine();
    while (reader.hasMoreChildren()) {
        reader.moveDown();
        nodeName = reader.getNodeName();
        value = reader.getValue();
        if (value.matches("\\$\\[.+]")) {
            Pattern pattern = Pattern.compile("\\$\\[(.+)\\(\\s*'\\s*(.*)\\s*'\\s*,\\s*'\\s*(.*)\\s*'\\s*\\)");
            Matcher matcher = pattern.matcher(value);
            if (matcher.find() != true) {
                throw new PatternUnmarshalException(value + " - invalid data generation expression!");
            }
            GeneratorInterface genType = new DataGenerator().getGenerator(matcher.group(1).trim());
            String init = matcher.group(2);
            String val = matcher.group(3);
            value = genType.generate(init, val);
        } else {
            JxltEngine.Expression expr = jxlt.createExpression(value);
            try {
                objValue = expr.evaluate(jexlContext);
                value = objValue.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        aliases.put(nodeName, value);
        if (objValue != null) {
            jexlContext.set(nodeName, objValue);
        } else {
            jexlContext.set(nodeName, value);
        }
        objValue = null;
        reader.moveUp();
    }
    return aliases;
}

From source file:com.streamsets.datacollector.antennadoctor.engine.AntennaDoctorEngine.java

public AntennaDoctorEngine(AntennaDoctorContext context, List<AntennaDoctorRuleBean> rules) {
    ImmutableList.Builder<RuntimeRule> builder = ImmutableList.builder();

    Map<String, Object> namespaces = new HashMap<>();
    namespaces.put("collection", CollectionEL.class);
    namespaces.put("file", FileEL.class);

    // Main engine used to evaluate all expressions and templates
    engine = new JexlBuilder().cache(512).strict(true).silent(false).debug(true).namespaces(namespaces)
            .create();/*from   www  . j  av a2  s .  co m*/
    templateEngine = engine.createJxltEngine();

    // Context for preconditions
    JexlContext jexlContext = new MapContext();
    jexlContext.set("version", new Version(context.getBuildInfo().getVersion()));
    jexlContext.set("sdc", new SdcJexl(context));

    // Evaluate each rule to see if it's applicable to this runtime (version, stage libs, ...)
    for (AntennaDoctorRuleBean ruleBean : rules) {
        LOG.trace("Loading rule {}", ruleBean.getUuid());

        // We're running in SDC and currently only in STAGE 'mode', other modes will be added later
        if (ruleBean.getEntity() == null || !ruleBean.getEntity().isOneOf(AntennaDoctorRuleBean.Entity.STAGE,
                AntennaDoctorRuleBean.Entity.REST)) {
            continue;
        }

        // Reset the variables that the rule is keeping
        jexlContext.set("context", new HashMap<>());

        for (String precondition : ruleBean.getPreconditions()) {
            try {
                LOG.trace("Evaluating precondition: {}", precondition);
                if (!evaluateCondition(precondition, jexlContext)) {
                    LOG.trace("Precondition {} failed, skipping rule {}", precondition, ruleBean.getUuid());
                    continue;
                }
            } catch (Throwable e) {
                LOG.error("Precondition {} failed, skipping rule {}: {}", precondition, ruleBean.getUuid(),
                        e.toString(), e);
                continue;
            }
        }

        // All checks passed, so we will accept this rule
        builder.add(new RuntimeRule(ruleBean));
    }

    this.rules = builder.build();
    LOG.info("Loaded new Antenna Doctor engine with {} rules", this.rules.size());
}

From source file:org.apache.jmeter.functions.Jexl3Function.java

/**
 * Get JexlEngine from ThreadLocal// w w  w  .j  a v  a 2 s . co  m
 * @return JexlEngine
 */
private static JexlEngine getJexlEngine() {
    JexlEngine engine = threadLocalJexl.get();
    if (engine == null) {
        engine = new JexlBuilder().cache(512).silent(true).strict(true)
                // debug is true by default an impact negatively performances
                // by a factory of 10
                // Use JexlInfo if necessary
                .debug(false)
                // see https://issues.apache.org/jira/browse/JEXL-186
                .arithmetic(new JMeterArithmetic(true)).create();
        threadLocalJexl.set(engine);
    }
    return engine;
}

From source file:org.apache.nifi.processors.ccda.ExtractCCDAAttributes.java

@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    getLogger().debug("Loading packages");
    final StopWatch stopWatch = new StopWatch(true);

    // Load required MDHT packages
    System.setProperty("org.eclipse.emf.ecore.EPackage.Registry.INSTANCE",
            "org.eclipse.emf.ecore.impl.EPackageRegistryImpl");
    CDAPackage.eINSTANCE.eClass();//from   ww w . j  av a2  s . c  om
    HITSPPackage.eINSTANCE.eClass();
    CCDPackage.eINSTANCE.eClass();
    ConsolPackage.eINSTANCE.eClass();
    IHEPackage.eINSTANCE.eClass();
    stopWatch.stop();
    getLogger().debug("Loaded packages in {}", new Object[] { stopWatch.getDuration(TimeUnit.MILLISECONDS) });

    // Initialize JEXL
    jexl = new JexlBuilder().cache(1024).debug(false).silent(true).strict(false).create();
    jexlCtx = new MapContext();

    getLogger().debug("Loading mappings");
    loadMappings(); // Load CDA mappings for parser

}

From source file:org.apache.syncope.core.provisioning.java.jexl.JexlUtils.java

private static JexlEngine getEngine() {
    synchronized (LOG) {
        if (JEXL_ENGINE == null) {
            JEXL_ENGINE = new JexlBuilder().uberspect(new ClassFreeUberspect()).loader(new EmptyClassLoader())
                    .namespaces(Collections.<String, Object>singletonMap("syncope", new SyncopeJexlFunctions()))
                    .cache(512).silent(false).strict(false).create();
        }/*from   www.j ava  2 s  .c o  m*/
    }

    return JEXL_ENGINE;
}

From source file:org.everit.expression.jexl.JexlExpressionCompiler.java

@Override
public CompiledExpression compile(final String expression, final ParserConfiguration parserConfiguration) {

    if (parserConfiguration == null) {
        throw new IllegalArgumentException("Parser configuration must be defined");
    }//from  w w w  .  ja v  a  2 s.  c  o m

    JexlInfo jexlInfo = new JexlInfo(parserConfiguration.getName(), parserConfiguration.getStartRow(),
            parserConfiguration.getStartColumn());
    String[] parameterNames = null;
    if (parserConfiguration.getVariableTypes() != null) {
        Set<String> parameterSet = parserConfiguration.getVariableTypes().keySet();
        parameterNames = parameterSet.toArray(new String[parameterSet.size()]);
    }

    JexlEngine jexlEngine = new JexlBuilder().silent(false).debug(true)
            .loader(parserConfiguration.getClassLoader()).arithmetic(new CustomizedJexlArithmetic(true))
            .create();

    JexlScript script = jexlEngine.createScript(jexlInfo, expression, parameterNames);
    return new JexlCompiledExpression(script);
}