Search in sources :

Example 1 with JexlContext

use of org.apache.commons.jexl2.JexlContext in project opennms by OpenNMS.

the class JEXL method filter.

@Override
public void filter(RowSortedTable<Long, String, Double> qrAsTable) throws Exception {
    // Prepare the JEXL context
    final Map<String, Object> jexlValues = Maps.newHashMap();
    jexlValues.put("table", qrAsTable);
    final JexlContext context = new MapContext(jexlValues);
    // Compile the expression
    Expression expression = jexl.createExpression(m_expression);
    // Evaluate the expression
    expression.evaluate(context);
}
Also used : Expression(org.apache.commons.jexl2.Expression) JexlContext(org.apache.commons.jexl2.JexlContext) MapContext(org.apache.commons.jexl2.MapContext)

Example 2 with JexlContext

use of org.apache.commons.jexl2.JexlContext in project opennms by OpenNMS.

the class JEXLExpressionEngine method applyExpressions.

/**
 * {@inheritDoc}
 */
@Override
public void applyExpressions(final QueryRequest request, final FetchResults results) throws ExpressionException {
    Preconditions.checkNotNull(request, "request argument");
    Preconditions.checkNotNull(results, "results argument");
    final int numExpressions = request.getExpressions().size();
    // Don't do anything if there are no expressions
    if (numExpressions < 1) {
        return;
    }
    // Use to keep track of transient expression so that we don't
    // allocate memory to store their results
    int numNonTransientExpression = 0;
    boolean[] transientFlags = new boolean[numExpressions];
    // Compile the expressions
    int j, k = 0;
    final LinkedHashMap<String, org.apache.commons.jexl2.Expression> expressions = Maps.newLinkedHashMap();
    for (final Expression e : request.getExpressions()) {
        // Populate the transientFlags array
        transientFlags[k] = e.getTransient();
        if (!transientFlags[k]) {
            numNonTransientExpression++;
        }
        k++;
        try {
            expressions.put(e.getLabel(), jexl.createExpression(e.getExpression()));
        } catch (JexlException ex) {
            throw new ExpressionException(ex, "Failed to parse expression label '{}'.", e.getLabel());
        }
    }
    // Prepare the JEXL context
    final Map<String, Object> jexlValues = Maps.newHashMap();
    final JexlContext context = new MapContext(jexlValues);
    // Add constants (i.e. values from strings.properties) retrieved by the fetch operation
    jexlValues.putAll(results.getConstants());
    LOG.debug("JEXL context constants: {}", jexlValues);
    // Add some additional constants for ease of use
    jexlValues.put("__inf", Double.POSITIVE_INFINITY);
    jexlValues.put("__neg_inf", Double.NEGATIVE_INFINITY);
    jexlValues.put("NaN", Double.NaN);
    jexlValues.put("__E", java.lang.Math.E);
    jexlValues.put("__PI", java.lang.Math.PI);
    // Add JexlEvaluateFunctions with current context and jexl engine to allow string constants to be evaluated.
    JexlEvaluateFunctions jexlEvaluateFunctions = new JexlEvaluateFunctions(context, jexl);
    jexl.getFunctions().put("jexl", jexlEvaluateFunctions);
    final long[] timestamps = results.getTimestamps();
    final Map<String, double[]> columns = results.getColumns();
    final int numRows = timestamps.length;
    // Calculate the time span
    jexlValues.put("__diff_time", numRows < 1 ? 0d : timestamps[numRows - 1] - timestamps[0]);
    final double[][] expressionValues = new double[numNonTransientExpression][numRows];
    // Iterate through all of the rows, apply the expressions
    for (int i = 0; i < numRows; i++) {
        // Evaluate every expression, in the same order as which they appeared in the query
        j = k = 0;
        for (final Map.Entry<String, org.apache.commons.jexl2.Expression> expressionEntry : expressions.entrySet()) {
            // Update the timestamp
            jexlValues.put("timestamp", timestamps[i]);
            // add index as a referenced variable in context
            jexlValues.put("__i", Integer.valueOf(i));
            // overwriting values from the last loop
            for (final String sourceLabel : columns.keySet()) {
                jexlValues.put(sourceLabel, columns.get(sourceLabel)[i]);
                // add reference to complete array for each column to allow backwards referencing of samples
                jexlValues.put("__" + sourceLabel, columns.get(sourceLabel));
            }
            // Evaluate the expression
            try {
                Object derived = expressionEntry.getValue().evaluate(context);
                double derivedAsDouble = Utils.toDouble(derived);
                // Only store the values for non-transient expressions
                if (!transientFlags[j++]) {
                    expressionValues[k++][i] = derivedAsDouble;
                }
                // Store the result back in the context, so that it can be referenced
                // by subsequent expression in the row
                jexlValues.put(expressionEntry.getKey(), derivedAsDouble);
            } catch (NullPointerException | NumberFormatException e) {
                throw new ExpressionException(e, "The return value from expression with label '" + expressionEntry.getKey() + "' could not be cast to a Double.");
            } catch (JexlException e) {
                throw new ExpressionException(e, "Failed to evaluate expression with label '" + expressionEntry.getKey() + "'.");
            }
        }
    }
    // Store the results
    j = k = 0;
    for (final String expressionLabel : expressions.keySet()) {
        if (!transientFlags[j++]) {
            columns.put(expressionLabel, expressionValues[k++]);
        }
    }
}
Also used : JexlException(org.apache.commons.jexl2.JexlException) MapContext(org.apache.commons.jexl2.MapContext) ExpressionException(org.opennms.netmgt.measurements.api.exceptions.ExpressionException) Expression(org.opennms.netmgt.measurements.model.Expression) JexlContext(org.apache.commons.jexl2.JexlContext) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 3 with JexlContext

