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