2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.tools.model.generator.model2cli;
24 import java.io.IOException;
25 import java.io.Writer;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.Properties;
34 import org.apache.commons.lang3.Validate;
35 import org.onap.policy.apex.auth.clicodegen.CodeGenCliEditorBuilder;
36 import org.onap.policy.apex.auth.clicodegen.CodeGeneratorCliEditor;
37 import org.onap.policy.apex.auth.clicodegen.EventDeclarationBuilder;
38 import org.onap.policy.apex.auth.clicodegen.TaskDeclarationBuilder;
39 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
40 import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
41 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
42 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
43 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
44 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
45 import org.onap.policy.apex.model.eventmodel.concepts.AxField;
46 import org.onap.policy.apex.model.modelapi.ApexApiResult;
47 import org.onap.policy.apex.model.modelapi.ApexModel;
48 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
49 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
50 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
51 import org.onap.policy.apex.model.policymodel.concepts.AxState;
52 import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
53 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
54 import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference;
55 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
56 import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic;
57 import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
58 import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic;
59 import org.onap.policy.apex.tools.common.OutputFile;
60 import org.onap.policy.apex.tools.model.generator.KeyInfoGetter;
61 import org.slf4j.ext.XLogger;
62 import org.slf4j.ext.XLoggerFactory;
63 import org.stringtemplate.v4.ST;
66 * Takes a model and generates the JSON event schemas.
68 * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
70 public class Model2Cli {
71 // Logger for this class
72 private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class);
74 /** Application name, used as prompt. */
75 private final String appName;
77 /** The file name of the policy model. */
78 private final String modelFile;
80 /** The output file, if any. */
81 private final OutputFile outFile;
83 /** Pre-validate the model. */
84 private final boolean validate;
86 /** utility for getting key information and parsing keys etc.. */
87 private KeyInfoGetter kig = null;
90 * Creates a new model to CLI commands generator.
92 * @param modelFile the model file to be used
93 * @param outFile the out file
94 * @param validate true for model validation, false otherwise
95 * @param appName application name for printouts
97 public Model2Cli(final String modelFile, final OutputFile outFile, final boolean validate, final String appName) {
98 Validate.notNull(modelFile, "Model2Cli: given model file name was blank");
99 Validate.notNull(appName, "Model2Cli: given application name was blank");
101 this.modelFile = modelFile;
102 this.outFile = outFile;
103 this.appName = appName;
104 this.validate = validate;
108 * Runs the application.
110 * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
111 * version), negative integer for errors
113 public int runApp() {
114 final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor();
116 final ApexModelFactory factory = new ApexModelFactory();
117 final ApexModel model = factory.createApexModel(new Properties(), true);
119 final ApexApiResult result = model.loadFromFile(modelFile);
120 if (result.isNok()) {
121 final String message = appName + ": " + result.getMessage();
122 LOGGER.error(message);
126 final AxPolicyModel policyModel = model.getPolicyModel();
127 policyModel.register();
130 final AxValidationResult val = new AxValidationResult();
131 policyModel.validate(val);
133 final String message = "Cannot translate the model. The model is not valid: \n" + val.toString();
134 LOGGER.error(message);
139 return generateCli(codeGen, policyModel);
143 * Generate the CLI from the model.
145 * @param codeGen the code generator
146 * @param policyModel the policy model
148 private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) {
149 kig = new KeyInfoGetter(policyModel);
151 // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies
153 final AxArtifactKey pmkey = policyModel.getKey();
154 codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey));
156 // 1: Context Schemas
157 for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) {
158 final AxArtifactKey key = s.getKey();
160 codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
161 s.getSchemaFlavour(), s.getSchema());
165 for (final AxTask t : policyModel.getTasks().getTaskMap().values()) {
166 final AxArtifactKey key = t.getKey();
167 final List<ST> infields = getInfieldsForTask(codeGen, t);
168 final List<ST> outfields = getOutfieldsForTask(codeGen, t);
169 final ST logic = getLogicForTask(codeGen, t);
170 final List<ST> parameters = getParametersForTask(codeGen, t);
171 final List<ST> contextRefs = getCtxtRefsForTask(codeGen, t);
173 codeGen.addTaskDeclaration(new TaskDeclarationBuilder().setName(kig.getName(key))
174 .setVersion(kig.getVersion(key)).setUuid(kig.getUuid(key))
175 .setDescription(kig.getDesc(key)).setInfields(infields).setOutfields(outfields)
176 .setLogic(logic).setParameters(parameters).setContextRefs(contextRefs));
180 for (final AxEvent e : policyModel.getEvents().getEventMap().values()) {
181 final AxArtifactKey key = e.getKey();
182 final List<ST> fields = getParametersForEvent(codeGen, e);
184 codeGen.addEventDeclaration(
185 new EventDeclarationBuilder()
186 .setName(kig.getName(key))
187 .setVersion(kig.getVersion(key))
188 .setUuid(kig.getUuid(key))
189 .setDescription(kig.getDesc(key))
190 .setNameSpace(e.getNameSpace())
191 .setSource(e.getSource())
192 .setTarget(e.getTarget())
197 for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) {
198 final AxArtifactKey key = a.getKey();
200 codeGen.addContextAlbumDeclaration(new CodeGenCliEditorBuilder().setName(kig.getName(key))
201 .setVersion(kig.getVersion(key)).setUuid(kig.getUuid(key)).setDescription(kig.getDesc(key))
202 .setScope(a.getScope()).setWritable(a.isWritable()).setSchemaName(kig.getName(a.getItemSchema()))
203 .setSchemaVersion(kig.getVersion(a.getItemSchema())));
207 for (final AxPolicy p : policyModel.getPolicies().getPolicyMap().values()) {
208 final AxArtifactKey key = p.getKey();
209 final List<ST> states = getStatesForPolicy(codeGen, p);
210 codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
211 p.getTemplate(), p.getFirstState(), states);
214 final String out = codeGen.getModel().render();
215 if (outFile != null) {
216 final String message = "Error writing output to file " + outFile;
218 final Writer w = outFile.toWriter();
220 LOGGER.error(message);
225 } catch (final IOException e) {
226 LOGGER.error(message, e);
237 * Gets the parameters for event.
239 * @param cg the code generator
240 * @param event the event
241 * @return the parameters for event
243 private List<ST> getParametersForEvent(final CodeGeneratorCliEditor cg, final AxEvent event) {
244 final Collection<AxField> fields = event.getFields();
245 final List<ST> ret = new ArrayList<>(fields.size());
246 for (final AxField f : fields) {
247 final AxReferenceKey fkey = f.getKey();
249 final ST val = cg.createEventFieldDefinition(kig.getPName(fkey), kig.getPVersion(fkey), kig.getLName(fkey),
250 kig.getName(f.getSchema()), kig.getVersion(f.getSchema()), f.getOptional());
258 * Gets the context references for task.
260 * @param cg the code generator
261 * @param task the task
262 * @return the context references for task
264 private List<ST> getCtxtRefsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
265 final Collection<AxArtifactKey> ctxs = task.getContextAlbumReferences();
266 final List<ST> ret = new ArrayList<>(ctxs.size());
267 final AxArtifactKey tkey = task.getKey();
268 for (final AxArtifactKey ckey : ctxs) {
270 final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey),
271 kig.getVersion(ckey));
279 * Gets the parameters for task.
281 * @param cg the code generator
282 * @param task the task
283 * @return the parameters for task
285 private List<ST> getParametersForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
286 final Collection<AxTaskParameter> pars = task.getTaskParameters().values();
287 final List<ST> ret = new ArrayList<>(pars.size());
288 for (final AxTaskParameter p : pars) {
289 final AxReferenceKey pkey = p.getKey();
291 final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey),
292 kig.getLName(pkey), p.getTaskParameterValue());
300 * Gets the logic for task.
302 * @param cg the code generator
303 * @param task the task
304 * @return the logic for task
306 private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
307 final AxArtifactKey tkey = task.getKey();
308 final AxTaskLogic tl = task.getTaskLogic();
310 return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic());
314 * Gets the output fields for task.
316 * @param cg the code generator
317 * @param task the task
318 * @return the output fields for task
320 private List<ST> getOutfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
321 final Collection<? extends AxField> fields = task.getOutputFields().values();
322 final List<ST> ret = new ArrayList<>(fields.size());
323 for (final AxField f : fields) {
324 final AxReferenceKey fkey = f.getKey();
326 final ST val = cg.createTaskDefinitionOutfields(kig.getPName(fkey), kig.getPVersion(fkey),
327 kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
335 * Gets the input fields for task.
337 * @param cg the code generator
338 * @param task the task
339 * @return the input fields for task
341 private List<ST> getInfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
342 final Collection<? extends AxField> fields = task.getInputFields().values();
343 final List<ST> ret = new ArrayList<>(fields.size());
344 for (final AxField f : fields) {
345 final AxReferenceKey fkey = f.getKey();
347 final ST val = cg.createTaskDefinitionInfields(kig.getPName(fkey), kig.getPVersion(fkey),
348 kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
356 * Gets the states for policy.
358 * @param cg the code generator
359 * @param pol the policy
360 * @return the states for policy
362 private List<ST> getStatesForPolicy(final CodeGeneratorCliEditor cg, final AxPolicy pol) {
363 final Collection<AxState> states = pol.getStateMap().values();
364 final List<ST> ret = new ArrayList<>(states.size());
365 for (final AxState st : states) {
366 final AxReferenceKey skey = st.getKey();
367 final List<ST> outputs = getStateOutputsForState(cg, st);
368 final List<ST> finalizerLogics = getFinalizersForState(cg, st);
369 final List<ST> tasks = getTaskRefsForState(cg, st);
370 final List<ST> tsLogic = getTslForState(cg, st);
371 final List<ST> ctxRefs = getCtxtRefsForState(cg, st);
373 final ST val = cg.createPolicyStateDef(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
374 kig.getName(st.getTrigger()), kig.getVersion(st.getTrigger()), kig.getName(st.getDefaultTask()),
375 kig.getVersion(st.getDefaultTask()), outputs, tasks, tsLogic, finalizerLogics, ctxRefs);
383 * Gets the finalizers for state.
385 * @param cg the code generator
386 * @param st the state
387 * @return the finalizers for state
389 private List<ST> getFinalizersForState(final CodeGeneratorCliEditor cg, final AxState st) {
390 final Collection<AxStateFinalizerLogic> fins = st.getStateFinalizerLogicMap().values();
391 final List<ST> ret = new ArrayList<>(fins.size());
392 final AxReferenceKey skey = st.getKey();
393 for (final AxStateFinalizerLogic fin : fins) {
394 final AxReferenceKey finkey = fin.getKey();
396 final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey),
397 kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic());
405 * Gets the context references for state.
407 * @param cg the code generator
408 * @param st the state
409 * @return the context references for state
411 private List<ST> getCtxtRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
412 final Collection<AxArtifactKey> ctxs = st.getContextAlbumReferences();
413 final List<ST> ret = new ArrayList<>(ctxs.size());
414 final AxReferenceKey skey = st.getKey();
415 for (final AxArtifactKey ctx : ctxs) {
417 final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey),
418 kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx));
426 * Gets the Task Selection Logic for state.
428 * @param cg the code generator
429 * @param st the state
430 * @return the TSL for state (if any) in a list
432 private List<ST> getTslForState(final CodeGeneratorCliEditor cg, final AxState st) {
433 final AxReferenceKey skey = st.getKey();
434 if (st.checkSetTaskSelectionLogic()) {
435 final AxTaskSelectionLogic tsl = st.getTaskSelectionLogic();
436 final ST val = cg.createPolicyStateDefTaskSelLogic(kig.getPName(skey), kig.getPVersion(skey),
437 kig.getLName(skey), tsl.getLogicFlavour(), tsl.getLogic());
438 return Collections.singletonList(val);
440 return Collections.emptyList();
445 * Gets the task references for state.
447 * @param cg the code generator
448 * @param st the state
449 * @return the task references for state
451 private List<ST> getTaskRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
452 final Map<AxArtifactKey, AxStateTaskReference> taskrefs = st.getTaskReferences();
453 final List<ST> ret = new ArrayList<>(taskrefs.size());
454 final AxReferenceKey skey = st.getKey();
455 for (final Entry<AxArtifactKey, AxStateTaskReference> e : taskrefs.entrySet()) {
456 final AxArtifactKey tkey = e.getKey();
457 final AxStateTaskReference tr = e.getValue();
458 final AxReferenceKey trkey = tr.getKey();
460 final ST val = cg.createPolicyStateTask(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
461 kig.getLName(trkey), kig.getName(tkey), kig.getVersion(tkey), tr.getStateTaskOutputType().name(),
462 kig.getLName(tr.getOutput()));
470 * Gets the state outputs for state.
472 * @param cg the code generator
473 * @param st the state
474 * @return the state outputs for state
476 private List<ST> getStateOutputsForState(final CodeGeneratorCliEditor cg, final AxState st) {
477 final Collection<AxStateOutput> outs = st.getStateOutputs().values();
478 final List<ST> ret = new ArrayList<>(outs.size());
479 final AxReferenceKey skey = st.getKey();
480 for (final AxStateOutput out : outs) {
481 final AxReferenceKey outkey = out.getKey();
483 final ST val = cg.createPolicyStateOutput(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
484 kig.getLName(outkey), kig.getName(out.getOutgingEvent()), kig.getVersion(out.getOutgingEvent()),
485 kig.getLName(out.getNextState()));