e4cdd0fdcc0c09e61ed43079202c8ec624d73233
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-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.context.impl.schema.java;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonElement;
27
28 import java.lang.reflect.Constructor;
29 import java.util.HashMap;
30 import java.util.Map;
31
32 import org.onap.policy.apex.context.ContextRuntimeException;
33 import org.onap.policy.apex.context.impl.schema.AbstractSchemaHelper;
34 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
35 import org.onap.policy.apex.context.parameters.SchemaParameters;
36 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
37 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
38 import org.onap.policy.apex.model.utilities.typeutils.TypeBuilder;
39 import org.onap.policy.common.parameters.ParameterService;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
42
43 /**
44  * This class implements translation to and from Apex distributed objects and Java objects when a Java schema is used.
45  * It creates schema items as Java objects and marshals and unmarshals these objects in various formats. All objects
46  * must be of the type of Java class defined in the schema.
47  *
48  * @author Liam Fallon (liam.fallon@ericsson.com)
49  */
50 public class JavaSchemaHelper extends AbstractSchemaHelper {
51     // Get a reference to the logger
52     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavaSchemaHelper.class);
53
54     // This map defines the built in types in types in Java
55     // @formatter:off
56     private static final Map<String, Class<?>> BUILT_IN_MAP = new HashMap<>();
57
58     static {
59         BUILT_IN_MAP.put("int",    Integer  .TYPE);
60         BUILT_IN_MAP.put("long",   Long     .TYPE);
61         BUILT_IN_MAP.put("double", Double   .TYPE);
62         BUILT_IN_MAP.put("float",  Float    .TYPE);
63         BUILT_IN_MAP.put("bool",   Boolean  .TYPE);
64         BUILT_IN_MAP.put("char",   Character.TYPE);
65         BUILT_IN_MAP.put("byte",   Byte     .TYPE);
66         BUILT_IN_MAP.put("void",   Void     .TYPE);
67         BUILT_IN_MAP.put("short",  Short    .TYPE);
68     }
69     // @formatter:on
70
71     /**
72      * {@inheritDoc}.
73      */
74     @Override
75     public void init(final AxKey userKey, final AxContextSchema schema) {
76         super.init(userKey, schema);
77
78         final String javatype = schema.getSchema();
79         // For Java, the schema is the Java class canonical path
80
81         try {
82             setSchemaClass(TypeBuilder.getJavaTypeClass(schema.getSchema()));
83         } catch (final IllegalArgumentException e) {
84
85             String resultSting = userKey.getId() + ": class/type " + schema.getSchema() + " for context schema \""
86                     + schema.getId() + "\" not found.";
87             if (JavaSchemaHelper.BUILT_IN_MAP.get(javatype) != null) {
88                 resultSting += " Primitive types are not supported. Use the appropriate Java boxing type instead.";
89             } else {
90                 resultSting += " Check the class path of the JVM";
91             }
92             LOGGER.warn(resultSting);
93             throw new ContextRuntimeException(resultSting, e);
94         }
95     }
96
97     /**
98      * {@inheritDoc}.
99      */
100     @Override
101     public Object createNewInstance(final Object incomingObject) {
102         if (incomingObject == null) {
103             return null;
104         }
105
106         if (getSchemaClass() == null) {
107             final String returnString =
108                     getUserKey().getId() + ": could not create an instance, schema class for the schema is null";
109             LOGGER.warn(returnString);
110             throw new ContextRuntimeException(returnString);
111         }
112
113         if (incomingObject instanceof JsonElement) {
114             final String elementJsonString = getGson().toJson((JsonElement) incomingObject);
115             return getGson().fromJson(elementJsonString, this.getSchemaClass());
116         }
117
118         if (getSchemaClass().isAssignableFrom(incomingObject.getClass())) {
119             return incomingObject;
120         }
121
122         final String returnString = getUserKey().getId() + ": the object \"" + incomingObject + "\" of type \""
123                 + incomingObject.getClass().getName()
124                 + "\" is not an instance of JsonObject and is not assignable to \"" + getSchemaClass().getName() + "\"";
125         LOGGER.warn(returnString);
126         throw new ContextRuntimeException(returnString);
127     }
128
129     /**
130      * {@inheritDoc}.
131      */
132     @Override
133     public Object unmarshal(final Object object) {
134         if (object == null) {
135             return null;
136         }
137
138         // If the object is an instance of the incoming object, carry on
139         if (object.getClass().equals(getSchemaClass())) {
140             return object;
141         }
142
143         // For numeric types, do a numeric conversion
144         if (Number.class.isAssignableFrom(getSchemaClass())) {
145             return numericConversion(object);
146         }
147
148         if (getSchemaClass().isAssignableFrom(object.getClass())) {
149             return object;
150         } else {
151             return stringConversion(object);
152         }
153     }
154
155     /**
156      * {@inheritDoc}.
157      */
158     @Override
159     public String marshal2String(final Object schemaObject) {
160         if (schemaObject == null) {
161             return "null";
162         }
163
164         // Check the incoming object is of a correct class
165         if (getSchemaClass().isAssignableFrom(schemaObject.getClass())) {
166             // Use Gson to translate the object
167             return getGson().toJson(schemaObject);
168         } else {
169             final String returnString = getUserKey().getId() + ": object \"" + schemaObject.toString()
170                     + "\" of class \"" + schemaObject.getClass().getName() + "\" not compatible with class \""
171                     + getSchemaClass().getName() + "\"";
172             LOGGER.warn(returnString);
173             throw new ContextRuntimeException(returnString);
174         }
175     }
176
177     /**
178      * {@inheritDoc}.
179      */
180     @Override
181     public Object marshal2Object(final Object schemaObject) {
182         // Use Gson to marshal the schema object into a Json element to return
183         return getGson().toJsonTree(schemaObject, getSchemaClass());
184     }
185
186     /**
187      * Do a numeric conversion between numeric types.
188      *
189      * @param object The incoming numeric object
190      * @return The converted object
191      */
192     private Object numericConversion(final Object object) {
193         // Check if the incoming object is a number, if not do a string conversion
194         if (object instanceof Number) {
195             if (getSchemaClass().isAssignableFrom(Byte.class)) {
196                 return ((Number) object).byteValue();
197             } else if (getSchemaClass().isAssignableFrom(Short.class)) {
198                 return ((Number) object).shortValue();
199             } else if (getSchemaClass().isAssignableFrom(Integer.class)) {
200                 return ((Number) object).intValue();
201             } else if (getSchemaClass().isAssignableFrom(Long.class)) {
202                 return ((Number) object).longValue();
203             } else if (getSchemaClass().isAssignableFrom(Float.class)) {
204                 return ((Number) object).floatValue();
205             } else if (getSchemaClass().isAssignableFrom(Double.class)) {
206                 return ((Number) object).doubleValue();
207             }
208         }
209
210         // OK, we'll try and convert from a string representation of the incoming object
211         return stringConversion(object);
212     }
213
214     /**
215      * Do a string conversion to the class type.
216      *
217      * @param object The incoming numeric object
218      * @return The converted object
219      */
220     private Object stringConversion(final Object object) {
221         // OK, we'll try and convert from a string representation of the incoming object
222         try {
223             final Constructor<?> stringConstructor = getSchemaClass().getConstructor(String.class);
224             return stringConstructor.newInstance(object.toString());
225         } catch (final Exception e) {
226             final String returnString = getUserKey().getId() + ": object \"" + object.toString() + "\" of class \""
227                     + object.getClass().getName() + "\" not compatible with class \"" + getSchemaClass().getName()
228                     + "\"";
229             LOGGER.warn(returnString, e);
230             throw new ContextRuntimeException(returnString);
231         }
232     }
233
234     /**
235      * Get a GSON instance that has the correct adaptation included.
236      *
237      * @return the GSON instance
238      */
239     private Gson getGson() {
240         GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
241
242         // Get the Java schema helper parameters from the parameter service
243         SchemaParameters schemaParameters = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
244
245         JavaSchemaHelperParameters javaSchemaHelperParmeters =
246                 (JavaSchemaHelperParameters) schemaParameters.getSchemaHelperParameterMap().get("Java");
247
248         if (javaSchemaHelperParmeters == null) {
249             javaSchemaHelperParmeters = new JavaSchemaHelperParameters();
250         }
251
252         for (JavaSchemaHelperJsonAdapterParameters jsonAdapterEntry : javaSchemaHelperParmeters.getJsonAdapters()
253                 .values()) {
254
255             Object adapterObject;
256             try {
257                 adapterObject = jsonAdapterEntry.getAdaptorClazz().getDeclaredConstructor().newInstance();
258             } catch (Exception e) {
259                 final String returnString = getUserKey().getId() + ": instantiation of adapter class \""
260                         + jsonAdapterEntry.getAdaptorClass() + "\"  to decode and encode class \""
261                         + jsonAdapterEntry.getAdaptedClass() + "\" failed: " + e.getMessage();
262                 LOGGER.warn(returnString, e);
263                 throw new ContextRuntimeException(returnString);
264             }
265
266             gsonBuilder.registerTypeAdapter(jsonAdapterEntry.getAdaptedClazz(), adapterObject);
267         }
268
269         return gsonBuilder.create();
270     }
271 }