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