2 * ============LICENSE_START==========================================
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
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;
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;
44 import org.w3c.dom.Node;
46 public class ModelArtifact extends AbstractModelArtifact {
48 private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
50 private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
51 private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
53 private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class.getName());
55 private String modelVerId;
56 private String modelInvariantId;
57 private Node modelVer;
58 private boolean firstVersionOfModel = false;
60 public ModelArtifact() {
61 super(ArtifactType.MODEL);
64 public String getModelVerId() {
68 public void setModelVerId(String modelVerId) {
69 this.modelVerId = modelVerId;
72 public String getModelInvariantId() {
73 return modelInvariantId;
76 public void setModelInvariantId(String modelInvariantId) {
77 this.modelInvariantId = modelInvariantId;
80 public Node getModelVer() {
84 public void setModelVer(Node modelVer) {
85 this.modelVer = modelVer;
89 public String getUniqueIdentifier() {
90 return getModelInvariantId() + "|" + getModelVerId();
95 * Test whether the specified resource (URL) can be requested successfully
99 * @param xmlResourceUrl
100 * @return true if a request to GET this resource as XML media is successful (status OK)
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();
108 * PUT the specified XML resource
114 * @return true if the resource PUT as XML media was successful (status OK)
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();
123 public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
124 List<Artifact> completedArtifacts) {
127 // See whether the model is already present
128 String resourceUrl = getModelUrl(config);
130 if (xmlResourceCanBeFetched(aaiClient, distId, resourceUrl)) {
131 logInfoMsg(getType().toString() + " " + getModelInvariantId() + " already exists. Skipping ingestion.");
132 success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
134 // Assume that the model does not exist and attempt the PUT
135 success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
137 completedArtifacts.add(this);
139 // Record state to remember that this is the first version of the model (just added).
140 firstVersionOfModel = true;
142 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
145 FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
156 * @param completedArtifacts
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.");
166 // Load the model version
167 boolean success = true;
169 success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer()));
171 completedArtifacts.add(this);
172 logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
175 FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ROLLBACK_MSG_SUFFIX);
177 } catch (TransformerException e) {
178 logErrorMsg(FAILURE_MSG_PREFIX + getType().toString() + " " + getUniqueIdentifier() + ": " + e.getMessage()
179 + ROLLBACK_MSG_SUFFIX);
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);
196 // Best effort to delete. Nothing we can do in the event this fails.
197 aaiClient.getAndDeleteResource(url, distId);
201 private void logInfoMsg(String infoMsg) {
202 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, infoMsg);
205 private void logErrorMsg(String errorMsg) {
206 logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, errorMsg);
209 private String getModelUrl(ModelLoaderConfig config) {
210 String baseURL = config.getAaiBaseUrl().trim();
211 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
212 String instance = getModelInvariantId();
214 if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
215 baseURL = baseURL + "/";
218 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
219 baseURL = baseURL.substring(0, baseURL.length() - 1);
222 if (!subURL.endsWith("/")) {
223 subURL = subURL + "/";
226 return baseURL + subURL + instance;
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();
235 if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
236 baseURL = baseURL + "/";
239 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
240 baseURL = baseURL.substring(0, baseURL.length() - 1);
243 if (!subURL.endsWith("/")) {
244 subURL = subURL + "/";
247 return baseURL + subURL + instance;
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();