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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.context.impl.schema.java;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonElement;
27 import java.lang.reflect.Constructor;
28 import java.util.HashMap;
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;
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.
47 * @author Liam Fallon (liam.fallon@ericsson.com)
49 public class JavaSchemaHelper extends AbstractSchemaHelper {
50 // Get a reference to the logger
51 private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavaSchemaHelper.class);
53 // This map defines the built in types in types in Java
55 private static final Map<String, Class<?>> BUILT_IN_MAP = new HashMap<>();
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);
74 public void init(final AxKey userKey, final AxContextSchema schema) {
75 super.init(userKey, schema);
77 final String javatype = schema.getSchema();
78 // For Java, the schema is the Java class canonical path
81 setSchemaClass(TypeBuilder.getJavaTypeClass(schema.getSchema()));
82 } catch (final IllegalArgumentException e) {
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.";
89 resultSting += " Check the class path of the JVM";
91 LOGGER.warn(resultSting);
92 throw new ContextRuntimeException(resultSting, e);
100 public Object createNewInstance(final Object incomingObject) {
101 if (incomingObject == null) {
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);
112 if (incomingObject instanceof JsonElement) {
113 final String elementJsonString = getGson().toJson((JsonElement) incomingObject);
114 return getGson().fromJson(elementJsonString, this.getSchemaClass());
117 if (getSchemaClass().isAssignableFrom(incomingObject.getClass())) {
118 return incomingObject;
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);
133 public Object unmarshal(final Object object) {
134 if (object == null) {
138 // If the object is an instance of the incoming object, carry on
139 if (object.getClass().equals(getSchemaClass())) {
143 // For numeric types, do a numeric conversion
144 if (Number.class.isAssignableFrom(getSchemaClass())) {
145 return numericConversion(object);
148 if (getSchemaClass().isAssignableFrom(object.getClass())) {
151 return stringConversion(object);
159 public String marshal2String(final Object schemaObject) {
160 if (schemaObject == null) {
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);
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);
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());
187 * Do a numeric conversion between numeric types.
189 * @param object The incoming numeric object
190 * @return The converted object
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();
210 // OK, we'll try and convert from a string representation of the incoming object
211 return stringConversion(object);
215 * Do a string conversion to the class type.
217 * @param object The incoming numeric object
218 * @return The converted object
220 private Object stringConversion(final Object object) {
221 // OK, we'll try and convert from a string representation of the incoming object
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);
235 * Get a GSON instance that has the correct adaptation included.
237 * @return the GSON instance
239 private Gson getGson() {
240 GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
242 // Get the Java schema helper parameters from the parameter service
243 SchemaParameters schemaParameters = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
245 JavaSchemaHelperParameters javaSchemaHelperParmeters = (JavaSchemaHelperParameters) schemaParameters
246 .getSchemaHelperParameterMap().get("Java");
248 if (javaSchemaHelperParmeters == null) {
249 javaSchemaHelperParmeters = new JavaSchemaHelperParameters();
252 for (JavaSchemaHelperJsonAdapterParameters jsonAdapterEntry : javaSchemaHelperParmeters.getJsonAdapters()
255 Object adapterObject;
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);
266 gsonBuilder.registerTypeAdapter(jsonAdapterEntry.getAdaptedClazz(), adapterObject);
269 return gsonBuilder.create();