1f33db6b8b1abfb78981f8d6084f934772e147c7
[policy/apex-pdp.git] / services / services-engine / src / main / java / org / onap / policy / apex / service / parameters / eventprotocol / EventProtocolParametersJSONAdapter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.service.parameters.eventprotocol;
22
23 import java.lang.reflect.Type;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters;
28 import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters;
29 import org.onap.policy.apex.service.parameters.ApexParameterRuntimeException;
30 import org.slf4j.ext.XLogger;
31 import org.slf4j.ext.XLoggerFactory;
32
33 import com.google.gson.JsonDeserializationContext;
34 import com.google.gson.JsonDeserializer;
35 import com.google.gson.JsonElement;
36 import com.google.gson.JsonObject;
37 import com.google.gson.JsonParseException;
38 import com.google.gson.JsonPrimitive;
39 import com.google.gson.JsonSerializationContext;
40 import com.google.gson.JsonSerializer;
41
42 /**
43  * This class serialises and deserialises various type of event protocol parameters to and from
44  * JSON.
45  *
46  * @author Liam Fallon (liam.fallon@ericsson.com)
47  */
48 public class EventProtocolParametersJSONAdapter
49         implements JsonSerializer<EventProtocolParameters>, JsonDeserializer<EventProtocolParameters> {
50     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJSONAdapter.class);
51
52     private static final String PARAMETER_CLASS_NAME = "parameterClassName";
53
54     private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol";
55     private static final String EVENT_PROTOCOL_PARAMETERS = "parameters";
56
57     // Built in event protocol parameters
58     private static final Map<String, String> BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP = new HashMap<>();
59     static {
60         BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName());
61         BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName());
62     }
63
64     /*
65      * (non-Javadoc)
66      *
67      * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type,
68      * com.google.gson.JsonSerializationContext)
69      */
70     @Override
71     public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc,
72             final JsonSerializationContext context) {
73         final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported";
74         LOGGER.error(returnMessage);
75         throw new ApexParameterRuntimeException(returnMessage);
76     }
77
78     /*
79      * (non-Javadoc)
80      *
81      * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement,
82      * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
83      */
84     @Override
85     public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT,
86             final JsonDeserializationContext context) throws JsonParseException {
87         final JsonObject jsonObject = json.getAsJsonObject();
88
89         // Get the event protocol label primitive
90         final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN);
91
92         // Check if we found our event protocol
93         if (labelJsonPrimitive == null) {
94             LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file");
95             return null;
96         }
97
98         // Get and check the event protocol label
99         final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", "");
100         if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) {
101             final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" value \""
102                     + labelJsonPrimitive.getAsString() + "\" invalid in JSON file";
103             LOGGER.warn(errorMessage);
104             throw new ApexParameterRuntimeException(errorMessage);
105         }
106
107         // We now get the event protocol parameter class
108         String eventProtocolParameterClassName = null;
109
110         // Get the event protocol parameter class for the event protocol plugin class from the
111         // configuration parameters
112         final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME);
113
114         // If no event protocol parameter class was specified, we use the default
115         if (classNameJsonPrimitive == null) {
116             eventProtocolParameterClassName = BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel);
117         } else {
118             // We use the specified one
119             eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", "");
120         }
121
122         // Check the event protocol parameter class
123         if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) {
124             final String errorMessage =
125                     "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \""
126                             + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null")
127                             + "\" invalid in JSON file";
128             LOGGER.warn(errorMessage);
129             throw new ApexParameterRuntimeException(errorMessage);
130         }
131
132         // Get the class for the event protocol
133         Class<?> eventProtocolParameterClass = null;
134         try {
135             eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName);
136         } catch (final ClassNotFoundException e) {
137             final String errorMessage =
138                     "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \""
139                             + eventProtocolParameterClassName + "\", could not find class";
140             LOGGER.warn(errorMessage, e);
141             throw new ApexParameterRuntimeException(errorMessage, e);
142         }
143
144         // Deserialise the class
145         EventProtocolParameters eventProtocolParameters =
146                 context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass);
147         if (eventProtocolParameters == null) {
148             // OK no parameters for the event protocol have been specified, just instantiate the
149             // default parameters
150             try {
151                 eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance();
152             } catch (final Exception e) {
153                 final String errorMessage = "could not create default parameters for event protocol \""
154                         + eventProtocolLabel + "\"\n" + e.getMessage();
155                 LOGGER.warn(errorMessage, e);
156                 throw new ApexParameterRuntimeException(errorMessage, e);
157             }
158         }
159
160         // Check that the event protocol label matches the label in the event protocol parameters
161         // object
162         if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) {
163             final String errorMessage = "event protocol \"" + eventProtocolLabel + "\" does not match plugin \""
164                     + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName
165                     + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME
166                     + "\"";
167             LOGGER.warn(errorMessage);
168             throw new ApexParameterRuntimeException(errorMessage);
169         }
170
171         return eventProtocolParameters;
172     }
173 }