c0c53cd9fea47e301a1931b670855c23fe978631
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
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.gui.editors.apex.rest.handling;
23
24 import java.util.Map;
25 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
26 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
27 import org.onap.policy.apex.model.modelapi.ApexApiResult;
28 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
29 import org.onap.policy.apex.model.modelapi.ApexModel;
30 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
31 import org.onap.policy.common.utils.coder.CoderException;
32 import org.onap.policy.common.utils.coder.StandardCoder;
33 import org.onap.policy.common.utils.coder.StandardYamlCoder;
34 import org.onap.policy.common.utils.resources.ResourceUtils;
35 import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.PolicyUploadHandler;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
38 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
39 import org.onap.policy.models.tosca.utils.ToscaUtils;
40
41 /**
42  * This class represents an ongoing editor session in the Apex editor and holds the information for the session.
43  *
44  */
45 public class RestSession {
46     // The default TOSCA wrapper for an APEX policy
47     private static final String APEX_TOSCA_POLICY_TEMPLATE = "templates/ApexToscaPolicyTemplate.yaml";
48
49     // Recurring string constants
50     private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters";
51     private static final String POLICY_TYPE_IMPL = "policy_type_impl";
52
53     // The ID of the session
54     private int sessionId;
55
56     // The TOSCA Service Template of the session
57     private ToscaServiceTemplate toscaServiceTemplate;
58
59     // The Apex policy model of the session
60     private ApexModel apexModel;
61
62     // The Apex policy model being edited
63     private ApexModel apexModelEdited;
64
65     /**
66      * Constructor, create the session.
67      *
68      * @param sessionId the session ID of the session
69      * @throws ApexRuntimeException when the APEX TOSCA template file cannot be loaded
70      */
71     public RestSession(final int sessionId) {
72         this.sessionId = sessionId;
73
74         try {
75             this.toscaServiceTemplate = new StandardYamlCoder()
76                 .decode(ResourceUtils.getResourceAsString(APEX_TOSCA_POLICY_TEMPLATE), ToscaServiceTemplate.class);
77         } catch (CoderException e) {
78             throw new ApexRuntimeException("could not load default APEX TOSCA template " + APEX_TOSCA_POLICY_TEMPLATE,
79                 e);
80         }
81
82         this.apexModel = new ApexModelFactory().createApexModel(null, true);
83     }
84
85     /**
86      * Load the policy model from a TOSCA Service Template.
87      *
88      * @param toscaServiceTemplateString The TOSCA service template string
89      * @return the result of the lading operation
90      */
91     public ApexApiResult loadFromString(final String toscaServiceTemplateString) {
92         try {
93             if (toscaServiceTemplateString.startsWith("{")) {
94                 toscaServiceTemplate = new StandardCoder().decode(toscaServiceTemplateString,
95                     ToscaServiceTemplate.class);
96             } else {
97                 toscaServiceTemplate = new StandardYamlCoder().decode(toscaServiceTemplateString,
98                     ToscaServiceTemplate.class);
99             }
100         } catch (Exception e) {
101             return new ApexApiResult(Result.FAILED, "incoming model is not a TOSCA Service template", e);
102         }
103
104         if (!ToscaUtils.doPoliciesExist(new JpaToscaServiceTemplate(toscaServiceTemplate))) {
105             return new ApexApiResult(Result.FAILED, "no policies found on incoming TOSCA service template");
106         }
107
108         @SuppressWarnings("unchecked")
109         Map<String, Object> apexEngineServiceParameterMap = (Map<String, Object>) toscaServiceTemplate
110             .getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next().getProperties()
111             .get(ENGINE_SERVICE_PARAMETERS);
112
113         String apexModelString;
114         try {
115             apexModelString = new StandardCoder().encode(apexEngineServiceParameterMap.get(POLICY_TYPE_IMPL));
116         } catch (CoderException e) {
117             return new ApexApiResult(Result.FAILED, "APEX model not found TOSCA Service template", e);
118         }
119
120         return apexModelEdited.loadFromString(apexModelString);
121     }
122
123     /**
124      * Commence making changes to the Apex model.
125      *
126      * @return the result of the edit commencement operation
127      */
128     public synchronized ApexApiResult editModel() {
129         if (apexModelEdited != null) {
130             return new ApexApiResult(Result.FAILED, "model is already being edited");
131         }
132
133         apexModelEdited = apexModel.clone();
134         return new ApexApiResult();
135     }
136
137     /**
138      * Commit the changes to the Apex model.
139      *
140      * @return the result of the commit operation
141      */
142     public synchronized ApexApiResult commitChanges() {
143         if (apexModelEdited == null) {
144             return new ApexApiResult(Result.FAILED, "model is not being edited");
145         }
146
147         apexModel = apexModelEdited;
148         apexModelEdited = null;
149         return new ApexApiResult();
150     }
151
152     /**
153      * Discard the changes to the Apex model.
154      *
155      * @return the result of the discard operation
156      */
157     public synchronized ApexApiResult discardChanges() {
158         if (apexModelEdited == null) {
159             return new ApexApiResult(Result.FAILED, "model is not being edited");
160         }
161
162         apexModelEdited = null;
163         return new ApexApiResult();
164     }
165
166     /**
167      * Download the apex model as a TOSCA service template YAML string.
168      *
169      * @return the apex model as a TOSCA service template YAML string
170      */
171     public ApexApiResult downloadModel() {
172         ApexModel apexModelToDownload = (apexModelEdited == null ? apexModel : apexModelEdited);
173
174         ToscaPolicy ap = toscaServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next();
175
176         @SuppressWarnings("unchecked")
177         Map<String, Object> apexEngineServiceParameterMap = (Map<String, Object>) ap.getProperties()
178             .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         ApexApiResult 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 }