2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 European Software Marketing Ltd.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.modelloader.entity.model;
23 import java.util.List;
25 import org.onap.aai.cl.api.Logger;
26 import org.onap.aai.cl.eelf.LoggerFactory;
27 import org.onap.aai.modelloader.config.ModelLoaderConfig;
28 import org.onap.aai.modelloader.entity.Artifact;
29 import org.onap.aai.modelloader.entity.ArtifactType;
30 import org.onap.aai.modelloader.restclient.AaiRestClient;
31 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
32 import org.springframework.http.HttpStatus;
33 import org.springframework.http.MediaType;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.web.client.HttpClientErrorException;
36 import org.springframework.web.client.HttpServerErrorException;
39 public class ModelArtifact extends AbstractModelArtifact {
41 private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifact.class);
43 private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
45 private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
46 private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
49 private String modelVerId;
50 private String modelInvariantId;
51 private String modelVer;
52 private boolean firstVersionOfModel = false;
54 public ModelArtifact() {
55 super(ArtifactType.MODEL);
58 public String getModelVerId() {
62 public void setModelVerId(String modelVerId) {
63 this.modelVerId = modelVerId;
66 public String getModelInvariantId() {
67 return modelInvariantId;
70 public void setModelInvariantId(String modelInvariantId) {
71 this.modelInvariantId = modelInvariantId;
74 public String getModelVer() {
78 public void setModelVer(String modelVer) {
79 this.modelVer = modelVer;
83 public String getUniqueIdentifier() {
84 return getModelInvariantId() + "|" + getModelVerId();
89 * Test whether the specified resource (URL) can be requested successfully
93 * @param xmlResourceUrl
94 * @return true if a request to GET this resource as XML media is successful (status OK)
96 private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
98 ResponseEntity<Model> getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl);
99 return getResponse.getStatusCode().equals(HttpStatus.OK);
100 } catch (HttpClientErrorException e) {
101 if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
110 * Test whether the specified resource (URL) can be requested successfully
114 * @param xmlResourceUrl
115 * @return OperationResult the result of the operation
117 private ResponseEntity<Model> getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
118 return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML, Model.class);
122 * PUT the specified XML resource
128 * @return true if the resource PUT as XML media was successful (status OK)
130 private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) {
131 ResponseEntity<String> putResponse = null;
134 aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML, String.class);
135 } catch (HttpClientErrorException | HttpServerErrorException e) {
136 logger.error(ModelLoaderMsgs.AAI_REST_REQUEST_ERROR, "Error putting resource: " + e.toString());
138 return putResponse != null && putResponse.getStatusCode() == HttpStatus.CREATED;
142 public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
143 List<Artifact> completedArtifacts) {
144 if (config.useGizmo()) {
145 return pushToGizmo(aaiClient, config, distId);
148 return pushToResources(aaiClient, config, distId, completedArtifacts);
151 private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
152 List<Artifact> completedArtifacts) {
153 boolean success = false;
155 // See whether the model is already present
156 String resourceUrl = getModelUrl(config);
157 // ResponseEntity<Model> result;
158 boolean modelExists = checkIfModelExists(aaiClient, distId, resourceUrl);
161 success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
163 success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
166 // if (result != null) {
167 // if (result.getStatusCode() == HttpStatus.OK) {
168 // success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
169 // } else if (result.getStatusCode() == HttpStatus.NOT_FOUND) {
170 // success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
172 // logModelUpdateFailure(
173 // "Response code " + result.getStatusCodeValue() + " invalid for getting resource model");
176 // logModelUpdateFailure("Null response from RestClient");
182 private boolean checkIfModelExists(AaiRestClient aaiClient, String distId, String resourceUrl) throws HttpClientErrorException {
184 ResponseEntity<Model> response = getResourceModel(aaiClient, distId, resourceUrl);
185 return response.getStatusCode().equals(HttpStatus.OK);
186 } catch (HttpClientErrorException e) {
187 if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
195 private boolean createNewModel(AaiRestClient aaiClient, String distId, List<Artifact> completedArtifacts,
196 String resourceUrl) {
198 // Assume that the model does not exist and attempt the PUT
199 success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
201 completedArtifacts.add(this);
203 // Record state to remember that this is the first version of the model (just added).
204 firstVersionOfModel = true;
206 logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
208 logModelUpdateFailure("Error creating model. Skipping ingestion.");
213 private void logModelUpdateFailure(String message) {
214 logErrorMsg(FAILURE_MSG_PREFIX + getType() + " " + getUniqueIdentifier() + " " + message + ROLLBACK_MSG_SUFFIX);
217 private boolean updateExistingModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
218 List<Artifact> completedArtifacts) {
220 logInfoMsg(getType() + " " + getModelInvariantId() + " already exists. Skipping ingestion.");
221 success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
229 * @param completedArtifacts
232 private boolean pushModelVersion(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
233 List<Artifact> completedArtifacts) {
234 if (xmlResourceCanBeFetched(aaiClient, distId, getModelVerUrl(config))) {
235 logInfoMsg(getType() + " " + getUniqueIdentifier() + " already exists. Skipping ingestion.");
239 // Load the model version
240 boolean success = true;
241 success = putXmlResource(aaiClient, distId, getModelVerUrl(config), getModelVer());
243 completedArtifacts.add(this);
244 logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
246 logModelUpdateFailure("Error pushing model");
254 public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
255 // Gizmo is resilient and doesn't require a rollback. A redistribution will work fine even if
256 // the model is partially loaded.
257 if (config.useGizmo()) {
261 String url = getModelVerUrl(config);
262 if (firstVersionOfModel) {
263 // If this was the first version of the model which was added, we want to remove the entire
264 // model rather than just the version.
265 url = getModelUrl(config);
268 // Best effort to delete. Nothing we can do in the event this fails.
269 aaiClient.getAndDeleteResource(url, distId);
272 private String getModelUrl(ModelLoaderConfig config) {
273 String baseURL = config.getAaiBaseUrl().trim();
274 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
275 String instance = getModelInvariantId();
277 if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
278 baseURL = baseURL + "/";
281 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
282 baseURL = baseURL.substring(0, baseURL.length() - 1);
285 if (!subURL.endsWith("/")) {
286 subURL = subURL + "/";
289 return baseURL + subURL + instance;
292 private String getModelVerUrl(ModelLoaderConfig config) {
293 String baseURL = config.getAaiBaseUrl().trim();
294 String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId()
295 + AAI_MODEL_VER_SUB_URL;
296 String instance = getModelVerId();
298 if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
299 baseURL = baseURL + "/";
302 if (baseURL.endsWith("/") && subURL.startsWith("/")) {
303 baseURL = baseURL.substring(0, baseURL.length() - 1);
306 if (!subURL.endsWith("/")) {
307 subURL = subURL + "/";
310 return baseURL + subURL + instance;