b4cc3860258f98597f2985dc9d3ea2d42507c26f
[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.plugins.context.schema.avro;
22
23 import java.io.ByteArrayOutputStream;
24
25 import org.apache.avro.Schema;
26 import org.apache.avro.generic.GenericDatumReader;
27 import org.apache.avro.generic.GenericDatumWriter;
28 import org.apache.avro.generic.GenericRecord;
29 import org.apache.avro.io.DatumWriter;
30 import org.apache.avro.io.DecoderFactory;
31 import org.apache.avro.io.EncoderFactory;
32 import org.apache.avro.io.JsonDecoder;
33 import org.apache.avro.io.JsonEncoder;
34 import org.onap.policy.apex.context.ContextRuntimeException;
35 import org.onap.policy.apex.context.impl.schema.AbstractSchemaHelper;
36 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
37 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
38 import org.slf4j.ext.XLogger;
39 import org.slf4j.ext.XLoggerFactory;
40
41 import com.google.gson.Gson;
42 import com.google.gson.GsonBuilder;
43 import com.google.gson.JsonElement;
44
45 /**
46  * This class is the implementation of the {@link org.onap.policy.apex.context.SchemaHelper}
47  * interface for Avro schemas.
48  *
49  * @author Liam Fallon (liam.fallon@ericsson.com)
50  */
51 public class AvroSchemaHelper extends AbstractSchemaHelper {
52     // Get a reference to the logger
53     private static final XLogger LOGGER = XLoggerFactory.getXLogger(AvroSchemaHelper.class);
54
55     // The Avro schema for this context schema
56     private Schema avroSchema;
57
58     // The mapper that translates between Java and Avro objects
59     private AvroObjectMapper avroObjectMapper;
60
61     @Override
62     public void init(final AxKey userKey, final AxContextSchema schema) throws ContextRuntimeException {
63         super.init(userKey, schema);
64
65         // Configure the Avro schema
66         try {
67             avroSchema = new Schema.Parser().parse(schema.getSchema());
68         } catch (final Exception e) {
69             final String resultSting = userKey.getID() + ": avro context schema \"" + schema.getID()
70                     + "\" schema is invalid: " + e.getMessage() + ", schema: " + schema.getSchema();
71             LOGGER.warn(resultSting);
72             throw new ContextRuntimeException(resultSting);
73         }
74
75         // Get the object mapper for the schema type to a Java class
76         avroObjectMapper = new AvroObjectMapperFactory().get(userKey, avroSchema);
77
78         // Get the Java type for this schema, if it is a primitive type then we can do direct
79         // conversion to JAva
80         setSchemaClass(avroObjectMapper.getJavaClass());
81     }
82
83     /**
84      * Getter to get the Avro schema.
85      *
86      * @return the Avro schema
87      */
88     public Schema getAvroSchema() {
89         return avroSchema;
90     }
91
92     @Override
93     public Object getSchemaObject() {
94         return avroSchema;
95     }
96
97     @Override
98     public Object createNewInstance() {
99         // Create a new instance using the Avro object mapper
100         final Object newInstance = avroObjectMapper.createNewInstance(avroSchema);
101
102         // If no new instance is created, use default schema handler behavior
103         if (newInstance != null) {
104             return newInstance;
105         } else {
106             return super.createNewInstance();
107         }
108     }
109
110     @Override
111     public Object createNewInstance(final String stringValue) {
112         return unmarshal(stringValue);
113     }
114
115     @Override
116     public Object createNewInstance(final JsonElement jsonElement) {
117         final Gson gson = new GsonBuilder().serializeNulls().create();
118         final String elementJsonString = gson.toJson(jsonElement);
119
120         return createNewInstance(elementJsonString);
121     }
122
123     @Override
124     public Object unmarshal(final Object object) {
125         // If an object is already in the correct format, just carry on
126         if (passThroughObject(object)) {
127             return object;
128         }
129
130         String objectString = getStringObject(object);
131
132         // Translate illegal characters in incoming JSON keys to legal Avro values
133         objectString = AvroSchemaKeyTranslationUtilities.translateIllegalKeys(objectString, false);
134
135         // Decode the object
136         Object decodedObject;
137         try {
138             final JsonDecoder jsonDecoder = DecoderFactory.get().jsonDecoder(avroSchema, objectString);
139             decodedObject = new GenericDatumReader<GenericRecord>(avroSchema).read(null, jsonDecoder);
140         } catch (final Exception e) {
141             final String returnString = getUserKey().getID() + ": object \"" + objectString
142                     + "\" Avro unmarshalling failed: " + e.getMessage();
143             LOGGER.warn(returnString, e);
144             throw new ContextRuntimeException(returnString, e);
145         }
146
147         // Now map the decoded object into something we can handle
148         return avroObjectMapper.mapFromAvro(decodedObject);
149     }
150
151     /**
152      * Check that the incoming object is a string, the incoming object must be a string containing
153      * Json
154      * 
155      * @param object incoming object
156      * @return object as String
157      */
158     private String getStringObject(final Object object) {
159         try {
160             if (isObjectString(object)) {
161                 String objectString = object.toString().trim();
162                 if (objectString.length() == 0) {
163                     return "\"\"";
164                 } else if (objectString.length() == 1) {
165                     return "\"" + objectString + "\"";
166                 } else {
167                     // All strings must be quoted for decoding
168                     if (objectString.charAt(0) != '"') {
169                         objectString = '"' + objectString;
170                     }
171                     if (objectString.charAt(objectString.length() - 1) != '"') {
172                         objectString += '"';
173                     }
174                 }
175                 return objectString;
176             } else {
177                 return (String) object;
178             }
179         } catch (final ClassCastException e) {
180             final String returnString = getUserKey().getID() + ": object \"" + object + "\" of type \""
181                     + (object != null ? object.getClass().getCanonicalName() : "null") + "\" must be assignable to \""
182                     + getSchemaClass().getCanonicalName()
183                     + "\" or be a Json string representation of it for Avro unmarshalling";
184             LOGGER.warn(returnString);
185             throw new ContextRuntimeException(returnString);
186         }
187     }
188
189     private boolean isObjectString(final Object object) {
190         return object != null && avroSchema.getType().equals(Schema.Type.STRING);
191     }
192
193     @Override
194     public String marshal2Json(final Object object) {
195         // Condition the object for Avro encoding
196         final Object conditionedObject = avroObjectMapper.mapToAvro(object);
197
198         final String jsonString = getJsonString(object, conditionedObject);
199
200         return AvroSchemaKeyTranslationUtilities.translateIllegalKeys(jsonString, true);
201     }
202
203     private String getJsonString(final Object object, final Object conditionedObject) {
204
205         try (final ByteArrayOutputStream output = new ByteArrayOutputStream();) {
206             final DatumWriter<Object> writer = new GenericDatumWriter<>(avroSchema);
207             final JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(avroSchema, output, true);
208             writer.write(conditionedObject, jsonEncoder);
209             jsonEncoder.flush();
210             return new String(output.toByteArray());
211         } catch (final Exception e) {
212             final String returnString =
213                     getUserKey().getID() + ": object \"" + object + "\" Avro marshalling failed: " + e.getMessage();
214             LOGGER.warn(returnString);
215             throw new ContextRuntimeException(returnString, e);
216         }
217     }
218
219     @Override
220     public JsonElement marshal2JsonElement(final Object schemaObject) {
221         // Get the object as a Json string
222         final String schemaObjectAsString = marshal2Json(schemaObject);
223
224         // Get a Gson instance to convert the Json string to an object created by Json
225         final Gson gson = new Gson();
226
227         // Convert the Json string into an object
228         final Object schemaObjectAsObject = gson.fromJson(schemaObjectAsString, Object.class);
229
230         return gson.toJsonTree(schemaObjectAsObject);
231     }
232
233     /**
234      * Check if we can pass this object straight through encoding or decoding, is it an object
235      * native to the schema.
236      *
237      * @param object the object to check
238      * @return true if it's a straight pass through
239      */
240     private boolean passThroughObject(final Object object) {
241         if (object == null || getSchemaClass() == null) {
242             return false;
243         }
244
245         // All strings must be mapped
246         if (object instanceof String) {
247             return false;
248         }
249
250         // Now, check if the object is native
251         return getSchemaClass().isAssignableFrom(object.getClass());
252     }
253 }