2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.modelloader.entity.model;
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.modelloader.config.ModelLoaderConfig;
35 import org.onap.aai.modelloader.entity.Artifact;
36 import org.onap.aai.modelloader.entity.ArtifactType;
37 import org.onap.aai.modelloader.restclient.AaiRestClient;
38 import org.onap.aai.restclient.client.OperationResult;
39 import org.w3c.dom.Node;
42 public class ModelArtifact extends AbstractModelArtifact {
44 private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
46 private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
47 private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
50 private String modelVerId;
51 private String modelInvariantId;
52 private Node modelVer;
53 private boolean firstVersionOfModel = false;
55 public ModelArtifact() {
56 super(ArtifactType.MODEL);
59 public String getModelVerId() {
63 public void setModelVerId(String modelVerId) {
64 this.modelVerId = modelVerId;
67 public String getModelInvariantId() {
68 return modelInvariantId;
71 public void setModelInvariantId(String modelInvariantId) {
72 this.modelInvariantId = modelInvariantId;
75 public Node getModelVer() {
79 public void setModelVer(Node modelVer) {
80 this.modelVer = modelVer;
84 public String getUniqueIdentifier() {
85 return getModelInvariantId() + "|" + getModelVerId();
90 * Test whether the specified resource (URL) can be requested successfully
94 * @param xmlResourceUrl
95 * @return true if a request to GET this resource as XML media is successful (status OK)
97 private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
98 OperationResult getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl);
99 return getResponse != null && getResponse.getResultCode() == Response.Status.OK.getStatusCode();
103 * Test whether the specified resource (URL) can be requested successfully
107 * @param xmlResourceUrl
108 * @return OperationResult the result of the operation
110 private OperationResult getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
111 return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML_TYPE);
115 * PUT the specified XML resource
121 * @return true if the resource PUT as XML media was successful (status OK)
123 private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) {
124 OperationResult putResponse =
125 aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML_TYPE);
126 return putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode();
130 public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
131 List<Artifact> completedArtifacts) {
132 if (config.useGizmo()) {
133 return pushToGizmo(aaiClient, config, distId);
136 return pushToResources(aaiClient, config, distId, completedArtifacts);
139 private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
140 List<Artifact> completedArtifacts) {
141 boolean success = false;
143 // See whether the model is already present
144 String resourceUrl = getModelUrl(config);
145 OperationResult result = getResourceModel(aaiClient, distId, resourceUrl);
147 if (result != null) {
148 if (result.getResultCode() == Response.Status.OK.getStatusCode()) {
149 success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
150 } else if (result.getResultCode() == Response.Status.NOT_FOUND.getStatusCode()) {
151 success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
153 logModelUpdateFailure(
154 "Response code " + result.getResultCode() + " invalid for getting resource model");
157 logModelUpdateFailure("Null response from RestClient");
163 private boolean createNewModel(AaiRestClient aaiClient, String distId, List<Artifact> completedArtifacts,
164 String resourceUrl) {
166 // Assume that the model does not exist and attempt the PUT
167 success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
169 completedArtifacts.add(this);
171 // Record state to remember that this is the first version of the model (just added).
172 firstVersionOfModel = true;
174 logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
176 logModelUpdateFailure("Error creating model. Skipping ingestion.");
181 private void logModelUpdateFailure(String message) {
182 logErrorMsg(FAILURE_MSG_PREFIX + getType() + " " + getUniqueIdentifier() + " " + message + ROLLBACK_MSG_SUFFIX);
185 private boolean updateExistingModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
186 List<Artifact> completedArtifacts) {
188 logInfoMsg(getType() + " " + getModelInvariantId() + " already exists. Skipping ingestion.");
189 success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
197 * @param completedArtifacts
200 private boolean pushModelVersion(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
201 List<Artifact> completedArtifacts) {
202 if (xmlResourceCanBeFetched(aaiClient, distId, getModelVerUrl(config))) {
203 logInfoMsg(getType() + " " + getUniqueIdentifier() + " already exists. Skipping ingestion.");
207 // Load the model version
208 boolean success = true;
210 success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer()));
212 completedArtifacts.add(this);
213 logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
215 logModelUpdateFailure("Error pushing model");
217 } catch (TransformerException e) {
218 logModelUpdateFailure(e.getMessage());
227 public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
228 // Gizmo is resilient and doesn't require a rollback. A redistribution will work fine even if
229 // the model is partially loaded.
230 if (config.useGizmo()) {
234 String url = getModelVerUrl(config);
235 if (firstVersionOfModel) {
236 // If this was the first version of the model which was added, we want to remove the entire
237 // model rather than just the version.
238 url = getModelUrl(config);
241 // Best effort to delete. Nothing we can do in the event this fails.
242 aaiClient.getAndDeleteResource(url, distId);
245 private String getModelUrl(ModelLoaderConfig config) {
246 String baseURL = config.getAaiBaseUrl().trim();
247 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
248 String instance = getModelInvariantId();
250 if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
251 baseURL = baseURL + "/";
254 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
255 baseURL = baseURL.substring(0, baseURL.length() - 1);
258 if (!subURL.endsWith("/")) {
259 subURL = subURL + "/";
262 return baseURL + subURL + instance;
265 private String getModelVerUrl(ModelLoaderConfig config) {
266 String baseURL = config.getAaiBaseUrl().trim();
267 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId()
268 + AAI_MODEL_VER_SUB_URL;
269 String instance = getModelVerId();
271 if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
272 baseURL = baseURL + "/";
275 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
276 baseURL = baseURL.substring(0, baseURL.length() - 1);
279 if (!subURL.endsWith("/")) {
280 subURL = subURL + "/";
283 return baseURL + subURL + instance;
286 private String nodeToString(Node node) throws TransformerException {
287 StringWriter sw = new StringWriter();
288 TransformerFactory transFact = TransformerFactory.newInstance();
289 transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
290 transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
291 transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
292 Transformer t = transFact.newTransformer();
293 t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
294 t.transform(new DOMSource(node), new StreamResult(sw));
295 return sw.toString();