6acbbbc024a77bf9386eacc3cd86e9a53e6155bd
[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         this.modelFile = modelFile;
86         this.type = type;
87         this.appName = appName;
88     }
89
90     /**
91      * Adds a type to a field for a given schema.
92      *
93      * @param schema the schema to add a type for
94      * @param stg the STG
95      * @return a template with the type
96      */
97     protected ST addFieldType(final Schema schema, final STGroup stg) {
98         ST ret = null;
99         switch (schema.getType()) {
100             case BOOLEAN:
101             case BYTES:
102             case DOUBLE:
103             case FIXED:
104             case FLOAT:
105             case INT:
106             case LONG:
107             case STRING:
108                 ret = stg.getInstanceOf("fieldTypeAtomic");
109                 ret.add("type", schema.getType());
110                 break;
111
112             case ARRAY:
113                 ret = stg.getInstanceOf("fieldTypeArray");
114                 ret.add("array", this.addFieldType(schema.getElementType(), stg));
115                 break;
116             case ENUM:
117                 ret = stg.getInstanceOf("fieldTypeEnum");
118                 ret.add("symbols", schema.getEnumSymbols());
119                 break;
120
121             case MAP:
122                 ret = stg.getInstanceOf("fieldTypeMap");
123                 ret.add("map", this.addFieldType(schema.getValueType(), stg));
124                 break;
125
126             case RECORD:
127                 ret = stg.getInstanceOf("fieldTypeRecord");
128                 for (final Field field : schema.getFields()) {
129                     final ST st = stg.getInstanceOf("field");
130                     st.add("name", field.name());
131                     st.add("type", this.addFieldType(field.schema(), stg));
132                     ret.add("fields", st);
133                 }
134                 break;
135
136             case NULL:
137                 break;
138             case UNION:
139                 break;
140             default:
141                 break;
142         }
143         return ret;
144     }
145
146     /**
147      * Runs the application.
148      *
149      *
150      * @return status of the application execution, 0 for success, positive integer for exit
151      *         condition (such as help or version), negative integer for errors
152      * @throws ApexException if any problem occurred in the model
153      */
154     public int runApp() throws ApexException {
155         final STGroupFile stg = new STGroupFile("org/onap/policy/apex/tools/model/generator/event-json.stg");
156         final ST stEvents = stg.getInstanceOf("events");
157
158         final ApexModelFactory factory = new ApexModelFactory();
159         final ApexModel model = factory.createApexModel(new Properties(), true);
160
161         final ApexApiResult result = model.loadFromFile(modelFile);
162         if (result.isNok()) {
163             String message = appName + ": " + result.getMessage();
164             LOGGER.error(message);
165             return -1;
166         }
167
168         final AxPolicyModel policyModel = model.getPolicyModel();
169         policyModel.register();
170         new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
171
172         final Set<AxEvent> events = new HashSet<>();
173         final Set<AxArtifactKey> eventKeys = new HashSet<>();
174         final AxPolicies policies = policyModel.getPolicies();
175         switch (type) {
176             case "stimuli":
177                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
178                     final String firsState = policy.getFirstState();
179                     for (final AxState state : policy.getStateMap().values()) {
180                         if (state.getKey().getLocalName().equals(firsState)) {
181                             eventKeys.add(state.getTrigger());
182                         }
183                     }
184                 }
185                 break;
186             case "response":
187                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
188                     for (final AxState state : policy.getStateMap().values()) {
189                         if (state.getNextStateSet().iterator().next().equals("NULL")) {
190                             for (final AxStateOutput output : state.getStateOutputs().values()) {
191                                 eventKeys.add(output.getOutgingEvent());
192                             }
193                         }
194                     }
195                 }
196                 break;
197             case "internal":
198                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
199                     final String firsState = policy.getFirstState();
200                     for (final AxState state : policy.getStateMap().values()) {
201                         if (state.getKey().getLocalName().equals(firsState)) {
202                             continue;
203                         }
204                         if (state.getNextStateSet().iterator().next().equals("NULL")) {
205                             continue;
206                         }
207                         for (final AxStateOutput output : state.getStateOutputs().values()) {
208                             eventKeys.add(output.getOutgingEvent());
209                         }
210                     }
211                 }
212                 break;
213             default:
214                 LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type);
215                 return -1;
216         }
217
218         for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
219             for (final AxArtifactKey key : eventKeys) {
220                 if (event.getKey().equals(key)) {
221                     events.add(event);
222                 }
223             }
224         }
225
226         for (final AxEvent event : events) {
227             final ST stEvent = stg.getInstanceOf("event");
228             stEvent.add("name", event.getKey().getName());
229             stEvent.add(NAME_SPACE, event.getNameSpace());
230             stEvent.add(VERSION, event.getKey().getVersion());
231             stEvent.add(SOURCE, event.getSource());
232             stEvent.add(TARGET, event.getTarget());
233
234             final Schema avro = SchemaUtils.getEventSchema(event);
235             for (final Field field : avro.getFields()) {
236                 // filter magic names
237                 switch (field.name()) {
238                     case "name":
239                     case NAME_SPACE:
240                     case VERSION:
241                     case SOURCE:
242                     case TARGET:
243                         break;
244                     default:
245                         stEvent.add("fields", this.setField(field, stg));
246                 }
247             }
248             stEvents.add("event", stEvent);
249         }
250         String renderMessage = stEvents.render();
251         LOGGER.error(renderMessage);
252         return 0;
253     }
254
255     /**
256      * Adds a field to the output.
257      *
258      * @param field the field from the event
259      * @param stg the STG
260      * @return a template for the field
261      */
262     protected ST setField(final Field field, final STGroup stg) {
263         final ST st = stg.getInstanceOf("field");
264         switch (field.name()) {
265             case "name":
266             case NAME_SPACE:
267             case VERSION:
268             case SOURCE:
269             case TARGET:
270                 break;
271             default:
272                 st.add("name", field.name());
273                 st.add("type", this.addFieldType(field.schema(), stg));
274         }
275         return st;
276     }
277
278 }