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