use of org.apache.commons.jexl2.JexlContext in project opennms by OpenNMS.

the class JMXMonitor method poll.

/**
 * {@inheritDoc}
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    final InetAddress ipv4Addr = svc.getAddress();
    PollStatus serviceStatus = PollStatus.unavailable();
    try {
        final Timer timer = new Timer();
        final JmxConnectionManager connectionManager = new DefaultConnectionManager(ParameterMap.getKeyedInteger(map, "retry", 3));
        final JmxConnectionManager.RetryCallback retryCallback = new JmxConnectionManager.RetryCallback() {

            @Override
            public void onRetry() {
                timer.reset();
            }
        };
        try (JmxServerConnectionWrapper connection = connectionManager.connect(getConnectionName(), ipv4Addr, JmxUtils.convertToStringMap(map), retryCallback)) {
            // Start with simple communication
            connection.getMBeanServerConnection().getMBeanCount();
            // Take time just here to get not influenced by test execution
            // time
            final long nanoResponseTime = System.nanoTime() - timer.getStartTime();
            // Find all variable definitions
            final Map<String, Object> variables = Maps.newHashMap();
            for (final String key : map.keySet()) {
                // Skip fast if it does not start with the prefix
                if (!key.startsWith(PARAM_BEAN_PREFIX)) {
                    continue;
                }
                // Get the variable name
                final String variable = key.substring(PARAM_BEAN_PREFIX.length());
                // Get the variable definition
                final String definition = ParameterMap.getKeyedString(map, key, null);
                // Store wrapper for variable definition
                variables.put(variable, ObjectNameWrapper.create(connection.getMBeanServerConnection(), definition));
            }
            // Find all test definitions
            final Map<String, Expression> tests = Maps.newHashMap();
            for (final String key : map.keySet()) {
                // Skip fast if it does not start with the prefix
                if (!key.startsWith(PARAM_TEST_PREFIX)) {
                    continue;
                }
                // Get the test name
                final String variable = key.substring(PARAM_TEST_PREFIX.length());
                // Get the test definition
                final String definition = ParameterMap.getKeyedString(map, key, null);
                // Build the expression from the definition
                final Expression expression = JEXL_ENGINE.createExpression(definition);
                // Store expressions
                tests.put(variable, expression);
            }
            // Also handle a single test
            if (map.containsKey(PARAM_TEST)) {
                // Get the test definition
                final String definition = ParameterMap.getKeyedString(map, PARAM_TEST, null);
                // Build the expression from the definition
                final Expression expression = JEXL_ENGINE.createExpression(definition);
                // Store expressions
                tests.put(null, expression);
            }
            // Build the context for all tests
            final JexlContext context = new ReadonlyContext(new MapContext(variables));
            serviceStatus = PollStatus.up(nanoResponseTime / 1000000.0);
            // Execute all tests
            for (final Map.Entry<String, Expression> e : tests.entrySet()) {
                if (!(boolean) e.getValue().evaluate(context)) {
                    serviceStatus = PollStatus.down("Test failed: " + e.getKey());
                    break;
                }
            }
        } catch (JmxServerConnectionException mbse) {
            // Number of retries exceeded
            String reason = "IOException while polling address: " + ipv4Addr;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        }
    } catch (Throwable e) {
        String reason = "Monitor - failed! " + InetAddressUtils.str(ipv4Addr);
        LOG.debug(reason);
        serviceStatus = PollStatus.unavailable(reason);
    }
    return serviceStatus;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) DefaultConnectionManager(org.opennms.netmgt.jmx.impl.connection.connectors.DefaultConnectionManager) JmxConnectionManager(org.opennms.netmgt.jmx.connection.JmxConnectionManager) ReadonlyContext(org.apache.commons.jexl2.ReadonlyContext) MapContext(org.apache.commons.jexl2.MapContext) JmxServerConnectionException(org.opennms.netmgt.jmx.connection.JmxServerConnectionException) Expression(org.apache.commons.jexl2.Expression) JexlContext(org.apache.commons.jexl2.JexlContext) JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map) ParameterMap(org.opennms.core.utils.ParameterMap)

Example 4 with JexlContext

use of org.apache.commons.jexl2.JexlContext in project nutch by apache.

the class CrawlDatum method evaluate.

public boolean evaluate(Expression expr, String url) {
    if (expr != null && url != null) {
        // Create a context and add data
        JexlContext jcontext = new MapContext();
        // https://issues.apache.org/jira/browse/NUTCH-2229
        jcontext.set("url", url);
        jcontext.set("status", getStatusName(getStatus()));
        jcontext.set("fetchTime", (long) (getFetchTime()));
        jcontext.set("modifiedTime", (long) (getModifiedTime()));
        jcontext.set("retries", getRetriesSinceFetch());
        jcontext.set("interval", new Integer(getFetchInterval()));
        jcontext.set("score", getScore());
        jcontext.set("signature", StringUtil.toHexString(getSignature()));
        // Set metadata variables
        for (Map.Entry<Writable, Writable> entry : getMetaData().entrySet()) {
            Object value = entry.getValue();
            Text tkey = (Text) entry.getKey();
            if (value instanceof FloatWritable) {
                FloatWritable fvalue = (FloatWritable) value;
                jcontext.set(tkey.toString(), fvalue.get());
            }
            if (value instanceof IntWritable) {
                IntWritable ivalue = (IntWritable) value;
                jcontext.set(tkey.toString(), ivalue.get());
            }
            if (value instanceof Text) {
                Text tvalue = (Text) value;
                jcontext.set(tkey.toString().replace("-", "_"), tvalue.toString());
            }
            if (value instanceof ProtocolStatus) {
                ProtocolStatus pvalue = (ProtocolStatus) value;
                jcontext.set(tkey.toString().replace("-", "_"), pvalue.toString());
            }
        }
        try {
            if (Boolean.TRUE.equals(expr.evaluate(jcontext))) {
                return true;
            }
        } catch (Exception e) {
        // 
        }
    }
    return false;
}
Also used : FloatWritable(org.apache.hadoop.io.FloatWritable) JexlContext(org.apache.commons.jexl2.JexlContext) Writable(org.apache.hadoop.io.Writable) FloatWritable(org.apache.hadoop.io.FloatWritable) IntWritable(org.apache.hadoop.io.IntWritable) Text(org.apache.hadoop.io.Text) MapContext(org.apache.commons.jexl2.MapContext) HashMap(java.util.HashMap) Map(java.util.Map) IntWritable(org.apache.hadoop.io.IntWritable) ProtocolStatus(org.apache.nutch.protocol.ProtocolStatus) IOException(java.io.IOException) VersionMismatchException(org.apache.hadoop.io.VersionMismatchException)

Example 5 with JexlContext

use of org.apache.commons.jexl2.JexlContext in project vorto by eclipse.

the class AbstractDataMapper method matchesCondition.

private boolean matchesCondition(Map<String, String> attributes, JXPathContext context) {
    if (attributes.containsKey(ATTRIBUTE_CONDITION) && !attributes.get(ATTRIBUTE_CONDITION).equals("")) {
        Expression e = JEXL.createExpression(normalizeCondition(attributes.get(ATTRIBUTE_CONDITION)));
        JexlContext jc = new ObjectContext<Object>(JEXL, context.getContextBean());
        jc.set("this", context.getContextBean());
        return (boolean) e.evaluate(jc);
    } else {
        return true;
    }
}
Also used : Expression(org.apache.commons.jexl2.Expression) JexlContext(org.apache.commons.jexl2.JexlContext) ObjectContext(org.apache.commons.jexl2.ObjectContext)

Aggregations

JexlContext (org.apache.commons.jexl2.JexlContext)31 Expression (org.apache.commons.jexl2.Expression)25 MapContext (org.apache.commons.jexl2.MapContext)23 JexlContext (org.apache.commons.jexl3.JexlContext)21 JexlEngine (org.apache.commons.jexl2.JexlEngine)20 MapContext (org.apache.commons.jexl3.MapContext)17 Test (org.testng.annotations.Test)13 HashMap (java.util.HashMap)5 Map (java.util.Map)4 ArrayList (java.util.ArrayList)3 JexlException (org.apache.commons.jexl2.JexlException)3 ObjectContext (org.apache.commons.jexl2.ObjectContext)3 IOException (java.io.IOException)2 ReadonlyContext (org.apache.commons.jexl2.ReadonlyContext)2 JexlScript (org.apache.commons.jexl3.JexlScript)2 NumberUtils (org.apache.commons.lang.math.NumberUtils)2 FloatWritable (org.apache.hadoop.io.FloatWritable)2 IntWritable (org.apache.hadoop.io.IntWritable)2 Text (org.apache.hadoop.io.Text)2 VersionMismatchException (org.apache.hadoop.io.VersionMismatchException)2