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