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