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