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.model2cli;
23 import java.io.IOException;
24 import java.io.Writer;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Properties;
33 import org.apache.commons.lang3.Validate;
34 import org.onap.policy.apex.auth.clicodegen.CodeGenCliEditorBuilder;
35 import org.onap.policy.apex.auth.clicodegen.CodeGeneratorCliEditor;
36 import org.onap.policy.apex.auth.clicodegen.EventDeclarationBuilder;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
39 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
40 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
41 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
42 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
43 import org.onap.policy.apex.model.eventmodel.concepts.AxField;
44 import org.onap.policy.apex.model.modelapi.ApexApiResult;
45 import org.onap.policy.apex.model.modelapi.ApexModel;
46 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
47 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
48 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
49 import org.onap.policy.apex.model.policymodel.concepts.AxState;
50 import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
51 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
52 import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference;
53 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
54 import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic;
55 import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
56 import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic;
57 import org.onap.policy.apex.tools.common.OutputFile;
58 import org.onap.policy.apex.tools.model.generator.KeyInfoGetter;
59 import org.slf4j.ext.XLogger;
60 import org.slf4j.ext.XLoggerFactory;
61 import org.stringtemplate.v4.ST;
64 * Takes a model and generates the JSON event schemas.
66 * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
68 public class Model2Cli {
69 // Logger for this class
70 private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class);
72 /** Application name, used as prompt. */
73 private final String appName;
75 /** The file name of the policy model. */
76 private final String modelFile;
78 /** The output file, if any. */
79 private final OutputFile outFile;
81 /** Pre-validate the model. */
82 private final boolean validate;
84 /** utility for getting key information and parsing keys etc.. */
85 private KeyInfoGetter kig = null;
88 * Creates a new model to CLI commands generator.
90 * @param modelFile the model file to be used
91 * @param outFile the out file
92 * @param validate true for model validation, false otherwise
93 * @param appName application name for printouts
95 public Model2Cli(final String modelFile, final OutputFile outFile, final boolean validate, final String appName) {
96 Validate.notNull(modelFile, "Model2Cli: given model file name was blank");
97 Validate.notNull(appName, "Model2Cli: given application name was blank");
99 this.modelFile = modelFile;
100 this.outFile = outFile;
101 this.appName = appName;
102 this.validate = validate;
106 * Runs the application.
108 * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
109 * version), negative integer for errors
111 public int runApp() {
112 final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor();
114 final ApexModelFactory factory = new ApexModelFactory();
115 final ApexModel model = factory.createApexModel(new Properties(), true);
117 final ApexApiResult result = model.loadFromFile(modelFile);
118 if (result.isNok()) {
119 final String message = appName + ": " + result.getMessage();
120 LOGGER.error(message);
124 final AxPolicyModel policyModel = model.getPolicyModel();
125 policyModel.register();
128 final AxValidationResult val = new AxValidationResult();
129 policyModel.validate(val);
131 final String message = "Cannot translate the model. The model is not valid: \n" + val.toString();
132 LOGGER.error(message);
137 return generateCli(codeGen, policyModel);
141 * Generate the CLI from the model.
143 * @param codeGen the code generator
144 * @param policyModel the policy model
146 private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) {
147 kig = new KeyInfoGetter(policyModel);
149 // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies
151 final AxArtifactKey pmkey = policyModel.getKey();
152 codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey));
154 // 1: Context Schemas
155 for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) {
156 final AxArtifactKey key = s.getKey();
158 codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
159 s.getSchemaFlavour(), s.getSchema());
163 for (final AxTask t : policyModel.getTasks().getTaskMap().values()) {
164 final AxArtifactKey key = t.getKey();
165 final List<ST> infields = getInfieldsForTask(codeGen, t);
166 final List<ST> outfields = getOutfieldsForTask(codeGen, t);
167 final ST logic = getLogicForTask(codeGen, t);
168 final List<ST> parameters = getParametersForTask(codeGen, t);
169 final List<ST> contextRefs = getCtxtRefsForTask(codeGen, t);
171 codeGen.addTaskDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
172 infields, outfields, logic, parameters, contextRefs);
176 for (final AxEvent e : policyModel.getEvents().getEventMap().values()) {
177 final AxArtifactKey key = e.getKey();
178 final List<ST> fields = getParametersForEvent(codeGen, e);
180 codeGen.addEventDeclaration(
181 new EventDeclarationBuilder()
182 .setName(kig.getName(key))
183 .setVersion(kig.getVersion(key))
184 .setUuid(kig.getUuid(key))
185 .setDescription(kig.getDesc(key))
186 .setNameSpace(e.getNameSpace())
187 .setSource(e.getSource())
188 .setTarget(e.getTarget())
193 for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) {
194 final AxArtifactKey key = a.getKey();
196 codeGen.addContextAlbumDeclaration(new CodeGenCliEditorBuilder().setName(kig.getName(key))
197 .setVersion(kig.getVersion(key)).setUuid(kig.getUuid(key)).setDescription(kig.getDesc(key))
198 .setScope(a.getScope()).setWritable(a.isWritable()).setSchemaName(kig.getName(a.getItemSchema()))
199 .setSchemaVersion(kig.getVersion(a.getItemSchema())));
203 for (final AxPolicy p : policyModel.getPolicies().getPolicyMap().values()) {
204 final AxArtifactKey key = p.getKey();
205 final List<ST> states = getStatesForPolicy(codeGen, p);
206 codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
207 p.getTemplate(), p.getFirstState(), states);
210 final String out = codeGen.getModel().render();
211 if (outFile != null) {
212 final String message = "Error writing output to file " + outFile;
214 final Writer w = outFile.toWriter();
216 LOGGER.error(message);
221 } catch (final IOException e) {
222 LOGGER.error(message, e);
233 * Gets the parameters for event.
235 * @param cg the code generator
236 * @param event the event
237 * @return the parameters for event
239 private List<ST> getParametersForEvent(final CodeGeneratorCliEditor cg, final AxEvent event) {
240 final Collection<AxField> fields = event.getFields();
241 final List<ST> ret = new ArrayList<>(fields.size());
242 for (final AxField f : fields) {
243 final AxReferenceKey fkey = f.getKey();
245 final ST val = cg.createEventFieldDefinition(kig.getPName(fkey), kig.getPVersion(fkey), kig.getLName(fkey),
246 kig.getName(f.getSchema()), kig.getVersion(f.getSchema()), f.getOptional());
254 * Gets the context references for task.
256 * @param cg the code generator
257 * @param task the task
258 * @return the context references for task
260 private List<ST> getCtxtRefsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
261 final Collection<AxArtifactKey> ctxs = task.getContextAlbumReferences();
262 final List<ST> ret = new ArrayList<>(ctxs.size());
263 final AxArtifactKey tkey = task.getKey();
264 for (final AxArtifactKey ckey : ctxs) {
266 final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey),
267 kig.getVersion(ckey));
275 * Gets the parameters for task.
277 * @param cg the code generator
278 * @param task the task
279 * @return the parameters for task
281 private List<ST> getParametersForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
282 final Collection<AxTaskParameter> pars = task.getTaskParameters().values();
283 final List<ST> ret = new ArrayList<>(pars.size());
284 for (final AxTaskParameter p : pars) {
285 final AxReferenceKey pkey = p.getKey();
287 final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey),
288 kig.getLName(pkey), p.getTaskParameterValue());
296 * Gets the logic for task.
298 * @param cg the code generator
299 * @param task the task
300 * @return the logic for task
302 private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
303 final AxArtifactKey tkey = task.getKey();
304 final AxTaskLogic tl = task.getTaskLogic();
306 return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic());
310 * Gets the output fields for task.
312 * @param cg the code generator
313 * @param task the task
314 * @return the output fields for task
316 private List<ST> getOutfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
317 final Collection<? extends AxField> fields = task.getOutputFields().values();
318 final List<ST> ret = new ArrayList<>(fields.size());
319 for (final AxField f : fields) {
320 final AxReferenceKey fkey = f.getKey();
322 final ST val = cg.createTaskDefinitionOutfields(kig.getPName(fkey), kig.getPVersion(fkey),
323 kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
331 * Gets the input fields for task.
333 * @param cg the code generator
334 * @param task the task
335 * @return the input fields for task
337 private List<ST> getInfieldsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
338 final Collection<? extends AxField> fields = task.getInputFields().values();
339 final List<ST> ret = new ArrayList<>(fields.size());
340 for (final AxField f : fields) {
341 final AxReferenceKey fkey = f.getKey();
343 final ST val = cg.createTaskDefinitionInfields(kig.getPName(fkey), kig.getPVersion(fkey),
344 kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
352 * Gets the states for policy.
354 * @param cg the code generator
355 * @param pol the policy
356 * @return the states for policy
358 private List<ST> getStatesForPolicy(final CodeGeneratorCliEditor cg, final AxPolicy pol) {
359 final Collection<AxState> states = pol.getStateMap().values();
360 final List<ST> ret = new ArrayList<>(states.size());
361 for (final AxState st : states) {
362 final AxReferenceKey skey = st.getKey();
363 final List<ST> outputs = getStateOutputsForState(cg, st);
364 final List<ST> finalizerLogics = getFinalizersForState(cg, st);
365 final List<ST> tasks = getTaskRefsForState(cg, st);
366 final List<ST> tsLogic = getTslForState(cg, st);
367 final List<ST> ctxRefs = getCtxtRefsForState(cg, st);
369 final ST val = cg.createPolicyStateDef(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
370 kig.getName(st.getTrigger()), kig.getVersion(st.getTrigger()), kig.getName(st.getDefaultTask()),
371 kig.getVersion(st.getDefaultTask()), outputs, tasks, tsLogic, finalizerLogics, ctxRefs);
379 * Gets the finalizers for state.
381 * @param cg the code generator
382 * @param st the state
383 * @return the finalizers for state
385 private List<ST> getFinalizersForState(final CodeGeneratorCliEditor cg, final AxState st) {
386 final Collection<AxStateFinalizerLogic> fins = st.getStateFinalizerLogicMap().values();
387 final List<ST> ret = new ArrayList<>(fins.size());
388 final AxReferenceKey skey = st.getKey();
389 for (final AxStateFinalizerLogic fin : fins) {
390 final AxReferenceKey finkey = fin.getKey();
392 final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey),
393 kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic());
401 * Gets the context references for state.
403 * @param cg the code generator
404 * @param st the state
405 * @return the context references for state
407 private List<ST> getCtxtRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
408 final Collection<AxArtifactKey> ctxs = st.getContextAlbumReferences();
409 final List<ST> ret = new ArrayList<>(ctxs.size());
410 final AxReferenceKey skey = st.getKey();
411 for (final AxArtifactKey ctx : ctxs) {
413 final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey),
414 kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx));
422 * Gets the Task Selection Logic for state.
424 * @param cg the code generator
425 * @param st the state
426 * @return the TSL for state (if any) in a list
428 private List<ST> getTslForState(final CodeGeneratorCliEditor cg, final AxState st) {
429 final AxReferenceKey skey = st.getKey();
430 if (st.checkSetTaskSelectionLogic()) {
431 final AxTaskSelectionLogic tsl = st.getTaskSelectionLogic();
432 final ST val = cg.createPolicyStateDefTaskSelLogic(kig.getPName(skey), kig.getPVersion(skey),
433 kig.getLName(skey), tsl.getLogicFlavour(), tsl.getLogic());
434 return Collections.singletonList(val);
436 return Collections.emptyList();
441 * Gets the task references for state.
443 * @param cg the code generator
444 * @param st the state
445 * @return the task references for state
447 private List<ST> getTaskRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
448 final Map<AxArtifactKey, AxStateTaskReference> taskrefs = st.getTaskReferences();
449 final List<ST> ret = new ArrayList<>(taskrefs.size());
450 final AxReferenceKey skey = st.getKey();
451 for (final Entry<AxArtifactKey, AxStateTaskReference> e : taskrefs.entrySet()) {
452 final AxArtifactKey tkey = e.getKey();
453 final AxStateTaskReference tr = e.getValue();
454 final AxReferenceKey trkey = tr.getKey();
456 final ST val = cg.createPolicyStateTask(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
457 kig.getLName(trkey), kig.getName(tkey), kig.getVersion(tkey), tr.getStateTaskOutputType().name(),
458 kig.getLName(tr.getOutput()));
466 * Gets the state outputs for state.
468 * @param cg the code generator
469 * @param st the state
470 * @return the state outputs for state
472 private List<ST> getStateOutputsForState(final CodeGeneratorCliEditor cg, final AxState st) {
473 final Collection<AxStateOutput> outs = st.getStateOutputs().values();
474 final List<ST> ret = new ArrayList<>(outs.size());
475 final AxReferenceKey skey = st.getKey();
476 for (final AxStateOutput out : outs) {
477 final AxReferenceKey outkey = out.getKey();
479 final ST val = cg.createPolicyStateOutput(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
480 kig.getLName(outkey), kig.getName(out.getOutgingEvent()), kig.getVersion(out.getOutgingEvent()),
481 kig.getLName(out.getNextState()));