Sonar Critical Fix
[dcaegen2/analytics/tca.git] / dcae-analytics-tca / src / main / java / org / onap / dcae / apod / analytics / tca / processor / TCACEFPolicyThresholdsProcessor.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *   You may obtain a copy of the License at
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============================LICENSE_END===========================================
19  */
20
21 package org.onap.dcae.apod.analytics.tca.processor;
22
23 import com.google.common.base.Optional;
24 import com.google.common.collect.Table;
25 import org.onap.dcae.apod.analytics.common.exception.MessageProcessingException;
26 import org.onap.dcae.apod.analytics.model.domain.cef.Domain;
27 import org.onap.dcae.apod.analytics.model.domain.cef.EventListener;
28 import org.onap.dcae.apod.analytics.model.domain.policy.tca.MetricsPerEventName;
29 import org.onap.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;
30 import org.onap.dcae.apod.analytics.model.domain.policy.tca.Threshold;
31 import org.onap.dcae.apod.analytics.tca.utils.TCAUtils;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 import java.math.BigDecimal;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40
41 import javax.annotation.Nonnull;
42
43 /**
44  *<p>
45  *     TCA CEF Policy Threshold processor
46  *     <br>
47  *     Pre Conditions: Domain and Functional Role must be present in CEF Event Listener Object
48  *</p>
49  *
50  * @author Rajiv Singla . Creation Date: 11/9/2016.
51  */
52 public class TCACEFPolicyThresholdsProcessor extends AbstractTCAECEFPolicyProcessor {
53
54     private static final long serialVersionUID = 1L;
55
56     private static final Logger LOG = LoggerFactory.getLogger(TCACEFPolicyThresholdsProcessor.class);
57
58     @Override
59     public TCACEFProcessorContext preProcessor(@Nonnull TCACEFProcessorContext processorContext) {
60         // validates Domain and Functional Role are present
61         final EventListener eventListener = processorContext.getCEFEventListener();
62         final Domain domain = eventListener.getEvent().getCommonEventHeader().getDomain();
63         final String eventName = eventListener.getEvent().getCommonEventHeader().getEventName();
64         if (domain == null || eventName == null) {
65             final String errorMessage = "CEF Event Listener domain or eventName not Present. " +
66                     "Invalid use of this Processor";
67             throw new MessageProcessingException(errorMessage, LOG, new IllegalArgumentException(errorMessage));
68         }
69         return super.preProcessor(processorContext);
70     }
71
72     @Override
73     public String getProcessorDescription() {
74         return "Applies TCA Policy rules to incoming CEF message. If any thresholds are violated attaches max " +
75                 "Severity violated threshold to TCA Processor Context";
76     }
77
78     @Override
79     public TCACEFProcessorContext processMessage(TCACEFProcessorContext processorContext) {
80
81         final String cefMessage = processorContext.getMessage();
82
83         // Determine domain and eventName
84         final EventListener eventListener = processorContext.getCEFEventListener();
85         final String eventName = eventListener.getEvent().getCommonEventHeader().getEventName();
86
87         // Get Table containing event Name and Thresholds Field Path
88         final TCAPolicy tcaPolicy = processorContext.getTCAPolicy();
89         final Table<String, String, List<Threshold>> eventNameFieldPathsTable =
90                 TCAUtils.getPolicyEventNameThresholdsTableSupplier(tcaPolicy).get();
91
92         // Get Policy Field Paths for that event Name
93         final Map<String, List<Threshold>> policyFieldPathsMap = eventNameFieldPathsTable.row(eventName);
94         final Set<String> policyFieldPaths = policyFieldPathsMap.keySet();
95
96         // Get Json Values for Policy Fields
97         final Map<String, List<BigDecimal>> messageFieldValuesMap =
98                 TCAUtils.getJsonPathValue(cefMessage, policyFieldPaths);
99
100         // Determine all violated thresholds per message field Path
101         final Map<String, Threshold> violatedThresholdsMap = new HashMap<>();
102         for (Map.Entry<String, List<BigDecimal>> messageFieldValuesMapEntry : messageFieldValuesMap.entrySet()) {
103             final String messageFieldPath = messageFieldValuesMapEntry.getKey();
104             final List<Threshold> messageFieldAssociatedPolicyThresholds = policyFieldPathsMap.get(messageFieldPath);
105             if (messageFieldAssociatedPolicyThresholds != null) {
106                 final Optional<Threshold> thresholdOptional = TCAUtils.thresholdCalculator(
107                         messageFieldValuesMapEntry.getValue(), messageFieldAssociatedPolicyThresholds);
108                 if (thresholdOptional.isPresent()) {
109                     violatedThresholdsMap.put(messageFieldPath, thresholdOptional.get());
110                 }
111             }
112         }
113
114         // No threshold were violated
115         if (violatedThresholdsMap.isEmpty()) {
116
117             final String terminationMessage = "No Policy Threshold violated by the VES CEF Message.";
118             setTerminatingProcessingMessage(terminationMessage, processorContext);
119
120         } else {
121
122             // If there are policy violations then determine max priority violation
123             final Threshold maxSeverityThresholdViolation =
124                     TCAUtils.prioritizeThresholdViolations(violatedThresholdsMap);
125             final MetricsPerEventName violatedMetrics = TCAUtils.createViolatedMetrics(tcaPolicy,
126                     maxSeverityThresholdViolation, eventName);
127             // attach policy violation to processor Context
128             processorContext.setMetricsPerEventName(violatedMetrics);
129
130             final String finishMessage = String.format("Policy Threshold violation detected for threshold: %s",
131                     maxSeverityThresholdViolation);
132             setFinishedProcessingMessage(finishMessage, processorContext);
133
134         }
135
136         return processorContext;
137     }
138 }