Configurable option to load models via Gizmo
[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.io.StringWriter;
24 import java.util.List;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27 import javax.xml.XMLConstants;
28 import javax.xml.transform.OutputKeys;
29 import javax.xml.transform.Transformer;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
34
35 import org.onap.aai.modelloader.config.ModelLoaderConfig;
36 import org.onap.aai.modelloader.entity.ArtifactType;
37 import org.onap.aai.modelloader.restclient.AaiRestClient;
38 import org.onap.aai.modelloader.entity.Artifact;
39 import org.onap.aai.restclient.client.OperationResult;
40
41 import org.w3c.dom.Node;
42
43
44 public class ModelArtifact extends AbstractModelArtifact {
45
46     private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
47
48     private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
49     private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
50
51
52     private String modelVerId;
53     private String modelInvariantId;
54     private Node modelVer;
55     private boolean firstVersionOfModel = false;
56
57     public ModelArtifact() {
58         super(ArtifactType.MODEL);
59     }
60
61     public String getModelVerId() {
62         return modelVerId;
63     }
64
65     public void setModelVerId(String modelVerId) {
66         this.modelVerId = modelVerId;
67     }
68
69     public String getModelInvariantId() {
70         return modelInvariantId;
71     }
72
73     public void setModelInvariantId(String modelInvariantId) {
74         this.modelInvariantId = modelInvariantId;
75     }
76
77     public Node getModelVer() {
78         return modelVer;
79     }
80
81     public void setModelVer(Node modelVer) {
82         this.modelVer = modelVer;
83     }
84
85     @Override
86     public String getUniqueIdentifier() {
87         return getModelInvariantId() + "|" + getModelVerId();
88     }
89
90
91     /**
92      * Test whether the specified resource (URL) can be requested successfully
93      * 
94      * @param aaiClient
95      * @param distId
96      * @param xmlResourceUrl
97      * @return true if a request to GET this resource as XML media is successful (status OK)
98      */
99     private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
100         OperationResult getResponse = aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML_TYPE);
101         return getResponse != null && getResponse.getResultCode() == Response.Status.OK.getStatusCode();
102     }
103
104     /**
105      * PUT the specified XML resource
106      * 
107      * @param aaiClient
108      * @param distId
109      * @param resourceUrl
110      * @param payload
111      * @return true if the resource PUT as XML media was successful (status OK)
112      */
113     private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) {
114         OperationResult putResponse =
115                 aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML_TYPE);
116         return putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode();
117     }
118
119     @Override
120     public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
121             List<Artifact> completedArtifacts) {        
122         if (config.useGizmo()) {
123             return pushToGizmo(aaiClient, config, distId, completedArtifacts);
124         }
125
126         return pushToResources(aaiClient, config, distId, completedArtifacts);
127     }
128     
129     private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
130             List<Artifact> completedArtifacts) {
131         boolean success;
132
133         // See whether the model is already present
134         String resourceUrl = getModelUrl(config);
135
136         if (xmlResourceCanBeFetched(aaiClient, distId, resourceUrl)) {
137             logInfoMsg(getType().toString() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
138             success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
139         } else {
140             // Assume that the model does not exist and attempt the PUT
141             success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
142             if (success) {
143                 completedArtifacts.add(this);
144
145                 // Record state to remember that this is the first version of the model (just added).
146                 firstVersionOfModel = true;
147
148                 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
149             } else {
150                 logErrorMsg(
151                         FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
152             }
153         }
154
155         return success;
156     }    
157
158     /**
159      * @param aaiClient
160      * @param config
161      * @param distId
162      * @param completedArtifacts
163      * @return
164      */
165     private boolean pushModelVersion(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
166             List<Artifact> completedArtifacts) {
167         if (xmlResourceCanBeFetched(aaiClient, distId, getModelVerUrl(config))) {
168             logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
169             return true;
170         }
171
172         // Load the model version
173         boolean success = true;
174         try {
175             success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer()));
176             if (success) {
177                 completedArtifacts.add(this);
178                 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
179             } else {
180                 logErrorMsg(
181                         FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
182             }
183         } catch (TransformerException e) {
184             logErrorMsg(FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ": " + e.getMessage()
185                     + ROLLBACK_MSG_SUFFIX);
186             success = false;
187         }
188
189         return success;
190     }
191
192
193     @Override
194     public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
195         // Gizmo is resilient and doesn't require a rollback.  A redistribution will work fine even if 
196         // the model is partially loaded.
197         if (config.useGizmo()) {
198             return;
199         }
200         
201         String url = getModelVerUrl(config);
202         if (firstVersionOfModel) {
203             // If this was the first version of the model which was added, we want to remove the entire
204             // model rather than just the version.
205             url = getModelUrl(config);
206         }
207
208         // Best effort to delete. Nothing we can do in the event this fails.
209         aaiClient.getAndDeleteResource(url, distId);
210     }
211
212     private String getModelUrl(ModelLoaderConfig config) {
213         String baseURL = config.getAaiBaseUrl().trim();
214         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
215         String instance = getModelInvariantId();
216
217         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
218             baseURL = baseURL + "/";
219         }
220
221         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
222             baseURL = baseURL.substring(0, baseURL.length() - 1);
223         }
224
225         if (!subURL.endsWith("/")) {
226             subURL = subURL + "/";
227         }
228
229         return baseURL + subURL + instance;
230     }
231
232     private String getModelVerUrl(ModelLoaderConfig config) {
233         String baseURL = config.getAaiBaseUrl().trim();
234         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId()
235                 + AAI_MODEL_VER_SUB_URL;
236         String instance = getModelVerId();
237
238         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
239             baseURL = baseURL + "/";
240         }
241
242         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
243             baseURL = baseURL.substring(0, baseURL.length() - 1);
244         }
245
246         if (!subURL.endsWith("/")) {
247             subURL = subURL + "/";
248         }
249
250         return baseURL + subURL + instance;
251     }
252
253     private String nodeToString(Node node) throws TransformerException {
254         StringWriter sw = new StringWriter();
255         TransformerFactory transFact = TransformerFactory.newInstance();
256         transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
257         Transformer t = transFact.newTransformer();
258         t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
259         t.transform(new DOMSource(node), new StreamResult(sw));
260         return sw.toString();
261     }
262 }