Changes for checkstyle 8.32
[policy/apex-pdp.git] / tools / model-generator / src / main / java / org / onap / policy / apex / tools / model / generator / model2event / Model2JsonEventSchema.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.model2event;
22
23 import java.util.HashSet;
24 import java.util.Properties;
25 import java.util.Set;
26 import org.apache.avro.Schema;
27 import org.apache.avro.Schema.Field;
28 import org.apache.avro.Schema.Type;
29 import org.apache.commons.lang3.Validate;
30 import org.onap.policy.apex.context.parameters.SchemaParameters;
31 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
32 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
33 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
34 import org.onap.policy.apex.model.modelapi.ApexApiResult;
35 import org.onap.policy.apex.model.modelapi.ApexModel;
36 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
37 import org.onap.policy.apex.model.policymodel.concepts.AxPolicies;
38 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
39 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
40 import org.onap.policy.apex.model.policymodel.concepts.AxState;
41 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
42 import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters;
43 import org.onap.policy.apex.service.engine.event.ApexEventException;
44 import org.onap.policy.apex.tools.model.generator.SchemaUtils;
45 import org.slf4j.ext.XLogger;
46 import org.slf4j.ext.XLoggerFactory;
47 import org.stringtemplate.v4.ST;
48 import org.stringtemplate.v4.STGroup;
49 import org.stringtemplate.v4.STGroupFile;
50
51 /**
52  * Takes a model and generates the JSON event schemas.
53  *
54  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
55  */
56 public class Model2JsonEventSchema {
57     // Logger for this class
58     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2JsonEventSchema.class);
59
60     // Recurring string constants
61     private static final String TARGET = "target";
62     private static final String SOURCE = "source";
63     private static final String VERSION = "version";
64     private static final String NAME_SPACE = "nameSpace";
65
66     /** Application name, used as prompt. */
67     private final String appName;
68
69     /** The file name of the policy model. */
70     private final String modelFile;
71
72     /** The type of events to generate: stimuli, response, internal. */
73     private final String type;
74
75     /**
76      * Creates a new model to event schema generator.
77      *
78      * @param modelFile the model file to be used
79      * @param type the type of events to generate, one of: stimuli, response, internal
80      * @param appName application name for printouts
81      */
82     public Model2JsonEventSchema(final String modelFile, final String type, final String appName) {
83         Validate.notNull(modelFile, "Model2JsonEvent: given model file name was blank");
84         Validate.notNull(type, "Model2JsonEvent: given type was blank");
85         Validate.notNull(appName, "Model2JsonEvent: given application name was blank");
86
87         this.modelFile = modelFile;
88         this.type = type;
89         this.appName = appName;
90     }
91
92     /**
93      * Adds a type to a field for a given schema.
94      *
95      * @param schema the schema to add a type for
96      * @param stg the STG
97      * @return a template with the type
98      */
99     protected ST addFieldType(final Schema schema, final STGroup stg) {
100         ST ret = null;
101
102         if (isSimpleType(schema.getType())) {
103             ret = stg.getInstanceOf("fieldTypeAtomic");
104             ret.add("type", schema.getType());
105             return ret;
106         }
107         
108         switch (schema.getType()) {
109             case ARRAY:
110                 ret = stg.getInstanceOf("fieldTypeArray");
111                 ret.add("array", this.addFieldType(schema.getElementType(), stg));
112                 break;
113             case ENUM:
114                 ret = stg.getInstanceOf("fieldTypeEnum");
115                 ret.add("symbols", schema.getEnumSymbols());
116                 break;
117
118             case MAP:
119                 ret = stg.getInstanceOf("fieldTypeMap");
120                 ret.add("map", this.addFieldType(schema.getValueType(), stg));
121                 break;
122
123             case RECORD:
124                 ret = processRecord(schema, stg);
125                 break;
126
127             case NULL:
128                 break;
129             case UNION:
130                 break;
131             default:
132                 break;
133         }
134         return ret;
135     }
136
137     /**
138      * Check if a schema is a simple type.
139      * 
140      * @param schemaType the type of the schema
141      * @return true if the schema is a simple type
142      */
143     private boolean isSimpleType(Type schemaType) {
144         switch (schemaType) {
145             case BOOLEAN:
146             case BYTES:
147             case DOUBLE:
148             case FIXED:
149             case FLOAT:
150             case INT:
151             case LONG:
152             case STRING:
153                 return true;
154             
155             default:
156                 return false;
157         }
158     }
159
160     /**
161      * Process a record entry.
162      * @param schema the schema to add a type for
163      * @param stg the STG
164      * @return a template with the type
165      */
166     private ST processRecord(final Schema schema, final STGroup stg) {
167         ST ret;
168         ret = stg.getInstanceOf("fieldTypeRecord");
169         for (final Field field : schema.getFields()) {
170             final ST st = stg.getInstanceOf("field");
171             st.add("name", field.name());
172             st.add("type", this.addFieldType(field.schema(), stg));
173             ret.add("fields", st);
174         }
175         return ret;
176     }
177
178     /**
179      * Runs the application.
180      *
181      *
182      * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
183      *         version), negative integer for errors
184      * @throws ApexException if any problem occurred in the model
185      */
186     public int runApp() throws ApexException {
187         final STGroupFile stg = new STGroupFile("org/onap/policy/apex/tools/model/generator/event-json.stg");
188         final ST stEvents = stg.getInstanceOf("events");
189
190         final ApexModelFactory factory = new ApexModelFactory();
191         final ApexModel model = factory.createApexModel(new Properties(), true);
192
193         final ApexApiResult result = model.loadFromFile(modelFile);
194         if (result.isNok()) {
195             String message = appName + ": " + result.getMessage();
196             LOGGER.error(message);
197             return -1;
198         }
199
200         final AxPolicyModel policyModel = model.getPolicyModel();
201         policyModel.register();
202         new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
203
204         final Set<AxEvent> events = new HashSet<>();
205         final Set<AxArtifactKey> eventKeys = new HashSet<>();
206         final AxPolicies policies = policyModel.getPolicies();
207         switch (type) {
208             case "stimuli":
209                 processStimuli(eventKeys, policies);
210                 break;
211             case "response":
212                 processResponse(eventKeys, policies);
213                 break;
214             case "internal":
215                 processInternal(eventKeys, policies);
216                 break;
217             default:
218                 LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type);
219                 return -1;
220         }
221
222         for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
223             for (final AxArtifactKey key : eventKeys) {
224                 if (event.getKey().equals(key)) {
225                     events.add(event);
226                 }
227             }
228         }
229
230         String renderMessage = renderEvents(stg, stEvents, events);
231         LOGGER.error(renderMessage);
232         return 0;
233     }
234
235     /**
236      * Render the events.
237      * 
238      * @param stg the string template
239      * @param stEvents the event template
240      * @param events the events to render
241      * @return the rendered events
242      * @throws ApexEventException on rendering exceptions
243      */
244     private String renderEvents(final STGroupFile stg, final ST stEvents, final Set<AxEvent> events)
245                     throws ApexEventException {
246         for (final AxEvent event : events) {
247             final ST stEvent = stg.getInstanceOf("event");
248             stEvent.add("name", event.getKey().getName());
249             stEvent.add(NAME_SPACE, event.getNameSpace());
250             stEvent.add(VERSION, event.getKey().getVersion());
251             stEvent.add(SOURCE, event.getSource());
252             stEvent.add(TARGET, event.getTarget());
253
254             final Schema avro = SchemaUtils.getEventSchema(event);
255             for (final Field field : avro.getFields()) {
256                 // filter magic names
257                 switch (field.name()) {
258                     case "name":
259                     case NAME_SPACE:
260                     case VERSION:
261                     case SOURCE:
262                     case TARGET:
263                         break;
264                     default:
265                         stEvent.add("fields", this.setField(field, stg));
266                 }
267             }
268             stEvents.add("event", stEvent);
269         }
270         return stEvents.render();
271     }
272
273     /**
274      * Process the "stimuli" keyword.
275      * @param eventKeys the event keys
276      * @param policies the policies to process
277      */
278     private void processStimuli(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
279         for (final AxPolicy policy : policies.getPolicyMap().values()) {
280             final String firsState = policy.getFirstState();
281             for (final AxState state : policy.getStateMap().values()) {
282                 if (state.getKey().getLocalName().equals(firsState)) {
283                     eventKeys.add(state.getTrigger());
284                 }
285             }
286         }
287     }
288
289     /**
290      * Process the "response" keyword.
291      * @param eventKeys the event keys
292      * @param policies the policies to process
293      */
294     private void processResponse(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
295         for (final AxPolicy policy : policies.getPolicyMap().values()) {
296             processState(eventKeys, policy);
297         }
298     }
299
300     /**
301      * Process the state in the response.
302      * @param eventKeys the event keys
303      * @param policies the policies to process
304      */
305     private void processState(final Set<AxArtifactKey> eventKeys, final AxPolicy policy) {
306         for (final AxState state : policy.getStateMap().values()) {
307             if ("NULL".equals(state.getNextStateSet().iterator().next())) {
308                 for (final AxStateOutput output : state.getStateOutputs().values()) {
309                     eventKeys.add(output.getOutgingEvent());
310                 }
311             }
312         }
313     }
314
315     /**
316      * Process the "internal" keyword.
317      * @param eventKeys the event keys
318      * @param policies the policies to process
319      */
320     private void processInternal(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
321         for (final AxPolicy policy : policies.getPolicyMap().values()) {
322             final String firsState = policy.getFirstState();
323             for (final AxState state : policy.getStateMap().values()) {
324                 processInternalState(eventKeys, firsState, state);
325             }
326         }
327     }
328
329     /**
330      * Process the internal state.
331      * @param eventKeys the event keys
332      * @param policies the policies to process
333      */
334     private void processInternalState(final Set<AxArtifactKey> eventKeys, final String firsState, final AxState state) {
335         if (state.getKey().getLocalName().equals(firsState)) {
336             return;
337         }
338         if ("NULL".equals(state.getNextStateSet().iterator().next())) {
339             return;
340         }
341         for (final AxStateOutput output : state.getStateOutputs().values()) {
342             eventKeys.add(output.getOutgingEvent());
343         }
344     }
345
346     /**
347      * Adds a field to the output.
348      *
349      * @param field the field from the event
350      * @param stg the STG
351      * @return a template for the field
352      */
353     protected ST setField(final Field field, final STGroup stg) {
354         final ST st = stg.getInstanceOf("field");
355         switch (field.name()) {
356             case "name":
357             case NAME_SPACE:
358             case VERSION:
359             case SOURCE:
360             case TARGET:
361                 break;
362             default:
363                 st.add("name", field.name());
364                 st.add("type", this.addFieldType(field.schema(), stg));
365         }
366         return st;
367     }
368
369 }