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