Initial OpenECOMP A&AI Model Loader commit
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / entity / model / ModelArtifactHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * MODEL LOADER SERVICE
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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
21 package org.openecomp.modelloader.entity.model;
22
23 import com.sun.jersey.api.client.ClientResponse;
24
25 import org.openecomp.cl.api.Logger;
26 import org.openecomp.cl.eelf.LoggerFactory;
27 import org.openecomp.modelloader.config.ModelLoaderConfig;
28 import org.openecomp.modelloader.entity.Artifact;
29 import org.openecomp.modelloader.entity.ArtifactHandler;
30 import org.openecomp.modelloader.entity.ArtifactType;
31 import org.openecomp.modelloader.restclient.AaiRestClient;
32 import org.openecomp.modelloader.service.ModelLoaderMsgs;
33
34 import java.util.ArrayList;
35 import java.util.List;
36
37 import javax.ws.rs.core.Response;
38
39 public class ModelArtifactHandler extends ArtifactHandler {
40
41   private static Logger logger = LoggerFactory.getInstance()
42       .getLogger(ArtifactHandler.class.getName());
43
44   public ModelArtifactHandler(ModelLoaderConfig config) {
45     super(config);
46   }
47
48   @Override
49   public boolean pushArtifacts(List<Artifact> artifacts, String distributionId) {
50     ModelSorter modelSorter = new ModelSorter();
51     List<Artifact> sortedModelArtifacts = modelSorter.sort(artifacts);
52
53     // Push the ordered list of model artifacts to A&AI. If one fails, we need
54     // to roll back
55     // the changes.
56     List<ModelArtifact> completedModels = new ArrayList<ModelArtifact>();
57     AaiRestClient aaiClient = new AaiRestClient(config);
58
59     for (Artifact art : sortedModelArtifacts) {
60       ModelArtifact model = (ModelArtifact) art;
61       ClientResponse getResponse = aaiClient.getResource(getUrl(model), distributionId,
62           AaiRestClient.MimeType.XML);
63       if ((getResponse == null)
64           || (getResponse.getStatus() != Response.Status.OK.getStatusCode())) {
65         // Only attempt the PUT if the model doesn't already exist
66         ClientResponse putResponse = aaiClient.putResource(getUrl(model), model.getPayload(),
67             distributionId, AaiRestClient.MimeType.XML);
68         if ((putResponse != null)
69             && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode())) {
70           completedModels.add(model);
71           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " "
72               + model.getNameVersionId() + " successfully ingested.");
73         } else {
74           logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR,
75               "Ingestion failed for " + model.getType().toString() + " " + model.getNameVersionId()
76                   + ". Rolling back distribution.");
77
78           for (ModelArtifact modelToDelete : completedModels) {
79             // Best effort to delete. Nothing we can do in the event this fails.
80             aaiClient.getAndDeleteResource(getUrl(modelToDelete), distributionId);
81           }
82
83           return false;
84         }
85       } else {
86         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " "
87             + model.getNameVersionId() + " already exists.  Skipping ingestion.");
88       }
89     }
90
91     return true;
92   }
93
94   private String getUrl(ModelArtifact model) {
95     String baseUrl = config.getAaiBaseUrl().trim();
96     String subUrl = null;
97     if (model.getType().equals(ArtifactType.MODEL)) {
98       subUrl = config.getAaiModelUrl().trim();
99     } else {
100       subUrl = config.getAaiNamedQueryUrl().trim();
101     }
102
103     if ((!baseUrl.endsWith("/")) && (!subUrl.startsWith("/"))) {
104       baseUrl = baseUrl + "/";
105     }
106
107     if (baseUrl.endsWith("/") && subUrl.startsWith("/")) {
108       baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
109     }
110
111     if (!subUrl.endsWith("/")) {
112       subUrl = subUrl + "/";
113     }
114
115     String url = baseUrl + subUrl + model.getNameVersionId();
116     return url;
117   }
118
119   /**
120    * This method is used for the test REST interface to load models without an
121    * ASDC.
122    * 
123    * @param payload content of the request
124    */
125   public void loadModelTest(byte[] payload) {
126     List<Artifact> modelArtifacts = new ArrayList<Artifact>();
127     ModelArtifactParser parser = new ModelArtifactParser();
128     modelArtifacts.addAll(parser.parse(payload, "Test-Artifact"));
129     ModelSorter modelSorter = new ModelSorter();
130     List<Artifact> sortedModelArtifacts = modelSorter.sort(modelArtifacts);
131     pushArtifacts(sortedModelArtifacts, "Test-Distribution");
132   }
133 }