ThresholdHandler.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cz.senslog.analyzer.analysis.module;
  2. import cz.senslog.analyzer.domain.*;
  3. import cz.senslog.analyzer.core.api.Handler;
  4. import cz.senslog.analyzer.core.api.HandlerContext;
  5. import org.apache.logging.log4j.LogManager;
  6. import org.apache.logging.log4j.Logger;
  7. import java.util.*;
  8. import static java.util.Collections.emptyList;
  9. public abstract class ThresholdHandler<T extends Data<?, ?>> extends Handler<T, T> {
  10. private static final Logger logger = LogManager.getLogger(ThresholdHandler.class);
  11. /** Map of thresholds rules order by group_id (Map<group_id, List<ThresholdRule>>). */
  12. private Map<Long, List<Threshold.Rule>> thresholdRules;
  13. protected abstract List<Threshold> loadThresholdValues();
  14. protected abstract long getGroupId(T data);
  15. @Override
  16. public void init() {
  17. List<Threshold> thresholds = loadThresholdValues();
  18. thresholdRules = new HashMap<>(thresholds.size());
  19. for (Threshold threshold : thresholds) {
  20. thresholdRules.computeIfAbsent(threshold.getGroupId(), k -> new ArrayList<>())
  21. .add(threshold.getRule());
  22. }
  23. }
  24. @Override
  25. public void handle(HandlerContext<T, T> context) {
  26. T data = context.data();
  27. long groupId = getGroupId(context.data());
  28. List<Threshold.Rule> rules = getThresholdRulesByGroupId(groupId);
  29. ValidationResult validateResult = data.validate(rules);
  30. if (validateResult.isNotValid()) {
  31. context.eventBus().notify(new Alert(
  32. groupId, String.format("group(%d)", groupId), data.getTimestamp(),
  33. validateResult.getMessages().toArray(new String[0])
  34. ));
  35. }
  36. context.next(data);
  37. }
  38. private List<Threshold.Rule> getThresholdRulesByGroupId(long groupId) {
  39. return thresholdRules.getOrDefault(groupId, emptyList());
  40. }
  41. }