f5f0d66253e85fc4ca4e6c22493ad0cb5eef4c15
[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  * ================================================================================
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.tools.model.generator.model2cli;
23
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;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Properties;
33
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;
64
65 /**
66  * Takes a model and generates the JSON event schemas.
67  *
68  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
69  */
70 public class Model2Cli {
71     // Logger for this class
72     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class);
73
74     /** Application name, used as prompt. */
75     private final String appName;
76
77     /** The file name of the policy model. */
78     private final String modelFile;
79
80     /** The output file, if any. */
81     private final OutputFile outFile;
82
83     /** Pre-validate the model. */
84     private final boolean validate;
85
86     /** utility for getting key information and parsing keys etc.. */
87     private KeyInfoGetter kig = null;
88
89     /**
90      * Creates a new model to CLI commands generator.
91      *
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
96      */
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");
100
101         this.modelFile = modelFile;
102         this.outFile = outFile;
103         this.appName = appName;
104         this.validate = validate;
105     }
106
107     /**
108      * Runs the application.
109      *
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
112      */
113     public int runApp() {
114         final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor();
115
116         final ApexModelFactory factory = new ApexModelFactory();
117         final ApexModel model = factory.createApexModel(new Properties(), true);
118
119         final ApexApiResult result = model.loadFromFile(modelFile);
120         if (result.isNok()) {
121             final String message = appName + ": " + result.getMessage();
122             LOGGER.error(message);
123             return -1;
124         }
125
126         final AxPolicyModel policyModel = model.getPolicyModel();
127         policyModel.register();
128
129         if (validate) {
130             final AxValidationResult val = new AxValidationResult();
131             policyModel.validate(val);
132             if (!val.isOk()) {
133                 final String message = "Cannot translate the model. The model is not valid: \n" + val.toString();
134                 LOGGER.error(message);
135                 return -1;
136             }
137         }
138
139         return generateCli(codeGen, policyModel);
140     }
141
142     /**
143      * Generate the CLI from the model.
144      *
145      * @param codeGen the code generator
146      * @param policyModel the policy model
147      */
148     private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) {
149         kig = new KeyInfoGetter(policyModel);
150
151         // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies
152         // 0: model
153         final AxArtifactKey pmkey = policyModel.getKey();
154         codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey));
155
156         // 1: Context Schemas
157         for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) {
158             final AxArtifactKey key = s.getKey();
159
160             codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
161                     s.getSchemaFlavour(), s.getSchema());
162         }
163
164         // 2: tasks
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);
172
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));
177         }
178
179         // 3: events
180         for (final AxEvent e : policyModel.getEvents().getEventMap().values()) {
181             final AxArtifactKey key = e.getKey();
182             final List<ST> fields = getParametersForEvent(codeGen, e);
183
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())
193                             .setFields(fields));
194         }
195
196         // 4: context albums
197         for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) {
198             final AxArtifactKey key = a.getKey();
199
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())));
204         }
205
206         // 5: policies
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);
212         }
213
214         final String out = codeGen.getModel().render();
215         if (outFile != null) {
216             final String message = "Error writing output to file " + outFile;
217             try {
218                 final Writer w = outFile.toWriter();
219                 if (w == null) {
220                     LOGGER.error(message);
221                     return -1;
222                 }
223                 w.write(out);
224                 w.close();
225             } catch (final IOException e) {
226                 LOGGER.error(message, e);
227                 return -1;
228             }
229         } else {
230             LOGGER.error(out);
231         }
232
233         return 0;
234     }
235
236     /**
237      * Gets the parameters for event.
238      *
239      * @param cg the code generator
240      * @param event the event
241      * @return the parameters for event
242      */
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();
248
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());
251
252             ret.add(val);
253         }
254         return ret;
255     }
256
257     /**
258      * Gets the context references for task.
259      *
260      * @param cg the code generator
261      * @param task the task
262      * @return the context references for task
263      */
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) {
269
270             final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey),
271                     kig.getVersion(ckey));
272
273             ret.add(val);
274         }
275         return ret;
276     }
277
278     /**
279      * Gets the parameters for task.
280      *
281      * @param cg the code generator
282      * @param task the task
283      * @return the parameters for task
284      */
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();
290
291             final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey),
292                     kig.getLName(pkey), p.getTaskParameterValue());
293
294             ret.add(val);
295         }
296         return ret;
297     }
298
299     /**
300      * Gets the logic for task.
301      *
302      * @param cg the code generator
303      * @param task the task
304      * @return the logic for task
305      */
306     private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
307         final AxArtifactKey tkey = task.getKey();
308         final AxTaskLogic tl = task.getTaskLogic();
309
310         return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic());
311     }
312
313     /**
314      * Gets the output fields for task.
315      *
316      * @param cg the code generator
317      * @param task the task
318      * @return the output fields for task
319      */
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();
325
326             final ST val = cg.createTaskDefinitionOutfields(kig.getPName(fkey), kig.getPVersion(fkey),
327                     kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
328
329             ret.add(val);
330         }
331         return ret;
332     }
333
334     /**
335      * Gets the input fields for task.
336      *
337      * @param cg the code generator
338      * @param task the task
339      * @return the input fields for task
340      */
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();
346
347             final ST val = cg.createTaskDefinitionInfields(kig.getPName(fkey), kig.getPVersion(fkey),
348                     kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
349
350             ret.add(val);
351         }
352         return ret;
353     }
354
355     /**
356      * Gets the states for policy.
357      *
358      * @param cg the code generator
359      * @param pol the policy
360      * @return the states for policy
361      */
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);
372
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);
376
377             ret.add(val);
378         }
379         return ret;
380     }
381
382     /**
383      * Gets the finalizers for state.
384      *
385      * @param cg the code generator
386      * @param st the state
387      * @return the finalizers for state
388      */
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();
395
396             final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey),
397                     kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic());
398
399             ret.add(val);
400         }
401         return ret;
402     }
403
404     /**
405      * Gets the context references for state.
406      *
407      * @param cg the code generator
408      * @param st the state
409      * @return the context references for state
410      */
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) {
416
417             final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey),
418                     kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx));
419
420             ret.add(val);
421         }
422         return ret;
423     }
424
425     /**
426      * Gets the Task Selection Logic for state.
427      *
428      * @param cg the code generator
429      * @param st the state
430      * @return the TSL for state (if any) in a list
431      */
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);
439         } else {
440             return Collections.emptyList();
441         }
442     }
443
444     /**
445      * Gets the task references for state.
446      *
447      * @param cg the code generator
448      * @param st the state
449      * @return the task references for state
450      */
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();
459
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()));
463
464             ret.add(val);
465         }
466         return ret;
467     }
468
469     /**
470      * Gets the state outputs for state.
471      *
472      * @param cg the code generator
473      * @param st the state
474      * @return the state outputs for state
475      */
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();
482
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()));
486
487             ret.add(val);
488         }
489         return ret;
490     }
491
492 }