com.ringcentral.platform.metrics.infoProviders.DefaultMetricNamedInfoProvider Maven / Gradle / Ivy
The newest version!
package com.ringcentral.platform.metrics.infoProviders;
import com.ringcentral.platform.metrics.names.MetricNamed;
import com.ringcentral.platform.metrics.predicates.MetricNamedPredicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
public class DefaultMetricNamedInfoProvider implements PredicativeMetricNamedInfoProvider {
private final List> entries;
private final Map> keyToEntry;
public DefaultMetricNamedInfoProvider() {
this(new ArrayList<>(), new HashMap<>());
}
protected DefaultMetricNamedInfoProvider(List> entries, Map> keyToEntry) {
this.entries = requireNonNull(entries);
this.keyToEntry = requireNonNull(keyToEntry);
}
@Override
public DefaultMetricNamedInfoProvider addInfo(MetricNamedPredicate predicate, I info) {
return addInfo(null, predicate, info);
}
@Override
public DefaultMetricNamedInfoProvider addInfo(String key, MetricNamedPredicate predicate, I info) {
Entry entry = new Entry<>(key, predicate, info);
if (key != null) {
if (keyToEntry.containsKey(key)) {
throw new IllegalArgumentException("Duplicate key " + key);
}
keyToEntry.put(key, entry);
}
entries.add(entry);
return this;
}
@Override
public DefaultMetricNamedInfoProvider removeInfo(String key) {
Entry entry = keyToEntry.remove(key);
if (entry != null) {
entries.remove(entry);
}
return this;
}
@Override
public PredicativeMetricNamedInfoProvider removeInfos(Predicate keyPredicate) {
keyToEntry.keySet().removeIf(keyPredicate);
entries.removeIf(e -> keyPredicate.test(e.key));
return this;
}
@Override
public List infosFor(MetricNamed named) {
return entries.stream().filter(e -> e.predicate.matches(named)).map(e -> e.info).collect(toList());
}
private static class Entry {
final String key;
final MetricNamedPredicate predicate;
final I info;
Entry(String key, MetricNamedPredicate predicate, I info) {
this.key = key;
this.predicate = predicate;
this.info = info;
}
}
}