Search in sources :

Example 6 with MapContext

use of org.apache.commons.jexl3.MapContext 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 7 with MapContext

use of org.apache.commons.jexl3.MapContext in project nutch by apache.

the class JexlIndexingFilter method filter.

@Override
public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException {
    // Create a context and add data
    JexlContext jcontext = new MapContext();
    jcontext.set("status", CrawlDatum.getStatusName(datum.getStatus()));
    jcontext.set("fetchTime", (long) (datum.getFetchTime()));
    jcontext.set("modifiedTime", (long) (datum.getModifiedTime()));
    jcontext.set("retries", datum.getRetriesSinceFetch());
    jcontext.set("interval", new Integer(datum.getFetchInterval()));
    jcontext.set("score", datum.getScore());
    jcontext.set("signature", StringUtil.toHexString(datum.getSignature()));
    jcontext.set("url", url.toString());
    jcontext.set("text", parse.getText());
    jcontext.set("title", parse.getData().getTitle());
    JexlContext httpStatusContext = new MapContext();
    httpStatusContext.set("majorCode", parse.getData().getStatus().getMajorCode());
    httpStatusContext.set("minorCode", parse.getData().getStatus().getMinorCode());
    httpStatusContext.set("message", parse.getData().getStatus().getMessage());
    jcontext.set("httpStatus", httpStatusContext);
    jcontext.set("documentMeta", metadataToContext(doc.getDocumentMeta()));
    jcontext.set("contentMeta", metadataToContext(parse.getData().getContentMeta()));
    jcontext.set("parseMeta", metadataToContext(parse.getData().getParseMeta()));
    JexlContext context = new MapContext();
    for (Entry<String, NutchField> entry : doc) {
        context.set(entry.getKey(), entry.getValue().getValues());
    }
    jcontext.set("doc", context);
    try {
        if (Boolean.TRUE.equals(expr.evaluate(jcontext))) {
            return doc;
        }
    } catch (Exception e) {
        LOG.warn("Failed evaluating JEXL {}", expr.getExpression(), e);
    }
    return null;
}
Also used : NutchField(org.apache.nutch.indexer.NutchField) JexlContext(org.apache.commons.jexl2.JexlContext) MapContext(org.apache.commons.jexl2.MapContext) IndexingException(org.apache.nutch.indexer.IndexingException)

Example 8 with MapContext

use of org.apache.commons.jexl3.MapContext 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 9 with MapContext

use of org.apache.commons.jexl3.MapContext in project traccar by tananaev.

the class ComputedAttributesHandler method prepareContext.

private MapContext prepareContext(Position position) {
    MapContext result = new MapContext();
    if (mapDeviceAttributes) {
        Device device = Context.getIdentityManager().getById(position.getDeviceId());
        if (device != null) {
            for (Object key : device.getAttributes().keySet()) {
                result.set((String) key, device.getAttributes().get(key));
            }
        }
    }
    Set<Method> methods = new HashSet<>(Arrays.asList(position.getClass().getMethods()));
    methods.removeAll(Arrays.asList(Object.class.getMethods()));
    for (Method method : methods) {
        if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
            String name = Character.toLowerCase(method.getName().charAt(3)) + method.getName().substring(4);
            try {
                if (!method.getReturnType().equals(Map.class)) {
                    result.set(name, method.invoke(position));
                } else {
                    for (Object key : ((Map) method.invoke(position)).keySet()) {
                        result.set((String) key, ((Map) method.invoke(position)).get(key));
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException error) {
                Log.warning(error);
            }
        }
    }
    return result;
}
Also used : Device(org.traccar.model.Device) MapContext(org.apache.commons.jexl2.MapContext) Method(java.lang.reflect.Method) Map(java.util.Map) InvocationTargetException(java.lang.reflect.InvocationTargetException) HashSet(java.util.HashSet)

Example 10 with MapContext

use of org.apache.commons.jexl3.MapContext in project opennms by OpenNMS.

the class JexlIndexStorageStrategy method getResourceNameFromIndex.

/**
 * {@inheritDoc}
 */
@Override
public String getResourceNameFromIndex(CollectionResource resource) {
    String resourceName = null;
    try {
        UnifiedJEXL.Expression expr = EL.parse(m_parameters.get(PARAM_INDEX_FORMAT));
        JexlContext context = new MapContext();
        m_parameters.entrySet().forEach((entry) -> {
            context.set(entry.getKey(), entry.getValue());
        });
        updateContext(context, resource);
        resourceName = (String) expr.evaluate(new ReadonlyContext(context));
    } catch (JexlException e) {
        LOG.error("getResourceNameFromIndex(): error evaluating index-format [{}] as a Jexl Expression", m_parameters.get(PARAM_INDEX_FORMAT), e);
    } finally {
        if (resourceName == null) {
            resourceName = resource.getInstance();
        }
    }
    if ("true".equals(m_parameters.get(PARAM_CLEAN_OUTPUT)) && resourceName != null) {
        resourceName = resourceName.replaceAll("\\s+", "_").replaceAll(":", "_").replaceAll("\\\\", "_").replaceAll("[\\[\\]]", "_").replaceAll("[|/]", "_").replaceAll("=", "").replaceAll("[_]+$", "").replaceAll("___", "_");
    }
    LOG.debug("getResourceNameFromIndex(): {}", resourceName);
    return resourceName;
}
Also used : UnifiedJEXL(org.apache.commons.jexl2.UnifiedJEXL) JexlException(org.apache.commons.jexl2.JexlException) JexlContext(org.apache.commons.jexl2.JexlContext) ReadonlyContext(org.apache.commons.jexl2.ReadonlyContext) MapContext(org.apache.commons.jexl2.MapContext)

Aggregations

MapContext (org.apache.commons.jexl2.MapContext)16 JexlContext (org.apache.commons.jexl2.JexlContext)12 Expression (org.apache.commons.jexl2.Expression)6 JexlEngine (org.apache.commons.jexl2.JexlEngine)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 JexlException (org.apache.commons.jexl2.JexlException)3 ReadonlyContext (org.apache.commons.jexl2.ReadonlyContext)2 CompoundVariable (org.apache.jmeter.engine.util.CompoundVariable)2 JMeterContext (org.apache.jmeter.threads.JMeterContext)2 JMeterVariables (org.apache.jmeter.threads.JMeterVariables)2 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 InetAddress (java.net.InetAddress)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 ColumnConfig (ml.shifu.shifu.container.obj.ColumnConfig)1 Script (org.apache.commons.jexl2.Script)1