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) {
162 * Process a record entry.
163 * @param schema the schema to add a type for
165 * @return a template with the type
167 private ST processRecord(final Schema schema, final STGroup stg) {
169 ret = stg.getInstanceOf("fieldTypeRecord");
170 for (final Field field : schema.getFields()) {
171 final ST st = stg.getInstanceOf("field");
172 st.add("name", field.name());
173 st.add("type", this.addFieldType(field.schema(), stg));
174 ret.add("fields", st);
180 * Runs the application.
183 * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
184 * version), negative integer for errors
185 * @throws ApexException if any problem occurred in the model
187 public int runApp() throws ApexException {
188 final STGroupFile stg = new STGroupFile("org/onap/policy/apex/tools/model/generator/event-json.stg");
189 final ST stEvents = stg.getInstanceOf("events");
191 final ApexModelFactory factory = new ApexModelFactory();
192 final ApexModel model = factory.createApexModel(new Properties(), true);
194 final ApexApiResult result = model.loadFromFile(modelFile);
195 if (result.isNok()) {
196 String message = appName + ": " + result.getMessage();
197 LOGGER.error(message);
201 final AxPolicyModel policyModel = model.getPolicyModel();
202 policyModel.register();
203 new SchemaParameters().getSchemaHelperParameterMap().put("Avro", new AvroSchemaHelperParameters());
205 final Set<AxEvent> events = new HashSet<>();
206 final Set<AxArtifactKey> eventKeys = new HashSet<>();
207 final AxPolicies policies = policyModel.getPolicies();
210 processStimuli(eventKeys, policies);
213 processResponse(eventKeys, policies);
216 processInternal(eventKeys, policies);
219 LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type);
223 for (final AxEvent event : policyModel.getEvents().getEventMap().values()) {
224 for (final AxArtifactKey key : eventKeys) {
225 if (event.getKey().equals(key)) {
231 String renderMessage = renderEvents(stg, stEvents, events);
232 LOGGER.error(renderMessage);
239 * @param stg the string template
240 * @param stEvents the event template
241 * @param events the events to render
242 * @return the rendered events
243 * @throws ApexEventException on rendering exceptions
245 private String renderEvents(final STGroupFile stg, final ST stEvents, final Set<AxEvent> events)
246 throws ApexEventException {
247 for (final AxEvent event : events) {
248 final ST stEvent = stg.getInstanceOf("event");
249 stEvent.add("name", event.getKey().getName());
250 stEvent.add(NAME_SPACE, event.getNameSpace());
251 stEvent.add(VERSION, event.getKey().getVersion());
252 stEvent.add(SOURCE, event.getSource());
253 stEvent.add(TARGET, event.getTarget());
255 final Schema avro = SchemaUtils.getEventSchema(event);
256 for (final Field field : avro.getFields()) {
257 // filter magic names
258 switch (field.name()) {
266 stEvent.add("fields", this.setField(field, stg));
269 stEvents.add("event", stEvent);
271 return stEvents.render();
275 * Process the "stimuli" keyword.
276 * @param eventKeys the event keys
277 * @param policies the policies to process
279 private void processStimuli(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
280 for (final AxPolicy policy : policies.getPolicyMap().values()) {
281 final String firsState = policy.getFirstState();
282 for (final AxState state : policy.getStateMap().values()) {
283 if (state.getKey().getLocalName().equals(firsState)) {
284 eventKeys.add(state.getTrigger());
291 * Process the "response" keyword.
292 * @param eventKeys the event keys
293 * @param policies the policies to process
295 private void processResponse(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
296 for (final AxPolicy policy : policies.getPolicyMap().values()) {
297 processState(eventKeys, policy);
302 * Process the state in the response.
303 * @param eventKeys the event keys
304 * @param policies the policies to process
306 private void processState(final Set<AxArtifactKey> eventKeys, final AxPolicy policy) {
307 for (final AxState state : policy.getStateMap().values()) {
308 if ("NULL".equals(state.getNextStateSet().iterator().next())) {
309 for (final AxStateOutput output : state.getStateOutputs().values()) {
310 eventKeys.add(output.getOutgingEvent());
317 * Process the "internal" keyword.
318 * @param eventKeys the event keys
319 * @param policies the policies to process
321 private void processInternal(final Set<AxArtifactKey> eventKeys, final AxPolicies policies) {
322 for (final AxPolicy policy : policies.getPolicyMap().values()) {
323 final String firsState = policy.getFirstState();
324 for (final AxState state : policy.getStateMap().values()) {
325 processInternalState(eventKeys, firsState, state);
331 * Process the internal state.
332 * @param eventKeys the event keys
333 * @param policies the policies to process
335 private void processInternalState(final Set<AxArtifactKey> eventKeys, final String firsState, final AxState state) {
336 if (state.getKey().getLocalName().equals(firsState)) {
339 if ("NULL".equals(state.getNextStateSet().iterator().next())) {
342 for (final AxStateOutput output : state.getStateOutputs().values()) {
343 eventKeys.add(output.getOutgingEvent());
348 * Adds a field to the output.
350 * @param field the field from the event
352 * @return a template for the field
354 protected ST setField(final Field field, final STGroup stg) {
355 final ST st = stg.getInstanceOf("field");
356 switch (field.name()) {
364 st.add("name", field.name());
365 st.add("type", this.addFieldType(field.schema(), stg));