use of java.util.Objects in project opennms by OpenNMS.
the class GeneratorConfigBuilder method build.
public GeneratorConfig build() {
final GeneratorConfig config = new GeneratorConfig();
if (label != null) {
config.setLabel(label);
}
if (providerId != null) {
config.setProviderId(providerId);
// if a label is not provided with new providerId
if (label == null)
config.setLabel(providerId);
}
if (preferredLayout != null) {
config.setPreferredLayout(preferredLayout);
}
if (hierarchy != null && !hierarchy.trim().isEmpty()) {
final List<String> layers = Arrays.asList(hierarchy.split(",")).stream().filter(Objects::nonNull).map(String::trim).filter(h -> !h.isEmpty()).collect(Collectors.toList());
config.setLayerHierarchies(layers);
}
if (filter != null && !filter.trim().isEmpty()) {
final List<String> filters = Arrays.asList(filter.split(";")).stream().filter(Objects::nonNull).map(String::trim).filter(h -> !h.isEmpty()).collect(Collectors.toList());
config.setFilters(filters);
}
if (breadcrumbStrategy != null) {
try {
BreadcrumbStrategy validValue = BreadcrumbStrategy.valueOf(breadcrumbStrategy);
config.setBreadcrumbStrategy(validValue.name());
} catch (IllegalArgumentException ex) {
LOG.warn("Given breadcrumbStrategy {} does not exist. Valid values are {}. Ignoring.", breadcrumbStrategy, BreadcrumbStrategy.values());
}
}
return config;
}
use of java.util.Objects in project opennms by OpenNMS.
the class JMXCollector method collect.
@Override
public CollectionSet collect(CollectionAgent agent, Map<String, Object> map) {
final Map<String, String> stringMap = JmxUtils.convertToUnmodifiableStringMap(map);
final InetAddress ipaddr = agent.getAddress();
final JmxCollection jmxCollection = (JmxCollection) map.get(JMX_COLLECTION_KEY);
final MBeanServer mBeanServer = (MBeanServer) map.get(JMX_MBEAN_SERVER_KEY);
final String collectionName = ParameterMap.getKeyedString(map, ParameterName.COLLECTION.toString(), serviceName);
final String port = ParameterMap.getKeyedString(map, ParameterName.PORT.toString(), null);
final String friendlyName = ParameterMap.getKeyedString(map, ParameterName.FRIENDLY_NAME.toString(), port);
final String collDir = JmxUtils.getCollectionDirectory(stringMap, friendlyName, serviceName);
final int retries = ParameterMap.getKeyedInteger(map, ParameterName.RETRY.toString(), 3);
InetAddress ipAddr = agent.getAddress();
int nodeID = agent.getNodeId();
// Retrieve the name of the JMX data collector
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("initialize: InetAddress={}, collectionName={}", hostAddress, collectionName);
JMXNodeInfo nodeInfo = new JMXNodeInfo(nodeID);
LOG.debug("nodeInfo: {} {} {}", hostAddress, nodeID, agent);
/*
* Retrieve list of MBean objects to be collected from the
* remote agent which are to be stored in the node-level RRD file.
* These objects pertain to the node itself not any individual
* interfaces.
*/
Map<String, List<Attrib>> attrMap = JMXDataCollectionConfigDao.getAttributeMap(jmxCollection, serviceName(), hostAddress);
nodeInfo.setAttributeMap(attrMap);
Map<String, JMXDataSource> dsList = buildDataSourceList(collectionName, attrMap);
nodeInfo.setDsMap(dsList);
nodeInfo.setMBeans(JMXDataCollectionConfigDao.getMBeanInfo(jmxCollection));
// Metrics collected from JMX are currently modeled as node level resources,
// but live in a sub-directory set to the service name
final NodeLevelResource nodeResource = new NodeLevelResource(agent.getNodeId(), collDir);
// This parent resource used for generic resource
final NodeLevelResource parentResource = new NodeLevelResource(agent.getNodeId());
// Used to gather the results
final CollectionSetBuilder collectionSetBuilder = new CollectionSetBuilder(agent);
LOG.debug("connecting to {} on node ID {}", InetAddressUtils.str(ipaddr), nodeInfo.getNodeId());
try {
// create config for JmxCollector
final JmxCollectorConfig config = new JmxCollectorConfig();
config.setAgentAddress(InetAddressUtils.str(ipaddr));
config.setConnectionName(getConnectionName());
config.setRetries(retries);
config.setServiceProperties(stringMap);
config.setJmxCollection(jmxCollection);
final DefaultJmxCollector jmxCollector = new DefaultJmxCollector();
jmxCollector.collect(config, mBeanServer, new JmxSampleProcessor() {
@Override
public void process(JmxAttributeSample attributeSample, ObjectName objectName) {
final String mbeanObjectName = attributeSample.getMbean().getObjectname();
final String attributeName = attributeSample.getCollectedAttribute().getName();
final String dsKey = mbeanObjectName + "|" + attributeName;
final JMXDataSource ds = nodeInfo.getDsMap().get(dsKey);
if (ds == null) {
LOG.info("Could not find datasource for {}. Skipping.", dsKey);
return;
}
String resourceType = attributeSample.getMbean().getResourceType();
if (resourceType != null) {
final String parsedObjectName = fixGroupName(objectName.getCanonicalName());
final Resource resource = new DeferredGenericTypeResource(parentResource, resourceType, parsedObjectName);
addNumericAttributeToCollectionSet(ds, attributeSample, resource);
addStringAttributesToCollectionSet(ds, attributeSample, resource, objectName);
} else {
addNumericAttributeToCollectionSet(ds, attributeSample, nodeResource);
}
}
@Override
public void process(JmxCompositeSample compositeSample, ObjectName objectName) {
final String mbeanObjectName = compositeSample.getMbean().getObjectname();
final String attributeName = compositeSample.getCollectedAttribute().getName();
final String dsKey = mbeanObjectName + "|" + attributeName + "|" + compositeSample.getCompositeKey();
final JMXDataSource ds = nodeInfo.getDsMap().get(dsKey);
if (ds == null) {
LOG.info("Could not find datasource for {}. Skipping.", dsKey);
return;
}
String resourceType = compositeSample.getMbean().getResourceType();
if (resourceType != null) {
final String parsedObjectName = fixGroupName(objectName.getCanonicalName());
final Resource resource = new DeferredGenericTypeResource(parentResource, resourceType, parsedObjectName);
addNumericAttributeToCollectionSet(ds, compositeSample, resource);
addStringAttributesToCollectionSet(ds, compositeSample, resource, objectName);
} else {
addNumericAttributeToCollectionSet(ds, compositeSample, nodeResource);
}
}
private void addStringAttributesToCollectionSet(JMXDataSource ds, AbstractJmxSample sample, Resource resource, ObjectName objectName) {
final String groupName = fixGroupName(JmxUtils.getGroupName(stringMap, sample.getMbean()));
final String domain = objectName.getDomain();
final Hashtable<String, String> properties = objectName.getKeyPropertyList();
properties.forEach((key, value) -> collectionSetBuilder.withStringAttribute(resource, groupName, key, value));
if (domain != null) {
collectionSetBuilder.withStringAttribute(resource, groupName, "domain", objectName.getDomain());
}
}
private void addNumericAttributeToCollectionSet(JMXDataSource ds, AbstractJmxSample sample, Resource resource) {
final String groupName = fixGroupName(JmxUtils.getGroupName(stringMap, sample.getMbean()));
// Only numeric data comes back from JMX in data collection
final String valueAsString = sample.getCollectedValueAsString();
final Double value = NumericAttributeUtils.parseNumericValue(valueAsString);
// Construct the metric identifier (used by NRTG)
String metricId = groupName;
metricId = metricId.replace("_type_", ":type=");
metricId = metricId.replace("_", ".");
metricId = metricId.concat(".");
metricId = metricId.concat(ds.getName());
metricId = "JMX_".concat(metricId);
collectionSetBuilder.withIdentifiedNumericAttribute(resource, groupName, ds.getName(), value, ds.getType(), metricId);
}
});
} catch (final Exception e) {
LOG.debug("{} Collector.collect: IOException while collecting address: {}", serviceName, agent.getAddress(), e);
}
return collectionSetBuilder.build();
}
use of java.util.Objects in project opennms by OpenNMS.
the class RangeChunker method chunk.
public Map<String, List<DiscoveryJob>> chunk(final DiscoveryConfiguration config) {
final int chunkSize = config.getChunkSize().orElse(DiscoveryConfigFactory.DEFAULT_CHUNK_SIZE);
final double packetsPerSecond = config.getPacketsPerSecond().orElse(DiscoveryConfigFactory.DEFAULT_PACKETS_PER_SECOND);
// If the foreign source for the discovery config is not set than use
// a value of null so that non-requisitioned nodes are created.
//
// TODO: Use the "default" foreign source instead so that we can move
// away from using non-requisitioned nodes.
//
final String foreignSourceFromConfig = config.getForeignSource().isPresent() ? config.getForeignSource().get().trim() : null;
// If the monitoring location for the discovery config is not set than use
// the default localhost location
final String locationFromConfig = config.getLocation().map(l -> {
final String trimmed = l.trim();
if ("".equals(trimmed)) {
return null;
}
return trimmed;
}).orElse(MonitoringLocationDao.DEFAULT_MONITORING_LOCATION_ID);
final DiscoveryConfigFactory configFactory = new DiscoveryConfigFactory(config);
final AtomicReference<IPPollRange> previousRange = new AtomicReference<>();
return StreamSupport.stream(configFactory.getConfiguredAddresses().spliterator(), false).filter(address -> {
// If there is no IP address filter set or the filter matches
return ipAddressFilter.matches(address.getLocation(), address.getAddress());
}).map(address -> {
// Create a singleton IPPollRange
return new IPPollRange(// Make sure that foreignSource is not null so that we can partition on the value
address.getForeignSource() == null ? foreignSourceFromConfig : address.getForeignSource(), // Make sure that location is not null so that we can partition on the value
address.getLocation() == null ? locationFromConfig : address.getLocation(), address.getAddress(), address.getAddress(), address.getTimeout(), address.getRetries());
}).collect(Collectors.groupingBy(range -> {
// Create a Map<ForeignSourceLocationKey,List<IPPollRange>>
return new ForeignSourceLocationKey(// Make sure that foreignSource is not null so that we can partition on the value
range.getForeignSource() == null ? foreignSourceFromConfig : range.getForeignSource(), // Make sure that location is not null so that we can partition on the value
range.getLocation() == null ? locationFromConfig : range.getLocation());
}, LinkedHashMap::new, Collectors.toList())).entrySet().stream().flatMap(entry -> {
// Partition the list of address values
return Lists.partition(entry.getValue(), chunkSize).stream().map(ranges -> {
DiscoveryJob retval = new DiscoveryJob(ranges.stream().map(address -> {
// then just extend the range to cover this address too
if (isConsecutive(previousRange.get(), address)) {
previousRange.get().getAddressRange().incrementEnd();
return null;
}
previousRange.set(address);
return address;
}).filter(Objects::nonNull).collect(Collectors.toList()), entry.getKey().getForeignSource(), entry.getKey().getLocation(), packetsPerSecond);
// Reset the previousRange value
previousRange.set(null);
return retval;
}).collect(Collectors.toList()).stream();
}).collect(Collectors.groupingBy(DiscoveryJob::getLocation, LinkedHashMap::new, Collectors.toList()));
}
use of java.util.Objects in project opennms by OpenNMS.
the class AbstractDaoRestServiceWithDTO method getPropertyValues.
@GET
@Path("properties/{propertyId}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getPropertyValues(@PathParam("propertyId") final String propertyId, @QueryParam("q") final String query, @QueryParam("limit") final Integer limit) {
Set<SearchProperty> props = getQueryProperties();
// Find the property with the matching ID
Optional<SearchProperty> prop = props.stream().filter(p -> p.getId().equals(propertyId)).findAny();
if (prop.isPresent()) {
SearchProperty property = prop.get();
if (property.values != null && property.values.size() > 0) {
final Set<String> validValues;
if (query != null && query.length() > 0) {
validValues = property.values.keySet().stream().filter(v -> v.contains(query)).collect(Collectors.toSet());
} else {
validValues = property.values.keySet();
}
switch(property.type) {
case FLOAT:
return Response.ok(new FloatCollection(validValues.stream().map(Float::parseFloat).collect(Collectors.toList()))).build();
case INTEGER:
return Response.ok(new IntegerCollection(validValues.stream().map(Integer::parseInt).collect(Collectors.toList()))).build();
case LONG:
return Response.ok(new LongCollection(validValues.stream().map(Long::parseLong).collect(Collectors.toList()))).build();
case IP_ADDRESS:
case STRING:
return Response.ok(new StringCollection(validValues)).build();
case TIMESTAMP:
return Response.ok(new DateCollection(validValues.stream().map(v -> {
try {
return ISO8601DateEditor.stringToDate(v);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
LOG.error("Invalid date in value list: " + v, e);
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList()))).build();
default:
return Response.noContent().build();
}
}
switch(property.type) {
case FLOAT:
List<Float> floats = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Float>(property, query, limit));
return Response.ok(new FloatCollection(floats)).build();
case INTEGER:
List<Integer> ints = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Integer>(property, query, limit));
return Response.ok(new IntegerCollection(ints)).build();
case LONG:
List<Long> longs = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Long>(property, query, limit));
return Response.ok(new LongCollection(longs)).build();
case IP_ADDRESS:
List<InetAddress> addresses = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<InetAddress>(property, query, limit));
return Response.ok(new StringCollection(addresses.stream().map(InetAddressUtils::str).collect(Collectors.toList()))).build();
case STRING:
List<String> strings = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<String>(property, query, limit));
return Response.ok(new StringCollection(strings)).build();
case TIMESTAMP:
List<Date> dates = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Date>(property, query, limit));
return Response.ok(new DateCollection(dates)).build();
default:
return Response.noContent().build();
}
} else {
// 404
return Response.status(Status.NOT_FOUND).build();
}
}
use of java.util.Objects in project caffeine by ben-manes.
the class CacheProxy method removeAll.
@Override
public void removeAll(Set<? extends K> keys) {
requireNotClosed();
keys.forEach(Objects::requireNonNull);
boolean statsEnabled = statistics.isEnabled();
long start = statsEnabled ? ticker.read() : 0L;
Set<K> keysToRemove = new HashSet<>(keys);
CacheWriterException e = deleteAllToCacheWriter(keysToRemove);
long removed = keysToRemove.stream().map(this::removeNoCopyOrAwait).filter(Objects::nonNull).count();
dispatcher.awaitSynchronous();
if (statsEnabled) {
statistics.recordRemovals(removed);
statistics.recordRemoveTime(ticker.read() - start);
}
if (e != null) {
throw e;
}
}
Aggregations