Initial TCA commit into DCAEGEN2
[dcaegen2/analytics/tca.git] / dcae-analytics-common / src / main / java / org / openecomp / dcae / apod / analytics / common / service / filter / GenericJsonMessageFilter.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.openecomp.dcae.apod.analytics.common.service.filter;
22
23 import com.google.common.collect.ImmutableSet;
24 import com.jayway.jsonpath.DocumentContext;
25 import com.jayway.jsonpath.JsonPath;
26 import com.jayway.jsonpath.PathNotFoundException;
27 import org.apache.commons.lang3.StringUtils;
28 import org.openecomp.dcae.apod.analytics.common.service.processor.AbstractMessageProcessor;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import java.util.Set;
33
34 /**
35  * A Generic Json Message Filter which filter the json message based on given json Path and list of expected values
36  * for that json path. The {@link JsonMessageFilterProcessorContext#isMatched} flag will be changed as per table below:
37  * <pre>
38  *      Incoming message is blank or invalid Json                               =  null
39  *      Incoming message path is matches expected values                        = true
40  *      Incoming message does not match expected values or path does not exist  = false
41  * </pre>
42  * <p>
43  * @author Rajiv Singla . Creation Date: 2/10/2017.
44  */
45 public class GenericJsonMessageFilter extends AbstractMessageProcessor<JsonMessageFilterProcessorContext> {
46
47     private static final Logger LOG = LoggerFactory.getLogger(GenericJsonMessageFilter.class);
48     private static final long serialVersionUID = 1L;
49
50     private final String filterName;
51     private final String jsonPath;
52     private final Set<String> expectedValues;
53
54     public GenericJsonMessageFilter(final String filterName, final String jsonPath, final Set<String> expectedValues) {
55         this.filterName = filterName;
56         this.jsonPath = jsonPath;
57         this.expectedValues = expectedValues;
58     }
59
60     public GenericJsonMessageFilter(final String filterName, final String jsonPath, final String expectedValue) {
61         this(filterName, jsonPath, ImmutableSet.of(expectedValue));
62     }
63
64     @Override
65     public String getProcessorDescription() {
66         return filterName;
67     }
68
69     @Override
70     public JsonMessageFilterProcessorContext processMessage(final JsonMessageFilterProcessorContext processorContext) {
71
72         final String jsonMessage = processorContext.getMessage().trim();
73
74         if (StringUtils.isNotBlank(jsonMessage) && jsonMessage.startsWith("{") && jsonMessage.endsWith("}")) {
75
76             // locate json path value
77             final DocumentContext documentContext = JsonPath.parse(jsonMessage);
78             String jsonPathValue = null;
79             try {
80                 jsonPathValue = documentContext.read(jsonPath, String.class);
81             } catch (PathNotFoundException ex) {
82                 LOG.info("Unable to find json Path: {}. Exception: {}, Json Message: {}", jsonPath, ex, jsonMessage);
83             }
84
85             LOG.debug("Value for jsonPath: {}, jsonPathValue: {}, expected Values: {}",
86                     jsonPath, jsonPathValue, expectedValues);
87
88             // if json path value is null or we json value is not present in expect values then terminate early
89             if (jsonPathValue == null || !expectedValues.contains(jsonPathValue)) {
90                 final String terminatingMessage = String.format("Filter match unsuccessful. " +
91                                 "JsonPath: %s, Actual JsonPathValue: %s, Excepted Json Path Values: %s",
92                         jsonPath, jsonPathValue, expectedValues);
93                 processorContext.setMatched(false);
94                 setTerminatingProcessingMessage(terminatingMessage, processorContext);
95             } else {
96                 final String finishProcessingMessage = String.format("Filter match successful. " +
97                                 "JsonPath: %s, Actual JsonPathValue: %s, Excepted Json Path Values: %s",
98                         jsonPath, jsonPathValue, expectedValues);
99                 processorContext.setMatched(true);
100                 setFinishedProcessingMessage(finishProcessingMessage, processorContext);
101             }
102         } else {
103             // if incoming message is blank of valid Json then matched flag will be null
104             final String terminatingMessage = "Incoming json message is blank or not json. " +
105                     "Json filter cannot be applied";
106             processorContext.setMatched(null);
107             setTerminatingProcessingMessage(terminatingMessage, processorContext);
108         }
109
110         return processorContext;
111     }
112 }