Allow handling of legact model artifacts
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / entity / model / ModelArtifact.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Model Loader
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  * http://www.apache.org/licenses/LICENSE-2.0
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  * ECOMP and OpenECOMP are trademarks
21  * and service marks of AT&T Intellectual Property.
22  */
23 package org.openecomp.modelloader.entity.model;
24
25 import java.io.StringWriter;
26 import java.util.List;
27
28 import javax.ws.rs.core.Response;
29 import javax.xml.transform.OutputKeys;
30 import javax.xml.transform.Transformer;
31 import javax.xml.transform.TransformerException;
32 import javax.xml.transform.TransformerFactory;
33 import javax.xml.transform.dom.DOMSource;
34 import javax.xml.transform.stream.StreamResult;
35
36 import org.openecomp.cl.api.Logger;
37 import org.openecomp.cl.eelf.LoggerFactory;
38 import org.openecomp.modelloader.config.ModelLoaderConfig;
39 import org.openecomp.modelloader.entity.ArtifactType;
40 import org.openecomp.modelloader.restclient.AaiRestClient;
41 import org.openecomp.modelloader.service.ModelLoaderMsgs;
42 import org.w3c.dom.Node;
43
44 import com.sun.jersey.api.client.ClientResponse;
45
46 public class ModelArtifact extends AbstractModelArtifact {
47
48   private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
49   
50   private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class.getName());
51   
52   private String modelVerId;
53         private String modelInvariantId;
54         private Node modelVer;
55         private boolean firstVersionOfModel = false;
56
57         public ModelArtifact() {
58           super(ArtifactType.MODEL);
59         }
60
61         public String getModelVerId() {
62           return modelVerId;
63         }
64         
65         public void setModelVerId(String modelVerId) {
66                 this.modelVerId = modelVerId;
67         }
68         
69         public String getModelInvariantId() {
70                 return modelInvariantId;
71         }
72         
73         public void setModelInvariantId(String modelInvariantId) {
74                 this.modelInvariantId = modelInvariantId;
75         }
76         
77         public Node getModelVer() {
78                 return modelVer;
79         }
80         
81         public void setModelVer(Node modelVer) {
82                 this.modelVer = modelVer;
83         }
84
85   @Override
86   public String getUniqueIdentifier() {
87     return getModelInvariantId() + "|" + getModelVerId();
88   }
89
90   @Override
91   public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId, List<AbstractModelArtifact> addedModels) {
92     ClientResponse getResponse  = aaiClient.getResource(getModelUrl(config), distId, AaiRestClient.MimeType.XML);
93     if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
94       // Only attempt the PUT if the model doesn't already exist
95       ClientResponse putResponse = aaiClient.putResource(getModelUrl(config), getPayload(), distId, AaiRestClient.MimeType.XML);
96       if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
97         addedModels.add(this);
98         
99         // Flag this as the first version of the model that has been added.
100         firstVersionOfModel = true;
101         
102         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
103       }
104       else {
105         logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() +
106             ". Rolling back distribution.");
107         return false;
108       }
109     }
110     else {
111       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
112       getResponse  = aaiClient.getResource(getModelVerUrl(config), distId, AaiRestClient.MimeType.XML);
113       if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
114         // Only attempt the PUT if the model-ver doesn't already exist
115         ClientResponse putResponse = null;
116
117         try {
118           putResponse = aaiClient.putResource(getModelVerUrl(config), nodeToString(getModelVer()), distId, AaiRestClient.MimeType.XML);
119         } catch (TransformerException e) {
120           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " + getUniqueIdentifier() 
121             + ": " + e.getMessage() + ". Rolling back distribution.");
122           return false;
123         }
124         if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
125           addedModels.add(this);
126           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " successfully ingested.");
127         }
128         else {
129           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + getType().toString() + " " 
130               + getUniqueIdentifier() + ". Rolling back distribution.");
131           return false;
132         }
133       }
134       else {
135         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, getType().toString() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
136       }
137     }
138     
139     return true;
140   }
141   
142   @Override
143   public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
144     String url = getModelVerUrl(config);
145     if (firstVersionOfModel) {
146       // If this was the first version of the model which was added, we want to remove the entire
147       // model rather than just the version.
148       url = getModelUrl(config);
149     }
150     
151     // Best effort to delete.  Nothing we can do in the event this fails.
152     aaiClient.getAndDeleteResource(url, distId);
153   }
154   
155   private String getModelUrl(ModelLoaderConfig config) {
156     String baseURL = config.getAaiBaseUrl().trim();
157     String subURL = null;
158     String instance = null;
159
160     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
161     instance = getModelInvariantId();
162
163     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
164       baseURL = baseURL + "/";
165     }
166
167     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
168       baseURL = baseURL.substring(0, baseURL.length()-1);
169     }
170
171     if (!subURL.endsWith("/")) {
172       subURL = subURL + "/";
173     }
174
175     String url = baseURL + subURL + instance;
176     return url;
177   }
178
179   private String getModelVerUrl(ModelLoaderConfig config) {
180     String baseURL = config.getAaiBaseUrl().trim();
181     String subURL = null;
182     String instance = null;
183
184     subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId() + AAI_MODEL_VER_SUB_URL;
185     instance = getModelVerId();
186
187     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
188       baseURL = baseURL + "/";
189     }
190
191     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
192       baseURL = baseURL.substring(0, baseURL.length()-1);
193     }
194
195     if (!subURL.endsWith("/")) {
196       subURL = subURL + "/";
197     }
198
199     String url = baseURL + subURL + instance;
200     return url;
201   }
202   
203   private String nodeToString(Node node) throws TransformerException {
204     StringWriter sw = new StringWriter();
205     Transformer t = TransformerFactory.newInstance().newTransformer();
206     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
207     t.transform(new DOMSource(node), new StreamResult(sw));
208     return sw.toString();
209   }
210 }