0a119cdc7f3c5f0622ee48ebb8dbec54feeb2590
[policy/apex-pdp.git] / tools / model-generator / src / main / java / org / onap / policy / apex / tools / model / generator / SchemaUtils.java
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.tools.model.generator;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import org.apache.avro.AvroRuntimeException;
30 import org.apache.avro.Schema;
31 import org.apache.avro.Schema.Field;
32 import org.apache.avro.reflect.ReflectData;
33 import org.onap.policy.apex.context.SchemaHelper;
34 import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
35 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
36 import org.onap.policy.apex.model.eventmodel.concepts.AxField;
37 import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelper;
38 import org.onap.policy.apex.service.engine.event.ApexEventException;
39
40 /**
41  * Utility methods for schema handling.
42  *
43  * @author John Keeney (john.keeney@ericsson.com)
44  */
45 public final class SchemaUtils {
46
47     /**
48      * Private constructor to avoid instantiation.
49      */
50     private SchemaUtils() {
51         // Private constructor to block subclassing
52     }
53
54     /**
55      * Returns the schema for an event.
56      *
57      * @param event the event to process
58      * @return the schema of the event
59      * @throws ApexEventException in any error case
60      */
61     public static Schema getEventSchema(final AxEvent event) throws ApexEventException {
62         final Schema skeletonSchema = Schema.createRecord(event.getKey().getName(), event.getNameSpace(),
63                 "org.onap.policy.apex.model.eventmodel.events", false);
64
65         // Get the schema field for each parameter
66         final List<Field> fields = new ArrayList<>(getSkeletonEventSchemaFields());
67
68         final Map<String, Schema> preExistingParamSchemas = new LinkedHashMap<>();
69         for (final AxField parameter : event.getParameterMap().values()) {
70             final Schema fieldSchema = getEventParameterSchema(parameter, preExistingParamSchemas);
71             final Field f = new Field(parameter.getKey().getLocalName(), fieldSchema, (String) null, (Object) null);
72             fields.add(f);
73         }
74         skeletonSchema.setFields(fields);
75
76         return skeletonSchema;
77     }
78
79     /**
80      * Returns the schema fields as an array.
81      *
82      * @return an array with schema fields in the following order: nameSpace, name, version, source, target
83      */
84     public static List<Field> getSkeletonEventSchemaFields() {
85         // Fixed fields
86         final Field f1 = new Field("nameSpace", Schema.create(Schema.Type.STRING), (String) null, (Object) null);
87         final Field f2 = new Field("name", Schema.create(Schema.Type.STRING), (String) null, (Object) null);
88         final Field f3 = new Field("version", Schema.create(Schema.Type.STRING), (String) null, (Object) null);
89         final Field f4 = new Field("source", Schema.create(Schema.Type.STRING), (String) null, (Object) null);
90         final Field f5 = new Field("target", Schema.create(Schema.Type.STRING), (String) null, (Object) null);
91
92         return Arrays.asList(f1, f2, f3, f4, f5);
93     }
94
95     /**
96      * Returns the schema for an event parameter.
97      *
98      * @param parameter the parameter to process
99      * @param preexistingParamSchemas map of pre-existing schemas
100      * @return the schema for the event parameter
101      * @throws ApexEventException in case of any error
102      */
103     public static Schema getEventParameterSchema(final AxField parameter,
104             final Map<String, Schema> preexistingParamSchemas) throws ApexEventException {
105         final SchemaHelper schemaHelper =
106                 new SchemaHelperFactory().createSchemaHelper(parameter.getKey(), parameter.getSchema().getKey());
107
108         Schema parameterSchema = null;
109         try {
110             if (schemaHelper instanceof AvroSchemaHelper) {
111                 parameterSchema = ((AvroSchemaHelper) schemaHelper).getAvroSchema();
112             } else {
113                 parameterSchema = ReflectData.get().getSchema(schemaHelper.getSchemaClass());
114             }
115         } catch (final AvroRuntimeException e) {
116             throw new ApexEventException("failed to decode a schema for parameter " + parameter.getKey().getLocalName()
117                     + " of type " + parameter.getSchema().getId() + " with Java type " + schemaHelper.getSchemaClass(),
118                     e);
119         }
120         final String schemaname = parameterSchema.getFullName();
121
122         // Get the Avro schema for this parameter, we need to keep track of sub-schemas for records because Avro does
123         // not
124         // allow re-declaration of sub-schema records of the same type. You simply reference the first sub-schema.
125         final Schema alreadyseen = preexistingParamSchemas.get(schemaname);
126
127         try {
128             processSubSchemas(parameterSchema, preexistingParamSchemas);
129         } catch (AvroRuntimeException | ApexEventException e) {
130             throw new ApexEventException("failed to decode a schema for parameter " + parameter.getKey().getLocalName()
131                     + " of type " + parameter.getSchema().getId() + " using Schema type " + schemaname, e);
132         }
133         if (alreadyseen != null) {
134             parameterSchema = alreadyseen;
135         }
136
137         return parameterSchema;
138     }
139
140     /**
141      * Processes a sub-schema.
142      *
143      * @param avroParameterSchema an AVRO schema to process
144      * @param map mapping of strings to schemas
145      * @throws ApexEventException in case of any error
146      */
147     public static void processSubSchemas(final Schema avroParameterSchema, final Map<String, Schema> map)
148             throws ApexEventException {
149         if (avroParameterSchema.getType() == Schema.Type.RECORD) {
150             final String schematypename = avroParameterSchema.getFullName();
151             final Schema alreadyregistered = map.get(schematypename);
152             if (alreadyregistered != null && !avroParameterSchema.equals(alreadyregistered)) {
153                 throw new ApexEventException(
154                         "Parameter attempts to redefine type " + schematypename + " when it has already been defined");
155             }
156             map.put(schematypename, avroParameterSchema);
157             for (final Schema.Field f : avroParameterSchema.getFields()) {
158                 final Schema fieldschema = f.schema();
159                 processSubSchemas(fieldschema, map);
160             }
161         } else if (avroParameterSchema.getType() == Schema.Type.ARRAY) {
162             processSubSchemas(avroParameterSchema.getElementType(), map);
163         } else if (avroParameterSchema.getType() == Schema.Type.MAP) {
164             processSubSchemas(avroParameterSchema.getValueType(), map);
165         } else if (avroParameterSchema.getType() == Schema.Type.UNION) {
166             for (final Schema s : avroParameterSchema.getTypes()) {
167                 processSubSchemas(s, map);
168             }
169         }
170     }
171
172 }