2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019 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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.context.impl.schema.java;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonElement;
28 import java.lang.reflect.Constructor;
29 import java.util.HashMap;
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;
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.
48 * @author Liam Fallon (liam.fallon@ericsson.com)
50 public class JavaSchemaHelper extends AbstractSchemaHelper {
51 // Get a reference to the logger
52 private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavaSchemaHelper.class);
54 // This map defines the built in types in types in Java
56 private static final Map<String, Class<?>> BUILT_IN_MAP = new HashMap<>();
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);
75 public void init(final AxKey userKey, final AxContextSchema schema) {
76 super.init(userKey, schema);
78 final String javatype = schema.getSchema();
79 // For Java, the schema is the Java class canonical path
82 setSchemaClass(TypeBuilder.getJavaTypeClass(schema.getSchema()));
83 } catch (final IllegalArgumentException e) {
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.";
90 resultSting += " Check the class path of the JVM";
92 LOGGER.warn(resultSting);
93 throw new ContextRuntimeException(resultSting, e);
101 public Object createNewInstance(final Object incomingObject) {
102 if (incomingObject == null) {
106 if (getSchemaClass() == null) {
107 final String returnString = getUserKey().getId()
108 + ": could not create an instance, schema class for the schema is null";
109 LOGGER.warn(returnString);
110 throw new ContextRuntimeException(returnString);
113 if (incomingObject instanceof JsonElement) {
114 final String elementJsonString = getGson().toJson((JsonElement) incomingObject);
115 return getGson().fromJson(elementJsonString, this.getSchemaClass());
118 if (getSchemaClass().isAssignableFrom(incomingObject.getClass())) {
119 return incomingObject;
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()
126 LOGGER.warn(returnString);
127 throw new ContextRuntimeException(returnString);
134 public Object unmarshal(final Object object) {
135 if (object == null) {
139 // If the object is an instance of the incoming object, carry on
140 if (object.getClass().equals(getSchemaClass())) {
144 // For numeric types, do a numeric conversion
145 if (Number.class.isAssignableFrom(getSchemaClass())) {
146 return numericConversion(object);
149 if (getSchemaClass().isAssignableFrom(object.getClass())) {
152 return stringConversion(object);
160 public String marshal2String(final Object schemaObject) {
161 if (schemaObject == null) {
165 // Check the incoming object is of a correct class
166 if (getSchemaClass().isAssignableFrom(schemaObject.getClass())) {
167 // Use Gson to translate the object
168 return getGson().toJson(schemaObject);
170 final String returnString = getUserKey().getId() + ": object \"" + schemaObject.toString()
171 + "\" of class \"" + schemaObject.getClass().getName() + "\" not compatible with class \""
172 + getSchemaClass().getName() + "\"";
173 LOGGER.warn(returnString);
174 throw new ContextRuntimeException(returnString);
182 public Object marshal2Object(final Object schemaObject) {
183 // Use Gson to marshal the schema object into a Json element to return
184 return getGson().toJsonTree(schemaObject, getSchemaClass());
188 * Do a numeric conversion between numeric types.
190 * @param object The incoming numeric object
191 * @return The converted object
193 private Object numericConversion(final Object object) {
194 // Check if the incoming object is a number, if not do a string conversion
195 if (object instanceof Number) {
196 if (getSchemaClass().isAssignableFrom(Byte.class)) {
197 return ((Number) object).byteValue();
198 } else if (getSchemaClass().isAssignableFrom(Short.class)) {
199 return ((Number) object).shortValue();
200 } else if (getSchemaClass().isAssignableFrom(Integer.class)) {
201 return ((Number) object).intValue();
202 } else if (getSchemaClass().isAssignableFrom(Long.class)) {
203 return ((Number) object).longValue();
204 } else if (getSchemaClass().isAssignableFrom(Float.class)) {
205 return ((Number) object).floatValue();
206 } else if (getSchemaClass().isAssignableFrom(Double.class)) {
207 return ((Number) object).doubleValue();
211 // OK, we'll try and convert from a string representation of the incoming object
212 return stringConversion(object);
216 * Do a string conversion to the class type.
218 * @param object The incoming numeric object
219 * @return The converted object
221 private Object stringConversion(final Object object) {
222 // OK, we'll try and convert from a string representation of the incoming object
224 final Constructor<?> stringConstructor = getSchemaClass().getConstructor(String.class);
225 return stringConstructor.newInstance(object.toString());
226 } catch (final Exception e) {
227 final String returnString = getUserKey().getId() + ": object \"" + object.toString() + "\" of class \""
228 + object.getClass().getName() + "\" not compatible with class \""
229 + getSchemaClass().getName() + "\"";
230 LOGGER.warn(returnString, e);
231 throw new ContextRuntimeException(returnString);
236 * Get a GSON instance that has the correct adaptation included.
238 * @return the GSON instance
240 private Gson getGson() {
241 GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
243 // Get the Java schema helper parameters from the parameter service
244 SchemaParameters schemaParameters = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
246 JavaSchemaHelperParameters javaSchemaHelperParmeters = (JavaSchemaHelperParameters) schemaParameters
247 .getSchemaHelperParameterMap().get("Java");
249 if (javaSchemaHelperParmeters == null) {
250 javaSchemaHelperParmeters = new JavaSchemaHelperParameters();
253 for (JavaSchemaHelperJsonAdapterParameters jsonAdapterEntry : javaSchemaHelperParmeters.getJsonAdapters()
256 Object adapterObject;
258 adapterObject = jsonAdapterEntry.getAdaptorClazz().newInstance();
259 } catch (InstantiationException | IllegalAccessException e) {
260 final String returnString = getUserKey().getId() + ": instantiation of adapter class \""
261 + jsonAdapterEntry.getAdaptorClass() + "\" to decode and encode class \""
262 + jsonAdapterEntry.getAdaptedClass() + "\" failed: " + e.getMessage();
263 LOGGER.warn(returnString, e);
264 throw new ContextRuntimeException(returnString);
267 gsonBuilder.registerTypeAdapter(jsonAdapterEntry.getAdaptedClazz(), adapterObject);
270 return gsonBuilder.create();