a8fedf24a981c6a511e41ae42beefa91988c1413
[policy/apex-pdp.git] /
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.context.impl.schema.java;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonElement;
26
27 import java.lang.reflect.Constructor;
28 import java.util.HashMap;
29 import java.util.Map;
30
31 import org.onap.policy.apex.context.ContextRuntimeException;
32 import org.onap.policy.apex.context.impl.schema.AbstractSchemaHelper;
33 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
34 import org.onap.policy.apex.context.parameters.SchemaParameters;
35 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
36 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
37 import org.onap.policy.apex.model.utilities.typeutils.TypeBuilder;
38 import org.onap.policy.common.parameters.ParameterService;
39 import org.slf4j.ext.XLogger;
40 import org.slf4j.ext.XLoggerFactory;
41
42 /**
43  * This class implements translation to and from Apex distributed objects and Java objects when a Java schema is used.
44  * It creates schema items as Java objects and marshals and unmarshals these objects in various formats. All objects
45  * must be of the type of Java class defined in the schema.
46  *
47  * @author Liam Fallon (liam.fallon@ericsson.com)
48  */
49 public class JavaSchemaHelper extends AbstractSchemaHelper {
50     // Get a reference to the logger
51     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavaSchemaHelper.class);
52
53     // This map defines the built in types in types in Java
54     // @formatter:off
55     private static final Map<String, Class<?>> BUILT_IN_MAP = new HashMap<>();
56
57     static {
58         BUILT_IN_MAP.put("int",    Integer  .TYPE);
59         BUILT_IN_MAP.put("long",   Long     .TYPE);
60         BUILT_IN_MAP.put("double", Double   .TYPE);
61         BUILT_IN_MAP.put("float",  Float    .TYPE);
62         BUILT_IN_MAP.put("bool",   Boolean  .TYPE);
63         BUILT_IN_MAP.put("char",   Character.TYPE);
64         BUILT_IN_MAP.put("byte",   Byte     .TYPE);
65         BUILT_IN_MAP.put("void",   Void     .TYPE);
66         BUILT_IN_MAP.put("short",  Short    .TYPE);
67     }
68     // @formatter:on
69
70     /**
71      * {@inheritDoc}.
72      */
73     @Override
74     public void init(final AxKey userKey, final AxContextSchema schema) {
75         super.init(userKey, schema);
76
77         final String javatype = schema.getSchema();
78         // For Java, the schema is the Java class canonical path
79
80         try {
81             setSchemaClass(TypeBuilder.getJavaTypeClass(schema.getSchema()));
82         } catch (final IllegalArgumentException e) {
83
84             String resultSting = userKey.getId() + ": class/type " + schema.getSchema() + " for context schema \""
85                             + schema.getId() + "\" not found.";
86             if (JavaSchemaHelper.BUILT_IN_MAP.get(javatype) != null) {
87                 resultSting += " Primitive types are not supported. Use the appropriate Java boxing type instead.";
88             } else {
89                 resultSting += " Check the class path of the JVM";
90             }
91             LOGGER.warn(resultSting);
92             throw new ContextRuntimeException(resultSting, e);
93         }
94     }
95
96     /**
97      * {@inheritDoc}.
98      */
99     @Override
100     public Object createNewInstance(final Object incomingObject) {
101         if (incomingObject == null) {
102             return null;
103         }
104
105         if (getSchemaClass() == null) {
106             final String returnString = getUserKey().getId()
107                             + ": could not create an instance, schema class for the schema is null";
108             LOGGER.warn(returnString);
109             throw new ContextRuntimeException(returnString);
110         }
111
112         if (incomingObject instanceof JsonElement) {
113             final String elementJsonString = getGson().toJson((JsonElement) incomingObject);
114             return getGson().fromJson(elementJsonString, this.getSchemaClass());
115         }
116
117         if (getSchemaClass().isAssignableFrom(incomingObject.getClass())) {
118             return incomingObject;
119         }
120
121         final String returnString = getUserKey().getId() + ": the object \"" + incomingObject + "\" of type \""
122                         + incomingObject.getClass().getCanonicalName()
123                         + "\" is not an instance of JsonObject and is not assignable to \""
124                         + getSchemaClass().getCanonicalName() + "\"";
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().getCanonicalName()
171                             + "\" not compatible with class \"" + getSchemaClass().getCanonicalName() + "\"";
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().getCanonicalName() + "\" not compatible with class \""
228                             + getSchemaClass().getCanonicalName() + "\"";
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 = (JavaSchemaHelperParameters) schemaParameters
246                         .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().newInstance();
258             } catch (InstantiationException | IllegalAccessException 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 }