8db76e96cb9a02499d7b94351ffb1e4f8fd8dae7
[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 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  *
22  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23  */
24 package org.onap.aai.modelloader.entity.model;
25
26 import java.io.StringWriter;
27 import java.util.List;
28
29 import javax.ws.rs.core.Response;
30 import javax.xml.transform.OutputKeys;
31 import javax.xml.transform.Transformer;
32 import javax.xml.transform.TransformerException;
33 import javax.xml.transform.TransformerFactory;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.stream.StreamResult;
36
37 import org.onap.aai.modelloader.config.ModelLoaderConfig;
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.cl.api.Logger;
42 import org.onap.aai.cl.eelf.LoggerFactory;
43 import org.w3c.dom.Node;
44
45 import com.sun.jersey.api.client.ClientResponse;
46
47 public class ModelArtifact extends AbstractModelArtifact {
48
49   private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
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   @Override
92   public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId, List<AbstractModelArtifact> addedModels) {
93     ClientResponse getResponse  = aaiClient.getResource(getModelUrl(config), distId, AaiRestClient.MimeType.XML);
94     if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
95       // Only attempt the PUT if the model doesn't already exist
96       ClientResponse putResponse = aaiClient.putResource(getModelUrl(config), getPayload(), distId, AaiRestClient.MimeType.XML);
97       if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
98         addedModels.add(this);
99         
100         // Flag this as the first version of the model that has been added.
101         firstVersionOfModel = true;
102         
103         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
104       }
105       else {
106         logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() +
107             ". Rolling back distribution.");
108         return false;
109       }
110     }
111     else {
112       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
113       getResponse  = aaiClient.getResource(getModelVerUrl(config), distId, AaiRestClient.MimeType.XML);
114       if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
115         // Only attempt the PUT if the model-ver doesn't already exist
116         ClientResponse putResponse = null;
117
118         try {
119           putResponse = aaiClient.putResource(getModelVerUrl(config), nodeToString(getModelVer()), distId, AaiRestClient.MimeType.XML);
120         } catch (TransformerException e) {
121           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() 
122             + ": " + e.getMessage() + ". Rolling back distribution.");
123           return false;
124         }
125         if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
126           addedModels.add(this);
127           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
128         }
129         else {
130           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " 
131               + getUniqueIdentifier() + ". Rolling back distribution.");
132           return false;
133         }
134       }
135       else {
136         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
137       }
138     }
139     
140     return true;
141   }
142   
143   @Override
144   public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
145     String url = getModelVerUrl(config);
146     if (firstVersionOfModel) {
147       // If this was the first version of the model which was added, we want to remove the entire
148       // model rather than just the version.
149       url = getModelUrl(config);
150     }
151     
152     // Best effort to delete.  Nothing we can do in the event this fails.
153     aaiClient.getAndDeleteResource(url, distId);
154   }
155   
156   private String getModelUrl(ModelLoaderConfig config) {
157     String baseURL = config.getAaiBaseUrl().trim();
158     String subURL = null;
159     String instance = null;
160
161     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
162     instance = getModelInvariantId();
163
164     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
165       baseURL = baseURL + "/";
166     }
167
168     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
169       baseURL = baseURL.substring(0, baseURL.length()-1);
170     }
171
172     if (!subURL.endsWith("/")) {
173       subURL = subURL + "/";
174     }
175
176     String url = baseURL + subURL + instance;
177     return url;
178   }
179
180   private String getModelVerUrl(ModelLoaderConfig config) {
181     String baseURL = config.getAaiBaseUrl().trim();
182     String subURL = null;
183     String instance = null;
184
185     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId() + AAI_MODEL_VER_SUB_URL;
186     instance = getModelVerId();
187
188     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
189       baseURL = baseURL + "/";
190     }
191
192     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
193       baseURL = baseURL.substring(0, baseURL.length()-1);
194     }
195
196     if (!subURL.endsWith("/")) {
197       subURL = subURL + "/";
198     }
199
200     String url = baseURL + subURL + instance;
201     return url;
202   }
203   
204   private String nodeToString(Node node) throws TransformerException {
205     StringWriter sw = new StringWriter();
206     Transformer t = TransformerFactory.newInstance().newTransformer();
207     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
208     t.transform(new DOMSource(node), new StreamResult(sw));
209     return sw.toString();
210   }
211 }