d15776a49a462771b13aea8c7e34531de0b15ccd
[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 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
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
26 import javax.ws.rs.core.Response;
27 import javax.xml.transform.OutputKeys;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.TransformerFactory;
31 import javax.xml.transform.dom.DOMSource;
32 import javax.xml.transform.stream.StreamResult;
33
34 import org.onap.aai.modelloader.config.ModelLoaderConfig;
35 import org.onap.aai.modelloader.entity.ArtifactType;
36 import org.onap.aai.modelloader.restclient.AaiRestClient;
37 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
38 import org.onap.aai.cl.api.Logger;
39 import org.onap.aai.cl.eelf.LoggerFactory;
40 import org.w3c.dom.Node;
41
42 import com.sun.jersey.api.client.ClientResponse;
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 Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class.getName());
49   
50   private String modelVerId;
51         private String modelInvariantId;
52         private Node modelVer;
53         private boolean firstVersionOfModel = false;
54
55         public ModelArtifact() {
56           super(ArtifactType.MODEL);
57         }
58
59         public String getModelVerId() {
60           return modelVerId;
61         }
62         
63         public void setModelVerId(String modelVerId) {
64                 this.modelVerId = modelVerId;
65         }
66         
67         public String getModelInvariantId() {
68                 return modelInvariantId;
69         }
70         
71         public void setModelInvariantId(String modelInvariantId) {
72                 this.modelInvariantId = modelInvariantId;
73         }
74         
75         public Node getModelVer() {
76                 return modelVer;
77         }
78         
79         public void setModelVer(Node modelVer) {
80                 this.modelVer = modelVer;
81         }
82
83   @Override
84   public String getUniqueIdentifier() {
85     return getModelInvariantId() + "|" + getModelVerId();
86   }
87
88   @Override
89   public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId, List<AbstractModelArtifact> addedModels) {
90     ClientResponse getResponse  = aaiClient.getResource(getModelUrl(config), distId, AaiRestClient.MimeType.XML);
91     if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
92       // Only attempt the PUT if the model doesn't already exist
93       ClientResponse putResponse = aaiClient.putResource(getModelUrl(config), getPayload(), distId, AaiRestClient.MimeType.XML);
94       if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
95         addedModels.add(this);
96         
97         // Flag this as the first version of the model that has been added.
98         firstVersionOfModel = true;
99         
100         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
101       }
102       else {
103         logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() +
104             ". Rolling back distribution.");
105         return false;
106       }
107     }
108     else {
109       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
110       getResponse  = aaiClient.getResource(getModelVerUrl(config), distId, AaiRestClient.MimeType.XML);
111       if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
112         // Only attempt the PUT if the model-ver doesn't already exist
113         ClientResponse putResponse = null;
114
115         try {
116           putResponse = aaiClient.putResource(getModelVerUrl(config), nodeToString(getModelVer()), distId, AaiRestClient.MimeType.XML);
117         } catch (TransformerException e) {
118           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() 
119             + ": " + e.getMessage() + ". Rolling back distribution.");
120           return false;
121         }
122         if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
123           addedModels.add(this);
124           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
125         }
126         else {
127           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " 
128               + getUniqueIdentifier() + ". Rolling back distribution.");
129           return false;
130         }
131       }
132       else {
133         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
134       }
135     }
136     
137     return true;
138   }
139   
140   @Override
141   public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
142     String url = getModelVerUrl(config);
143     if (firstVersionOfModel) {
144       // If this was the first version of the model which was added, we want to remove the entire
145       // model rather than just the version.
146       url = getModelUrl(config);
147     }
148     
149     // Best effort to delete.  Nothing we can do in the event this fails.
150     aaiClient.getAndDeleteResource(url, distId);
151   }
152   
153   private String getModelUrl(ModelLoaderConfig config) {
154     String baseURL = config.getAaiBaseUrl().trim();
155     String subURL = null;
156     String instance = null;
157
158     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
159     instance = getModelInvariantId();
160
161     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
162       baseURL = baseURL + "/";
163     }
164
165     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
166       baseURL = baseURL.substring(0, baseURL.length()-1);
167     }
168
169     if (!subURL.endsWith("/")) {
170       subURL = subURL + "/";
171     }
172
173     String url = baseURL + subURL + instance;
174     return url;
175   }
176
177   private String getModelVerUrl(ModelLoaderConfig config) {
178     String baseURL = config.getAaiBaseUrl().trim();
179     String subURL = null;
180     String instance = null;
181
182     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId() + AAI_MODEL_VER_SUB_URL;
183     instance = getModelVerId();
184
185     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
186       baseURL = baseURL + "/";
187     }
188
189     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
190       baseURL = baseURL.substring(0, baseURL.length()-1);
191     }
192
193     if (!subURL.endsWith("/")) {
194       subURL = subURL + "/";
195     }
196
197     String url = baseURL + subURL + instance;
198     return url;
199   }
200   
201   private String nodeToString(Node node) throws TransformerException {
202     StringWriter sw = new StringWriter();
203     Transformer t = TransformerFactory.newInstance().newTransformer();
204     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
205     t.transform(new DOMSource(node), new StreamResult(sw));
206     return sw.toString();
207   }
208 }