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;
}
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;
}
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;
}
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;
}
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;
}
Aggregations