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