4d2e99b2387cf5ed826b2831323ba200bf1d524f
[policy/apex-pdp.git] /
1 /*-
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.tools.model.generator.model2cli;
22
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;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Properties;
32
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;
62
63 /**
64  * Takes a model and generates the JSON event schemas.
65  *
66  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
67  */
68 public class Model2Cli {
69     // Logger for this class
70     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Model2Cli.class);
71
72     /** Application name, used as prompt. */
73     private final String appName;
74
75     /** The file name of the policy model. */
76     private final String modelFile;
77
78     /** The output file, if any. */
79     private final OutputFile outFile;
80
81     /** Pre-validate the model. */
82     private final boolean validate;
83
84     /** utility for getting key information and parsing keys etc.. */
85     private KeyInfoGetter kig = null;
86
87     /**
88      * Creates a new model to CLI commands generator.
89      *
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
94      */
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");
98
99         this.modelFile = modelFile;
100         this.outFile = outFile;
101         this.appName = appName;
102         this.validate = validate;
103     }
104
105     /**
106      * Runs the application.
107      *
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
110      */
111     public int runApp() {
112         final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor();
113
114         final ApexModelFactory factory = new ApexModelFactory();
115         final ApexModel model = factory.createApexModel(new Properties(), true);
116
117         final ApexApiResult result = model.loadFromFile(modelFile);
118         if (result.isNok()) {
119             final String message = appName + ": " + result.getMessage();
120             LOGGER.error(message);
121             return -1;
122         }
123
124         final AxPolicyModel policyModel = model.getPolicyModel();
125         policyModel.register();
126
127         if (validate) {
128             final AxValidationResult val = new AxValidationResult();
129             policyModel.validate(val);
130             if (!val.isOk()) {
131                 final String message = "Cannot translate the model. The model is not valid: \n" + val.toString();
132                 LOGGER.error(message);
133                 return -1;
134             }
135         }
136
137         return generateCli(codeGen, policyModel);
138     }
139
140     /**
141      * Generate the CLI from the model.
142      *
143      * @param codeGen the code generator
144      * @param policyModel the policy model
145      */
146     private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) {
147         kig = new KeyInfoGetter(policyModel);
148
149         // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies
150         // 0: model
151         final AxArtifactKey pmkey = policyModel.getKey();
152         codeGen.addModelParams(kig.getName(pmkey), kig.getVersion(pmkey), kig.getUuid(pmkey), kig.getDesc(pmkey));
153
154         // 1: Context Schemas
155         for (final AxContextSchema s : policyModel.getSchemas().getSchemasMap().values()) {
156             final AxArtifactKey key = s.getKey();
157
158             codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
159                     s.getSchemaFlavour(), s.getSchema());
160         }
161
162         // 2: tasks
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);
170
171             codeGen.addTaskDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key),
172                     infields, outfields, logic, parameters, contextRefs);
173         }
174
175         // 3: events
176         for (final AxEvent e : policyModel.getEvents().getEventMap().values()) {
177             final AxArtifactKey key = e.getKey();
178             final List<ST> fields = getParametersForEvent(codeGen, e);
179
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())
189                             .setFields(fields));
190         }
191
192         // 4: context albums
193         for (final AxContextAlbum a : policyModel.getAlbums().getAlbumsMap().values()) {
194             final AxArtifactKey key = a.getKey();
195
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())));
200         }
201
202         // 5: policies
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);
208         }
209
210         final String out = codeGen.getModel().render();
211         if (outFile != null) {
212             final String message = "Error writing output to file " + outFile;
213             try {
214                 final Writer w = outFile.toWriter();
215                 if (w == null) {
216                     LOGGER.error(message);
217                     return -1;
218                 }
219                 w.write(out);
220                 w.close();
221             } catch (final IOException e) {
222                 LOGGER.error(message, e);
223                 return -1;
224             }
225         } else {
226             LOGGER.error(out);
227         }
228
229         return 0;
230     }
231
232     /**
233      * Gets the parameters for event.
234      *
235      * @param cg the code generator
236      * @param event the event
237      * @return the parameters for event
238      */
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();
244
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());
247
248             ret.add(val);
249         }
250         return ret;
251     }
252
253     /**
254      * Gets the context references for task.
255      *
256      * @param cg the code generator
257      * @param task the task
258      * @return the context references for task
259      */
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) {
265
266             final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey),
267                     kig.getVersion(ckey));
268
269             ret.add(val);
270         }
271         return ret;
272     }
273
274     /**
275      * Gets the parameters for task.
276      *
277      * @param cg the code generator
278      * @param task the task
279      * @return the parameters for task
280      */
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();
286
287             final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey),
288                     kig.getLName(pkey), p.getTaskParameterValue());
289
290             ret.add(val);
291         }
292         return ret;
293     }
294
295     /**
296      * Gets the logic for task.
297      *
298      * @param cg the code generator
299      * @param task the task
300      * @return the logic for task
301      */
302     private ST getLogicForTask(final CodeGeneratorCliEditor cg, final AxTask task) {
303         final AxArtifactKey tkey = task.getKey();
304         final AxTaskLogic tl = task.getTaskLogic();
305
306         return cg.createTaskDefLogic(kig.getName(tkey), kig.getVersion(tkey), tl.getLogicFlavour(), tl.getLogic());
307     }
308
309     /**
310      * Gets the output fields for task.
311      *
312      * @param cg the code generator
313      * @param task the task
314      * @return the output fields for task
315      */
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();
321
322             final ST val = cg.createTaskDefinitionOutfields(kig.getPName(fkey), kig.getPVersion(fkey),
323                     kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
324
325             ret.add(val);
326         }
327         return ret;
328     }
329
330     /**
331      * Gets the input fields for task.
332      *
333      * @param cg the code generator
334      * @param task the task
335      * @return the input fields for task
336      */
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();
342
343             final ST val = cg.createTaskDefinitionInfields(kig.getPName(fkey), kig.getPVersion(fkey),
344                     kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema()));
345
346             ret.add(val);
347         }
348         return ret;
349     }
350
351     /**
352      * Gets the states for policy.
353      *
354      * @param cg the code generator
355      * @param pol the policy
356      * @return the states for policy
357      */
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);
368
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);
372
373             ret.add(val);
374         }
375         return ret;
376     }
377
378     /**
379      * Gets the finalizers for state.
380      *
381      * @param cg the code generator
382      * @param st the state
383      * @return the finalizers for state
384      */
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();
391
392             final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey),
393                     kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic());
394
395             ret.add(val);
396         }
397         return ret;
398     }
399
400     /**
401      * Gets the context references for state.
402      *
403      * @param cg the code generator
404      * @param st the state
405      * @return the context references for state
406      */
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) {
412
413             final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey),
414                     kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx));
415
416             ret.add(val);
417         }
418         return ret;
419     }
420
421     /**
422      * Gets the Task Selection Logic for state.
423      *
424      * @param cg the code generator
425      * @param st the state
426      * @return the TSL for state (if any) in a list
427      */
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);
435         } else {
436             return Collections.emptyList();
437         }
438     }
439
440     /**
441      * Gets the task references for state.
442      *
443      * @param cg the code generator
444      * @param st the state
445      * @return the task references for state
446      */
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();
455
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()));
459
460             ret.add(val);
461         }
462         return ret;
463     }
464
465     /**
466      * Gets the state outputs for state.
467      *
468      * @param cg the code generator
469      * @param st the state
470      * @return the state outputs for state
471      */
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();
478
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()));
482
483             ret.add(val);
484         }
485         return ret;
486     }
487
488 }