aboutsummaryrefslogtreecommitdiffstats
path: root/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java
blob: 9d087bf31c3d1d5e34c5bde6a1e54037126e544b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.service.parameters.eventprotocol;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters;
import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters;
import org.onap.policy.apex.service.parameters.ApexParameterRuntimeException;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * This class serialises and deserialises various type of event protocol parameters to and from
 * JSON.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class EventProtocolParametersJSONAdapter
        implements JsonSerializer<EventProtocolParameters>, JsonDeserializer<EventProtocolParameters> {
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJSONAdapter.class);

    private static final String PARAMETER_CLASS_NAME = "parameterClassName";

    private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol";
    private static final String EVENT_PROTOCOL_PARAMETERS = "parameters";

    // Built in event protocol parameters
    private static final Map<String, String> BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP = new HashMap<>();
    
    static {
        BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName());
        BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName());
    }

    /*
     * (non-Javadoc)
     *
     * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type,
     * com.google.gson.JsonSerializationContext)
     */
    @Override
    public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc,
            final JsonSerializationContext context) {
        final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported";
        LOGGER.error(returnMessage);
        throw new ApexParameterRuntimeException(returnMessage);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement,
     * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
     */
    @Override
    public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT,
            final JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();

        // Get the event protocol label primitive
        final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN);

        // Check if we found our event protocol
        if (labelJsonPrimitive == null) {
            LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file");
            return null;
        }

        // Get and check the event protocol label
        final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", "");
        if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) {
            final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" value \""
                    + labelJsonPrimitive.getAsString() + "\" invalid in JSON file";
            LOGGER.warn(errorMessage);
            throw new ApexParameterRuntimeException(errorMessage);
        }

        // We now get the event protocol parameter class
        String eventProtocolParameterClassName = null;

        // Get the event protocol parameter class for the event protocol plugin class from the
        // configuration parameters
        final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME);

        // If no event protocol parameter class was specified, we use the default
        if (classNameJsonPrimitive == null) {
            eventProtocolParameterClassName = BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel);
        } else {
            // We use the specified one
            eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", "");
        }

        // Check the event protocol parameter class
        if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) {
            final String errorMessage =
                    "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \""
                            + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null")
                            + "\" invalid in JSON file";
            LOGGER.warn(errorMessage);
            throw new ApexParameterRuntimeException(errorMessage);
        }

        // Get the class for the event protocol
        Class<?> eventProtocolParameterClass = null;
        try {
            eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName);
        } catch (final ClassNotFoundException e) {
            final String errorMessage =
                    "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \""
                            + eventProtocolParameterClassName + "\", could not find class";
            LOGGER.warn(errorMessage, e);
            throw new ApexParameterRuntimeException(errorMessage, e);
        }

        // Deserialise the class
        EventProtocolParameters eventProtocolParameters =
                context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass);
        if (eventProtocolParameters == null) {
            // OK no parameters for the event protocol have been specified, just instantiate the
            // default parameters
            try {
                eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance();
            } catch (final Exception e) {
                final String errorMessage = "could not create default parameters for event protocol \""
                        + eventProtocolLabel + "\"\n" + e.getMessage();
                LOGGER.warn(errorMessage, e);
                throw new ApexParameterRuntimeException(errorMessage, e);
            }
        }

        // Check that the event protocol label matches the label in the event protocol parameters
        // object
        if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) {
            final String errorMessage = "event protocol \"" + eventProtocolLabel + "\" does not match plugin \""
                    + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName
                    + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME
                    + "\"";
            LOGGER.warn(errorMessage);
            throw new ApexParameterRuntimeException(errorMessage);
        }

        return eventProtocolParameters;
    }
}