662c634bf2f84c8272c33f6d68ac399554baaf82
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.gui.editors.apex.rest.handling;
25
26 import java.util.Map;
27 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
28 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
29 import org.onap.policy.apex.model.modelapi.ApexApiResult;
30 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
31 import org.onap.policy.apex.model.modelapi.ApexModel;
32 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
33 import org.onap.policy.common.utils.coder.CoderException;
34 import org.onap.policy.common.utils.coder.StandardCoder;
35 import org.onap.policy.common.utils.coder.StandardYamlCoder;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.PolicyUploadHandler;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
40 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
41 import org.onap.policy.models.tosca.utils.ToscaUtils;
42
43 /**
44  * This class represents an ongoing editor session in the Apex editor and holds the information for the session.
45  *
46  */
47 public class RestSession {
48     // The default TOSCA wrapper for an APEX policy
49     private static final String APEX_TOSCA_POLICY_TEMPLATE = "templates/ApexToscaPolicyTemplate.yaml";
50
51     // Recurring string constants
52     private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters";
53     private static final String POLICY_TYPE_IMPL = "policy_type_impl";
54
55     // The ID of the session
56     private int sessionId;
57
58     // The TOSCA Service Template of the session
59     private ToscaServiceTemplate toscaServiceTemplate;
60
61     // The Apex policy model of the session
62     private ApexModel apexModel;
63
64     // The Apex policy model being edited
65     private ApexModel apexModelEdited;
66
67     /**
68      * Constructor, create the session.
69      *
70      * @param sessionId the session ID of the session
71      * @throws ApexRuntimeException when the APEX TOSCA template file cannot be loaded
72      */
73     public RestSession(final int sessionId) {
74         this.sessionId = sessionId;
75
76         try {
77             this.toscaServiceTemplate = new StandardYamlCoder()
78                 .decode(ResourceUtils.getResourceAsString(APEX_TOSCA_POLICY_TEMPLATE), ToscaServiceTemplate.class);
79         } catch (CoderException e) {
80             throw new ApexRuntimeException("could not load default APEX TOSCA template " + APEX_TOSCA_POLICY_TEMPLATE,
81                 e);
82         }
83
84         this.apexModel = new ApexModelFactory().createApexModel(null, true);
85     }
86
87     /**
88      * Load the policy model from a TOSCA Service Template.
89      *
90      * @param toscaServiceTemplateString The TOSCA service template string
91      * @return the result of the lading operation
92      */
93     public ApexApiResult loadFromString(final String toscaServiceTemplateString) {
94         try {
95             if (toscaServiceTemplateString.startsWith("{")) {
96                 toscaServiceTemplate = new StandardCoder().decode(toscaServiceTemplateString,
97                     ToscaServiceTemplate.class);
98             } else {
99                 toscaServiceTemplate = new StandardYamlCoder().decode(toscaServiceTemplateString,
100                     ToscaServiceTemplate.class);
101             }
102         } catch (Exception e) {
103             return new ApexApiResult(Result.FAILED, "incoming model is not a TOSCA Service template", e);
104         }
105
106         if (!ToscaUtils.doPoliciesExist(new JpaToscaServiceTemplate(toscaServiceTemplate))) {
107             return new ApexApiResult(Result.FAILED, "no policies found on incoming TOSCA service template");
108         }
109
110         @SuppressWarnings("unchecked")
111         var apexEngineServiceParameterMap = (Map<String, Object>) toscaServiceTemplate
112             .getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next().getProperties()
113             .get(ENGINE_SERVICE_PARAMETERS);
114
115         String apexModelString;
116         try {
117             apexModelString = new StandardCoder().encode(apexEngineServiceParameterMap.get(POLICY_TYPE_IMPL));
118         } catch (CoderException e) {
119             return new ApexApiResult(Result.FAILED, "APEX model not found TOSCA Service template", e);
120         }
121
122         return apexModelEdited.loadFromString(apexModelString);
123     }
124
125     /**
126      * Commence making changes to the Apex model.
127      *
128      * @return the result of the edit commencement operation
129      */
130     public synchronized ApexApiResult editModel() {
131         if (apexModelEdited != null) {
132             return new ApexApiResult(Result.FAILED, "model is already being edited");
133         }
134
135         apexModelEdited = apexModel.clone();
136         return new ApexApiResult();
137     }
138
139     /**
140      * Commit the changes to the Apex model.
141      *
142      * @return the result of the commit operation
143      */
144     public synchronized ApexApiResult commitChanges() {
145         if (apexModelEdited == null) {
146             return new ApexApiResult(Result.FAILED, "model is not being edited");
147         }
148
149         apexModel = apexModelEdited;
150         apexModelEdited = null;
151         return new ApexApiResult();
152     }
153
154     /**
155      * Discard the changes to the Apex model.
156      *
157      * @return the result of the discard operation
158      */
159     public synchronized ApexApiResult discardChanges() {
160         if (apexModelEdited == null) {
161             return new ApexApiResult(Result.FAILED, "model is not being edited");
162         }
163
164         apexModelEdited = null;
165         return new ApexApiResult();
166     }
167
168     /**
169      * Download the apex model as a TOSCA service template YAML string.
170      *
171      * @return the apex model as a TOSCA service template YAML string
172      */
173     public ApexApiResult downloadModel() {
174         ApexModel apexModelToDownload = (apexModelEdited == null ? apexModel : apexModelEdited);
175
176         ToscaPolicy ap = toscaServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next();
177
178         @SuppressWarnings("unchecked")
179         var apexEngineServiceParameterMap = (Map<String, Object>) ap.getProperties().get(ENGINE_SERVICE_PARAMETERS);
180
181         Object decoded = null;
182         try {
183             decoded = new StandardCoder().decode(apexModelToDownload.listModel().getMessage(), Object.class);
184         } catch (Exception e) {
185             return new ApexApiResult(Result.FAILED, "insertion of APEX model into TOSCA Service template failed", e);
186         }
187
188         apexEngineServiceParameterMap.put(POLICY_TYPE_IMPL, decoded);
189
190         var result = new ApexApiResult();
191         try {
192             result.addMessage(new StandardYamlCoder().encode(toscaServiceTemplate));
193         } catch (CoderException e) {
194             return new ApexApiResult(Result.FAILED, "encoding of TOSCA Service template into YAML failed", e);
195         }
196
197         return result;
198     }
199
200     /**
201      * Upload the apex model as a TOSCA service template YAML string to the configured URL.
202      *
203      * @return a result indicating if the upload was successful or not
204      */
205     public ApexApiResult uploadModel() {
206         // Get the model in TOSCA format
207         ApexApiResult result = downloadModel();
208         if (result.isNok()) {
209             return result;
210         }
211
212         ApexModel apexModelBeingUploaded = (apexModelEdited == null ? apexModel : apexModelEdited);
213
214         AxArtifactKey policyModelKey = apexModelBeingUploaded.getPolicyModel().getKey();
215
216         var policyModelUUid = apexModelBeingUploaded.getPolicyModel().getKeyInformation().get(policyModelKey)
217             .getUuid().toString();
218         return new PolicyUploadHandler().doUpload(result.getMessage(), policyModelKey, policyModelUUid);
219     }
220
221     /**
222      * Finish a session by committing or discarding the changes.
223      *
224      * @param commitFlag if true, commit changes otherwise discard them
225      */
226     public void finishSession(boolean commitFlag) {
227         if (commitFlag) {
228             commitChanges();
229         } else {
230             discardChanges();
231         }
232     }
233
234     /**
235      * Get the session ID of the session.
236      *
237      * @return the sessionId
238      */
239     public int getSessionId() {
240         return sessionId;
241     }
242
243     /**
244      * Get the Apex model of the session.
245      *
246      * @return the apexModel
247      */
248     public ApexModel getApexModel() {
249         return apexModel;
250     }
251
252     /**
253      * Get the edited Apex model of the session.
254      *
255      * @return the apexModel
256      */
257     public ApexModel getApexModelEdited() {
258         return apexModelEdited;
259     }
260 }