b5f6f432ab372270796e133e0ea879b5c30e851e
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.tools.model.generator.model2cli;
24
25 import java.io.IOException;
26 import java.io.Writer;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 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.PolicyStateDefBuilder;
39 import org.onap.policy.apex.auth.clicodegen.PolicyStateTaskBuilder;
40 import org.onap.policy.apex.auth.clicodegen.TaskDeclarationBuilder;
41 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
42 import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
43 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
44 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
45 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
46 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
47 import org.onap.policy.apex.model.eventmodel.concepts.AxField;
48 import org.onap.policy.apex.model.modelapi.ApexApiResult;
49 import org.onap.policy.apex.model.modelapi.ApexModel;
50 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
51 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
52 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
53 import org.onap.policy.apex.model.policymodel.concepts.AxState;
54 import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
55 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
56 import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference;
57 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
58 import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic;
59 import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
60 import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic;
61 import org.onap.policy.apex.tools.common.OutputFile;
62 import org.onap.policy.apex.tools.model.generator.KeyInfoGetter;
63 import org.slf4j.ext.XLogger;
64 import org.slf4j.ext.XLoggerFactory;
65 import org.stringtemplate.v4.ST;
66
67 /**
68  * Takes a model and generates the JSON event schemas.
69  *
70  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
71  */
72 public class Model2Cli {
73     // Logger for this class
74     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class);
75
76     /** Application name, used as prompt. */
77     private final String appName;
78
79     /** The file name of the policy model. */
80     private final String modelFile;
81
82     /** The output file, if any. */
83     private final OutputFile outFile;
84
85     /** Pre-validate the model. */
86     private final boolean validate;
87
88     /** utility for getting key information and parsing keys etc.. */
89     private KeyInfoGetter kig = null;
90
91     /**
92      * Creates a new model to CLI commands generator.
93      *
94      * @param modelFile the model file to be used
95      * @param outFile the out file
96      * @param validate true for model validation, false otherwise
97      * @param appName application name for printouts
98      */
99     public Model2Cli(final String modelFile, final OutputFile outFile, final boolean validate, final String appName) {
100         Validate.notNull(modelFile, "Model2Cli: given model file name was blank");
101         Validate.notNull(appName, "Model2Cli: given application name was blank");
102
103         this.modelFile = modelFile;
104         this.outFile = outFile;
105         this.appName = appName;
106         this.validate = validate;
107     }
108
109     /**
110      * Runs the application.
111      *
112      * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or
113      *         version), negative integer for errors
114      */
115     public int runApp() {
116         final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor();
117
118         final ApexModelFactory factory = new ApexModelFactory();
119         final ApexModel model = factory.createApexModel(new Properties(), true);
120
121         final ApexApiResult result = model.loadFromFile(modelFile);
122         if (result.isNok()) {
123             final String message = appName + ": " + result.getMessage();
124             LOGGER.error(message);
125             return -1;
126         }
127
128         final AxPolicyModel policyModel = model.getPolicyModel();
129         policyModel.register();
130
131         if (validate) {
132             final AxValidationResult val = new AxValidationResult();
133             policyModel.validate(val);
134             if (!val.isOk()) {
135                 final String message = "Cannot translate the model. The model is not valid: \n" + val.toString();
136                 LOGGER.error(message);
137                 return -1;
138             }
139         }
140
141         return generateCli(codeGen, policyModel);
142     }
143
144     /**
145      * Generate the CLI from the model.
146      *
147      * @param codeGen the code generator
148      * @param policyModel the policy model
149      */
150     private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) {
151         kig = new KeyInfoGetter(policyModel);
152
153         // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies
154         // 0: model
155         final AxArtifactKey pmkey = policyModel.getKey();
156         codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey));
157
158         // 1: Context Schemas
159         for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) {
160             final AxArtifactKey key = s.getKey();
161
162             codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
163                     s.getSchemaFlavour(), s.getSchema());
164         }
165
166         // 2: tasks
167         for (final AxTask t : policyModel.getTasks().getTaskMap().values()) {
168             final AxArtifactKey key = t.getKey();
169             final ST logic = getLogicForTask(codeGen, t);
170             final List<ST> parameters = getParametersForTask(codeGen, t);
171             final List<ST> contextRefs = getCtxtRefsForTask(codeGen, t);
172
173             codeGen.addTaskDeclaration(new TaskDeclarationBuilder().setName(kig.getName(key))
174                 .setVersion(kig.getVersion(key)).setUuid(kig.getUuid(key)).setDescription(kig.getDesc(key))
175                 .setLogic(logic).setParameters(parameters).setContextRefs(contextRefs));
176         }
177
178         // 3: events
179         for (final AxEvent e : policyModel.getEvents().getEventMap().values()) {
180             final AxArtifactKey key = e.getKey();
181             final List<ST> fields = getParametersForEvent(codeGen, e);
182
183             codeGen.addEventDeclaration(
184                     new EventDeclarationBuilder()
185                             .setName(kig.getName(key))
186                             .setVersion(kig.getVersion(key))
187                             .setUuid(kig.getUuid(key))
188                             .setDescription(kig.getDesc(key))
189                             .setNameSpace(e.getNameSpace())
190                             .setSource(e.getSource())
191                             .setTarget(e.getTarget())
192                             .setFields(fields));
193         }
194
195         // 4: context albums
196         for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) {
197             final AxArtifactKey key = a.getKey();
198
199             codeGen.addContextAlbumDeclaration(new CodeGenCliEditorBuilder().setName(kig.getName(key))
200                     .setVersion(kig.getVersion(key)).setUuid(kig.getUuid(key)).setDescription(kig.getDesc(key))
201                     .setScope(a.getScope()).setWritable(a.isWritable()).setSchemaName(kig.getName(a.getItemSchema()))
202                     .setSchemaVersion(kig.getVersion(a.getItemSchema())));
203         }
204
205         // 5: policies
206         for (final AxPolicy p : policyModel.getPolicies().getPolicyMap().values()) {
207             final AxArtifactKey key = p.getKey();
208             final List<ST> states = getStatesForPolicy(codeGen, p);
209             codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
210                     p.getTemplate(), p.getFirstState(), states);
211         }
212
213         final String out = codeGen.getModel().render();
214         if (outFile != null) {
215             final String message = "Error writing output to file " + outFile;
216             try {
217                 final Writer w = outFile.toWriter();
218                 if (w == null) {
219                     LOGGER.error(message);
220                     return -1;
221                 }
222                 w.write(out);
223                 w.close();
224             } catch (final IOException e) {
225                 LOGGER.error(message, e);
226                 return -1;
227             }
228         } else {
229             LOGGER.error(out);
230         }
231
232         return 0;
233     }
234
235     /**
236      * Gets the parameters for event.
237      *
238      * @param cg the code generator
239      * @param event the event
240      * @return the parameters for event
241      */
242     private List<ST> getParametersForEvent(final CodeGeneratorCliEditor cg, final AxEvent event) {
243         final Collection<AxField> fields = event.getFields();
244         final List<ST> ret = new ArrayList<>(fields.size());
245         for (final AxField f : fields) {
246             final AxReferenceKey fkey = f.getKey();
247
248             final ST val = cg.createEventFieldDefinition(kig.getPName(fkey), kig.getPVersion(fkey), kig.getLName(fkey),
249                     kig.getName(f.getSchema()), kig.getVersion(f.getSchema()), f.getOptional());
250
251             ret.add(val);
252         }
253         return ret;
254     }
255
256     /**
257      * Gets the context references for task.
258      *
259      * @param cg the code generator
260      * @param task the task
261      * @return the context references for task
262      */
263     private List<ST> getCtxtRefsForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
264         final Collection<AxArtifactKey> ctxs = task.getContextAlbumReferences();
265         final List<ST> ret = new ArrayList<>(ctxs.size());
266         final AxArtifactKey tkey = task.getKey();
267         for (final AxArtifactKey ckey : ctxs) {
268
269             final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey),
270                     kig.getVersion(ckey));
271
272             ret.add(val);
273         }
274         return ret;
275     }
276
277     /**
278      * Gets the parameters for task.
279      *
280      * @param cg the code generator
281      * @param task the task
282      * @return the parameters for task
283      */
284     private List<ST> getParametersForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
285         final Collection<AxTaskParameter> pars = task.getTaskParameters().values();
286         final List<ST> ret = new ArrayList<>(pars.size());
287         for (final AxTaskParameter p : pars) {
288             final AxReferenceKey pkey = p.getKey();
289
290             final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey),
291                     kig.getLName(pkey), p.getTaskParameterValue());
292
293             ret.add(val);
294         }
295         return ret;
296     }
297
298     /**
299      * Gets the logic for task.
300      *
301      * @param cg the code generator
302      * @param task the task
303      * @return the logic for task
304      */
305     private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
306         final AxArtifactKey tkey = task.getKey();
307         final AxTaskLogic tl = task.getTaskLogic();
308
309         return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic());
310     }
311
312     /**
313      * Gets the states for policy.
314      *
315      * @param cg the code generator
316      * @param pol the policy
317      * @return the states for policy
318      */
319     private List<ST> getStatesForPolicy(final CodeGeneratorCliEditor cg, final AxPolicy pol) {
320         final Collection<AxState> states = pol.getStateMap().values();
321         final List<ST> ret = new ArrayList<>(states.size());
322         for (final AxState st : states) {
323             final AxReferenceKey skey = st.getKey();
324             final List<ST> outputs = getStateOutputsForState(cg, st);
325             final List<ST> finalizerLogics = getFinalizersForState(cg, st);
326             final List<ST> tasks = getTaskRefsForState(cg, st);
327             final List<ST> tsLogic = getTslForState(cg, st);
328             final List<ST> ctxRefs = getCtxtRefsForState(cg, st);
329
330             final ST val = cg.createPolicyStateDef(new PolicyStateDefBuilder()
331                     .setPolicyName(kig.getPName(skey)).setVersion(kig.getPVersion(skey))
332                     .setStateName(kig.getLName(skey)).setTriggerName(kig.getName(st.getTrigger()))
333                     .setTriggerVersion(kig.getVersion(st.getTrigger()))
334                     .setDefaultTask(kig.getName(st.getDefaultTask()))
335                     .setDefaultTaskVersion(kig.getVersion(st.getDefaultTask())).setOutputs(outputs)
336                     .setTasks(tasks).setTsLogic(tsLogic).setFinalizerLogics(finalizerLogics)
337                     .setCtxRefs(ctxRefs));
338
339             ret.add(val);
340         }
341         return ret;
342     }
343
344     /**
345      * Gets the finalizers for state.
346      *
347      * @param cg the code generator
348      * @param st the state
349      * @return the finalizers for state
350      */
351     private List<ST> getFinalizersForState(final CodeGeneratorCliEditor cg, final AxState st) {
352         final Collection<AxStateFinalizerLogic> fins = st.getStateFinalizerLogicMap().values();
353         final List<ST> ret = new ArrayList<>(fins.size());
354         final AxReferenceKey skey = st.getKey();
355         for (final AxStateFinalizerLogic fin : fins) {
356             final AxReferenceKey finkey = fin.getKey();
357
358             final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey),
359                     kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic());
360
361             ret.add(val);
362         }
363         return ret;
364     }
365
366     /**
367      * Gets the context references for state.
368      *
369      * @param cg the code generator
370      * @param st the state
371      * @return the context references for state
372      */
373     private List<ST> getCtxtRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
374         final Collection<AxArtifactKey> ctxs = st.getContextAlbumReferences();
375         final List<ST> ret = new ArrayList<>(ctxs.size());
376         final AxReferenceKey skey = st.getKey();
377         for (final AxArtifactKey ctx : ctxs) {
378
379             final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey),
380                     kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx));
381
382             ret.add(val);
383         }
384         return ret;
385     }
386
387     /**
388      * Gets the Task Selection Logic for state.
389      *
390      * @param cg the code generator
391      * @param st the state
392      * @return the TSL for state (if any) in a list
393      */
394     private List<ST> getTslForState(final CodeGeneratorCliEditor cg, final AxState st) {
395         final AxReferenceKey skey = st.getKey();
396         if (st.checkSetTaskSelectionLogic()) {
397             final AxTaskSelectionLogic tsl = st.getTaskSelectionLogic();
398             final ST val = cg.createPolicyStateDefTaskSelLogic(kig.getPName(skey), kig.getPVersion(skey),
399                     kig.getLName(skey), tsl.getLogicFlavour(), tsl.getLogic());
400             return Collections.singletonList(val);
401         } else {
402             return Collections.emptyList();
403         }
404     }
405
406     /**
407      * Gets the task references for state.
408      *
409      * @param cg the code generator
410      * @param st the state
411      * @return the task references for state
412      */
413     private List<ST> getTaskRefsForState(final CodeGeneratorCliEditor cg, final AxState st) {
414         final Map<AxArtifactKey, AxStateTaskReference> taskrefs = st.getTaskReferences();
415         final List<ST> ret = new ArrayList<>(taskrefs.size());
416         final AxReferenceKey skey = st.getKey();
417         for (final Entry<AxArtifactKey, AxStateTaskReference> e : taskrefs.entrySet()) {
418             final AxArtifactKey tkey = e.getKey();
419             final AxStateTaskReference tr = e.getValue();
420             final AxReferenceKey trkey = tr.getKey();
421
422             final ST val = cg.createPolicyStateTask(new PolicyStateTaskBuilder()
423                     .setPolicyName(kig.getPName(skey)).setVersion(kig.getPVersion(skey))
424                     .setStateName(kig.getLName(skey)).setTaskLocalName(kig.getLName(trkey))
425                     .setTaskName(kig.getName(tkey)).setTaskVersion(kig.getVersion(tkey))
426                     .setOutputType(tr.getStateTaskOutputType().name())
427                     .setOutputName(kig.getLName(tr.getOutput())));
428
429             ret.add(val);
430         }
431         return ret;
432     }
433
434     /**
435      * Gets the state outputs for state.
436      *
437      * @param cg the code generator
438      * @param st the state
439      * @return the state outputs for state
440      */
441     private List<ST> getStateOutputsForState(final CodeGeneratorCliEditor cg, final AxState st) {
442         final Collection<AxStateOutput> outs = st.getStateOutputs().values();
443         final List<ST> ret = new ArrayList<>(outs.size());
444         final AxReferenceKey skey = st.getKey();
445         for (final AxStateOutput out : outs) {
446             final AxReferenceKey outkey = out.getKey();
447
448             final ST val = cg.createPolicyStateOutput(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey),
449                     kig.getLName(outkey), kig.getName(out.getOutgoingEvent()), kig.getVersion(out.getOutgoingEvent()),
450                     kig.getLName(out.getNextState()));
451
452             ret.add(val);
453         }
454         return ret;
455     }
456
457 }