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.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;
44 public class ModelArtifact extends AbstractModelArtifact {
46 private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
48 private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
49 private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
51 private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class.getName());
53 private String modelVerId;
54 private String modelInvariantId;
55 private Node modelVer;
56 private boolean firstVersionOfModel = false;
58 public ModelArtifact() {
59 super(ArtifactType.MODEL);
62 public String getModelVerId() {
66 public void setModelVerId(String modelVerId) {
67 this.modelVerId = modelVerId;
70 public String getModelInvariantId() {
71 return modelInvariantId;
74 public void setModelInvariantId(String modelInvariantId) {
75 this.modelInvariantId = modelInvariantId;
78 public Node getModelVer() {
82 public void setModelVer(Node modelVer) {
83 this.modelVer = modelVer;
87 public String getUniqueIdentifier() {
88 return getModelInvariantId() + "|" + getModelVerId();
93 * Test whether the specified resource (URL) can be requested successfully
97 * @param xmlResourceUrl
98 * @return true if a request to GET this resource as XML media is successful (status OK)
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();
106 * PUT the specified XML resource
112 * @return true if the resource PUT as XML media was successful (status OK)
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();
121 public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
122 List<Artifact> completedArtifacts) {
125 // See whether the model is already present
126 String resourceUrl = getModelUrl(config);
128 if (xmlResourceCanBeFetched(aaiClient, distId, resourceUrl)) {
129 logInfoMsg(getType().toString() + " " + getModelInvariantId() + " already exists. Skipping ingestion.");
130 success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
132 // Assume that the model does not exist and attempt the PUT
133 success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
135 completedArtifacts.add(this);
137 // Record state to remember that this is the first version of the model (just added).
138 firstVersionOfModel = true;
140 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
143 FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
154 * @param completedArtifacts
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.");
164 // Load the model version
165 boolean success = true;
167 success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer()));
169 completedArtifacts.add(this);
170 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
173 FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
175 } catch (TransformerException e) {
176 logErrorMsg(FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ": " + e.getMessage()
177 + ROLLBACK_MSG_SUFFIX);
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);
194 // Best effort to delete. Nothing we can do in the event this fails.
195 aaiClient.getAndDeleteResource(url, distId);
199 private void logInfoMsg(String infoMsg) {
200 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, infoMsg);
203 private void logErrorMsg(String errorMsg) {
204 logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, errorMsg);
207 private String getModelUrl(ModelLoaderConfig config) {
208 String baseURL = config.getAaiBaseUrl().trim();
209 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
210 String instance = getModelInvariantId();
212 if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
213 baseURL = baseURL + "/";
216 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
217 baseURL = baseURL.substring(0, baseURL.length() - 1);
220 if (!subURL.endsWith("/")) {
221 subURL = subURL + "/";
224 return baseURL + subURL + instance;
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();
233 if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
234 baseURL = baseURL + "/";
237 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
238 baseURL = baseURL.substring(0, baseURL.length() - 1);
241 if (!subURL.endsWith("/")) {
242 subURL = subURL + "/";
245 return baseURL + subURL + instance;
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();