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