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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.tools.model.generator.model2event;
23 import java.util.HashSet;
24 import java.util.Properties;
27 import org.apache.avro.Schema;
28 import org.apache.avro.Schema.Field;
29 import org.apache.avro.Schema.Type;
30 import org.apache.commons.lang3.Validate;
31 import org.onap.policy.apex.context.parameters.SchemaParameters;
32 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
33 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
34 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
35 import org.onap.policy.apex.model.modelapi.ApexApiResult;
36 import org.onap.policy.apex.model.modelapi.ApexModel;
37 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
38 import org.onap.policy.apex.model.policymodel.concepts.AxPolicies;
39 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
40 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
41 import org.onap.policy.apex.model.policymodel.concepts.AxState;
42 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
43 import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters;
44 import org.onap.policy.apex.service.engine.event.ApexEventException;
45 import org.onap.policy.apex.tools.model.generator.SchemaUtils;
46 import org.slf4j.ext.XLogger;
47 import org.slf4j.ext.XLoggerFactory;
48 import org.stringtemplate.v4.ST;
49 import org.stringtemplate.v4.STGroup;
50 import org.stringtemplate.v4.STGroupFile;
53 * Takes a model and generates the JSON event schemas.
55 * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
57 public class Model2JsonEventSchema {
58 // Logger for this class
59 private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2JsonEventSchema.class);
61 // Recurring string constants
62 private static final String TARGET = "target";
63 private static final String SOURCE = "source";
64 private static final String VERSION = "version";
65 private static final String NAME_SPACE = "nameSpace";
67 /** Application name, used as prompt. */
68 private final String appName;
70 /** The file name of the policy model. */
71 private final String modelFile;
73 /** The type of events to generate: stimuli, response, internal. */
74 private final String type;
77 * Creates a new model to event schema generator.
79 * @param modelFile the model file to be used
80 * @param type the type of events to generate, one of: stimuli, response, internal
81 * @param appName application name for printouts
83 public Model2JsonEventSchema(final String modelFile, final String type, final String appName) {
84 Validate.notNull(modelFile, "Model2JsonEvent: given model file name was blank");
85 Validate.notNull(type, "Model2JsonEvent: given type was blank");
86 Validate.notNull(appName, "Model2JsonEvent: given application name was blank");
88 this.modelFile = modelFile;
90 this.appName = appName;
94 * Adds a type to a field for a given schema.
96 * @param schema the schema to add a type for
98 * @return a template with the type
100 protected ST addFieldType(final Schema schema, final STGroup stg) {
103 if (isSimpleType(schema.getType())) {
104 ret = stg.getInstanceOf("fieldTypeAtomic");
105 ret.add("type", schema.getType());
109 switch (schema.getType()) {
111 ret = stg.getInstanceOf("fieldTypeArray");
112 ret.add("array", this.addFieldType(schema.getElementType(), stg));
115 ret = stg.getInstanceOf("fieldTypeEnum");
116 ret.add("symbols", schema.getEnumSymbols());
120 ret = stg.getInstanceOf("fieldTypeMap");
121 ret.add("map", this.addFieldType(schema.getValueType(), stg));
125 ret = processRecord(schema, stg);
139 * Check if a schema is a simple type.
141 * @param schemaType the type of the schema
142 * @return true if the schema is a simple type
144 private boolean isSimpleType(Type schemaType) {
145 switch (schemaType) {
164 * Process a record entry.
165 * @param schema the schema to add a type for
167 * @return a template with the type
169 private ST processRecord(final Schema schema, final STGroup stg) {
171 ret = stg.getInstanceOf("fieldTypeRecord");
172 for (final Field field : schema.getFields()) {
173 final ST st = stg.getInstanceOf("field");
174 st.add("name", field.name());
175 st.add("type", this.addFieldType(field.schema(), stg));
176 ret.add("fields", st);
182 * Runs the application.
185 * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
186 * version), negative integer for errors
187 * @throws ApexException if any problem occurred in the model
189 public int runApp() throws ApexException {
190 final STGroupFile stg = new STGroupFile("org/onap/policy/apex/tools/model/generator/event-json.stg");
191 final ST stEvents = stg.getInstanceOf("events");
193 final ApexModelFactory factory = new ApexModelFactory();
194 final ApexModel model = factory.createApexModel(new Properties(), true);
196 final ApexApiResult result = model.loadFromFile(modelFile);
197 if (result.isNok()) {
198 String message = appName + ": " + result.getMessage();
199 LOGGER.error(message);
203 final AxPolicyModel policyModel = model.getPolicyModel();
204 policyModel.register();
205 new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
207 final Set<AxEvent> events = new HashSet<>();
208 final Set<AxArtifactKey> eventKeys = new HashSet<>();
209 final AxPolicies policies = policyModel.getPolicies();
212 processStimuli(eventKeys, policies);
215 processResponse(eventKeys, policies);
218 processInternal(eventKeys, policies);
221 LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type);
225 for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
226 for (final AxArtifactKey key : eventKeys) {
227 if (event.getKey().equals(key)) {
233 String renderMessage = renderEvents(stg, stEvents, events);
234 LOGGER.error(renderMessage);
241 * @param stg the string template
242 * @param stEvents the event template
243 * @param events the events to render
244 * @return the rendered events
245 * @throws ApexEventException on rendering exceptions
247 private String renderEvents(final STGroupFile stg, final ST stEvents, final Set<AxEvent> events)
248 throws ApexEventException {
249 for (final AxEvent event : events) {
250 final ST stEvent = stg.getInstanceOf("event");
251 stEvent.add("name", event.getKey().getName());
252 stEvent.add(NAME_SPACE, event.getNameSpace());
253 stEvent.add(VERSION, event.getKey().getVersion());
254 stEvent.add(SOURCE, event.getSource());
255 stEvent.add(TARGET, event.getTarget());
257 final Schema avro = SchemaUtils.getEventSchema(event);
258 for (final Field field : avro.getFields()) {
259 // filter magic names
260 switch (field.name()) {
268 stEvent.add("fields", this.setField(field, stg));
271 stEvents.add("event", stEvent);
273 return stEvents.render();
277 * Process the "stimuli" keyword.
278 * @param eventKeys the event keys
279 * @param policies the policies to process
281 private void processStimuli(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
282 for (final AxPolicy policy : policies.getPolicyMap().values()) {
283 final String firsState = policy.getFirstState();
284 for (final AxState state : policy.getStateMap().values()) {
285 if (state.getKey().getLocalName().equals(firsState)) {
286 eventKeys.add(state.getTrigger());
293 * Process the "response" keyword.
294 * @param eventKeys the event keys
295 * @param policies the policies to process
297 private void processResponse(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
298 for (final AxPolicy policy : policies.getPolicyMap().values()) {
299 processState(eventKeys, policy);
304 * Process the state in the response.
305 * @param eventKeys the event keys
306 * @param policies the policies to process
308 private void processState(final Set<AxArtifactKey> eventKeys, final AxPolicy policy) {
309 for (final AxState state : policy.getStateMap().values()) {
310 if ("NULL".equals(state.getNextStateSet().iterator().next())) {
311 for (final AxStateOutput output : state.getStateOutputs().values()) {
312 eventKeys.add(output.getOutgingEvent());
319 * Process the "internal" keyword.
320 * @param eventKeys the event keys
321 * @param policies the policies to process
323 private void processInternal(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
324 for (final AxPolicy policy : policies.getPolicyMap().values()) {
325 final String firsState = policy.getFirstState();
326 for (final AxState state : policy.getStateMap().values()) {
327 processInternalState(eventKeys, firsState, state);
333 * Process the internal state.
334 * @param eventKeys the event keys
335 * @param policies the policies to process
337 private void processInternalState(final Set<AxArtifactKey> eventKeys, final String firsState, final AxState state) {
338 if (state.getKey().getLocalName().equals(firsState)) {
341 if ("NULL".equals(state.getNextStateSet().iterator().next())) {
344 for (final AxStateOutput output : state.getStateOutputs().values()) {
345 eventKeys.add(output.getOutgingEvent());
350 * Adds a field to the output.
352 * @param field the field from the event
354 * @return a template for the field
356 protected ST setField(final Field field, final STGroup stg) {
357 final ST st = stg.getInstanceOf("field");
358 switch (field.name()) {
366 st.add("name", field.name());
367 st.add("type", this.addFieldType(field.schema(), stg));