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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.tools.model.generator.model2event;
25 import java.util.HashSet;
26 import java.util.Properties;
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;
54 * Takes a model and generates the JSON event schemas.
56 * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
58 public class Model2JsonEventSchema {
59 // Logger for this class
60 private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2JsonEventSchema.class);
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";
68 /** Application name, used as prompt. */
69 private final String appName;
71 /** The file name of the policy model. */
72 private final String modelFile;
74 /** The type of events to generate: stimuli, response, internal. */
75 private final String type;
78 * Creates a new model to event schema generator.
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
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");
89 this.modelFile = modelFile;
91 this.appName = appName;
95 * Adds a type to a field for a given schema.
97 * @param schema the schema to add a type for
99 * @return a template with the type
101 protected ST addFieldType(final Schema schema, final STGroup stg) {
104 if (isSimpleType(schema.getType())) {
105 ret = stg.getInstanceOf("fieldTypeAtomic");
106 ret.add("type", schema.getType());
110 switch (schema.getType()) {
112 ret = stg.getInstanceOf("fieldTypeArray");
113 ret.add("array", this.addFieldType(schema.getElementType(), stg));
116 ret = stg.getInstanceOf("fieldTypeEnum");
117 ret.add("symbols", schema.getEnumSymbols());
121 ret = stg.getInstanceOf("fieldTypeMap");
122 ret.add("map", this.addFieldType(schema.getValueType(), stg));
126 ret = processRecord(schema, stg);
140 * Check if a schema is a simple type.
142 * @param schemaType the type of the schema
143 * @return true if the schema is a simple type
145 private boolean isSimpleType(Type schemaType) {
146 switch (schemaType) {
163 * Process a record entry.
164 * @param schema the schema to add a type for
166 * @return a template with the type
168 private ST processRecord(final Schema schema, final STGroup stg) {
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);
181 * Runs the application.
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
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");
192 final ApexModelFactory factory = new ApexModelFactory();
193 final ApexModel model = factory.createApexModel(new Properties(), true);
195 final ApexApiResult result = model.loadFromFile(modelFile);
196 if (result.isNok()) {
197 String message = appName + ": " + result.getMessage();
198 LOGGER.error(message);
202 final AxPolicyModel policyModel = model.getPolicyModel();
203 policyModel.register();
204 new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
206 final Set<AxEvent> events = new HashSet<>();
207 final Set<AxArtifactKey> eventKeys = new HashSet<>();
208 final AxPolicies policies = policyModel.getPolicies();
211 processStimuli(eventKeys, policies);
214 processResponse(eventKeys, policies);
217 processInternal(eventKeys, policies);
220 LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type);
224 for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
225 for (final AxArtifactKey key : eventKeys) {
226 if (event.getKey().equals(key)) {
232 String renderMessage = renderEvents(stg, stEvents, events);
233 LOGGER.error(renderMessage);
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
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());
256 final Schema avro = SchemaUtils.getEventSchema(event);
257 for (final Field field : avro.getFields()) {
258 // filter magic names
259 switch (field.name()) {
267 stEvent.add("fields", this.setField(field, stg));
270 stEvents.add("event", stEvent);
272 return stEvents.render();
276 * Process the "stimuli" keyword.
277 * @param eventKeys the event keys
278 * @param policies the policies to process
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());
292 * Process the "response" keyword.
293 * @param eventKeys the event keys
294 * @param policies the policies to process
296 private void processResponse(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
297 for (final AxPolicy policy : policies.getPolicyMap().values()) {
298 processState(eventKeys, policy);
303 * Process the state in the response.
304 * @param eventKeys the event keys
305 * @param policy the policy to process
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());
318 * Process the "internal" keyword.
319 * @param eventKeys the event keys
320 * @param policies the policies to process
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);
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
337 private void processInternalState(final Set<AxArtifactKey> eventKeys, final String firstState,
338 final AxState state) {
339 if (state.getKey().getLocalName().equals(firstState)) {
342 if ("NULL".equals(state.getNextStateSet().iterator().next())) {
345 for (final AxStateOutput output : state.getStateOutputs().values()) {
346 eventKeys.add(output.getOutgoingEvent());
351 * Adds a field to the output.
353 * @param field the field from the event
355 * @return a template for the field
357 protected ST setField(final Field field, final STGroup stg) {
358 final ST st = stg.getInstanceOf("field");
359 switch (field.name()) {
367 st.add("name", field.name());
368 st.add("type", this.addFieldType(field.schema(), stg));