ec6d72c4bbcaf6c35a19f3f0e5df6a6969a2d342
[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.stringtemplate.v4.ST;
45 import org.stringtemplate.v4.STGroup;
46 import org.stringtemplate.v4.STGroupFile;
47
48 /**
49  * Takes a model and generates the JSON event schemas.
50  *
51  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
52  */
53 public class Model2JsonEventSchema {
54
55     /** Application name, used as prompt. */
56     private final String appName;
57
58     /** The file name of the policy model. */
59     private final String modelFile;
60
61     /** The type of events to generate: stimuli, response, internal. */
62     private final String type;
63
64     /**
65      * Creates a new model to event schema generator.
66      *
67      * @param modelFile the model file to be used
68      * @param type the type of events to generate, one of: stimuli, response, internal
69      * @param appName application name for printouts
70      */
71     public Model2JsonEventSchema(final String modelFile, final String type, final String appName) {
72         Validate.notNull(modelFile, "Model2JsonEvent: given model file name was blank");
73         Validate.notNull(type, "Model2JsonEvent: given type was blank");
74         Validate.notNull(appName, "Model2JsonEvent: given application name was blank");
75         this.modelFile = modelFile;
76         this.type = type;
77         this.appName = appName;
78     }
79
80     /**
81      * Adds a type to a field for a given schema.
82      *
83      * @param schema the schema to add a type for
84      * @param stg the STG
85      * @return a template with the type
86      */
87     protected ST addFieldType(final Schema schema, final STGroup stg) {
88         ST ret = null;
89         switch (schema.getType()) {
90             case BOOLEAN:
91             case BYTES:
92             case DOUBLE:
93             case FIXED:
94             case FLOAT:
95             case INT:
96             case LONG:
97             case STRING:
98                 ret = stg.getInstanceOf("fieldTypeAtomic");
99                 ret.add("type", schema.getType());
100                 break;
101
102             case ARRAY:
103                 ret = stg.getInstanceOf("fieldTypeArray");
104                 ret.add("array", this.addFieldType(schema.getElementType(), stg));
105                 break;
106             case ENUM:
107                 ret = stg.getInstanceOf("fieldTypeEnum");
108                 ret.add("symbols", schema.getEnumSymbols());
109                 break;
110
111             case MAP:
112                 ret = stg.getInstanceOf("fieldTypeMap");
113                 ret.add("map", this.addFieldType(schema.getValueType(), stg));
114                 break;
115
116             case RECORD:
117                 ret = stg.getInstanceOf("fieldTypeRecord");
118                 for (final Field field : schema.getFields()) {
119                     final ST st = stg.getInstanceOf("field");
120                     st.add("name", field.name());
121                     st.add("type", this.addFieldType(field.schema(), stg));
122                     ret.add("fields", st);
123                 }
124                 break;
125
126             case NULL:
127                 break;
128             case UNION:
129                 break;
130             default:
131                 break;
132         }
133         return ret;
134     }
135
136     /**
137      * Runs the application.
138      *
139      * @throws ApexException if any problem occurred in the model
140      * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
141      *         version), negative integer for errors
142      */
143     public int runApp() throws ApexException {
144         final STGroupFile stg = new STGroupFile("org/onap/policy/apex/tools/model/generator/event-json.stg");
145         final ST stEvents = stg.getInstanceOf("events");
146
147         final ApexModelFactory factory = new ApexModelFactory();
148         final ApexModel model = factory.createApexModel(new Properties(), true);
149
150         final ApexAPIResult result = model.loadFromFile(modelFile);
151         if (result.isNOK()) {
152             System.err.println(appName + ": " + result.getMessage());
153             return -1;
154         }
155
156         final AxPolicyModel policyModel = model.getPolicyModel();
157         policyModel.register();
158         new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
159
160         final Set<AxEvent> events = new HashSet<>();
161         final Set<AxArtifactKey> eventKeys = new HashSet<>();
162         final AxPolicies policies = policyModel.getPolicies();
163         switch (type) {
164             case "stimuli":
165                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
166                     final String firsState = policy.getFirstState();
167                     for (final AxState state : policy.getStateMap().values()) {
168                         if (state.getKey().getLocalName().equals(firsState)) {
169                             eventKeys.add(state.getTrigger());
170                         }
171                     }
172                 }
173                 break;
174             case "response":
175                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
176                     for (final AxState state : policy.getStateMap().values()) {
177                         if (state.getNextStateSet().iterator().next().equals("NULL")) {
178                             for (final AxStateOutput output : state.getStateOutputs().values()) {
179                                 eventKeys.add(output.getOutgingEvent());
180                             }
181                         }
182                     }
183                 }
184                 break;
185             case "internal":
186                 for (final AxPolicy policy : policies.getPolicyMap().values()) {
187                     final String firsState = policy.getFirstState();
188                     for (final AxState state : policy.getStateMap().values()) {
189                         if (state.getKey().getLocalName().equals(firsState)) {
190                             continue;
191                         }
192                         if (state.getNextStateSet().iterator().next().equals("NULL")) {
193                             continue;
194                         }
195                         for (final AxStateOutput output : state.getStateOutputs().values()) {
196                             eventKeys.add(output.getOutgingEvent());
197                         }
198                     }
199                 }
200                 break;
201             default:
202                 System.err.println(appName + ": unknown type <" + type + ">, cannot proceed");
203                 return -1;
204         }
205
206         for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
207             for (final AxArtifactKey key : eventKeys) {
208                 if (event.getKey().equals(key)) {
209                     events.add(event);
210                 }
211             }
212         }
213
214         for (final AxEvent event : events) {
215             final ST stEvent = stg.getInstanceOf("event");
216             stEvent.add("name", event.getKey().getName());
217             stEvent.add("nameSpace", event.getNameSpace());
218             stEvent.add("version", event.getKey().getVersion());
219             stEvent.add("source", event.getSource());
220             stEvent.add("target", event.getTarget());
221
222             final Schema avro = SchemaUtils.getEventSchema(event);
223             for (final Field field : avro.getFields()) {
224                 // filter magic names
225                 switch (field.name()) {
226                     case "name":
227                     case "nameSpace":
228                     case "version":
229                     case "source":
230                     case "target":
231                         break;
232                     default:
233                         stEvent.add("fields", this.setField(field, stg));
234                 }
235             }
236             stEvents.add("event", stEvent);
237         }
238         System.err.println(stEvents.render());
239         return 0;
240     }
241
242     /**
243      * Adds a field to the output.
244      *
245      * @param field the field from the event
246      * @param stg the STG
247      * @return a template for the field
248      */
249     protected ST setField(final Field field, final STGroup stg) {
250         final ST st = stg.getInstanceOf("field");
251         switch (field.name()) {
252             case "name":
253             case "nameSpace":
254             case "version":
255             case "source":
256             case "target":
257                 break;
258             default:
259                 st.add("name", field.name());
260                 st.add("type", this.addFieldType(field.schema(), stg));
261         }
262         return st;
263     }
264
265 }