summaryrefslogtreecommitdiffstats
path: root/mod2
diff options
context:
space:
mode:
authorRavi Mantena <rx908f@att.com>2020-11-27 13:34:11 -0500
committerRavi Mantena <rx908f@att.com>2020-12-08 14:13:43 -0500
commite3578fcdcd65c9f919c0f7cc16949b79b70d12b4 (patch)
treee85f8b4048dfc3e7118216894ee36c255cbd6211 /mod2
parent437e1f4e621d63cf576caa5de9c5c4804ea455f9 (diff)
Policy Model Distribution POC Issue-ID: DCAEGEN2-1868
Issue-ID: DCAEGEN2-1868 Change-Id: Ife6421558af59405f3026f66950ff8f2d7aeba17 Signed-off-by: Ravi Mantena <rx908f@att.com>
Diffstat (limited to 'mod2')
-rw-r--r--mod2/catalog-service/pom.xml6
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/ErrorMessages.java2
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelConflictException.java27
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelDistributionEnvNotFoundException.java27
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelNotFoundException.java27
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/DistributionInfo.java42
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModel.java54
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelDistributionEnv.java28
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelStatus.java28
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/MetadataRequest.java46
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelCreateRequest.java59
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelDistributionRequest.java45
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelUpdateRequest.java54
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoGateway.java60
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoRepo.java39
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/util/PolicyModelUtils.java186
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/AppExceptionHandler.java49
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelController.java114
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelDistributionController.java82
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionService.java43
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionServiceImpl.java183
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelGateway.java42
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelService.java44
-rw-r--r--mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelServiceImpl.java203
-rw-r--r--mod2/catalog-service/src/main/resources/application.properties28
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelDistributionObjectMother.java35
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelObjectMother.java57
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelControllerTest.java110
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelCreateRequestValidationTest.java95
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelDistributionControllerTest.java120
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelUpdateRequestValidationTest.java83
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelDistributionServiceImplTest.java329
-rw-r--r--mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelServiceImplTest.java152
-rw-r--r--mod2/catalog-service/src/test/resources/http/requests/pmdist_sample.json142
-rw-r--r--mod2/catalog-service/src/test/resources/http/requests/policy-model_create_request.json6
-rw-r--r--mod2/catalog-service/src/test/resources/http/requests/policy-model_update_request.json5
-rw-r--r--mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response.json12
-rw-r--r--mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response1.json16
38 files changed, 2673 insertions, 7 deletions
diff --git a/mod2/catalog-service/pom.xml b/mod2/catalog-service/pom.xml
index fee27ec..9a82b7b 100644
--- a/mod2/catalog-service/pom.xml
+++ b/mod2/catalog-service/pom.xml
@@ -44,7 +44,7 @@
<dependency>
<groupId>org.onap.dcaegen2.platform.mod</groupId>
<artifactId>blueprint-generator</artifactId>
- <version>1.5.2-SNAPSHOT</version>
+ <version>1.5.2</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -102,12 +102,12 @@
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
- <version>4.0.1</version>
+ <version>4.2.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
- <version>4.0.1</version>
+ <version>4.2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/ErrorMessages.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/ErrorMessages.java
index 9b96066..27f335f 100644
--- a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/ErrorMessages.java
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/ErrorMessages.java
@@ -30,4 +30,6 @@ public class ErrorMessages {
public static final String MS_SERVICE_NAME_CONFLICT_MESSAGE = "Microservice with this core name already exists.";
public static final String MS_SERVICE_NAME_VALIDATION_MESSAGE =
"Service name is Invalid. Accepts lowercase letters and hyphens";
+ public static final String POLICYMODEL_NAME_VERSION_CONFLICT_MESSAGE = "Policy Model with this name and version already exists.";
+
}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelConflictException.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelConflictException.java
new file mode 100644
index 0000000..8d5098f
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelConflictException.java
@@ -0,0 +1,27 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.exceptions.policymodel;
+
+public class PolicyModelConflictException extends RuntimeException {
+ public PolicyModelConflictException(String message) {
+ super(message);
+ }
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelDistributionEnvNotFoundException.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelDistributionEnvNotFoundException.java
new file mode 100644
index 0000000..dfc47e3
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelDistributionEnvNotFoundException.java
@@ -0,0 +1,27 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.exceptions.policymodel;
+
+public class PolicyModelDistributionEnvNotFoundException extends RuntimeException {
+ public PolicyModelDistributionEnvNotFoundException(String message) {
+ super(message);
+ }
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelNotFoundException.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelNotFoundException.java
new file mode 100644
index 0000000..16e30c7
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/exceptions/policymodel/PolicyModelNotFoundException.java
@@ -0,0 +1,27 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.exceptions.policymodel;
+
+public class PolicyModelNotFoundException extends RuntimeException {
+ public PolicyModelNotFoundException(String message) {
+ super(message);
+ }
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/DistributionInfo.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/DistributionInfo.java
new file mode 100644
index 0000000..1d15623
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/DistributionInfo.java
@@ -0,0 +1,42 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.policymodel;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * A model class which represents Distribution Info of a Policy Model entity
+ */
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DistributionInfo {
+
+ private String url;
+ private PolicyModelStatus status;
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModel.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModel.java
new file mode 100644
index 0000000..d4b5bf0
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModel.java
@@ -0,0 +1,54 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.policymodel;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.onap.dcaegen2.platform.mod.model.restapi.MetadataRequest;
+import org.springframework.data.annotation.Id;
+import org.springframework.data.mongodb.core.mapping.Document;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A model class which represents Policy Model entity
+ */
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@Document("policy-model")
+public class PolicyModel {
+ @Id
+ private String id;
+ private String name;
+ private String content;
+ private String owner;
+ private String version;
+ private MetadataRequest metadata;
+ private List<DistributionInfo> distributionInfo = new ArrayList<>();
+
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelDistributionEnv.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelDistributionEnv.java
new file mode 100644
index 0000000..a750bcb
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelDistributionEnv.java
@@ -0,0 +1,28 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.policymodel;
+
+/**
+ * Supported Environments for Policy Model Distribution
+ */
+public enum PolicyModelDistributionEnv {
+ DEV,PST,ETE,PROD
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelStatus.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelStatus.java
new file mode 100644
index 0000000..11e3283
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/policymodel/PolicyModelStatus.java
@@ -0,0 +1,28 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.policymodel;
+
+/**
+ * Supported statuses for Policy Model entity
+ */
+public enum PolicyModelStatus {
+ SUCCESS, FAILED, NOTDISTRIBUTED
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/MetadataRequest.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/MetadataRequest.java
new file mode 100644
index 0000000..279c596
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/MetadataRequest.java
@@ -0,0 +1,46 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.restapi;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.util.Date;
+import java.util.List;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class MetadataRequest {
+
+ private String createdBy;
+ private Date createdOn;
+ private String updatedBy;
+ private Date updatedOn;
+ private String notes = "";
+ private List<String> labels;
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelCreateRequest.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelCreateRequest.java
new file mode 100644
index 0000000..a4258f4
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelCreateRequest.java
@@ -0,0 +1,59 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.restapi;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+
+/**
+ * A model that represent request body to create Policy Model entity.
+ */
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class PolicyModelCreateRequest {
+
+ @NotBlank
+ @Pattern(regexp = "^([a-z0-9](-[a-z0-9])*)+$", message = "Policy Model name is invalid. Accepts lower alphanumerics and hyphens.")
+ @Size(min = 5, max = 50, message = "Policy Model name length cannot exceed 50 characters")
+ private String name;
+
+ @NotBlank
+ private String content;
+
+ @NotBlank
+ private String owner;
+
+ @NotBlank
+ @Pattern(regexp = "[0-9].[0-9].[0-9]", message = "Policy Model version is invalid. Should be in x.x.x format.")
+ private String version;
+
+ private MetadataRequest metadata;
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelDistributionRequest.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelDistributionRequest.java
new file mode 100644
index 0000000..9feff64
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelDistributionRequest.java
@@ -0,0 +1,45 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.restapi;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModelDistributionEnv;
+
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+
+/**
+ * A model that represent request body to Distribute Policy Model entity.
+ */
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class PolicyModelDistributionRequest {
+
+ private PolicyModelDistributionEnv env;
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelUpdateRequest.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelUpdateRequest.java
new file mode 100644
index 0000000..08d1e65
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/model/restapi/PolicyModelUpdateRequest.java
@@ -0,0 +1,54 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.model.restapi;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+
+/**
+ * A model that represent request body to create Policy Model entity.
+ */
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class PolicyModelUpdateRequest {
+
+ @Pattern(regexp = "^([a-z0-9](-[a-z0-9])*)+$", message = "Policy Model name is invalid. Accepts alphanumerics and hyphens.")
+ @Size(min = 5, max = 50, message = "Policy Model name length cannot exceed 50 characters")
+ private String name;
+
+ private String content;
+
+ private String owner;
+
+ @Pattern(regexp = "[0-9].[0-9].[0-9]", message = "Policy Model version is invalid. Should be in x.x.x format.")
+ private String version;
+
+ private MetadataRequest metadata;
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoGateway.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoGateway.java
new file mode 100644
index 0000000..e4c8fc2
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoGateway.java
@@ -0,0 +1,60 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.mongo.policymodel;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelGateway;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Sort;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Mongo implementation of Policy Model
+ */
+
+@Service
+public class PolicyModelMongoGateway implements PolicyModelGateway {
+
+ @Autowired
+ private PolicyModelMongoRepo repo;
+
+ @Override
+ public List<PolicyModel> findAll() {
+ Sort sortByCreatedDate = Sort.by(Sort.Direction.DESC, "metadata.createdOn");
+ return repo.findAll(sortByCreatedDate);
+ }
+
+ @Override
+ public Optional<PolicyModel> findById(String id) {
+ return repo.findById(id);
+ }
+
+ @Override
+ public PolicyModel save(PolicyModel newPolicyModel) { return repo.save(newPolicyModel); }
+
+ @Override
+ public Optional<PolicyModel> findByNameAndVersion(String name, String version) { return repo.findByNameIgnoreCaseAndVersionIgnoreCase(name,version); }
+
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoRepo.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoRepo.java
new file mode 100644
index 0000000..491de22
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/mongo/policymodel/PolicyModelMongoRepo.java
@@ -0,0 +1,39 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.mongo.policymodel;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.springframework.data.mongodb.repository.MongoRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.Optional;
+
+
+/**
+ * An interface to use Spring MongoRepository for Policy Model
+ */
+
+@Repository
+public interface PolicyModelMongoRepo extends MongoRepository<PolicyModel, String> {
+
+ Optional<PolicyModel> findByNameIgnoreCaseAndVersionIgnoreCase(String name, String version);
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/util/PolicyModelUtils.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/util/PolicyModelUtils.java
new file mode 100644
index 0000000..8d7b643
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/util/PolicyModelUtils.java
@@ -0,0 +1,186 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.util;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelDistributionEnvNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModelDistributionEnv;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.client.reactive.ReactorClientHttpConnector;
+import org.springframework.stereotype.Component;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
+import org.springframework.web.reactive.function.client.WebClient;
+import reactor.netty.http.client.HttpClient;
+
+import javax.annotation.PostConstruct;
+import javax.net.ssl.SSLException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Policy Model Service Utils to get URL, Username, Password, Webclient
+ */
+
+@Component
+public class PolicyModelUtils {
+
+ @Value("${url.path}")
+ private String urlpath;
+
+ @Value("${dev.server}")
+ private String devServer;
+
+ @Value("${dev.port}")
+ private String devServerPort;
+
+ @Value("${dev.user}")
+ private String devServerUser;
+
+ @Value("${dev.password}")
+ private String devServerUserPassword;
+
+ @Value("${pst.server}")
+ private String pstServer;
+
+ @Value("${pst.port}")
+ private String pstServerPort;
+
+ @Value("${pst.user}")
+ private String pstServerUser;
+
+ @Value("${pst.password}")
+ private String pstServerUserPassword;
+
+ @Value("${ete.server}")
+ private String eteServer;
+
+ @Value("${ete.port}")
+ private String eteServerPort;
+
+ @Value("${ete.user}")
+ private String eteServerUser;
+
+ @Value("${ete.password}")
+ private String eteServerUserPassword;
+
+ @Value("${prod.server}")
+ private String prodServer;
+
+ @Value("${prod.port}")
+ private String prodServerPort;
+
+ @Value("${prod.user}")
+ private String prodServerUser;
+
+ @Value("${prod.password}")
+ private String prodServerUserPassword;
+
+ Map<String, String> envToUrlMap,envToUserNameMap,envToPasswordMap;
+
+ /**
+ * Creates a Policy Model Distribution Engine URL for the Environment requested
+ */
+ @PostConstruct
+ public void init() {
+ envToUrlMap = new HashMap<>();
+ envToUserNameMap = new HashMap();
+ envToPasswordMap = new HashMap();
+
+ envToUrlMap.put(PolicyModelDistributionEnv.DEV.name(), "https://"+ devServer + ":" + devServerPort + urlpath);
+ envToUrlMap.put(PolicyModelDistributionEnv.PST.name(), "https://"+ pstServer + ":" + pstServerPort + urlpath);
+ envToUrlMap.put(PolicyModelDistributionEnv.ETE.name(), "https://"+ eteServer + ":" + eteServerPort + urlpath);
+ envToUrlMap.put(PolicyModelDistributionEnv.PROD.name(), "https://"+ prodServer + ":" + prodServerPort + urlpath);
+
+ envToUserNameMap.put(PolicyModelDistributionEnv.DEV.name(), devServerUser);
+ envToUserNameMap.put(PolicyModelDistributionEnv.PST.name(), pstServerUser);
+ envToUserNameMap.put(PolicyModelDistributionEnv.ETE.name(), eteServerUser);
+ envToUserNameMap.put(PolicyModelDistributionEnv.PROD.name(), prodServerUser);
+
+ envToPasswordMap.put(PolicyModelDistributionEnv.DEV.name(), devServerUserPassword);
+ envToPasswordMap.put(PolicyModelDistributionEnv.PST.name(), pstServerUserPassword);
+ envToPasswordMap.put(PolicyModelDistributionEnv.ETE.name(), eteServerUserPassword);
+ envToPasswordMap.put(PolicyModelDistributionEnv.PROD.name(), prodServerUserPassword);
+ }
+
+ /**
+ * Generates a Policy Model Distribution Engine URL for the Environment
+ *
+ * @param env
+ * @return
+ */
+ public String getPolicyEngineURL(String env) {
+ if(!envToUrlMap.containsKey(env)) throw new PolicyModelDistributionEnvNotFoundException(String.format("Policy Model Environment with env %s invalid", env));
+ return envToUrlMap.get(env);
+ }
+
+
+
+ /**
+ * Generates a Policy Model Distribution Engine UserName for the Environment
+ *
+ * @param env
+ * @return
+ */
+
+ public String getUserName(String env) {
+ if(!envToUserNameMap.containsKey(env)) throw new PolicyModelDistributionEnvNotFoundException(String.format("Policy Model Environment with env %s invalid", env));
+ return envToUserNameMap.get(env);
+ }
+
+
+ /**
+ * Generates a Policy Model Distribution Engine Password for the Environment
+ *
+ * @param env
+ * @return
+ */
+
+ public String getPassword(String env) {
+ if(!envToPasswordMap.containsKey(env)) throw new PolicyModelDistributionEnvNotFoundException(String.format("Policy Model Environment with env %s invalid", env));
+ return envToPasswordMap.get(env);
+ }
+
+ /**
+ * Generates a Policy Model Distribution Engine Webclient for the Environment
+ *
+ * @param env
+ * @return
+ */
+ public WebClient getWebClient(String env) throws SSLException {
+ String userName = getUserName(env);
+ String password = getPassword(env);
+
+ SslContext sslContext = SslContextBuilder.forClient()
+ .trustManager(InsecureTrustManagerFactory.INSTANCE)
+ .build();
+ HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));
+ return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient))
+ .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/yaml")
+ .filter(ExchangeFilterFunctions.basicAuthentication(userName, password))
+ .build();
+ }
+
+
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/AppExceptionHandler.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/AppExceptionHandler.java
index 1a2f5f9..b8aeca6 100644
--- a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/AppExceptionHandler.java
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/AppExceptionHandler.java
@@ -20,6 +20,9 @@
package org.onap.dcaegen2.platform.mod.web.controller;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.google.gson.Gson;
+import lombok.extern.slf4j.Slf4j;
import org.onap.dcaegen2.platform.mod.model.exceptions.MissingRequestBodyException;
import org.onap.dcaegen2.platform.mod.model.exceptions.OperationNotAllowedException;
import org.onap.dcaegen2.platform.mod.model.exceptions.ResourceConflictException;
@@ -27,12 +30,10 @@ import org.onap.dcaegen2.platform.mod.model.exceptions.basemicroservice.BaseMicr
import org.onap.dcaegen2.platform.mod.model.exceptions.common.UserNotPassedException;
import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.DeploymentArtifactNotFound;
import org.onap.dcaegen2.platform.mod.model.exceptions.msinstance.MsInstanceNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelNotFoundException;
import org.onap.dcaegen2.platform.mod.model.exceptions.specification.SpecificationInvalid;
import org.onap.dcaegen2.platform.mod.model.restapi.ErrorResponse;
import org.onap.dcaegen2.platform.mod.model.restapi.GenericErrorResponse;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.google.gson.Gson;
-import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
@@ -54,6 +55,9 @@ import java.util.Map;
@Slf4j
public class AppExceptionHandler {
+ /**
+ * Exception Handler for Invalid Component Spec
+ */
@ExceptionHandler(value = {WebClientResponseException.class})
public ResponseEntity<ErrorResponse> handleCompSpecInvalidException
(WebClientResponseException ex, WebRequest request) {
@@ -61,6 +65,9 @@ public class AppExceptionHandler {
(new ErrorResponse(ex.getResponseBodyAsString()), HttpStatus.INTERNAL_SERVER_ERROR);
}
+ /**
+ * Exception Handler for Json Parsing
+ */
@ExceptionHandler(value = {JsonParseException.class})
public ResponseEntity<GenericErrorResponse> handleJsonParsedException
(JsonParseException ex, WebRequest request) {
@@ -72,6 +79,9 @@ public class AppExceptionHandler {
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for Invalid Specification
+ */
@ExceptionHandler
public ResponseEntity<GenericErrorResponse> specificationInvalid(SpecificationInvalid ex) {
Map<String, Object> errorResponse = new Gson().fromJson(ex.getMessage(), Map.class);
@@ -82,6 +92,9 @@ public class AppExceptionHandler {
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for Missing requested Body
+ */
@ExceptionHandler
public ResponseEntity<GenericErrorResponse> missingRequestBodyException(MissingRequestBodyException ex){
GenericErrorResponse response = new GenericErrorResponse();
@@ -91,17 +104,35 @@ public class AppExceptionHandler {
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for missing User
+ */
@ExceptionHandler
public ResponseEntity<ErrorResponse> resolveUserNotPassedException(UserNotPassedException ex){
return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for MsInstance Not Found
+ */
@ExceptionHandler
public ResponseEntity<ErrorResponse> resolveMsInstanceNotFoundException(MsInstanceNotFoundException ex) {
log.error(ex.getMessage());
return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for Policy Model Not Found
+ */
+ @ExceptionHandler
+ public ResponseEntity<ErrorResponse> resolvePolicyModelNotFoundException(PolicyModelNotFoundException ex) {
+ log.error(ex.getMessage());
+ return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.BAD_REQUEST);
+ }
+
+ /**
+ * Exception Handler for Policy Model Not Found
+ */
@ExceptionHandler
public ResponseEntity<ErrorResponse> resolveDeploymentArtifactNotFound(DeploymentArtifactNotFound ex) {
log.error(ex.getMessage());
@@ -109,6 +140,9 @@ public class AppExceptionHandler {
HttpStatus.BAD_REQUEST);
}
+ /**
+ * Exception Handler for Operation Not Allowed
+ */
@ExceptionHandler
public ResponseEntity<ErrorResponse> resolveOperationNotAllowed(OperationNotAllowedException ex) {
log.error(ex.getMessage());
@@ -116,17 +150,26 @@ public class AppExceptionHandler {
HttpStatus.CONFLICT);
}
+ /**
+ * Exception Handler for Resource Conflict
+ */
@ExceptionHandler
public ResponseEntity<ErrorResponse> resolveResourceConflict(ResourceConflictException ex) {
return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.CONFLICT);
}
+ /**
+ * Exception Handler for Resource Not Found
+ */
@ExceptionHandler(value = {BaseMicroserviceNotFoundException.class})
public ResponseEntity<ErrorResponse> resolveResourceNotFoundExcetions(RuntimeException ex) {
log.error(ex.getMessage(), ex);
return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.CONFLICT);
}
+ /**
+ * Exception Handler for Bean Validation
+ */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<GenericErrorResponse> resolveBeanValidationException(MethodArgumentNotValidException ex){
log.error(ex.getMessage());
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelController.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelController.java
new file mode 100644
index 0000000..44ad88f
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelController.java
@@ -0,0 +1,114 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.controller;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.dcaegen2.platform.mod.model.exceptions.common.UserNotPassedException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelConflictException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelDistributionEnvNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.policymodel.DistributionInfo;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.ErrorResponse;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PatchMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotBlank;
+import java.util.List;
+
+/**
+ * Controller class to manage Policy Model's REST endpoints
+ */
+@CrossOrigin
+@RestController
+@Api(tags = "Policy Model", description = "APIs to manage Policy Model Rest endpoints")
+@RequestMapping("/api/policy-model")
+@Slf4j
+public class PolicyModelController {
+
+ @Autowired
+ PolicyModelService policyModelService;
+
+ /**
+ * Controller class to manage Policy Model's GET all policy model's
+ */
+ @GetMapping
+ @ApiOperation("Get all Policy Models")
+ public List<PolicyModel> getAll() {
+ return policyModelService.getAll();
+ }
+
+ /**
+ * Controller class to manage Policy Model's GET by policy model id
+ */
+ @GetMapping("/{modelId}")
+ @ApiOperation("Get specific Policy model")
+ public PolicyModel getPolicyModelById(@PathVariable String modelId) {
+ log.info(modelId);
+ return policyModelService.getPolicyModelById(modelId);
+ }
+
+ /**
+ * Controller class to manage Policy Model's POST
+ */
+ @PostMapping
+ @ApiOperation("Create a Policy Model")
+ @ResponseStatus(HttpStatus.CREATED)
+ public PolicyModel createPolicyModel(@RequestBody @Valid PolicyModelCreateRequest request, @RequestParam @NotBlank String user) {
+ return policyModelService.createPolicyModel(request,user);
+ }
+
+ /**
+ * Controller class to manage Policy Model's PATCH by policy model id
+ */
+ @PatchMapping("/{modelId}")
+ @ApiOperation("Patch a Policy Model")
+ @ResponseStatus(HttpStatus.OK)
+ public PolicyModel patchPolicyModel(@RequestBody @Valid PolicyModelUpdateRequest request, @PathVariable String modelId, @RequestParam @NotBlank String user) {
+ return policyModelService.updatePolicyModel(request, modelId,user);
+ }
+
+ /**
+ * Controller class to manage Policy Model's conflict exception
+ */
+ @ExceptionHandler
+ public ResponseEntity<ErrorResponse> resolvePolicyModelConflict(PolicyModelConflictException ex) {
+ return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.CONFLICT);
+ }
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelDistributionController.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelDistributionController.java
new file mode 100644
index 0000000..3a3571c
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/controller/PolicyModelDistributionController.java
@@ -0,0 +1,82 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.controller;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelDistributionEnvNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.restapi.ErrorResponse;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelDistributionService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Controller class to manage Policy Model's REST endpoints
+ */
+@CrossOrigin
+@RestController
+@Api(tags = "Policy Model Distribution", description = "APIs to manage Policy Model Distribution Rest endpoints")
+@RequestMapping("/api/policy-type")
+@Slf4j
+public class PolicyModelDistributionController {
+
+ @Autowired
+ PolicyModelDistributionService policyModelDistributionService;
+
+ /**
+ * Controller class to manage Policy Model Distribution's GET by policy model id
+ */
+ @GetMapping("/{modelId}")
+ @ApiOperation("Get the status of specific Policy model Distribution")
+ public ResponseEntity getPolicyModelDistributionById(@RequestParam("env") String env,@PathVariable String modelId) {
+ log.info(modelId);
+ return policyModelDistributionService.getPolicyModelDistributionById(env,modelId);
+ }
+
+ /**
+ * Controller class to manage Policy Model Distribution's POST by policy model id
+ */
+ @PostMapping("/{modelId}")
+ @ApiOperation("Distribute a specific Policy Model")
+ public ResponseEntity distributePolicyModelById(@RequestParam("env") String env, @PathVariable String modelId) {
+ return policyModelDistributionService.distributePolicyModel(env,modelId);
+ }
+
+ /**
+ * Controller class to manage Policy Model Distribution Environment Not Found exception
+ */
+ @ExceptionHandler
+ public ResponseEntity<ErrorResponse> resolvePolicyModelDistributionEnvNotFound(PolicyModelDistributionEnvNotFoundException ex){
+ return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), HttpStatus.BAD_REQUEST);
+ }
+
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionService.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionService.java
new file mode 100644
index 0000000..8847a63
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionService.java
@@ -0,0 +1,43 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service.policymodel;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.DistributionInfo;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelDistributionRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.springframework.http.ResponseEntity;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * An interface to access Policy Model Services
+ */
+
+public interface PolicyModelDistributionService {
+
+ ResponseEntity getPolicyModelDistributionById(String env, String modelId);
+
+ ResponseEntity distributePolicyModel(String env, String modelId);
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionServiceImpl.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionServiceImpl.java
new file mode 100644
index 0000000..d0646d2
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelDistributionServiceImpl.java
@@ -0,0 +1,183 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service.policymodel;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelDistributionEnvNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.policymodel.DistributionInfo;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModelDistributionEnv;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModelStatus;
+import org.onap.dcaegen2.platform.mod.util.PolicyModelUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.reactive.ReactorClientHttpConnector;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.Base64Utils;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.reactive.function.client.ClientResponse;
+import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
+import org.springframework.web.reactive.function.client.WebClient;
+import reactor.core.publisher.Mono;
+import reactor.netty.http.client.HttpClient;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Policy Model Service implementation
+ */
+
+@Service
+@Setter
+@Slf4j
+public class PolicyModelDistributionServiceImpl implements PolicyModelDistributionService {
+
+ @Autowired
+ PolicyModelServiceImpl policyModelServiceImpl;
+
+ @Autowired
+ PolicyModelGateway policyModelGateway;
+
+ @Autowired
+ PolicyModelUtils policyModelUtils;
+
+ /**
+ * Gets the Policy Model Distribution by Policy Model ID
+ * @param env
+ * @param modelId
+ * @return
+ */
+ @Override
+ public ResponseEntity getPolicyModelDistributionById(String env,String modelId) {
+
+ String responseBody = null;
+ HttpStatus httpStatus;
+ String url = policyModelUtils.getPolicyEngineURL(env);
+ PolicyModel policyModel = policyModelServiceImpl.getPolicyModelById(modelId);
+
+ try{
+ WebClient webClient = policyModelUtils.getWebClient(env);
+ WebClient.RequestHeadersSpec<?> requestHeadersSpec = webClient.method(HttpMethod.GET).uri(url + "/" + policyModel.getName());
+ httpStatus = requestHeadersSpec.exchange().map(response -> response.statusCode()).block();
+ if (httpStatus.is2xxSuccessful()) {
+ responseBody = requestHeadersSpec.retrieve().bodyToMono(String.class).block();
+ } else if(httpStatus.is4xxClientError()){
+ if(httpStatus.value() == 401) {
+ responseBody = "Authentication Error";
+ } else if(httpStatus.value() == 403) {
+ responseBody = "Authorization Error";
+ } else if(httpStatus.value() == 404) {
+ responseBody = "Resource Not Found";
+ }
+ } else if(httpStatus.is5xxServerError()){
+ responseBody = "Internal Server Error";
+ }
+ else {
+ responseBody = "Problem in getting the Policy Model.";
+ }
+ }catch(Exception ex){
+ log.error("Problem in getting the Policy Model.");
+ log.error("error: ", ex);
+ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
+ responseBody = "Problem in getting the Policy Model.";
+
+ }
+
+ return ResponseEntity.status(httpStatus).body(responseBody);
+
+ }
+
+ /**
+ * Distributes a Policy Model
+ * @param env
+ * @param modelId
+ * @return
+ */
+ @Override
+ @Transactional
+ public ResponseEntity distributePolicyModel(String env, String modelId) {
+
+ String responseBody = null;
+ HttpStatus httpStatus;
+ String url = policyModelUtils.getPolicyEngineURL(env);
+ PolicyModel policyModel = policyModelServiceImpl.getPolicyModelById(modelId);
+ String content = policyModel.getContent();
+ DistributionInfo distributionInfo = DistributionInfo.builder().url(env).build();
+
+ try{
+ WebClient webClient = policyModelUtils.getWebClient(env);
+ WebClient.RequestHeadersSpec<?> requestHeadersSpec = webClient.method(HttpMethod.POST).uri(url).bodyValue(content.getBytes());
+ httpStatus = requestHeadersSpec.exchange().map(response -> response.statusCode()).block();
+ if (httpStatus.is2xxSuccessful()) {
+ distributionInfo.setStatus(PolicyModelStatus.SUCCESS);
+ responseBody = requestHeadersSpec.retrieve().bodyToMono(String.class).block();
+ } else if(httpStatus.is4xxClientError()){
+ distributionInfo.setStatus(PolicyModelStatus.FAILED);
+ if(httpStatus.value() == 400) {
+ responseBody = "Invalid Body";
+ } else if(httpStatus.value() == 401) {
+ responseBody = "Authentication Error";
+ } else if(httpStatus.value() == 403) {
+ responseBody = "Authorization Error";
+ } else if(httpStatus.value() == 406) {
+ responseBody = "Not Acceptable Version";
+ } else if(httpStatus.value() == 415) {
+ responseBody = "UnSupported Media Type";
+ }
+ } else if(httpStatus.is5xxServerError()){
+ responseBody = "Internal Server Error";
+ distributionInfo.setStatus(PolicyModelStatus.FAILED);
+ }
+ else {
+ distributionInfo.setStatus(PolicyModelStatus.FAILED);
+ responseBody = "Problem in Distributing the Policy Model.";
+ }
+ }catch(Exception ex){
+ log.error("Problem in Distributing the Policy Model.");
+ log.error("error: ", ex);
+ distributionInfo.setStatus(PolicyModelStatus.FAILED);
+ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
+ responseBody = "Problem in Distributing the Policy Model.";
+
+ }
+ List<DistributionInfo> distributionInfos = new ArrayList<>();
+ distributionInfos.add(distributionInfo);
+ policyModel.setDistributionInfo(distributionInfos);
+
+ policyModelGateway.save(policyModel);
+ return ResponseEntity.status(httpStatus).body(responseBody);
+
+ }
+
+
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelGateway.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelGateway.java
new file mode 100644
index 0000000..bda3998
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelGateway.java
@@ -0,0 +1,42 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service.policymodel;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * An interface to interact with Policy Model persistence
+ */
+public interface PolicyModelGateway {
+
+ List<PolicyModel> findAll();
+
+ Optional<PolicyModel> findById(String id);
+
+ PolicyModel save(PolicyModel newPolicyModel) ;
+
+ Optional<PolicyModel> findByNameAndVersion(String name,String version);
+
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelService.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelService.java
new file mode 100644
index 0000000..61abf60
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelService.java
@@ -0,0 +1,44 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service.policymodel;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.DistributionInfo;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+
+import java.util.List;
+
+/**
+ * An interface to access Policy Model Services
+ */
+
+public interface PolicyModelService {
+
+ List<PolicyModel> getAll();
+
+ PolicyModel getPolicyModelById(String modelId);
+
+ PolicyModel createPolicyModel(PolicyModelCreateRequest request, String user);
+
+ PolicyModel updatePolicyModel(PolicyModelUpdateRequest request, String modelId, String user);
+
+}
diff --git a/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelServiceImpl.java b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelServiceImpl.java
new file mode 100644
index 0000000..58fc447
--- /dev/null
+++ b/mod2/catalog-service/src/main/java/org/onap/dcaegen2/platform/mod/web/service/policymodel/PolicyModelServiceImpl.java
@@ -0,0 +1,203 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service.policymodel;
+
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelConflictException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelDistributionEnvNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.policymodel.DistributionInfo;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModelDistributionEnv;
+import org.onap.dcaegen2.platform.mod.model.restapi.MetadataRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Policy Model Service implementation
+ */
+
+@Service
+@Setter
+@Slf4j
+public class PolicyModelServiceImpl implements PolicyModelService {
+
+ @Value("${dev.server}")
+ private String devServer;
+
+ @Value("${dev.port}")
+ private String devServerPort;
+
+ @Value("${dev.user}")
+ private String devServerUser;
+
+ @Value("${dev.password}")
+ private String devServerPassword;
+
+ @Autowired
+ private PolicyModelGateway policyModelGateway;
+
+ /**
+ * Lists all Policy Models
+ *
+ * @return
+ */
+ @Override
+ public List<PolicyModel> getAll() {
+ return policyModelGateway.findAll();
+ }
+
+ /**
+ * List a Policy Model by policyModel ID
+ *
+ * @param id
+ * @return
+ */
+ @Override
+ public PolicyModel getPolicyModelById(String id) {
+ return policyModelGateway.findById(id).orElseThrow(() -> new PolicyModelNotFoundException(String.format("Policy Model with id %s not found", id)));
+ }
+
+ /**
+ * creates a Policy Model
+ *
+ * @param request
+ * @return
+ */
+ @Override
+ @Transactional
+ public PolicyModel createPolicyModel(PolicyModelCreateRequest request, String user) {
+ checkIfPMNameAndVersionAlreadyExists(request.getName(), request.getVersion());
+ PolicyModel policyModel = new PolicyModel();
+ policyModel.setName(request.getName());
+ policyModel.setContent(request.getContent());
+ policyModel.setVersion(request.getVersion());
+ policyModel.setOwner(request.getOwner());
+ policyModel.setMetadata(getMetadataFields(request.getMetadata(), user));
+ return policyModelGateway.save(policyModel);
+ }
+
+ /**
+ * Update a Policy Model
+ *
+ * @param request
+ * @param modelId
+ * @return
+ */
+ @Override
+ public PolicyModel updatePolicyModel(PolicyModelUpdateRequest request, String modelId, String user) {
+ PolicyModel policyModel = getPolicyModelById(modelId);
+ updateFields(request, policyModel,user);
+ return policyModelGateway.save(policyModel);
+
+ }
+
+
+ /**
+ * Cerifies if a Policy Model Exist
+ *
+ * @param pmName
+ * @param pmVersion
+ * @return
+ */
+ private void checkIfPMNameAndVersionAlreadyExists(String pmName, String pmVersion) {
+ if (policyModelGateway.findByNameAndVersion(pmName, pmVersion).isPresent())
+ throw new PolicyModelConflictException(ErrorMessages.POLICYMODEL_NAME_VERSION_CONFLICT_MESSAGE);
+ }
+
+ /**
+ * creates a Policy Model Metadata
+ *
+ * @param metadata
+ * @param user
+ * @return
+ */
+ private MetadataRequest getMetadataFields(MetadataRequest metadata, String user) {
+ MetadataRequest metadataFields = MetadataRequest.builder().build();
+ metadataFields.setCreatedBy(user);
+ metadataFields.setCreatedOn(new Date());
+ if(metadata != null) {
+ if (metadata.getNotes() != null)
+ metadataFields.setNotes(metadata.getNotes());
+ if (metadata.getLabels() != null)
+ metadataFields.setLabels(metadata.getLabels());
+ }
+ return metadataFields;
+ }
+
+
+ /**
+ * Updates a Policy Model
+ *
+ * @param request
+ * @param policyModel
+ * @param user
+ * @return
+ */
+ private void updateFields(PolicyModelUpdateRequest request, PolicyModel policyModel, String user) {
+ String name = request.getName();
+ String version = request.getVersion();
+ if (!(name.equalsIgnoreCase(policyModel.getName()) && version.equalsIgnoreCase(policyModel.getVersion()))) {
+ checkIfPMNameAndVersionAlreadyExists(name, version);
+ policyModel.setName(name);
+ policyModel.setVersion(version);
+ }
+ if (request.getOwner() != null) {
+ policyModel.setOwner(request.getOwner());
+ }
+
+ if (request.getContent() != null) {
+ policyModel.setContent(request.getContent());
+ }
+ if (request.getMetadata() != null) {
+ updateMetadata(request,user);
+ policyModel.setMetadata(request.getMetadata());
+ }
+ }
+
+
+ /**
+ * Updates a Policy Model Metadata
+ *
+ * @param request
+ * @param user
+ * @return
+ */
+ private void updateMetadata(PolicyModelUpdateRequest request, String user) {
+ MetadataRequest metadataRequest = request.getMetadata();
+ metadataRequest.setUpdatedBy(user);
+ metadataRequest.setUpdatedOn(new Date());
+ }
+
+
+}
diff --git a/mod2/catalog-service/src/main/resources/application.properties b/mod2/catalog-service/src/main/resources/application.properties
index 1f20c6a..f818c6c 100644
--- a/mod2/catalog-service/src/main/resources/application.properties
+++ b/mod2/catalog-service/src/main/resources/application.properties
@@ -21,4 +21,30 @@
#add connection to mongo db once its up and running
spring.data.mongodb.host=mongo_db
spring.data.mongodb.port=27017
-spring.data.mongodb.database=dcae_mod \ No newline at end of file
+spring.data.mongodb.database=dcae_mod
+
+
+
+#Distribution Info Environment details
+
+url.path=/policy/api/v1/policytypes
+
+dev.server=10.12.6.2
+dev.port=31317
+dev.user=healthcheck
+dev.password=PASSWORD_GOES_HERE
+
+pst.server=policy-api
+pst.port=6969
+pst.user=healthcheck
+pst.password=PASSWORD_GOES_HERE
+
+ete.server=policy-api
+ete.port=6969
+ete.user=healthcheck
+ete.password=PASSWORD_GOES_HERE
+
+prod.server=policy-api
+prod.port=6969
+prod.user=healthcheck
+prod.password=PASSWORD_GOES_HERE \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelDistributionObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelDistributionObjectMother.java
new file mode 100644
index 0000000..dfd1bd7
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelDistributionObjectMother.java
@@ -0,0 +1,35 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.objectmothers;
+
+import org.onap.dcaegen2.platform.mod.util.TestUtil;
+import org.springframework.http.ResponseEntity;
+
+import static org.mockito.ArgumentMatchers.anyString;
+
+public class PolicyModelDistributionObjectMother {
+ public static final String PM_DISTRIBUTION_ENV = "DEV";
+ public static final String PM_DISTRIBUTION_ENV_ERROR = "DEV1";
+ public static final String PM_DISTRIBUTION_MODEL_ID = "5fbfc375f9f1d44e8b0e0ec2";
+ public static final String PM_DISTRIBUTION_MODEL_NAME = "onap-policies-naming";
+ public static final String PM_DISTRIBUTION_MODEL_ID_ERROR = "5fb896389387ea1087bdb1aa";
+
+}
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelObjectMother.java
new file mode 100644
index 0000000..a868e82
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/PolicyModelObjectMother.java
@@ -0,0 +1,57 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.objectmothers;
+
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.onap.dcaegen2.platform.mod.util.TestUtil;
+
+/**
+ * Object Mother for Policy Model to generate request for Create, Update and Get Policy Model Response
+ */
+public class PolicyModelObjectMother {
+ public static final String PM_CREATE_REQUEST = "src/test/resources/http/requests/policy-model_create_request.json";
+ public static final String PM_UPDATE_REQUEST = "src/test/resources/http/requests/policy-model_update_request.json";
+ public static final String PM_RESPONSE = "src/test/resources/http/responses/policy-model_create_response.json";
+ public static final String POLICY_MODEL_ID = "5fb896389387ea1087bdb1aa"; //"5fae8956cd1bac74e55c9d3a";
+
+ /**
+ * Object Mother for Policy Model to generate request for Create
+ */
+ public static PolicyModelCreateRequest getPolicyModelCreateRequest() {
+ return TestUtil.deserializeJsonFileToModel(PM_CREATE_REQUEST, PolicyModelCreateRequest.class);
+ }
+
+ /**
+ * Object Mother for Policy Model to generate request for Get Policy Model Response
+ */
+ public static PolicyModel getPolicyModelResponse() {
+ return TestUtil.deserializeJsonFileToModel(PM_RESPONSE, PolicyModel.class);
+ }
+
+ /**
+ * Object Mother for Policy Model to generate request for Update
+ */
+ public static PolicyModelUpdateRequest getPolicyModelUpdateRequest() {
+ return TestUtil.deserializeJsonFileToModel(PM_UPDATE_REQUEST, PolicyModelUpdateRequest.class);
+ }
+}
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelControllerTest.java
new file mode 100644
index 0000000..e69ba22
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelControllerTest.java
@@ -0,0 +1,110 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web;
+
+import org.hamcrest.Matchers;
+import org.junit.Ignore;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.onap.dcaegen2.platform.mod.web.controller.PolicyModelController;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.test.web.servlet.MockMvc;
+
+import java.util.Arrays;
+
+import static org.hamcrest.Matchers.notNullValue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.USER;
+import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.asJsonString;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.POLICY_MODEL_ID;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelCreateRequest;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelResponse;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelUpdateRequest;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@ExtendWith(SpringExtension.class)
+@WebMvcTest(PolicyModelController.class)
+public class PolicyModelControllerTest {
+
+ @Autowired
+ MockMvc mockMvc;
+
+ @MockBean
+ private PolicyModelService mockPolicyModelService;
+
+ @BeforeEach
+ void setup() {
+ }
+
+ @Test
+ void test_getAllPolicyModels() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(mockPolicyModelService.getAll()).thenReturn(Arrays.asList(policyModel));
+
+ mockMvc.perform(get("/api/policy-model")
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$", Matchers.hasSize(1)));
+ }
+
+ @Test
+ void test_getPolicyModelById() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(mockPolicyModelService.getPolicyModelById(POLICY_MODEL_ID)).thenReturn(policyModel);
+
+ mockMvc.perform(get("/api/policy-model/" + POLICY_MODEL_ID)
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.id", notNullValue()));
+ }
+
+ @Test
+ void test_patchPolicyModel_shouldReturn204AndResponseBody() throws Exception{
+ PolicyModelUpdateRequest policyModelpdateRequest = getPolicyModelUpdateRequest();
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(mockPolicyModelService.updatePolicyModel(policyModelpdateRequest,POLICY_MODEL_ID, USER)).thenReturn(policyModel);
+
+ mockMvc.perform(patch("/api/policy-model/" + POLICY_MODEL_ID).param("user", USER)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(asJsonString(policyModelpdateRequest)).accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isBadRequest());
+ verify(mockPolicyModelService, times(0)).updatePolicyModel(policyModelpdateRequest,POLICY_MODEL_ID, USER);
+ }
+
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelCreateRequestValidationTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelCreateRequestValidationTest.java
new file mode 100644
index 0000000..4b34e02
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelCreateRequestValidationTest.java
@@ -0,0 +1,95 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import java.util.Set;
+
+public class PolicyModelCreateRequestValidationTest {
+
+ public Validator validator;
+ private PolicyModelCreateRequest request;
+
+ @BeforeEach
+ public void setup(){
+ validator = Validation.buildDefaultValidatorFactory().getValidator();
+ request = PolicyModelObjectMother.getPolicyModelCreateRequest();
+ }
+
+ @Test
+ void test_pmNameShouldNotBeBlank(){
+ request.setName("");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(3);
+ }
+
+ @Test
+ void test_pmNameShouldFollowRegex() throws Exception{
+ request.setName("pm-1");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+ @Test
+ void test_pmNameSizeValidation() throws Exception {
+ request.setName("core-name-should-not-exceed-fifty-chars-core-name-should-not-exceed-fifty-chars");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+
+ @Test
+ void test_pmVersionShouldNotBeNull(){
+ request.setVersion("");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(3);
+
+ }
+
+ @Test
+ void test_pmVersionShouldFollowRegex() throws Exception{
+ request.setContent("1.1.1");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+ @Test
+ void test_pmContentShouldNotBeBlank(){
+ request.setContent("");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(2);
+ }
+
+ @Test
+ void test_pmOwnerShouldNotBeBlank(){
+ request.setOwner("");
+ Set<ConstraintViolation<PolicyModelCreateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(2);
+ }
+}
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelDistributionControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelDistributionControllerTest.java
new file mode 100644
index 0000000..216d4c8
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelDistributionControllerTest.java
@@ -0,0 +1,120 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.web.controller.PolicyModelDistributionController;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelDistributionService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.test.web.servlet.MockMvc;
+
+import static org.hamcrest.Matchers.notNullValue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.USER;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_ENV;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_MODEL_ID;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_MODEL_NAME;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelResponse;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@ExtendWith(SpringExtension.class)
+@WebMvcTest(PolicyModelDistributionController.class)
+public class PolicyModelDistributionControllerTest {
+
+ @Autowired
+ MockMvc mockMvc;
+
+ @MockBean
+ private PolicyModelDistributionService mockPolicyModelDistributionService;
+
+ @BeforeEach
+ void setup() {
+ }
+
+ @Test
+ void test_getPolicyModelById() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+ ResponseEntity mockResponseEntity = ResponseEntity.status(200).body(policyModel.getContent());
+
+ when(mockPolicyModelDistributionService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID)).thenReturn(mockResponseEntity);
+
+ mockMvc.perform(get("/api/policy-type/" + PM_DISTRIBUTION_MODEL_ID)
+ .param("env",PM_DISTRIBUTION_ENV).contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk());
+
+ verify(mockPolicyModelDistributionService, times(1)).getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+ }
+
+ @Test
+ void test_getPolicyModelById_BadRequest() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+ ResponseEntity mockResponseEntity = ResponseEntity.status(400).body(policyModel.getContent());
+
+ when(mockPolicyModelDistributionService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID)).thenReturn(mockResponseEntity);
+
+ mockMvc.perform(get("/api/policy-type/" + PM_DISTRIBUTION_MODEL_ID)
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().is4xxClientError());
+
+ verify(mockPolicyModelDistributionService, times(0)).getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+ }
+
+ @Test
+ void test_distributePolicyModelById_shouldReturn201AndResponseBody() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+ ResponseEntity mockResponseEntity = ResponseEntity.status(200).body(policyModel.getContent());
+
+ when(mockPolicyModelDistributionService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID)).thenReturn(mockResponseEntity);
+
+ mockMvc.perform(post("/api/policy-type/" + PM_DISTRIBUTION_MODEL_ID)
+ .param("env",PM_DISTRIBUTION_ENV).contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk());
+ verify(mockPolicyModelDistributionService, times(1)).distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+ }
+
+ @Test
+ void test_distributePolicyModelById_BadRequest() throws Exception {
+ PolicyModel policyModel = getPolicyModelResponse();
+ ResponseEntity mockResponseEntity = ResponseEntity.status(400).body(policyModel.getContent());
+
+ when(mockPolicyModelDistributionService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID)).thenReturn(mockResponseEntity);
+
+ mockMvc.perform(post("/api/policy-type/" + PM_DISTRIBUTION_MODEL_ID)
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().is4xxClientError());
+ verify(mockPolicyModelDistributionService, times(0)).distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+ }
+
+
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelUpdateRequestValidationTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelUpdateRequestValidationTest.java
new file mode 100644
index 0000000..f1945fd
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/PolicyModelUpdateRequestValidationTest.java
@@ -0,0 +1,83 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import java.util.Set;
+
+public class PolicyModelUpdateRequestValidationTest {
+
+ public Validator validator;
+ private PolicyModelUpdateRequest request;
+
+ @BeforeEach
+ public void setup(){
+ validator = Validation.buildDefaultValidatorFactory().getValidator();
+ request = PolicyModelObjectMother.getPolicyModelUpdateRequest();
+ }
+
+ @Test
+ void test_pmNameShouldNotBeBlank(){
+ request.setName("");
+ Set<ConstraintViolation<PolicyModelUpdateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(2);
+ }
+
+ @Test
+ void test_pmNameShouldFollowRegex() throws Exception{
+ request.setName("pm-1");
+ Set<ConstraintViolation<PolicyModelUpdateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+ @Test
+ void test_pmNameSizeValidation() throws Exception {
+ request.setName("core-name-should-not-exceed-fifty-chars-core-name-should-not-exceed-fifty-chars");
+ Set<ConstraintViolation<PolicyModelUpdateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+
+ @Test
+ void test_pmVersionShouldNotBeNull(){
+ request.setVersion("1.1.1");
+ Set<ConstraintViolation<PolicyModelUpdateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+
+ }
+
+ @Test
+ void test_pmVersionShouldFollowRegex() throws Exception{
+ request.setContent("1.1.1");
+ Set<ConstraintViolation<PolicyModelUpdateRequest>> violations = validator.validate(request);
+ Assertions.assertThat(violations.size()).isEqualTo(1);
+ }
+
+}
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelDistributionServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelDistributionServiceImplTest.java
new file mode 100644
index 0000000..a1451c4
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelDistributionServiceImplTest.java
@@ -0,0 +1,329 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service;
+
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.util.PolicyModelUtils;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelDistributionServiceImpl;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelGateway;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelServiceImpl;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.reactive.function.client.WebClient;
+
+import java.io.IOException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_ENV;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_MODEL_ID;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelDistributionObjectMother.PM_DISTRIBUTION_MODEL_ID_ERROR;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelResponse;
+
+@ExtendWith(MockitoExtension.class)
+class PolicyModelDistributionServiceImplTest {
+
+ @Spy
+ private PolicyModelDistributionServiceImpl pmDistributionImplService = new PolicyModelDistributionServiceImpl();
+
+ @Mock
+ private PolicyModelServiceImpl policyModelServiceImpl;
+
+ @Mock
+ private PolicyModelGateway policyModelGateway;
+
+ @Mock
+ private PolicyModelUtils policyModelUtils;
+
+ @BeforeEach
+ void initialize(){
+ pmDistributionImplService.setPolicyModelServiceImpl(policyModelServiceImpl);
+ pmDistributionImplService.setPolicyModelGateway(policyModelGateway);
+ pmDistributionImplService.setPolicyModelUtils(policyModelUtils);
+ }
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnSucess() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ // Calling the same method twice to resolve the issue of mock server hanging for response
+ initResponse(mockBackEnd,200,"Operation Successfull");
+ initResponse(mockBackEnd,200,"Operation Successfull");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.OK);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ mockBackEnd.shutdown();
+ }
+
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnUnauthorized() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,401,"Authentication Error");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnForbidden() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR)).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,403,"Authorization Error");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID_ERROR);
+
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR);
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnNotFound() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR)).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,404,"Policy Model Not Found");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID_ERROR);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR);
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnUnsupportedMediaType() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,415,"Unsupported Media Type");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_getPolicyModelDistributionByIdReturnInternalServerError() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById("test")).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,500,"Internal Server Error");
+
+ ResponseEntity expected = pmDistributionImplService.getPolicyModelDistributionById(PM_DISTRIBUTION_ENV,"test");
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById("test");
+ mockBackEnd.shutdown();
+ }
+
+
+ @Test
+ void test_distributePolicyModelReturnSucess() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ // Calling the same method twice to resolve the issue of mock server hanging for response
+ initResponse(mockBackEnd,200,"Operation Successfull");
+ initResponse(mockBackEnd,200,"Operation Successfull");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.OK);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ verify(policyModelGateway, times(1)).save(any());
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_distributePolicyModelReturnBadRequest() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,400,"Invalid Body of Policy Model");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID_ERROR);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID_ERROR);
+ verify(policyModelGateway, times(1)).save(any());
+ mockBackEnd.shutdown();
+ }
+
+ @Test
+ void test_distributePolicyModelReturnUnauthorized() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,401,"Authentication Error");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ @Test
+ void test_distributePolicyModelReturnForbidden() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,403,"Authorization Error");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ @Test
+ void test_distributePolicyModelReturnNotAcceptable() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,406,"Not Acceptable Policy Model Version");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ @Test
+ void test_distributePolicyModelReturnUnsupportedMediaType() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById(PM_DISTRIBUTION_MODEL_ID)).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,415,"Unsupported Media Type");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,PM_DISTRIBUTION_MODEL_ID);
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById(PM_DISTRIBUTION_MODEL_ID);
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ @Test
+ void test_distributePolicyModelReturnInternalServerError() throws IOException {
+ PolicyModel policyModel = getPolicyModelResponse();
+
+ when(policyModelServiceImpl.getPolicyModelById("test")).thenReturn(policyModel);
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ MockWebServer mockBackEnd = initialize_webServer();
+
+ initResponse(mockBackEnd,500,"Internal Server Error");
+
+ ResponseEntity expected = pmDistributionImplService.distributePolicyModel(PM_DISTRIBUTION_ENV,"test");
+
+ assertThat(expected.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
+ verify(policyModelServiceImpl, times(1)).getPolicyModelById("test");
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ private MockWebServer initialize_webServer() throws IOException {
+ MockWebServer mockBackEnd = new MockWebServer();
+ mockBackEnd.start();
+
+ String baseUrl = String.format("http://localhost:%s", mockBackEnd.getPort());
+ when(policyModelUtils.getPolicyEngineURL(PM_DISTRIBUTION_ENV)).thenReturn(baseUrl);
+ when(policyModelUtils.getWebClient(PM_DISTRIBUTION_ENV)).thenReturn(WebClient.create(baseUrl));
+
+ return mockBackEnd;
+ }
+
+ private void initResponse(MockWebServer mockBackEnd, int responseCode, String responseBody) {
+ String webClientResponse = responseBody;
+ mockBackEnd.enqueue(new MockResponse().setResponseCode(responseCode).setBody(webClientResponse)
+ .addHeader("Content-Type", "text/plain;charset=ISO-8859-1"));
+ }
+
+
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelServiceImplTest.java
new file mode 100644
index 0000000..726ed3b
--- /dev/null
+++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/PolicyModelServiceImplTest.java
@@ -0,0 +1,152 @@
+/*
+ * ============LICENSE_START=======================================================
+ * org.onap.dcae
+ * ================================================================================
+ * Copyright (c) 2020 AT&T 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.dcaegen2.platform.mod.web.service;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelConflictException;
+import org.onap.dcaegen2.platform.mod.model.exceptions.policymodel.PolicyModelNotFoundException;
+import org.onap.dcaegen2.platform.mod.model.policymodel.PolicyModel;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelCreateRequest;
+import org.onap.dcaegen2.platform.mod.model.restapi.PolicyModelUpdateRequest;
+import org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelGateway;
+import org.onap.dcaegen2.platform.mod.web.service.policymodel.PolicyModelServiceImpl;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.USER;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.POLICY_MODEL_ID;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelCreateRequest;
+import static org.onap.dcaegen2.platform.mod.objectmothers.PolicyModelObjectMother.getPolicyModelUpdateRequest;
+
+@ExtendWith(MockitoExtension.class)
+class PolicyModelServiceImplTest {
+
+ @Spy
+ private PolicyModelServiceImpl pmImplService = new PolicyModelServiceImpl();
+
+ @Mock
+ private PolicyModelGateway policyModelGateway;
+
+
+ @BeforeEach
+ void setUp() {
+ pmImplService.setPolicyModelGateway(policyModelGateway);
+ }
+
+ @Test
+ void getAll() {
+ PolicyModel instance_1 = PolicyModel.builder().id("123").name("test").owner("user").version("1.0.0").build();
+ PolicyModel instance_2 = PolicyModel.builder().id("345").name("test1").owner("user1").version("1.1.0").build();
+
+ when(policyModelGateway.findAll()).thenReturn(Arrays.asList(instance_1, instance_2));
+
+ List<PolicyModel> instances = pmImplService.getAll();
+
+ assertThat(instances.size()).isEqualTo(2);
+ verify(policyModelGateway, times(1)).findAll();
+ }
+
+ @Test
+ void test_getPolicyModelById() {
+ PolicyModel expected = PolicyModelObjectMother.getPolicyModelResponse();
+
+ when(policyModelGateway.findById(POLICY_MODEL_ID)).thenReturn(Optional.of(expected));
+
+ PolicyModel original = pmImplService.getPolicyModelById(POLICY_MODEL_ID);
+
+ assertThat(original.getId()).isEqualTo(expected.getId());
+ verify(policyModelGateway, times(1)).findById(POLICY_MODEL_ID);
+ }
+
+ @Test
+ void test_policyModelNotFound_willRaiseException() {
+ when(policyModelGateway.findById(POLICY_MODEL_ID)).thenReturn(Optional.empty());
+ assertThatExceptionOfType(PolicyModelNotFoundException.class).isThrownBy(() -> pmImplService.getPolicyModelById(POLICY_MODEL_ID));
+ }
+
+
+ @Test
+ void test_createPolicyModel() {
+
+ PolicyModelCreateRequest policyModelCreateRequest = getPolicyModelCreateRequest();
+ PolicyModel policyModel = PolicyModelObjectMother.getPolicyModelResponse();
+
+ when(policyModelGateway.findByNameAndVersion(policyModelCreateRequest.getName(), policyModelCreateRequest.getVersion())).thenReturn(Optional.empty());
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ pmImplService.createPolicyModel(policyModelCreateRequest,USER);
+
+ assertThat(policyModel.getVersion()).isEqualTo(policyModelCreateRequest.getVersion());
+ assertThat(policyModel.getName()).isEqualTo(policyModelCreateRequest.getName());
+
+ verify(policyModelGateway, times(1)).findByNameAndVersion(policyModelCreateRequest.getName(), policyModelCreateRequest.getVersion());
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+ @Test
+ void test_createPolicyModel_willRaiseException() {
+ PolicyModelCreateRequest policyModelCreateRequest = getPolicyModelCreateRequest();
+ PolicyModel policyModel = PolicyModelObjectMother.getPolicyModelResponse();
+
+ when(policyModelGateway.findByNameAndVersion(policyModelCreateRequest.getName(), policyModelCreateRequest.getVersion())).thenReturn(Optional.of(policyModel));
+
+ assertThatExceptionOfType(PolicyModelConflictException.class).isThrownBy(() -> pmImplService.createPolicyModel(policyModelCreateRequest,USER));
+ }
+
+ @Test
+ void test_updatePolicyModel() {
+
+ PolicyModelUpdateRequest policyModelUpdateRequest = getPolicyModelUpdateRequest();
+ policyModelUpdateRequest.setName("test1");
+ policyModelUpdateRequest.setVersion("1.2.1");
+ PolicyModel policyModel = PolicyModelObjectMother.getPolicyModelResponse();
+
+ when(policyModelGateway.findById(POLICY_MODEL_ID)).thenReturn(Optional.of(policyModel));
+
+ when(policyModelGateway.findByNameAndVersion(policyModelUpdateRequest.getName(), policyModelUpdateRequest.getVersion())).thenReturn(Optional.empty());
+ when(policyModelGateway.save(any())).thenReturn(policyModel);
+
+ pmImplService.updatePolicyModel(policyModelUpdateRequest,POLICY_MODEL_ID, USER);
+
+ assertThat(policyModel.getVersion()).isEqualTo(policyModelUpdateRequest.getVersion());
+ assertThat(policyModel.getName()).isEqualTo(policyModelUpdateRequest.getName());
+
+ verify(policyModelGateway, times(1)).findById(POLICY_MODEL_ID);
+ verify(policyModelGateway, times(1)).findByNameAndVersion(policyModelUpdateRequest.getName(), policyModelUpdateRequest.getVersion());
+ verify(policyModelGateway, times(1)).save(any());
+ }
+
+
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/resources/http/requests/pmdist_sample.json b/mod2/catalog-service/src/test/resources/http/requests/pmdist_sample.json
new file mode 100644
index 0000000..16ab65a
--- /dev/null
+++ b/mod2/catalog-service/src/test/resources/http/requests/pmdist_sample.json
@@ -0,0 +1,142 @@
+{
+ "self": {
+ "component_type": "docker",
+ "description": "Hello World mS for subscribing the data from local DMaaP, DR or MR, processing them and publishing them as PM files to local DMaaP DR",
+ "name": "dcae-collectors-vcc-helloworld-pm",
+ "version": "1.0.1"
+ },
+ "services": {
+ "calls": [],
+ "provides": []
+ },
+ "streams": {
+ "publishes": [
+ {
+ "config_key": "DCAE-HELLO-WORLD-PUB-DR",
+ "format": "dataformat_Hello_World_PM",
+ "type": "data_router",
+ "version": "1.0.0"
+ },
+ {
+ "config_key": "DCAE-HELLO-WORLD-PUB-MR",
+ "format": "dataformat_Hello_World_PM",
+ "type": "message_router",
+ "version": "1.0.0"
+ }
+ ],
+ "subscribes": [
+ {
+ "config_key": "DCAE-HELLO-WORLD-SUB-MR",
+ "format": "dataformat_Hello_World_PM",
+ "route": "/DCAE_HELLO_WORLD_SUB_MR",
+ "type": "message_router",
+ "version": "1.0.0"
+ },
+ {
+ "config_key": "DCAE-HELLO-WORLD-SUB-DR",
+ "format": "dataformat_Hello_World_PM",
+ "route": "/DCAE-HELLO-WORLD-SUB-DR",
+ "type": "data_router",
+ "version": "1.0.0"
+ }
+ ]
+ },
+ "parameters": [
+ {
+ "name": "vcc_hello_name",
+ "value": "120",
+ "type": "integer",
+ "description": "the name entered for specific person",
+ "sourced_at_deployment": false,
+ "designer_editable": false,
+ "policy_editable": false
+ },
+ {
+ "name": "useDtiConfig",
+ "value": false,
+ "type": "boolean",
+ "description": "component depends on configuration from dti.",
+ "sourced_at_deployment": false,
+ "designer_editable": true,
+ "policy_editable": false,
+ "required": true
+ },
+ {
+ "name": "isSelfServeComponent",
+ "value": false,
+ "type": "boolean",
+ "description": "Is this used as self serve component.",
+ "sourced_at_deployment": false,
+ "designer_editable": true,
+ "policy_editable": false,
+ "required": true
+ }
+ ],
+ "auxilary": {
+ "healthcheck": {
+ "interval": "60s",
+ "initialDelaySeconds": "120s",
+ "timeout": "20s",
+ "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh",
+ "type": "docker"
+ },
+ "livehealthcheck": {
+ "interval": "60s",
+ "initialDelaySeconds": "120s",
+ "timeout": "20s",
+ "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh",
+ "type": "docker"
+ },
+ "reconfigs": {
+ "app_reconfig": "abc"
+ },
+ "volumes": [
+ {
+ "container": {
+ "bind": "/opt/app/dcae-certificate"
+ },
+ "host": {
+ "path": "/opt/app/dcae-certificate"
+ }
+ },
+ {
+ "container": {
+ "bind": "/opt/logs/DCAE/dmd/AGENT"
+ },
+ "host": {
+ "path": "/opt/logs/DCAE/helloworldpm/dmd/AGENT"
+ }
+ },
+ {
+ "container": {
+ "bind": "/opt/logs/DCAE/dmd/WATCHER"
+ },
+ "host": {
+ "path": "/opt/logs/DCAE/helloworldpm/dmd/WATCHER"
+ }
+ },
+ {
+ "container": {
+ "bind": "/opt/app/vcc/logs/DCAE"
+ },
+ "host": {
+ "path": "/opt/logs/DCAE/helloworldpm/vcc-logs"
+ }
+ },
+ {
+ "container": {
+ "bind": "/opt/app/vcc/archive/data"
+ },
+ "host": {
+ "path": "/opt/data/DCAE/helloworldpm/vcc-archive"
+ }
+ }
+ ]
+ },
+ "artifacts": [
+ {
+ "type": "docker image",
+ "uri": "dockercentral.it.att.com:5100/com.att.sample/dcae-controller-vcc-helloworld-pm:18.02-001"
+ }
+ ]
+ } \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/resources/http/requests/policy-model_create_request.json b/mod2/catalog-service/src/test/resources/http/requests/policy-model_create_request.json
new file mode 100644
index 0000000..ace9181
--- /dev/null
+++ b/mod2/catalog-service/src/test/resources/http/requests/policy-model_create_request.json
@@ -0,0 +1,6 @@
+{
+ "name": "tca_policy_dublin12345",
+ "content": "tosca_definitions_version: tosca_simple_yaml_1_1_0\r\npolicy_types:\r\n onap.policies.Monitoring:\r\n derived_from: tosca.policies.Root\r\n version: 1.0.0\r\n name: tca_policy_dublin12345\r\n description: a base policy type for all policies that govern monitoring provisioning\r\n onap.policies.monitoring.tcagen2:\r\n derived_from: onap.policies.Monitoring\r\n version: 1.0.0\r\n name: onap.policies.monitoring.tcagen2\r\n properties:\r\n tca.policy:\r\n type: onap.datatypes.monitoring.tca_policy\r\n description: TCA Policy JSON\r\n required: true\r\ndata_types:\r\n onap.datatypes.monitoring.metricsPerEventName:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n controlLoopSchemaType:\r\n type: string\r\n required: true\r\n description: Specifies Control Loop Schema Type for the event Name e.g. VNF, VM\r\n constraints:\r\n - valid_values:\r\n - VM\r\n - VNF\r\n eventName:\r\n type: string\r\n required: true\r\n description: Event name to which thresholds need to be applied\r\n policyName:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Name\r\n policyScope:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope\r\n policyVersion:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Version\r\n thresholds:\r\n type: list\r\n required: true\r\n description: Thresholds associated with eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.thresholds\r\n onap.datatypes.monitoring.tca_policy:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n domain:\r\n type: string\r\n required: true\r\n description: Domain name to which TCA needs to be applied\r\n default: measurementsForVfScaling\r\n constraints:\r\n - equal: measurementsForVfScaling\r\n metricsPerEventName:\r\n type: list\r\n required: true\r\n description: Contains eventName and threshold details that need to be applied to given eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.metricsPerEventName\r\n onap.datatypes.monitoring.thresholds:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n closedLoopControlName:\r\n type: string\r\n required: true\r\n description: Closed Loop Control Name associated with the threshold\r\n closedLoopEventStatus:\r\n type: string\r\n required: true\r\n description: Closed Loop Event Status of the threshold\r\n constraints:\r\n - valid_values:\r\n - ONSET\r\n - ABATED\r\n direction:\r\n type: string\r\n required: true\r\n description: Direction of the threshold\r\n constraints:\r\n - valid_values:\r\n - LESS\r\n - LESS_OR_EQUAL\r\n - GREATER\r\n - GREATER_OR_EQUAL\r\n - EQUAL\r\n fieldPath:\r\n type: string\r\n required: true\r\n description: Json field Path as per CEF message which needs to be analyzed for TCA\r\n constraints:\r\n - valid_values:\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage\r\n - $.event.measurementsForVfScalingFields.meanRequestLatency\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed\r\n - $.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value\r\n severity:\r\n type: string\r\n required: true\r\n description: Threshold Event Severity\r\n constraints:\r\n - valid_values:\r\n - CRITICAL\r\n - MAJOR\r\n - MINOR\r\n - WARNING\r\n - NORMAL\r\n thresholdValue:\r\n type: integer\r\n required: true\r\n description: Threshold value for the field Path inside CEF message\r\n version:\r\n type: string\r\n required: true\r\n description: Version number associated with the threshold",
+ "owner": "admin",
+ "version": "1.0.0"
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/resources/http/requests/policy-model_update_request.json b/mod2/catalog-service/src/test/resources/http/requests/policy-model_update_request.json
new file mode 100644
index 0000000..8f2cf5b
--- /dev/null
+++ b/mod2/catalog-service/src/test/resources/http/requests/policy-model_update_request.json
@@ -0,0 +1,5 @@
+{
+ "name": "tca_policy_dublin12345",
+ "owner": "admin123",
+ "version": "1.0.0"
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response.json b/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response.json
new file mode 100644
index 0000000..d689dcb
--- /dev/null
+++ b/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response.json
@@ -0,0 +1,12 @@
+{
+ "id": "5fae8956cd1bac74e55c9d3a",
+ "name": "tca_policy_dublin12345",
+ "content": "\ttosca_definitions_version: tosca_simple_yaml_1_0_0\r\npolicy_types:\r\n onap.policies.Monitoring:\r\n derived_from: tosca.policies.Root\r\n description: a base policy type for all policies that governs monitoring provisioning\r\n onap.policies.monitoring.cdap.tca.hi.lo.app:\r\n derived_from: onap.policies.Monitoring\r\n version: 1.0.0\r\n properties:\r\n tca_policy:\r\n type: map\r\n description: TCA Policy JSON\r\n entry_schema:\r\n type: onap.datatypes.monitoring.tca_policy\r\ndata_types:\r\n onap.datatypes.monitoring.metricsPerEventName:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n controlLoopSchemaType:\r\n type: string\r\n required: true\r\n description: Specifies Control Loop Schema Type for the event Name e.g. VNF, VM\r\n constraints:\r\n - valid_values:\r\n - VM\r\n - VNF\r\n eventName:\r\n type: string\r\n required: true\r\n description: Event name to which thresholds need to be applied\r\n policyName:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Name\r\n policyScope:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope\r\n policyVersion:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Version\r\n thresholds:\r\n type: list\r\n required: true\r\n description: Thresholds associated with eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.thresholds\r\n onap.datatypes.monitoring.tca_policy:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n domain:\r\n type: string\r\n required: true\r\n description: Domain name to which TCA needs to be applied\r\n default: measurementsForVfScaling\r\n constraints:\r\n - equal: measurementsForVfScaling\r\n metricsPerEventName:\r\n type: list\r\n required: true\r\n description: Contains eventName and threshold details that need to be applied to given eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.metricsPerEventName\r\n onap.datatypes.monitoring.thresholds:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n closedLoopControlName:\r\n type: string\r\n required: true\r\n description: Closed Loop Control Name associated with the threshold\r\n closedLoopEventStatus:\r\n type: string\r\n required: true\r\n description: Closed Loop Event Status of the threshold\r\n constraints:\r\n - valid_values:\r\n - ONSET\r\n - ABATED\r\n direction:\r\n type: string\r\n required: true\r\n description: Direction of the threshold\r\n constraints:\r\n - valid_values:\r\n - LESS\r\n - LESS_OR_EQUAL\r\n - GREATER\r\n - GREATER_OR_EQUAL\r\n - EQUAL\r\n fieldPath:\r\n type: string\r\n required: true\r\n description: Json field Path as per CEF message which needs to be analyzed for TCA\r\n constraints:\r\n - valid_values:\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage\r\n - $.event.measurementsForVfScalingFields.meanRequestLatency\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed\r\n - $.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value\r\n severity:\r\n type: string\r\n required: true\r\n description: Threshold Event Severity\r\n constraints:\r\n - valid_values:\r\n - CRITICAL\r\n - MAJOR\r\n - MINOR\r\n - WARNING\r\n - NORMAL\r\n thresholdValue:\r\n type: integer\r\n required: true\r\n description: Threshold value for the field Path inside CEF message\r\n version:\r\n type: string\r\n required: true\r\n description: Version number associated with the threshold",
+ "owner": "admin",
+ "version": "1.0.0",
+ "metadata": {
+ "createdBy": "rx908f",
+ "createdOn": "2020-11-13T13:25:42.434+0000",
+ "notes": ""
+ }
+} \ No newline at end of file
diff --git a/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response1.json b/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response1.json
new file mode 100644
index 0000000..3d3516c
--- /dev/null
+++ b/mod2/catalog-service/src/test/resources/http/responses/policy-model_create_response1.json
@@ -0,0 +1,16 @@
+{
+ "id": "5fae8956cd1bac74e55c9d3a",
+ "name": "tca_policy_dublin12345",
+ "content": "\tosca_definitions_version: tosca_simple_yaml_1_1_0\r\npolicy_types:\r\n onap.policies.Monitoring:\r\n derived_from: tosca.policies.Root\r\n version: 1.0.0\r\n name: onap.policies.Monitoring\r\n description: a base policy type for all policies that govern monitoring provisioning\r\n onap.policies.monitoring.tcagen2:\r\n derived_from: onap.policies.Monitoring\r\n version: 1.0.0\r\n name: onap.policies.monitoring.tcagen2\r\n properties:\r\n tca.policy:\r\n type: onap.datatypes.monitoring.tca_policy\r\n description: TCA Policy JSON\r\n required: true\r\ndata_types:\r\n onap.datatypes.monitoring.metricsPerEventName:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n controlLoopSchemaType:\r\n type: string\r\n required: true\r\n description: Specifies Control Loop Schema Type for the event Name e.g. VNF, VM\r\n constraints:\r\n - valid_values:\r\n - VM\r\n - VNF\r\n eventName:\r\n type: string\r\n required: true\r\n description: Event name to which thresholds need to be applied\r\n policyName:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Name\r\n policyScope:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope\r\n policyVersion:\r\n type: string\r\n required: true\r\n description: TCA Policy Scope Version\r\n thresholds:\r\n type: list\r\n required: true\r\n description: Thresholds associated with eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.thresholds\r\n onap.datatypes.monitoring.tca_policy:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n domain:\r\n type: string\r\n required: true\r\n description: Domain name to which TCA needs to be applied\r\n default: measurementsForVfScaling\r\n constraints:\r\n - equal: measurementsForVfScaling\r\n metricsPerEventName:\r\n type: list\r\n required: true\r\n description: Contains eventName and threshold details that need to be applied to given eventName\r\n entry_schema:\r\n type: onap.datatypes.monitoring.metricsPerEventName\r\n onap.datatypes.monitoring.thresholds:\r\n derived_from: tosca.datatypes.Root\r\n properties:\r\n closedLoopControlName:\r\n type: string\r\n required: true\r\n description: Closed Loop Control Name associated with the threshold\r\n closedLoopEventStatus:\r\n type: string\r\n required: true\r\n description: Closed Loop Event Status of the threshold\r\n constraints:\r\n - valid_values:\r\n - ONSET\r\n - ABATED\r\n direction:\r\n type: string\r\n required: true\r\n description: Direction of the threshold\r\n constraints:\r\n - valid_values:\r\n - LESS\r\n - LESS_OR_EQUAL\r\n - GREATER\r\n - GREATER_OR_EQUAL\r\n - EQUAL\r\n fieldPath:\r\n type: string\r\n required: true\r\n description: Json field Path as per CEF message which needs to be analyzed for TCA\r\n constraints:\r\n - valid_values:\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait\r\n - $.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage\r\n - $.event.measurementsForVfScalingFields.meanRequestLatency\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree\r\n - $.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed\r\n - $.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value\r\n severity:\r\n type: string\r\n required: true\r\n description: Threshold Event Severity\r\n constraints:\r\n - valid_values:\r\n - CRITICAL\r\n - MAJOR\r\n - MINOR\r\n - WARNING\r\n - NORMAL\r\n thresholdValue:\r\n type: integer\r\n required: true\r\n description: Threshold value for the field Path inside CEF message\r\n version:\r\n type: string\r\n required: true\r\n description: Version number associated with the threshold",
+ "owner": "admin",
+ "version": "1.0.0",
+ "metadata": {
+ "createdBy": "rx908f",
+ "createdOn": "2020-11-13T13:25:42.434+0000",
+ "notes": ""
+ },
+ "distributionInfo": [{
+ "url": "https://<policy-api-server>:6969/policy/api/v1/",
+ "status": "FAILED"
+ }]
+} \ No newline at end of file