From 93a7defb8a10ac29f97d3cfd860ca12a629bdc41 Mon Sep 17 00:00:00 2001 From: Fiete Ostkamp Date: Fri, 19 Apr 2024 08:39:27 +0200 Subject: [PATCH] Use RestTemplate in AaiRestClient - brings tracing support for the requests towards aai-resources - leverage automatic object mapping done by Jackson in the background - add model related entities Issue-ID: AAI-3833 Change-Id: I4f6ec65c80a6dcc1e1e3fa10786a119996c3bc79 Signed-off-by: Fiete Ostkamp --- pom.xml | 4 + .../aai/modelloader/entity/AaiResourcesObject.java | 34 +++++ .../aai/modelloader/entity/ArtifactHandler.java | 1 + .../entity/catalog/VnfCatalogArtifactHandler.java | 25 +-- .../entity/model/AbstractModelArtifact.java | 11 +- .../entity/model/ConstrainedElementSet.java | 58 +++++++ .../modelloader/entity/model/ElementChoiceSet.java | 58 +++++++ .../aai/modelloader/entity/model/Metadatum.java | 51 +++++++ .../onap/aai/modelloader/entity/model/Model.java | 59 ++++++++ .../modelloader/entity/model/ModelArtifact.java | 115 +++++++------- .../entity/model/ModelArtifactParser.java | 28 +++- .../modelloader/entity/model/ModelConstraint.java | 55 +++++++ .../aai/modelloader/entity/model/ModelElement.java | 64 ++++++++ .../aai/modelloader/entity/model/ModelVersion.java | 76 ++++++++++ .../entity/model/NamedQueryArtifact.java | 18 +-- .../onap/aai/modelloader/entity/vnf/VnfImage.java | 58 +++++++ .../onap/aai/modelloader/entity/vnf/VnfImages.java | 35 +++++ .../aai/modelloader/restclient/AaiRestClient.java | 167 +++++++-------------- .../restclient/BabelServiceClientImpl.java | 6 +- .../service/ArtifactDeploymentManager.java | 8 +- .../modelloader/config/TestModelLoaderConfig.java | 21 --- .../catalog/TestVnfCatalogArtifactHandler.java | 49 +++--- .../entity/model/TestModelArtifactHandler.java | 62 +++----- .../notification/ArtifactDownloadManagerTest.java | 7 +- .../notification/ModelArtifactHandlerTest.java | 55 ++++--- .../TestArtifactDeploymentManager.java | 5 +- .../modelloader/restclient/TestAaiRestClient.java | 21 +-- .../restclient/TestAaiServiceClient.java | 114 -------------- src/test/resources/__files/modelVersion.xml | 8 + 29 files changed, 836 insertions(+), 437 deletions(-) create mode 100644 src/main/java/org/onap/aai/modelloader/entity/AaiResourcesObject.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/ConstrainedElementSet.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/ElementChoiceSet.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/Metadatum.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/Model.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/ModelConstraint.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/ModelElement.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/model/ModelVersion.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImage.java create mode 100644 src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImages.java delete mode 100644 src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java create mode 100644 src/test/resources/__files/modelVersion.xml diff --git a/pom.xml b/pom.xml index 1a3028c..633350a 100644 --- a/pom.xml +++ b/pom.xml @@ -357,6 +357,10 @@ org.springframework.cloud spring-cloud-sleuth-zipkin + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + diff --git a/src/main/java/org/onap/aai/modelloader/entity/AaiResourcesObject.java b/src/main/java/org/onap/aai/modelloader/entity/AaiResourcesObject.java new file mode 100644 index 0000000..35232f3 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/AaiResourcesObject.java @@ -0,0 +1,34 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AaiResourcesObject { + @JsonProperty("resource-version") + private String resourceVersion; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/ArtifactHandler.java b/src/main/java/org/onap/aai/modelloader/entity/ArtifactHandler.java index 50abdd0..c630822 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/ArtifactHandler.java +++ b/src/main/java/org/onap/aai/modelloader/entity/ArtifactHandler.java @@ -23,6 +23,7 @@ package org.onap.aai.modelloader.entity; import java.util.List; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.restclient.AaiRestClient; +import org.springframework.web.client.RestTemplate; public abstract class ArtifactHandler { diff --git a/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandler.java b/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandler.java index c1f6e9b..95d3426 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandler.java +++ b/src/main/java/org/onap/aai/modelloader/entity/catalog/VnfCatalogArtifactHandler.java @@ -30,8 +30,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.text.StringEscapeUtils; @@ -41,10 +39,14 @@ import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.ArtifactHandler; +import org.onap.aai.modelloader.entity.vnf.VnfImages; import org.onap.aai.modelloader.restclient.AaiRestClient; import org.onap.aai.modelloader.service.ModelLoaderMsgs; -import org.onap.aai.restclient.client.OperationResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -147,7 +149,7 @@ public class VnfCatalogArtifactHandler extends ArtifactHandler { String imageId = imageIdBuilder.toString(); int resultCode = getVnfImage(restClient, distributionId, imageId, dataItem); - if (resultCode == Response.Status.NOT_FOUND.getStatusCode()) { + if (resultCode == HttpStatus.NOT_FOUND.value()) { // This vnf-image is missing, so add it boolean success = putVnfImage(restClient, dataItem, distributionId); if (success) { @@ -156,7 +158,7 @@ public class VnfCatalogArtifactHandler extends ArtifactHandler { } else { throw new VnfImageException(imageId); } - } else if (resultCode == Response.Status.OK.getStatusCode()) { + } else if (resultCode == HttpStatus.OK.value()) { logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, imageId + " already exists. Skipping ingestion."); } else { // if other than 404 or 200, something went wrong @@ -172,12 +174,12 @@ public class VnfCatalogArtifactHandler extends ArtifactHandler { for (Entry entry : dataItem.entrySet()) { b.addParameter(entry.getKey(), entry.getValue()); } - OperationResult tryGet = - restClient.getResource(b.build().toString(), distributionId, MediaType.APPLICATION_JSON_TYPE); + ResponseEntity tryGet = + restClient.getResource(b.build().toString(), distributionId, MediaType.APPLICATION_JSON, VnfImages.class); if (tryGet == null) { throw new VnfImageException(imageId); } - return tryGet.getResultCode(); + return tryGet.getStatusCodeValue(); } catch (URISyntaxException ex) { throw new VnfImageException(ex); } @@ -188,11 +190,12 @@ public class VnfCatalogArtifactHandler extends ArtifactHandler { String uuid = UUID.randomUUID().toString(); dataItem.put(ATTR_UUID, uuid); + // TODO: Get rid of the dataItem map and replace it with the VnfImage object String payload = new Gson().toJson(dataItem); String putUrl = config.getAaiBaseUrl() + config.getAaiVnfImageUrl() + "/vnf-image/" + uuid; - OperationResult putResp = - restClient.putResource(putUrl, payload, distributionId, MediaType.APPLICATION_JSON_TYPE); - return putResp != null && putResp.getResultCode() == Response.Status.CREATED.getStatusCode(); + ResponseEntity putResp = + restClient.putResource(putUrl, payload, distributionId, MediaType.APPLICATION_JSON, String.class); + return putResp != null && putResp.getStatusCode() == HttpStatus.CREATED; } private List> unmarshallVnfcData(Artifact vnfcArtifact) { diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/AbstractModelArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/model/AbstractModelArtifact.java index 7d5cafb..eebead3 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/model/AbstractModelArtifact.java +++ b/src/main/java/org/onap/aai/modelloader/entity/model/AbstractModelArtifact.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.ws.rs.core.MediaType; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.config.ModelLoaderConfig; @@ -34,8 +33,9 @@ import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.restclient.AaiRestClient; import org.onap.aai.modelloader.service.ModelLoaderMsgs; import org.onap.aai.modelloader.util.GizmoTranslator; -import org.onap.aai.restclient.client.OperationResult; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; public abstract class AbstractModelArtifact extends Artifact implements IModelArtifact { @@ -85,10 +85,11 @@ public abstract class AbstractModelArtifact extends Artifact implements IModelAr protected boolean pushToGizmo(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) { try { String gizmoPayload = GizmoTranslator.translate(getPayload()); - OperationResult postResponse = aaiClient.postResource(config.getAaiBaseUrl().trim(), gizmoPayload, distId, - MediaType.APPLICATION_JSON_TYPE); + // TODO: Use correct responseType here + ResponseEntity postResponse = aaiClient.postResource(config.getAaiBaseUrl().trim(), gizmoPayload, distId, + MediaType.APPLICATION_JSON, String.class); - if (postResponse.getResultCode() != HttpStatus.OK.value()) { + if (postResponse.getStatusCode() != HttpStatus.OK) { return false; } } catch (IOException e) { diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ConstrainedElementSet.java b/src/main/java/org/onap/aai/modelloader/entity/model/ConstrainedElementSet.java new file mode 100644 index 0000000..a91cd58 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ConstrainedElementSet.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ConstrainedElementSet { + @JsonProperty("constrained-element-set-uuid") + private String constrainedElementSetUuid; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("constraint-type") + private String constraintType; + + @JsonProperty("check-type") + private String checkType; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("element-choice-sets") + private List elementChoiceSets; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ElementChoiceSet.java b/src/main/java/org/onap/aai/modelloader/entity/model/ElementChoiceSet.java new file mode 100644 index 0000000..02f9314 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ElementChoiceSet.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ElementChoiceSet { + @JsonProperty("element-choice-set-uuid") + private String elementChoiceSetUuid; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("element-choice-set-name") + private String elementChoiceSetName; + + @JsonProperty("cardinality") + private String cardinality; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("model-elements") + private List modelElements; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/Metadatum.java b/src/main/java/org/onap/aai/modelloader/entity/model/Metadatum.java new file mode 100644 index 0000000..f44e108 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/Metadatum.java @@ -0,0 +1,51 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Metadatum { + @JsonProperty("metaname") + private String metaName; + + @JsonProperty("metaval") + private String metaVal; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("resource-version") + private String resourceVersion; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/Model.java b/src/main/java/org/onap/aai/modelloader/entity/model/Model.java new file mode 100644 index 0000000..8dea197 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/Model.java @@ -0,0 +1,59 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Describes the model returned by aai-resources + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Model { + + @JsonProperty("model-invariant-id") + private String modelInvariantId; + + @JsonProperty("model-role") + private String modelRole; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("model-vers") + List modelVersions; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java index c7631e8..fa22969 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifact.java @@ -20,23 +20,15 @@ */ package org.onap.aai.modelloader.entity.model; -import java.io.StringWriter; import java.util.List; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.xml.XMLConstants; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.aai.restclient.client.OperationResult; -import org.w3c.dom.Node; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; public class ModelArtifact extends AbstractModelArtifact { @@ -49,7 +41,7 @@ public class ModelArtifact extends AbstractModelArtifact { private String modelVerId; private String modelInvariantId; - private Node modelVer; + private String modelVer; private boolean firstVersionOfModel = false; public ModelArtifact() { @@ -72,11 +64,11 @@ public class ModelArtifact extends AbstractModelArtifact { this.modelInvariantId = modelInvariantId; } - public Node getModelVer() { + public String getModelVer() { return modelVer; } - public void setModelVer(Node modelVer) { + public void setModelVer(String modelVer) { this.modelVer = modelVer; } @@ -95,8 +87,16 @@ public class ModelArtifact extends AbstractModelArtifact { * @return true if a request to GET this resource as XML media is successful (status OK) */ private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) { - OperationResult getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl); - return getResponse != null && getResponse.getResultCode() == Response.Status.OK.getStatusCode(); + try { + ResponseEntity getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl); + return getResponse.getStatusCode().equals(HttpStatus.OK); + } catch (HttpClientErrorException e) { + if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + return false; + } else { + throw e; + } + } } /** @@ -107,8 +107,8 @@ public class ModelArtifact extends AbstractModelArtifact { * @param xmlResourceUrl * @return OperationResult the result of the operation */ - private OperationResult getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) { - return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML_TYPE); + private ResponseEntity getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) { + return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML, Model.class); } /** @@ -121,9 +121,9 @@ public class ModelArtifact extends AbstractModelArtifact { * @return true if the resource PUT as XML media was successful (status OK) */ private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) { - OperationResult putResponse = - aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML_TYPE); - return putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode(); + ResponseEntity putResponse = + aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML, String.class); + return putResponse != null && putResponse.getStatusCode() == HttpStatus.CREATED; } @Override @@ -142,24 +142,44 @@ public class ModelArtifact extends AbstractModelArtifact { // See whether the model is already present String resourceUrl = getModelUrl(config); - OperationResult result = getResourceModel(aaiClient, distId, resourceUrl); + // ResponseEntity result; + boolean modelExists = checkIfModelExists(aaiClient, distId, resourceUrl); - if (result != null) { - if (result.getResultCode() == Response.Status.OK.getStatusCode()) { - success = updateExistingModel(aaiClient, config, distId, completedArtifacts); - } else if (result.getResultCode() == Response.Status.NOT_FOUND.getStatusCode()) { - success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl); - } else { - logModelUpdateFailure( - "Response code " + result.getResultCode() + " invalid for getting resource model"); - } + if(modelExists) { + success = updateExistingModel(aaiClient, config, distId, completedArtifacts); } else { - logModelUpdateFailure("Null response from RestClient"); + success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl); } + // if (result != null) { + // if (result.getStatusCode() == HttpStatus.OK) { + // success = updateExistingModel(aaiClient, config, distId, completedArtifacts); + // } else if (result.getStatusCode() == HttpStatus.NOT_FOUND) { + // success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl); + // } else { + // logModelUpdateFailure( + // "Response code " + result.getStatusCodeValue() + " invalid for getting resource model"); + // } + // } else { + // logModelUpdateFailure("Null response from RestClient"); + // } + return success; } + private boolean checkIfModelExists(AaiRestClient aaiClient, String distId, String resourceUrl) throws HttpClientErrorException { + try { + ResponseEntity response = getResourceModel(aaiClient, distId, resourceUrl); + return response.getStatusCode().equals(HttpStatus.OK); + } catch (HttpClientErrorException e) { + if(e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + return false; + } else { + throw e; + } + } + } + private boolean createNewModel(AaiRestClient aaiClient, String distId, List completedArtifacts, String resourceUrl) { boolean success; @@ -206,17 +226,12 @@ public class ModelArtifact extends AbstractModelArtifact { // Load the model version boolean success = true; - try { - success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer())); - if (success) { - completedArtifacts.add(this); - logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested."); - } else { - logModelUpdateFailure("Error pushing model"); - } - } catch (TransformerException e) { - logModelUpdateFailure(e.getMessage()); - success = false; + success = putXmlResource(aaiClient, distId, getModelVerUrl(config), getModelVer()); + if (success) { + completedArtifacts.add(this); + logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested."); + } else { + logModelUpdateFailure("Error pushing model"); } return success; @@ -282,16 +297,4 @@ public class ModelArtifact extends AbstractModelArtifact { return baseURL + subURL + instance; } - - private String nodeToString(Node node) throws TransformerException { - StringWriter sw = new StringWriter(); - TransformerFactory transFact = TransformerFactory.newInstance(); - transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); - transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); - Transformer t = transFact.newTransformer(); - t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - t.transform(new DOMSource(node), new StreamResult(sw)); - return sw.toString(); - } } diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java index adab6df..de99880 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java @@ -20,11 +20,19 @@ */ package org.onap.aai.modelloader.entity.model; +import java.io.StringWriter; import java.util.List; import java.util.Objects; import java.util.stream.Collector; import java.util.stream.IntStream; import javax.xml.XMLConstants; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.entity.Artifact; @@ -53,7 +61,13 @@ public class ModelArtifactParser extends AbstractModelArtifactParser { parseRelationshipNode(node, model); } else { if (node.getNodeName().equalsIgnoreCase(MODEL_VER)) { - ((ModelArtifact) model).setModelVer(node); + String modelVersion; + try { + modelVersion = nodeToString(node); + ((ModelArtifact) model).setModelVer(modelVersion); + } catch (TransformerException e) { + logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Failed to parse resource version for input: " + node.toString()); + } if (((ModelArtifact) model).getModelNamespace() != null && !((ModelArtifact) model).getModelNamespace().isEmpty()) { Element e = (Element) node; @@ -66,6 +80,18 @@ public class ModelArtifactParser extends AbstractModelArtifactParser { } } + private String nodeToString(Node node) throws TransformerException { + StringWriter sw = new StringWriter(); + TransformerFactory transFact = TransformerFactory.newInstance(); + transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer t = transFact.newTransformer(); + t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + t.transform(new DOMSource(node), new StreamResult(sw)); + return sw.toString(); + } + /** * {@inheritDoc} */ diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelConstraint.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelConstraint.java new file mode 100644 index 0000000..5081bda --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelConstraint.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ModelConstraint { + @JsonProperty("model-constraint-uuid") + private String modelConstraintUuid; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("constrained-element-set-uuid-to-replace") + private String constrainedElementSetUuidToReplace; + + @JsonProperty("constrained-element-sets") + private List constrainedElementSets; + + @JsonProperty("resource-version") + private String resourceVersion; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelElement.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelElement.java new file mode 100644 index 0000000..b259586 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelElement.java @@ -0,0 +1,64 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ModelElement { + @JsonProperty("model-element-uuid") + private String modelElementUuid; + + @JsonProperty("new-data-del-flag") + private String newDataDelFlag; + + @JsonProperty("cardinality") + private String cardinality; + + @JsonProperty("linkage-points") + private String linkagePoints; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("model-elements") + private List modelElements; + + @JsonProperty("model-constraints") + private List modelConstraints; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/ModelVersion.java b/src/main/java/org/onap/aai/modelloader/entity/model/ModelVersion.java new file mode 100644 index 0000000..19703bd --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/model/ModelVersion.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ModelVersion { + + @JsonProperty("model-version-id") + private String modelVersionId; + + @JsonProperty("model-name") + private String modelName; + + @JsonProperty("model-version") + private String modelVersion; + + @JsonProperty("distribution-status") + private String distributionStatus; + + @JsonProperty("model-description") + private String modelDescription; + + @JsonProperty("sdnc-model-name") + private String sdncModelName; + + @JsonProperty("sdnc-model-version") + private String sdncModelVersion; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("model-elements") + private List modelElements; + + @JsonProperty("metadata") + private List metadata; + +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java b/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java index 04a17fa..ff3b734 100644 --- a/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java +++ b/src/main/java/org/onap/aai/modelloader/entity/model/NamedQueryArtifact.java @@ -21,15 +21,15 @@ package org.onap.aai.modelloader.entity.model; import java.util.List; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.restclient.AaiRestClient; import org.onap.aai.modelloader.entity.Artifact; -import org.onap.aai.restclient.client.OperationResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; public class NamedQueryArtifact extends AbstractModelArtifact { @@ -64,13 +64,13 @@ public class NamedQueryArtifact extends AbstractModelArtifact { private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId, List completedArtifacts) { - OperationResult getResponse = - aaiClient.getResource(getNamedQueryUrl(config), distId, MediaType.APPLICATION_XML_TYPE); - if (getResponse == null || getResponse.getResultCode() != Response.Status.OK.getStatusCode()) { + ResponseEntity getResponse = + aaiClient.getResource(getNamedQueryUrl(config), distId, MediaType.APPLICATION_XML, String.class); + if (getResponse == null || getResponse.getStatusCode() != HttpStatus.OK) { // Only attempt the PUT if the model doesn't already exist - OperationResult putResponse = aaiClient.putResource(getNamedQueryUrl(config), getPayload(), distId, - MediaType.APPLICATION_XML_TYPE); - if (putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode()) { + ResponseEntity putResponse = aaiClient.putResource(getNamedQueryUrl(config), getPayload(), distId, + MediaType.APPLICATION_XML, String.class); + if (putResponse != null && putResponse.getStatusCode() == HttpStatus.CREATED) { completedArtifacts.add(this); logInfoMsg(getType().toString() + " " + getUniqueIdentifier() + " successfully ingested."); } else { diff --git a/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImage.java b/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImage.java new file mode 100644 index 0000000..3eb1600 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImage.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.vnf; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class VnfImage { + @JsonProperty("vnf-image-uuid") + private String vnfImageUuid; + + private String application; + + @JsonProperty("application-vendor") + private String applicationVendor; + + @JsonProperty("application-version") + private String applicationVersion; + + private String selfLink; + + @JsonProperty("data-owner") + private String dataOwner; + + @JsonProperty("data-source") + private String dataSource; + + @JsonProperty("data-source-version") + private String dataSourceVersion; + + @JsonProperty("resource-version") + private String resourceVersion; +} diff --git a/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImages.java b/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImages.java new file mode 100644 index 0000000..e687366 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/entity/vnf/VnfImages.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.modelloader.entity.vnf; + +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class VnfImages { + List vnfImages; +} diff --git a/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java b/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java index 45f84d6..fca517d 100644 --- a/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java +++ b/src/main/java/org/onap/aai/modelloader/restclient/AaiRestClient.java @@ -20,34 +20,20 @@ */ package org.onap.aai.modelloader.restclient; -import com.sun.jersey.core.util.MultivaluedMapImpl; // NOSONAR -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.IntStream; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.entity.AaiResourcesObject; import org.onap.aai.modelloader.service.ModelLoaderMsgs; -import org.onap.aai.restclient.client.OperationResult; -import org.onap.aai.restclient.client.RestClient; -import org.onap.aai.restclient.enums.RestAuthenticationMode; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; +import org.springframework.web.client.RestTemplate; /** * Wrapper around the standard A&AI Rest Client interface. This currently uses Jersey client 1.x @@ -56,30 +42,34 @@ import org.xml.sax.SAXException; @Component public class AaiRestClient { + private static Logger logger = LoggerFactory.getInstance().getLogger(AaiRestClient.class.getName()); public static final String HEADER_TRANS_ID = "X-TransactionId"; public static final String HEADER_FROM_APP_ID = "X-FromAppId"; public static final String ML_APP_NAME = "ModelLoader"; private static final String RESOURCE_VERSION_PARAM = "resource-version"; + private final ModelLoaderConfig config; + private final RestTemplate restTemplate; - private static Logger logger = LoggerFactory.getInstance().getLogger(AaiRestClient.class.getName()); - - private ModelLoaderConfig config = null; - - public AaiRestClient(ModelLoaderConfig config) { + public AaiRestClient(ModelLoaderConfig config, RestTemplate restTemplate) { this.config = config; + this.restTemplate = restTemplate; } - /** * Send a GET request to the A&AI for a resource. + * @param * * @param url * @param transId * @param mediaType * @return */ - public OperationResult getResource(String url, String transId, MediaType mediaType) { - return setupClient().get(url, buildHeaders(transId), mediaType); + public ResponseEntity getResource(String url, String transId, MediaType mediaType, Class responseType) { + HttpHeaders headers = defaultHeaders(transId); + headers.setAccept(Collections.singletonList(mediaType)); + HttpEntity entity = new HttpEntity<>(headers); + + return restTemplate.exchange(url, HttpMethod.GET, entity, responseType); } /** @@ -91,27 +81,26 @@ public class AaiRestClient { * @param mediaType - the content type (XML or JSON) * @return operation result */ - public OperationResult putResource(String url, String payload, String transId, MediaType mediaType) { - logger.info(ModelLoaderMsgs.AAI_REST_REQUEST_PAYLOAD, payload); - return setupClient().put(url, payload, buildHeaders(transId), mediaType, mediaType); + public ResponseEntity putResource(String url, T payload, String transId, MediaType mediaType, Class responseType) { + logger.info(ModelLoaderMsgs.AAI_REST_REQUEST_PAYLOAD, payload.toString()); + HttpHeaders headers = defaultHeaders(transId); + headers.setAccept(Collections.singletonList(mediaType)); + headers.setContentType(mediaType); + HttpEntity entity = new HttpEntity<>(payload, headers); + + return restTemplate.exchange(url, HttpMethod.PUT, entity, responseType); } + public ResponseEntity postResource(String url, T payload, String transId, MediaType mediaType, Class responseType) { + logger.info(ModelLoaderMsgs.AAI_REST_REQUEST_PAYLOAD, payload.toString()); + HttpHeaders headers = defaultHeaders(transId); + headers.setAccept(Collections.singletonList(mediaType)); + headers.setContentType(mediaType); + HttpEntity entity = new HttpEntity<>(payload, headers); - /** - * Send a POST request to the A&AI. - * - * @param url - the url - * @param transId - transaction ID - * @param payload - the XML or JSON payload for the request - * @param mimeType - the content type (XML or JSON) - * @return ClientResponse - */ - public OperationResult postResource(String url, String payload, String transId, MediaType mediaType) { - logger.info(ModelLoaderMsgs.AAI_REST_REQUEST_PAYLOAD, payload); - return setupClient().post(url, payload, buildHeaders(transId), mediaType, mediaType); + return restTemplate.exchange(url, HttpMethod.POST, entity, responseType); } - /** * Send a DELETE request to the A&AI. * @@ -120,9 +109,11 @@ public class AaiRestClient { * @param transId - transaction ID * @return ClientResponse */ - public OperationResult deleteResource(String url, String resourceVersion, String transId) { - URI uri = UriBuilder.fromUri(url).queryParam(RESOURCE_VERSION_PARAM, resourceVersion).build(); - return setupClient().delete(uri.toString(), buildHeaders(transId), null); + public ResponseEntity deleteResource(String url, String resourceVersion, String transId) { + HttpHeaders headers = defaultHeaders(transId); + String uri = url + "?" + RESOURCE_VERSION_PARAM + "=" + resourceVersion; + HttpEntity entity = new HttpEntity<>(headers); + return restTemplate.exchange(uri, HttpMethod.DELETE, entity, String.class); } /** @@ -132,86 +123,34 @@ public class AaiRestClient { * @param transId - transaction ID * @return ClientResponse */ - public OperationResult getAndDeleteResource(String url, String transId) { + public ResponseEntity getAndDeleteResource(String url, String transId) { + ResponseEntity response = getResource(url, transId, MediaType.APPLICATION_XML, AaiResourcesObject.class); // First, GET the model - OperationResult getResponse = getResource(url, transId, MediaType.APPLICATION_XML_TYPE); - if (getResponse == null || getResponse.getResultCode() != Response.Status.OK.getStatusCode()) { - return getResponse; + if (response == null || response.getStatusCode() != HttpStatus.OK) { + return response; } - // Delete the model using the resource version in the response - String resVersion = null; - try { - resVersion = getResourceVersion(getResponse); - } catch (Exception e) { - logger.error(ModelLoaderMsgs.AAI_REST_REQUEST_ERROR, "GET", url, e.getLocalizedMessage()); - return null; - } - - return deleteResource(url, resVersion, transId); + return deleteResource(url, response.getBody().getResourceVersion(), transId); } - public boolean useBasicAuth() { + private boolean useBasicAuth() { return config.getAaiAuthenticationUser() != null && config.getAaiAuthenticationPassword() != null; } - private RestClient setupClient() { - RestClient restClient = new RestClient(); - restClient.validateServerHostname(false) - .validateServerCertChain(false) - .connectTimeoutMs(config.getClientConnectTimeoutMs()) - .readTimeoutMs(config.getClientReadTimeoutMs()); - - //Use certs only if SSL is enabled - if (config.useHttpsWithAAI()) - {// @formatter:off - restClient - .clientCertFile(config.getAaiKeyStorePath()) - .clientCertPassword(config.getAaiKeyStorePassword()); - // @formatter:on - } - - if (useBasicAuth()) { - restClient.authenticationMode(RestAuthenticationMode.SSL_BASIC); - restClient.basicAuthUsername(config.getAaiAuthenticationUser()); - restClient.basicAuthPassword(config.getAaiAuthenticationPassword()); - } - - return restClient; - } - /** * Create the HTTP headers required for an A&AI operation (GET/POST/PUT/DELETE) * * @param transId * @return map of headers */ - private Map> buildHeaders(String transId) { - MultivaluedMap headers = new MultivaluedMapImpl(); - headers.put(HEADER_TRANS_ID, Collections.singletonList(transId)); - headers.put(HEADER_FROM_APP_ID, Collections.singletonList(ML_APP_NAME)); + private HttpHeaders defaultHeaders(String transId) { + HttpHeaders headers = new HttpHeaders(); + headers.set(AaiRestClient.HEADER_TRANS_ID, transId); + headers.set(AaiRestClient.HEADER_FROM_APP_ID, AaiRestClient.ML_APP_NAME); + if (useBasicAuth()) { + headers.setBasicAuth(config.getAaiAuthenticationUser(), config.getAaiAuthenticationPassword()); + } return headers; } - - private String getResourceVersion(OperationResult getResponse) - throws ParserConfigurationException, SAXException, IOException { - String respData = getResponse.getResult(); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(respData)); - Document doc = builder.parse(is); - - NodeList nodesList = doc.getDocumentElement().getChildNodes(); - - // @formatter:off - return IntStream.range(0, nodesList.getLength()).mapToObj(nodesList::item) - .filter(childNode -> childNode.getNodeName().equals(RESOURCE_VERSION_PARAM)) - .findFirst() - .map(Node::getTextContent) - .orElse(null); - // @formatter:on - } } diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java index 53ce917..474fcc6 100644 --- a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java +++ b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java @@ -21,11 +21,10 @@ package org.onap.aai.modelloader.restclient; +import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import org.onap.aai.babel.service.data.BabelArtifact; import org.onap.aai.babel.service.data.BabelRequest; -import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.config.ModelLoaderConfig; @@ -35,6 +34,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @@ -65,6 +65,8 @@ public class BabelServiceClientImpl implements BabelServiceClient { String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl(); HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.set(AaiRestClient.HEADER_TRANS_ID, transactionId); headers.set(AaiRestClient.HEADER_FROM_APP_ID, AaiRestClient.ML_APP_NAME); HttpEntity entity = new HttpEntity<>(babelRequest, headers); diff --git a/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java b/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java index 9f09703..222ae34 100644 --- a/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java +++ b/src/main/java/org/onap/aai/modelloader/service/ArtifactDeploymentManager.java @@ -22,7 +22,6 @@ package org.onap.aai.modelloader.service; import java.util.ArrayList; import java.util.List; -import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifactHandler; import org.onap.aai.modelloader.entity.model.ModelArtifactHandler; @@ -36,14 +35,14 @@ import org.springframework.stereotype.Component; @Component public class ArtifactDeploymentManager { - private final ModelLoaderConfig config; private final ModelArtifactHandler modelArtifactHandler; private final VnfCatalogArtifactHandler vnfCatalogArtifactHandler; + private final AaiRestClient aaiClient; - public ArtifactDeploymentManager(ModelLoaderConfig config, ModelArtifactHandler modelArtifactHandler, VnfCatalogArtifactHandler vnfCatalogArtifactHandler) { - this.config = config; + public ArtifactDeploymentManager(ModelArtifactHandler modelArtifactHandler, VnfCatalogArtifactHandler vnfCatalogArtifactHandler, AaiRestClient aaiClient) { this.modelArtifactHandler = modelArtifactHandler; this.vnfCatalogArtifactHandler = vnfCatalogArtifactHandler; + this.aaiClient = aaiClient; } /** @@ -58,7 +57,6 @@ public class ArtifactDeploymentManager { public boolean deploy(final INotificationData data, final List modelArtifacts, final List catalogArtifacts) { - AaiRestClient aaiClient = new AaiRestClient(config); String distributionId = data.getDistributionID(); List completedArtifacts = new ArrayList<>(); diff --git a/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java index 87fbd6a..89f343c 100644 --- a/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java +++ b/src/test/java/org/onap/aai/modelloader/config/TestModelLoaderConfig.java @@ -21,16 +21,12 @@ package org.onap.aai.modelloader.config; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; import java.util.List; import java.util.Properties; import org.eclipse.jetty.util.security.Password; import org.junit.jupiter.api.Test; -import org.onap.aai.modelloader.restclient.AaiRestClient; import org.onap.sdc.utils.ArtifactTypeEnum; /** @@ -149,23 +145,6 @@ public class TestModelLoaderConfig { assertEquals(url, config.getBabelGenerateArtifactsUrl()); } - @Test - public void testMissingAuthenticationProperties() throws IOException { - Properties props = new Properties(); - props.load(new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties")); - - ModelLoaderConfig config = new ModelLoaderConfig(props, null); - AaiRestClient aaiClient = new AaiRestClient(config); - - assertFalse(aaiClient.useBasicAuth(), "Empty AAI Password should result in no basic authentication"); - - props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties")); - config = new ModelLoaderConfig(props, null); - aaiClient = new AaiRestClient(config); - - assertFalse(aaiClient.useBasicAuth(), "No AAI Password should result in no basic authentication"); - } - @Test public void testGetUrls() { Properties props = new Properties(); diff --git a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java index 8145599..3da25b0 100644 --- a/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java +++ b/src/test/java/org/onap/aai/modelloader/entity/catalog/TestVnfCatalogArtifactHandler.java @@ -23,6 +23,7 @@ package org.onap.aai.modelloader.entity.catalog; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -35,9 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -45,7 +43,9 @@ import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.aai.restclient.client.OperationResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; public class TestVnfCatalogArtifactHandler { @@ -61,24 +61,23 @@ public class TestVnfCatalogArtifactHandler { @Test public void testUpdateVnfImages() throws Exception { // GET operation - OperationResult mockGetResp = mock(OperationResult.class); + ResponseEntity mockGetResp = mock(ResponseEntity.class); // @formatter:off - when(mockGetResp.getResultCode()) - .thenReturn(Response.Status.OK.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.OK.getStatusCode()); + when(mockGetResp.getStatusCodeValue()) + .thenReturn(HttpStatus.OK.value()) + .thenReturn(HttpStatus.NOT_FOUND.value()) + .thenReturn(HttpStatus.NOT_FOUND.value()) + .thenReturn(HttpStatus.OK.value()); // @formatter:on - when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class))) + when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class), Mockito.any())) .thenReturn(mockGetResp); mockPutOperations(); // Example VNF Catalog XML VnfCatalogArtifactHandler handler = new VnfCatalogArtifactHandler(createConfig()); - assertThat(handler.pushArtifacts(createVnfCatalogArtifact(), "test", new ArrayList(), mockRestClient), - is(true)); + assertTrue(handler.pushArtifacts(createVnfCatalogArtifact(), "test", new ArrayList(), mockRestClient)); assertPutOperationsSucceeded(); } @@ -86,17 +85,17 @@ public class TestVnfCatalogArtifactHandler { @Test public void testUpdateVnfImagesFromXml() throws Exception { // GET operation - OperationResult mockGetResp = mock(OperationResult.class); + ResponseEntity mockGetResp = mock(ResponseEntity.class); // @formatter:off - when(mockGetResp.getResultCode()) - .thenReturn(Response.Status.OK.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.NOT_FOUND.getStatusCode()) - .thenReturn(Response.Status.OK.getStatusCode()); + when(mockGetResp.getStatusCodeValue()) + .thenReturn(HttpStatus.OK.value()) + .thenReturn(HttpStatus.NOT_FOUND.value()) + .thenReturn(HttpStatus.NOT_FOUND.value()) + .thenReturn(HttpStatus.OK.value()); // @formatter:on - when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class))) + when(mockRestClient.getResource(Mockito.anyString(), Mockito.anyString(), Mockito.any(MediaType.class), Mockito.any())) .thenReturn(mockGetResp); mockPutOperations(); @@ -109,7 +108,7 @@ public class TestVnfCatalogArtifactHandler { // Only two of the VNF images should be pushed ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); AaiRestClient client = Mockito.verify(mockRestClient, Mockito.times(2)); - client.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), Mockito.any(MediaType.class)); + client.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), Mockito.any(MediaType.class), Mockito.any()); assertThat(argument.getAllValues().size(), is(2)); assertThat(argument.getAllValues().get(0), containsString("5.2.5")); assertThat(argument.getAllValues().get(0), containsString("VM00")); @@ -161,10 +160,10 @@ public class TestVnfCatalogArtifactHandler { * Always return CREATED (success) for a PUT operation. */ private void mockPutOperations() { - OperationResult mockPutResp = mock(OperationResult.class); - when(mockPutResp.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode()); + ResponseEntity mockPutResp = mock(ResponseEntity.class); + when(mockPutResp.getStatusCode()).thenReturn(HttpStatus.CREATED); when(mockRestClient.putResource(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), - Mockito.any(MediaType.class))).thenReturn(mockPutResp); + Mockito.any(MediaType.class), Mockito.any())).thenReturn(mockPutResp); } private void assertPutOperationsSucceeded() { @@ -172,7 +171,7 @@ public class TestVnfCatalogArtifactHandler { ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); AaiRestClient mockedClient = Mockito.verify(mockRestClient, Mockito.times(2)); mockedClient.putResource(Mockito.anyString(), argument.capture(), Mockito.anyString(), - Mockito.any(MediaType.class)); + Mockito.any(MediaType.class), Mockito.any()); assertThat(argument.getAllValues().get(0), containsString("3.16.9")); assertThat(argument.getAllValues().get(0), containsString("VM00")); assertThat(argument.getAllValues().get(1), containsString("3.16.1")); diff --git a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java index 177a8d2..b16c8a0 100644 --- a/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java +++ b/src/test/java/org/onap/aai/modelloader/entity/model/TestModelArtifactHandler.java @@ -32,8 +32,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import javax.ws.rs.core.Response; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -41,7 +39,8 @@ import org.mockito.MockitoAnnotations; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.aai.restclient.client.OperationResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; /** * Test the Model Artifact Handler using Mocks @@ -68,26 +67,14 @@ public class TestModelArtifactHandler { assertTrue(true); } - @Test - public void testSingleItemList() { - when(config.getAaiBaseUrl()).thenReturn(""); - when(config.getAaiModelUrl(any())).thenReturn(""); - - ModelArtifactHandler handler = new ModelArtifactHandler(config); - List artifacts = Collections.singletonList(new ModelArtifact()); - handler.pushArtifacts(artifacts, "", Collections.emptyList(), aaiClient); - handler.rollback(Collections.emptyList(), "", aaiClient); - assertThat(artifacts, hasSize(1)); - } - @Test public void testPushExistingModelsWithRollback() { when(config.getAaiBaseUrl()).thenReturn(""); when(config.getAaiModelUrl(any())).thenReturn(""); - OperationResult operationResult = mock(OperationResult.class); - when(aaiClient.getResource(any(), any(), any())).thenReturn(operationResult); - when(operationResult.getResultCode()).thenReturn(Response.Status.OK.getStatusCode()); + ResponseEntity operationResult = mock(ResponseEntity.class); + when(aaiClient.getResource(any(), any(), any(), any())).thenReturn(operationResult); + when(operationResult.getStatusCode()).thenReturn(HttpStatus.OK); List artifacts = new ArrayList<>(); Artifact artifact = new ModelArtifact(); @@ -105,13 +92,13 @@ public class TestModelArtifactHandler { when(config.getAaiModelUrl(any())).thenReturn(""); when(config.getAaiNamedQueryUrl(any())).thenReturn(""); - OperationResult getResult = mock(OperationResult.class); - when(aaiClient.getResource(any(), any(), any())).thenReturn(getResult); - when(getResult.getResultCode()).thenReturn(Response.Status.NOT_FOUND.getStatusCode()); + ResponseEntity getResult = mock(ResponseEntity.class); + when(aaiClient.getResource(any(), any(), any(), any())).thenReturn(getResult); + when(getResult.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); - OperationResult putResult = mock(OperationResult.class); - when(aaiClient.putResource(any(), any(), any(), any())).thenReturn(putResult); - when(putResult.getResultCode()).thenReturn(Response.Status.CREATED.getStatusCode()); + ResponseEntity putResult = mock(ResponseEntity.class); + when(aaiClient.putResource(any(), any(), any(), any(), any())).thenReturn(putResult); + when(putResult.getStatusCode()).thenReturn(HttpStatus.CREATED); List artifacts = new ArrayList<>(); artifacts.add(new ModelArtifact()); @@ -133,13 +120,13 @@ public class TestModelArtifactHandler { when(config.getAaiModelUrl(any())).thenReturn(""); when(config.getAaiNamedQueryUrl(any())).thenReturn(""); - OperationResult getResult = mock(OperationResult.class); - when(aaiClient.getResource(any(), any(), any())).thenReturn(getResult); - when(getResult.getResultCode()).thenReturn(Response.Status.NOT_FOUND.getStatusCode()); + ResponseEntity getResult = mock(ResponseEntity.class); + when(aaiClient.getResource(any(), any(), any(), any())).thenReturn(getResult); + when(getResult.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); - OperationResult putResult = mock(OperationResult.class); - when(aaiClient.putResource(any(), any(), any(), any())).thenReturn(putResult); - when(putResult.getResultCode()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode()); + ResponseEntity putResult = mock(ResponseEntity.class); + when(aaiClient.putResource(any(), any(), any(), any(), any())).thenReturn(putResult); + when(putResult.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); checkRollback(Collections.singletonList(new ModelArtifact())); } @@ -149,18 +136,9 @@ public class TestModelArtifactHandler { when(config.getAaiBaseUrl()).thenReturn(""); when(config.getAaiModelUrl(any())).thenReturn(""); - OperationResult operationResult = mock(OperationResult.class); - when(aaiClient.getResource(any(), any(), any())).thenReturn(operationResult); - when(operationResult.getResultCode()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode()); - - checkRollback(Collections.singletonList(new ModelArtifact())); - } - - @Test - public void testNullResourceModelResult() { - when(config.getAaiBaseUrl()).thenReturn(""); - when(config.getAaiModelUrl(any())).thenReturn(""); - when(aaiClient.getResource(any(), any(), any())).thenReturn(null); + ResponseEntity operationResult = mock(ResponseEntity.class); + when(aaiClient.getResource(any(), any(), any(), any())).thenReturn(operationResult); + when(operationResult.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); checkRollback(Collections.singletonList(new ModelArtifact())); } diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java index 0985790..eb31688 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java +++ b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerTest.java @@ -33,7 +33,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.apache.http.entity.ContentType; import org.junit.jupiter.api.Test; import org.onap.aai.modelloader.DistributionClientTestConfiguration; import org.onap.aai.modelloader.entity.Artifact; @@ -66,11 +65,11 @@ public class ArtifactDownloadManagerTest { notificationData.setServiceVersion("2.0"); stubFor(get(urlEqualTo("/sdc/v1/catalog/services/DemovlbCds/1.0/artifacts/service-TestSvc-csar.csar")) - .withHeader("Accept", equalTo(ContentType.APPLICATION_OCTET_STREAM.toString())) + .withHeader("Accept", equalTo(MediaType.APPLICATION_OCTET_STREAM_VALUE)) .withHeader("X-ECOMP-RequestID", matching(".+")) .withHeader("X-ECOMP-InstanceID", equalTo("aai-ml-id-test")) .willReturn(aResponse() - .withHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM.toString()) + .withHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE) .withBodyFile("service-TestSvc-csar.csar"))); stubFor( @@ -83,7 +82,7 @@ public class ArtifactDownloadManagerTest { .withRequestBody(matchingJsonPath("$.csar", matching(".*"))) .willReturn( aResponse() - .withHeader("Content-Type", "application/json") + .withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE) .withBodyFile("service-TestSvc-csar-babel-response.json"))); ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); diff --git a/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java index 4d7b53e..d3495d4 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java +++ b/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java @@ -41,13 +41,13 @@ import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.model.ModelArtifact; import org.onap.aai.modelloader.entity.model.ModelArtifactHandler; import org.onap.aai.modelloader.restclient.AaiRestClient; -import org.onap.aai.restclient.client.OperationResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.http.HttpStatus; -import org.w3c.dom.Node; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.client.WireMock; @@ -89,7 +89,8 @@ public class ModelArtifactHandlerTest { WireMock.stubFor( WireMock.put(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId")) - .withHeader("Content-Type", equalTo("application/xml")) + .withHeader("Accept", equalTo(MediaType.APPLICATION_XML_VALUE)) + .withHeader("Content-Type", equalTo(MediaType.APPLICATION_XML_VALUE)) .withHeader("X-TransactionId", equalTo("someId")) .withHeader("X-FromAppId", equalTo("ModelLoader")) .willReturn( @@ -98,6 +99,7 @@ public class ModelArtifactHandlerTest { ModelArtifact modelArtifact = new ModelArtifact(); modelArtifact.setModelInvariantId("modelInvariantId"); + modelArtifact.setPayload(""); List artifacts = List.of(modelArtifact); List completedArtifacts = new ArrayList<>(); @@ -134,7 +136,8 @@ public class ModelArtifactHandlerTest { WireMock.stubFor( WireMock.put(urlEqualTo( "/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId")) - .withHeader("Content-Type", equalTo("application/xml")) + .withHeader("Accept", equalTo(MediaType.APPLICATION_XML_VALUE)) + .withHeader("Content-Type", equalTo(MediaType.APPLICATION_XML_VALUE)) .withHeader("X-TransactionId", equalTo("distributionId")) .withHeader("X-FromAppId", equalTo("ModelLoader")) .willReturn( @@ -144,8 +147,8 @@ public class ModelArtifactHandlerTest { ModelArtifact modelArtifact = new ModelArtifact(); modelArtifact.setModelInvariantId("modelInvariantId"); modelArtifact.setModelVerId("modelVersionId"); - Node node = Mockito.mock(Node.class); - modelArtifact.setModelVer(node); + modelArtifact.setPayload(""); + modelArtifact.setModelVer("2.0"); List artifacts = List.of(modelArtifact); List completedArtifacts = new ArrayList<>(); @@ -159,9 +162,11 @@ public class ModelArtifactHandlerTest { @Test public void thatModelCanBeRolledBack() { stubFor(WireMock.get(urlEqualTo("/aai/v28/service-design-and-creation/models/model/3a40ab73-6694-4e75-bb6d-9a4a86ce35b3")) + .withHeader("Accept", equalTo(MediaType.APPLICATION_XML_VALUE)) .withHeader("X-FromAppId", equalTo("ModelLoader")) .withHeader("X-TransactionId", equalTo("distributionId")) .willReturn(aResponse() + .withHeader("Content-Type", MediaType.APPLICATION_XML_VALUE) .withBodyFile("modelResponse.xml"))); stubFor(WireMock.delete(urlEqualTo("/aai/v28/service-design-and-creation/models/model/3a40ab73-6694-4e75-bb6d-9a4a86ce35b3?resource-version=1710523260974")) @@ -172,8 +177,8 @@ public class ModelArtifactHandlerTest { ModelArtifact modelArtifact = new ModelArtifact(); modelArtifact.setModelInvariantId("3a40ab73-6694-4e75-bb6d-9a4a86ce35b3"); modelArtifact.setModelVerId("modelVersionId"); - Node node = Mockito.mock(Node.class); - modelArtifact.setModelVer(node); + // modelArtifact.setModelVer("2.0"); + List completedArtifacts = new ArrayList<>(); completedArtifacts.add(modelArtifact); @@ -195,30 +200,46 @@ public class ModelArtifactHandlerTest { * @param modelArtifact */ private void mockModelCreation(ModelArtifact modelArtifact) { - OperationResult createdResult = Mockito.mock(OperationResult.class); - when(createdResult.getResultCode()).thenReturn(HttpStatus.CREATED.value()); - OperationResult notFoundResult = Mockito.mock(OperationResult.class); - when(notFoundResult.getResultCode()).thenReturn(HttpStatus.NOT_FOUND.value()); + ResponseEntity createdResult = Mockito.mock(ResponseEntity.class); + when(createdResult.getStatusCode()).thenReturn(HttpStatus.CREATED); + ResponseEntity notFoundResult = Mockito.mock(ResponseEntity.class); + when(notFoundResult.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); AaiRestClient aaiClient = Mockito.mock(AaiRestClient.class); - when(aaiClient.putResource(any(), any(), any(), any())).thenReturn(createdResult); - when(aaiClient.getResource(any(), any(), any())).thenReturn(notFoundResult); + when(aaiClient.putResource(any(), any(), any(), any(), any())).thenReturn(createdResult); + when(aaiClient.getResource(any(), any(), any(), any())).thenReturn(notFoundResult); modelArtifact.push(aaiClient, config, null, new ArrayList<>()); } @Test public void thatModelVersionCanBeRolledBack() { - // "http://localhost:10594/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId" + WireMock.stubFor( + WireMock.get(urlEqualTo( + "/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId")) + .withHeader("Accept", equalTo("application/xml")) + .withHeader("X-TransactionId", equalTo("distributionId")) + .withHeader("X-FromAppId", equalTo("ModelLoader")) + .willReturn( + WireMock.aResponse() + .withHeader("Content-Type", MediaType.APPLICATION_XML_VALUE) + .withBodyFile("modelVersion.xml"))); + + stubFor(WireMock.delete(urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId?resource-version=1708937324692")) + .withHeader("X-FromAppId", equalTo("ModelLoader")) + .withHeader("X-TransactionId", equalTo("distributionId")) + .willReturn(aResponse().withStatus(HttpStatus.OK.value()))); ModelArtifact modelArtifact = new ModelArtifact(); modelArtifact.setModelInvariantId("modelInvariantId"); modelArtifact.setModelVerId("modelVersionId"); - Node node = Mockito.mock(Node.class); - modelArtifact.setModelVer(node); + List completedArtifacts = new ArrayList<>(); completedArtifacts.add(modelArtifact); modelArtifactHandler.rollback(completedArtifacts, "distributionId", restClient); + verify( + deleteRequestedFor( + urlEqualTo("/aai/v28/service-design-and-creation/models/model/modelInvariantId/model-vers/model-ver/modelVersionId?resource-version=1708937324692"))); } } \ No newline at end of file diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java index dfced1a..618a268 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java +++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDeploymentManager.java @@ -48,9 +48,11 @@ import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; import org.onap.aai.modelloader.entity.model.ModelArtifactHandler; import org.onap.aai.modelloader.extraction.InvalidArchiveException; import org.onap.aai.modelloader.fixture.NotificationDataFixtureBuilder; +import org.onap.aai.modelloader.restclient.AaiRestClient; import org.onap.aai.modelloader.service.ArtifactDeploymentManager; import org.onap.aai.modelloader.util.ArtifactTestUtils; import org.onap.sdc.api.notification.INotificationData; +import org.springframework.web.client.RestTemplate; /** * Tests {@link ArtifactDeploymentManager}. @@ -73,7 +75,8 @@ public class TestArtifactDeploymentManager { configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE)); ModelLoaderConfig modelLoaderConfig = new ModelLoaderConfig(configProperties, null); - manager = new ArtifactDeploymentManager(modelLoaderConfig, modelArtifactHandlerMock, vnfCatalogArtifactHandlerMock); + AaiRestClient aaiRestClient = new AaiRestClient(modelLoaderConfig, new RestTemplate()); + manager = new ArtifactDeploymentManager(modelArtifactHandlerMock, vnfCatalogArtifactHandlerMock, aaiRestClient); } @AfterEach diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java index 37b7e12..c992d06 100644 --- a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java +++ b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiRestClient.java @@ -30,15 +30,16 @@ import java.util.Properties; import java.util.stream.IntStream; import java.util.stream.Stream; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.entity.model.ModelArtifact; import org.onap.aai.modelloader.entity.model.ModelArtifactParser; -import org.onap.aai.restclient.client.OperationResult; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -89,21 +90,21 @@ public class TestAaiRestClient { model.setPayload(readFile(MODEL_FILE)); model.setModelNamespace("http://org.openecomp.aai.inventory/v9"); - AaiRestClient aaiClient = new AaiRestClient(config); + AaiRestClient aaiClient = new AaiRestClient(config, new RestTemplate()); // GET model - OperationResult opResult = - aaiClient.getResource(getUrl(model, config), "example-trans-id-0", MediaType.APPLICATION_XML_TYPE); - assertEquals(opResult.getResultCode(), Response.Status.NOT_FOUND.getStatusCode()); + ResponseEntity opResult = + aaiClient.getResource(getUrl(model, config), "example-trans-id-0", MediaType.APPLICATION_XML, String.class); + assertEquals(opResult.getStatusCode(), HttpStatus.NOT_FOUND); // PUT the model opResult = aaiClient.putResource(getUrl(model, config), model.getPayload(), "example-trans-id-1", - MediaType.APPLICATION_XML_TYPE); - assertEquals(opResult.getResultCode(), Response.Status.CREATED.getStatusCode()); + MediaType.APPLICATION_XML, String.class); + assertEquals(opResult.getStatusCode(), HttpStatus.CREATED); // DELETE the model opResult = aaiClient.getAndDeleteResource(getUrl(model, config), "example-trans-id-3"); - assertEquals(opResult.getResultCode(), Response.Status.NO_CONTENT.getStatusCode()); + assertEquals(opResult.getStatusCode(), HttpStatus.NO_CONTENT); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java deleted file mode 100644 index 18753b1..0000000 --- a/src/test/java/org/onap/aai/modelloader/restclient/TestAaiServiceClient.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.aai.modelloader.restclient; - -import static javax.servlet.http.HttpServletResponse.SC_OK; -import static org.apache.commons.io.IOUtils.write; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Properties; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.eclipse.jetty.server.Handler; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.aai.modelloader.config.ModelLoaderConfig; - -/** - * Local testing of the A&AI Service client. - * - */ -public class TestAaiServiceClient { - - private Server server; - private AaiRestClient aaiClient; - - @BeforeEach - public void startJetty() throws Exception { - server = new Server(0); - server.setHandler(getMockHandler()); - server.start(); - - Properties props = new Properties(); - props.put("ml.aai.KEYSTORE_PASSWORD", "2244"); - props.put("ml.aai.RESTCLIENT_CONNECT_TIMEOUT", "3000"); - props.put("ml.aai.RESTCLIENT_READ_TIMEOUT", "3000"); - ModelLoaderConfig config = new ModelLoaderConfig(props, "."); - aaiClient = new AaiRestClient(config); - } - - @AfterEach - public void stopJetty() throws Exception { - server.stop(); - } - - @Test - public void testBuildAaiRestClient() { - Properties props = new Properties(); - ModelLoaderConfig config = new ModelLoaderConfig(props, "."); - new AaiRestClient(config); - assertTrue(true); - } - - @Test - public void testOperations() { - String url = server.getURI().toString(); - String transId = ""; - MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; - aaiClient.getResource(url, "", mediaType); - aaiClient.deleteResource(url, "", transId); - aaiClient.getAndDeleteResource(url, transId); - aaiClient.postResource(url, "", transId, mediaType); - aaiClient.putResource(url, "", transId, mediaType); - assertTrue(true); - } - - - /** - * Creates an {@link AbstractHandler handler} returning an arbitrary String as a response. - * - * @return never null. - */ - private Handler getMockHandler() { - Handler handler = new AbstractHandler() { - @Override - public void handle(String target, Request request, HttpServletRequest servletRequest, - HttpServletResponse response) throws IOException, ServletException { - response.setStatus(SC_OK); - response.setContentType("text/json;charset=utf-8"); - write("", response.getOutputStream(), Charset.defaultCharset()); - request.setHandled(true); - } - }; - return handler; - } -} - diff --git a/src/test/resources/__files/modelVersion.xml b/src/test/resources/__files/modelVersion.xml new file mode 100644 index 0000000..efee516 --- /dev/null +++ b/src/test/resources/__files/modelVersion.xml @@ -0,0 +1,8 @@ + + + fe578080-ce19-4604-8760-fc264fbb2565 + group-assignment + 1.0 + 1708937324692 + \ No newline at end of file -- 2.16.6