Refactor babel-related code to not update parameter values
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / entity / model / ModelArtifact.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
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  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.entity.model;
22
23 import java.util.List;
24
25 import org.onap.aai.cl.api.Logger;
26 import org.onap.aai.cl.eelf.LoggerFactory;
27 import org.onap.aai.modelloader.config.ModelLoaderConfig;
28 import org.onap.aai.modelloader.entity.Artifact;
29 import org.onap.aai.modelloader.entity.ArtifactType;
30 import org.onap.aai.modelloader.restclient.AaiRestClient;
31 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
32 import org.springframework.http.HttpStatus;
33 import org.springframework.http.MediaType;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.web.client.HttpClientErrorException;
36 import org.springframework.web.client.HttpServerErrorException;
37
38
39 public class ModelArtifact extends AbstractModelArtifact {
40
41     private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class);
42
43     private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
44
45     private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
46     private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
47
48
49     private String modelVerId;
50     private String modelInvariantId;
51     private String modelVer;
52     private boolean firstVersionOfModel = false;
53
54     public ModelArtifact() {
55         super(ArtifactType.MODEL);
56     }
57
58     public String getModelVerId() {
59         return modelVerId;
60     }
61
62     public void setModelVerId(String modelVerId) {
63         this.modelVerId = modelVerId;
64     }
65
66     public String getModelInvariantId() {
67         return modelInvariantId;
68     }
69
70     public void setModelInvariantId(String modelInvariantId) {
71         this.modelInvariantId = modelInvariantId;
72     }
73
74     public String getModelVer() {
75         return modelVer;
76     }
77
78     public void setModelVer(String modelVer) {
79         this.modelVer = modelVer;
80     }
81
82     @Override
83     public String getUniqueIdentifier() {
84         return getModelInvariantId() + "|" + getModelVerId();
85     }
86
87
88     /**
89      * Test whether the specified resource (URL) can be requested successfully
90      *
91      * @param aaiClient
92      * @param distId
93      * @param xmlResourceUrl
94      * @return true if a request to GET this resource as XML media is successful (status OK)
95      */
96     private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
97         try {
98             ResponseEntity<Model> getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl);
99             return getResponse.getStatusCode().equals(HttpStatus.OK);
100         } catch (HttpClientErrorException e) {
101             if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
102                 return false;
103             } else {
104                 throw e;
105             }
106         }
107     }
108
109     /**
110      * Test whether the specified resource (URL) can be requested successfully
111      *
112      * @param aaiClient
113      * @param distId
114      * @param xmlResourceUrl
115      * @return OperationResult the result of the operation
116      */
117     private ResponseEntity<Model> getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
118         return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML, Model.class);
119     }
120
121     /**
122      * PUT the specified XML resource
123      *
124      * @param aaiClient
125      * @param distId
126      * @param resourceUrl
127      * @param payload
128      * @return true if the resource PUT as XML media was successful (status OK)
129      */
130     private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) {
131         ResponseEntity<String> putResponse = null;
132         try {
133             putResponse =
134                     aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML, String.class);
135         } catch (HttpClientErrorException | HttpServerErrorException e) {
136             logger.error(ModelLoaderMsgs.AAI_REST_REQUEST_ERROR, "Error putting resource: " + e.toString());
137         }
138         return putResponse != null && putResponse.getStatusCode() == HttpStatus.CREATED;
139     }
140
141     @Override
142     public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
143             List<Artifact> completedArtifacts) {
144         if (config.useGizmo()) {
145             return pushToGizmo(aaiClient, config, distId);
146         }
147
148         return pushToResources(aaiClient, config, distId, completedArtifacts);
149     }
150
151     private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
152             List<Artifact> completedArtifacts) {
153         boolean success = false;
154
155         // See whether the model is already present
156         String resourceUrl = getModelUrl(config);
157         // ResponseEntity<Model> result;
158         boolean modelExists = checkIfModelExists(aaiClient, distId, resourceUrl);
159
160         if(modelExists) {
161             success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
162         } else {
163             success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
164         }
165
166         // if (result != null) {
167         //     if (result.getStatusCode() == HttpStatus.OK) {
168         //         success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
169         //     } else if (result.getStatusCode() == HttpStatus.NOT_FOUND) {
170         //         success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
171         //     } else {
172         //         logModelUpdateFailure(
173         //                 "Response code " + result.getStatusCodeValue() + " invalid for getting resource model");
174         //     }
175         // } else {
176         //     logModelUpdateFailure("Null response from RestClient");
177         // }
178
179         return success;
180     }
181
182     private boolean checkIfModelExists(AaiRestClient aaiClient, String distId, String resourceUrl) throws HttpClientErrorException {
183         try {
184             ResponseEntity<Model> response = getResourceModel(aaiClient, distId, resourceUrl);
185             return response.getStatusCode().equals(HttpStatus.OK);
186         } catch (HttpClientErrorException e) {
187             if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
188                 return false;
189             } else {
190                 throw e;
191             }
192         }
193     }
194
195     private boolean createNewModel(AaiRestClient aaiClient, String distId, List<Artifact> completedArtifacts,
196             String resourceUrl) {
197         boolean success;
198         // Assume that the model does not exist and attempt the PUT
199         success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
200         if (success) {
201             completedArtifacts.add(this);
202
203             // Record state to remember that this is the first version of the model (just added).
204             firstVersionOfModel = true;
205
206             logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
207         } else {
208             logModelUpdateFailure("Error creating model. Skipping ingestion.");
209         }
210         return success;
211     }
212
213     private void logModelUpdateFailure(String message) {
214         logErrorMsg(FAILURE_MSG_PREFIX + getType() + " " + getUniqueIdentifier() + " " + message + ROLLBACK_MSG_SUFFIX);
215     }
216
217     private boolean updateExistingModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
218             List<Artifact> completedArtifacts) {
219         boolean success;
220         logInfoMsg(getType() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
221         success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
222         return success;
223     }
224
225     /**
226      * @param aaiClient
227      * @param config
228      * @param distId
229      * @param completedArtifacts
230      * @return
231      */
232     private boolean pushModelVersion(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
233             List<Artifact> completedArtifacts) {
234         if (xmlResourceCanBeFetched(aaiClient, distId, getModelVerUrl(config))) {
235             logInfoMsg(getType() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
236             return true;
237         }
238
239         // Load the model version
240         boolean success = true;
241         success = putXmlResource(aaiClient, distId, getModelVerUrl(config), getModelVer());
242         if (success) {
243             completedArtifacts.add(this);
244             logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
245         } else {
246             logModelUpdateFailure("Error pushing model");
247         }
248
249         return success;
250     }
251
252
253     @Override
254     public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
255         // Gizmo is resilient and doesn't require a rollback. A redistribution will work fine even if
256         // the model is partially loaded.
257         if (config.useGizmo()) {
258             return;
259         }
260
261         String url = getModelVerUrl(config);
262         if (firstVersionOfModel) {
263             // If this was the first version of the model which was added, we want to remove the entire
264             // model rather than just the version.
265             url = getModelUrl(config);
266         }
267
268         // Best effort to delete. Nothing we can do in the event this fails.
269         aaiClient.getAndDeleteResource(url, distId);
270     }
271
272     private String getModelUrl(ModelLoaderConfig config) {
273         String baseURL = config.getAaiBaseUrl().trim();
274         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
275         String instance = getModelInvariantId();
276
277         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
278             baseURL = baseURL + "/";
279         }
280
281         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
282             baseURL = baseURL.substring(0, baseURL.length() - 1);
283         }
284
285         if (!subURL.endsWith("/")) {
286             subURL = subURL + "/";
287         }
288
289         return baseURL + subURL + instance;
290     }
291
292     private String getModelVerUrl(ModelLoaderConfig config) {
293         String baseURL = config.getAaiBaseUrl().trim();
294         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId()
295                 + AAI_MODEL_VER_SUB_URL;
296         String instance = getModelVerId();
297
298         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
299             baseURL = baseURL + "/";
300         }
301
302         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
303             baseURL = baseURL.substring(0, baseURL.length() - 1);
304         }
305
306         if (!subURL.endsWith("/")) {
307             subURL = subURL + "/";
308         }
309
310         return baseURL + subURL + instance;
311     }
312 }