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

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

Introduction

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

Prototype

public MapContext() 

Source Link

Document

Creates a MapContext on an automatically allocated underlying HashMap.

Usage

From source file:datainstiller.data.DataAliasesConverter.java

public DataAliasesConverter(JexlContext jexlContext) {
    if (jexlContext == null) {
        this.jexlContext = new MapContext();
    } else {/*from   w w w  .j a  v a2  s . c o m*/
        this.jexlContext = jexlContext;
    }
}

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//  www . j a  v  a 2s  .com
 */
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.DataPersistence.java

private void initJexlContext() {
    if (jexlContext != null) {
        System.out.println("WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }// ww  w.  java2  s .c o  m
    JexlContext jContext = new MapContext();
    jContext.set("AddressGen", new AddressGenerator());
    jContext.set("AlphaNumericGen", new AlphaNumericGenerator());
    jContext.set("ListGen", new CustomListGenerator());
    jContext.set("DateGen", new DateGenerator());
    jContext.set("HumanNameGen", new HumanNameGenerator());
    jContext.set("NumberGen", new NumberGenerator());
    jContext.set("WordGen", new WordGenerator());
    jContext.set("File2ListGen", new File2ListGenerator());
    LocalDateTime now = LocalDateTime.now();
    jContext.set("now", now);
    jContext.set("DateTimeFormatter", DateTimeFormatter.BASIC_ISO_DATE);
    initJexlContext(jContext);
    jexlContext = jContext;
}

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   w  ww . j  a v a2  s .  c o  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:com.streamsets.datacollector.antennadoctor.engine.AntennaDoctorEngine.java

public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, Exception exception) {
    JexlContext jexlContext = new MapContext();
    jexlContext.set("issue", new StageIssueJexl(exception));
    jexlContext.set("stageDef", context.getStageDefinition());
    jexlContext.set("stageConf", context.getStageConfiguration());
    return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}

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

public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, ErrorCode errorCode,
        Object... args) {//  w w w  .  ja  v a2 s .c  om
    JexlContext jexlContext = new MapContext();
    jexlContext.set("issue", new StageIssueJexl(errorCode, args));
    jexlContext.set("stageDef", context.getStageDefinition());
    jexlContext.set("stageConf", context.getStageConfiguration());
    return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}

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

public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, String errorMessage) {
    JexlContext jexlContext = new MapContext();
    jexlContext.set("issue", new StageIssueJexl(errorMessage));
    jexlContext.set("stageDef", context.getStageDefinition());
    jexlContext.set("stageConf", context.getStageConfiguration());
    return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}

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

public List<AntennaDoctorMessage> onRest(AntennaDoctorContext context, ErrorCode errorCode, Object... args) {
    JexlContext jexlContext = new MapContext();
    jexlContext.set("issue", new StageIssueJexl(errorCode, args));
    return evaluate(context, AntennaDoctorRuleBean.Entity.REST, jexlContext);
}

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

public List<AntennaDoctorMessage> onRest(AntennaDoctorContext context, Exception exception) {
    JexlContext jexlContext = new MapContext();
    jexlContext.set("issue", new StageIssueJexl(exception));
    return evaluate(context, AntennaDoctorRuleBean.Entity.REST, jexlContext);
}

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

/** {@inheritDoc} */
@Override//w  ww  .j av  a2  s.  com
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    String str = ""; //$NON-NLS-1$

    CompoundVariable var = (CompoundVariable) values[0];
    String exp = var.execute();

    String varName = ""; //$NON-NLS-1$
    if (values.length > 1) {
        varName = ((CompoundVariable) values[1]).execute().trim();
    }

    JMeterContext jmctx = JMeterContextService.getContext();
    JMeterVariables vars = jmctx.getVariables();

    try {
        JexlContext jc = new MapContext();
        jc.set("log", log); //$NON-NLS-1$
        jc.set("ctx", jmctx); //$NON-NLS-1$
        jc.set("vars", vars); //$NON-NLS-1$
        jc.set("props", JMeterUtils.getJMeterProperties()); //$NON-NLS-1$
        // Previously mis-spelt as theadName
        jc.set("threadName", Thread.currentThread().getName()); //$NON-NLS-1$
        jc.set("sampler", currentSampler); //$NON-NLS-1$ (may be null)
        jc.set("sampleResult", previousResult); //$NON-NLS-1$ (may be null)
        jc.set("OUT", System.out);//$NON-NLS-1$

        // Now evaluate the script, getting the result
        JexlExpression e = getJexlEngine().createExpression(exp);
        Object o = e.evaluate(jc);
        if (o != null) {
            str = o.toString();
        }
        if (vars != null && varName.length() > 0) {// vars will be null on TestPlan
            vars.put(varName, str);
        }
    } catch (Exception e) {
        log.error("An error occurred while evaluating the expression \"" + exp + "\"\n", e);
    }
    return str;
}