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