Ensure shutdown hook is called on docker stop
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / entity / model / ModelArtifactHandler.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 com.sun.jersey.api.client.ClientResponse;
26
27 import org.openecomp.cl.api.Logger;
28 import org.openecomp.cl.eelf.LoggerFactory;
29 import org.openecomp.modelloader.config.ModelLoaderConfig;
30 import org.openecomp.modelloader.entity.Artifact;
31 import org.openecomp.modelloader.entity.ArtifactHandler;
32 import org.openecomp.modelloader.entity.ArtifactType;
33 import org.openecomp.modelloader.restclient.AaiRestClient;
34 import org.openecomp.modelloader.service.ModelLoaderMsgs;
35
36 import org.w3c.dom.Node;
37
38 import java.io.StringWriter;
39 import java.util.ArrayList;
40 import java.util.List;
41
42 import javax.ws.rs.core.Response;
43 import javax.xml.transform.OutputKeys;
44 import javax.xml.transform.Transformer;
45 import javax.xml.transform.TransformerException;
46 import javax.xml.transform.TransformerFactory;
47 import javax.xml.transform.dom.DOMSource;
48 import javax.xml.transform.stream.StreamResult;
49
50
51 public class ModelArtifactHandler extends ArtifactHandler {
52
53   private static final String AAI_MODEL_VER = "/model-vers/model-ver";
54   private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactHandler.class.getName());
55
56
57   public ModelArtifactHandler(ModelLoaderConfig config) {
58     super(config);
59   }
60
61   @Override
62   public boolean pushArtifacts(List<Artifact> artifacts, String distributionID) {
63     ModelSorter modelSorter = new ModelSorter();
64     List<Artifact> sortedModelArtifacts = modelSorter.sort(artifacts);
65
66     // Push the ordered list of model artifacts to A&AI.  If one fails, we need to roll back
67     // the changes.
68     List<ModelArtifact> completedModels = new ArrayList<ModelArtifact>();
69     AaiRestClient aaiClient = new AaiRestClient(config);
70
71     for (Artifact art : sortedModelArtifacts) {
72       ModelArtifact model = (ModelArtifact)art;
73
74       boolean version = model.isV9Artifact();
75       //Non - V9 version for models
76       if(version == false){
77         ClientResponse getResponse = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);
78         if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
79           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, " Artifact format not valid for " + 
80               model.getType().toString() + "- model-invariant-id[model-id]: " + 
81               model.getModelInvariantId() + " and model-version-id[model-name-version-id]: "+ 
82               model.getModelVerId()+ " . Rolling back distribution.");
83           return false;
84         }
85         else{
86           completedModels.add(model);
87           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + 
88               " " + model.getModelInvariantId() + " successfully ingested.");
89         }
90       }
91       else
92       {
93         ClientResponse getResponse  = aaiClient.getResource(getURL(model), distributionID, 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(getURL(model), model.getPayload(), distributionID, AaiRestClient.MimeType.XML);
97           if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
98             completedModels.add(model);
99             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + 
100                 " " + model.getModelInvariantId() + " successfully ingested.");
101           }
102           else {
103             logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + 
104                 model.getType().toString() + " " + model.getModelInvariantId() + ". Rolling back distribution.");
105
106             for (ModelArtifact modelToDelete : completedModels) {
107               // Best effort to delete.  Nothing we can do in the event this fails.
108               aaiClient.getAndDeleteResource(getURL(modelToDelete), distributionID);
109             }
110
111             return false;
112           }
113         }
114         else {
115           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + model.getModelInvariantId() + 
116               " already exists.  Skipping ingestion.");
117           getResponse  = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);
118           if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
119             // Only attempt the PUT if the model-ver doesn't already exist
120             ClientResponse putResponse = null;
121
122             try {
123               putResponse = aaiClient.putResource(getModelVerURL(model), nodeToString(model.getModelVer()), distributionID, AaiRestClient.MimeType.XML);
124             } catch (TransformerException e) {
125               // TODO Auto-generated catch block
126               e.printStackTrace();
127             }
128             if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
129               completedModels.add(model);
130               logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + 
131                   model.getNameVersionId() + " successfully ingested.");
132             }
133             else {
134               logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + 
135                   model.getType().toString() + " " + model.getNameVersionId() + ". Rolling back distribution.");
136
137               for (ModelArtifact modelToDelete : completedModels) {
138                 // Best effort to delete.  Nothing we can do in the event this fails.
139                 aaiClient.getAndDeleteResource(getModelVerURL(modelToDelete), distributionID);
140               }
141
142               return false;
143             }
144           }
145           else {
146             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + 
147                 model.getModelInvariantId() + " already exists.  Skipping ingestion.");
148           }
149         }
150       }
151     }
152
153     return true;
154   }
155
156
157   private String nodeToString(Node node) throws TransformerException {
158     StringWriter sw = new StringWriter();
159     Transformer t = TransformerFactory.newInstance().newTransformer();
160     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
161     t.transform(new DOMSource(node), new StreamResult(sw));
162     System.out.println(sw.toString());
163     return sw.toString();
164   }
165
166   private String getURL(ModelArtifact model) {
167     String baseURL = config.getAaiBaseUrl().trim();
168     String subURL = null;
169     String instance = null;
170     if (model.getType().equals(ArtifactType.MODEL)) {
171       subURL = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim();
172       instance = model.getModelInvariantId();
173     }
174     else {
175       subURL = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
176       instance = model.getNameVersionId();
177     }
178
179     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
180       baseURL = baseURL + "/";
181     }
182
183     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
184       baseURL = baseURL.substring(0, baseURL.length()-1);
185     }
186
187     if (!subURL.endsWith("/")) {
188       subURL = subURL + "/";
189     }
190
191     String url = baseURL + subURL + instance;
192     return url;
193   }
194
195   private String getModelVerURL(ModelArtifact model) {
196     String baseURL = config.getAaiBaseUrl().trim();
197     String subURL = null;
198     String instance = null;
199     if (model.getType().equals(ArtifactType.MODEL)) {
200       subURL = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim() + model.getModelInvariantId() + AAI_MODEL_VER;
201       instance = model.getModelVerId();
202     }
203     else {
204       subURL = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
205       instance = model.getNameVersionId();
206     }
207
208     if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
209       baseURL = baseURL + "/";
210     }
211
212     if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
213       baseURL = baseURL.substring(0, baseURL.length()-1);
214     }
215
216     if (!subURL.endsWith("/")) {
217       subURL = subURL + "/";
218     }
219
220     String url = baseURL + subURL + instance;
221     return url;
222   }
223
224   // This method is used for the test REST interface to load models without an ASDC
225   public void loadModelTest(byte[] payload) {
226     List<Artifact> modelArtifacts = new ArrayList<Artifact>();
227     ModelArtifactParser parser = new ModelArtifactParser();
228     modelArtifacts.addAll(parser.parse(payload, "Test-Artifact"));
229     ModelSorter modelSorter = new ModelSorter();
230     List<Artifact> sortedModelArtifacts = modelSorter.sort(modelArtifacts);
231     pushArtifacts(sortedModelArtifacts, "Test-Distribution");
232   }
233 }