From a4b28fed45ecdceade0c7a3dc105694e26fe4b3e Mon Sep 17 00:00:00 2001 From: rameshiyer27 Date: Thu, 17 Feb 2022 17:14:15 +0000 Subject: Add REST Apis for Tosca Node template operations Statistics handling for the new Apis are not added as it is going to be handled via spring actuators as part of spring migration.Please suggest if manual stats handling is required. Issue-ID: POLICY-3832 Signed-off-by: zrrmmua Change-Id: I1eeaec9e617fd586238e7ff9e96d40a75c517885 --- .../policy/api/main/rest/TestApiRestServer.java | 242 ++++++++------------- .../api/main/rest/TestNodeTemplateController.java | 223 +++++++++++++++++++ .../main/rest/utils/CommonTestRestController.java | 153 +++++++++++++ 3 files changed, 462 insertions(+), 156 deletions(-) create mode 100644 main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java create mode 100644 main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java (limited to 'main/src/test/java') diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java index ae654c6c..a22a0a07 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2020,2022 Nordix Foundation. * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -31,27 +31,17 @@ import static org.junit.Assert.assertNull; import java.io.File; import java.io.IOException; -import java.security.SecureRandom; import java.util.List; import java.util.Map; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.policy.api.main.PolicyApiApplication; -import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; +import org.onap.policy.api.main.rest.utils.CommonTestRestController; import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.gson.GsonMessageBodyHandler; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.StandardYamlCoder; import org.onap.policy.common.utils.network.NetworkUtil; @@ -79,7 +69,7 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DirtiesContext(classMode = ClassMode.AFTER_CLASS) -public class TestApiRestServer { +public class TestApiRestServer extends CommonTestRestController { private static final String ALIVE = "alive"; private static final String SELF = NetworkUtil.getHostname(); @@ -196,7 +186,7 @@ public class TestApiRestServer { @Test public void testCreatePolicyTypes() throws Exception { for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName); + Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertNotNull(response); @@ -204,12 +194,12 @@ public class TestApiRestServer { } // Send a policy type with a null value to trigger an error - Response rawResponse = readResource(POLICYTYPES, APP_JSON); + Response rawResponse = readResource(POLICYTYPES, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); String firstPolicyType = response.getPolicyTypes().keySet().iterator().next(); response.getPolicyTypes().put(firstPolicyType, null); - Response rawResponse2 = createResource(POLICYTYPES, standardCoder.encode(response)); + Response rawResponse2 = createResource(POLICYTYPES, standardCoder.encode(response), apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse2.getStatus()); ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); assertEquals("no policy types specified on service template", errorResponse.getErrorMessage()); @@ -218,7 +208,7 @@ public class TestApiRestServer { @Test public void testCreatePolicies() throws Exception { for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -232,7 +222,8 @@ public class TestApiRestServer { TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml"); Response rawResponse2 = - createResource(POLICYTYPES_TCA_POLICIES, "src/test/resources/policies/BadTestPolicy.yaml"); + createResource(POLICYTYPES_TCA_POLICIES, + "src/test/resources/policies/BadTestPolicy.yaml", apiPort); assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus()); ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); assertThat(errorResponse.getErrorMessage()) @@ -242,7 +233,7 @@ public class TestApiRestServer { @Test public void testSimpleCreatePolicies() throws Exception { for (String resrcName : TOSCA_POLICIES_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICIES, resrcName); + Response rawResponse = createResource(POLICIES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -256,7 +247,8 @@ public class TestApiRestServer { toscaPolicy = toscaPolicy.replaceAll("onap.restart.tca", "onap.restart.tca.IDontExist"); TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml"); - Response rawResponse2 = createResource(POLICIES, "src/test/resources/policies/BadTestPolicy.yaml"); + Response rawResponse2 = + createResource(POLICIES, "src/test/resources/policies/BadTestPolicy.yaml", apiPort); ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus()); assertThat(errorResponse.getErrorMessage()) @@ -266,31 +258,31 @@ public class TestApiRestServer { @SuppressWarnings("unchecked") @Test public void testToscaCompliantOpDroolsPolicies() throws Exception { - Response rawResponse = createResource(POLICYTYPES, TOSCA_POLICYTYPE_OP_RESOURCE); + Response rawResponse = createResource(POLICYTYPES, TOSCA_POLICYTYPE_OP_RESOURCE, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, APP_JSON); + rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON); + rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML); + rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON); + rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON); + rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML); + rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON); + rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_YAML); + rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_YAML, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate toscaVcpeSt = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -311,7 +303,7 @@ public class TestApiRestServer { assertEquals("APPC", operation.get("actor")); assertEquals("Restart", operation.get("operation")); - rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON); + rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -326,7 +318,7 @@ public class TestApiRestServer { } private void testHealthCheckSuccess(String mediaType) throws Exception { - final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT, mediaType); + final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT, mediaType, apiPort); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); } @@ -342,11 +334,11 @@ public class TestApiRestServer { } private void testApiStatistics_200(String mediaType) throws Exception { - Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType); + Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType, apiPort); StatisticsReport report = invocationBuilder.get(StatisticsReport.class); validateStatisticsReport(report, 200); updateApiStatistics(); - invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType); + invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType, apiPort); report = invocationBuilder.get(StatisticsReport.class); validateStatisticsReport(report, 200); // ApiStatisticsManager.resetAllStatistics(); @@ -363,46 +355,48 @@ public class TestApiRestServer { } private void testReadPolicyTypes(String mediaType) throws Exception { - Response rawResponse = readResource("policytypes/onap.policies.optimization.resource.HpaPolicy", mediaType); + Response rawResponse = + readResource("policytypes/onap.policies.optimization.resource.HpaPolicy", mediaType, + apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); assertNotNull(namingServiceTemplate); assertEquals(3, namingServiceTemplate.getPolicyTypesAsMap().size()); assertEquals(5, namingServiceTemplate.getDataTypesAsMap().size()); - rawResponse = readResource(POLICYTYPES, mediaType); + rawResponse = readResource(POLICYTYPES, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertFalse(response.getPolicyTypes().isEmpty()); - rawResponse = readResource(POLICYTYPES_TCA, mediaType); + rawResponse = readResource(POLICYTYPES_TCA, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_LATEST, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_LATEST, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType); + rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType); + rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType); + rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS, mediaType); + rawResponse = readResource(POLICYTYPES_DROOLS, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, mediaType); + rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION_LATEST, mediaType); + rawResponse = readResource(POLICYTYPES_DROOLS_VERSION_LATEST, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_NAMING_VERSION, mediaType); + rawResponse = readResource(POLICYTYPES_NAMING_VERSION, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -417,19 +411,23 @@ public class TestApiRestServer { } private void testDeletePolicyType(String mediaType) throws Exception { - Response rawResponse = deleteResource("policytypes/onap.policies.IDoNotExist/versions/1.0.0", mediaType); + Response rawResponse = deleteResource("policytypes/onap.policies.IDoNotExist/versions/1.0.0", + mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - rawResponse = createResource(POLICYTYPES, "policytypes/onap.policies.Test.yaml"); + rawResponse = createResource(POLICYTYPES, "policytypes/onap.policies.Test.yaml", apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType); + rawResponse = + readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = deleteResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType); + rawResponse = + deleteResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType); + rawResponse = + readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); } @@ -445,23 +443,23 @@ public class TestApiRestServer { private void testReadPolicies(String mediaType) throws Exception { for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } - Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType); + Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType); + rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -470,11 +468,11 @@ public class TestApiRestServer { public void testNamingPolicyGet() throws Exception { Response rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON); + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0?mode=referenced", APP_JSON); + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0?mode=referenced", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -483,7 +481,7 @@ public class TestApiRestServer { assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest?mode=referenced", APP_JSON); + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest?mode=referenced", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -491,8 +489,8 @@ public class TestApiRestServer { assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size()); assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); - rawResponse = - readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies?mode=referenced", APP_JSON); + rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies" + + "?mode=referenced", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -501,7 +499,7 @@ public class TestApiRestServer { assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON); + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -511,7 +509,7 @@ public class TestApiRestServer { assertNull(namingServiceTemplate.getDataTypes()); rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest", APP_JSON); + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest", APP_JSON, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -519,7 +517,9 @@ public class TestApiRestServer { assertNull(namingServiceTemplate.getPolicyTypes()); assertNull(namingServiceTemplate.getDataTypes()); - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies", APP_JSON); + rawResponse = + readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies", APP_JSON, + apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); @@ -539,7 +539,7 @@ public class TestApiRestServer { } private void testDeletePolicies(String mediaType) throws Exception { - Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType); + Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); ErrorResponse error = rawResponse.readEntity(ErrorResponse.class); assertEquals("policy onap.restart.tca:1.0.0 not found", error.getErrorMessage()); @@ -557,30 +557,30 @@ public class TestApiRestServer { private void testDeletePolicyVersion(String mediaType) throws Exception { for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName); + Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertNotNull(response); assertFalse(response.getPolicyTypes().isEmpty()); } for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } - Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType); + Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class); assertEquals("policies for onap.restart.tca:1.0.0 do not exist", errorResponse.getErrorMessage()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); errorResponse = rawResponse.readEntity(ErrorResponse.class); assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage()); - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType); + rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType, apiPort); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); errorResponse = rawResponse.readEntity(ErrorResponse.class); assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage()); @@ -598,17 +598,17 @@ public class TestApiRestServer { private void testGetAllVersionOfPolicy(String mediaType) throws Exception { for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName); + Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertNotNull(response); assertFalse(response.getPolicyTypes().isEmpty()); } for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } - Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType); + Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType, apiPort); assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); } @@ -624,17 +624,17 @@ public class TestApiRestServer { private void getPolicies(String mediaType) throws Exception { for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName); + Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertThat(response).isNotNull(); assertThat(response.getPolicyTypes()).isNotEmpty(); } for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); } - Response rawResponse = readResource(POLICIES, mediaType); + Response rawResponse = readResource(POLICIES, mediaType, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertThat(response.getToscaTopologyTemplate().getPolicies()).isNotEmpty(); @@ -652,17 +652,17 @@ public class TestApiRestServer { private void getSpecificPolicy(String mediaType) throws Exception { for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName); + Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertThat(response).isNotNull(); assertThat(response.getPolicyTypes()).isNotEmpty(); } for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); } - Response rawResponse = readResource(POLICIES_VCPE_VERSION1, mediaType); + Response rawResponse = readResource(POLICIES_VCPE_VERSION1, mediaType, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertThat(response.getToscaTopologyTemplate().getPolicies()).hasSize(1); @@ -672,102 +672,32 @@ public class TestApiRestServer { public void testDeleteSpecificPolicy() throws Exception { Response rawResponse; for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - rawResponse = createResource(POLICYTYPES, resrcName); + rawResponse = createResource(POLICYTYPES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); assertThat(response).isNotNull(); assertThat(response.getPolicyTypes()).isNotEmpty(); } for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName); + rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); } - rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON); + rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); // delete a particular policy - rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON); + rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON); + rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode()); - rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON); + rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode()); } - - private Response createResource(String endpoint, String resourceName) throws Exception { - - String mediaType = APP_JSON; // default media type - ToscaServiceTemplate rawServiceTemplate = new ToscaServiceTemplate(); - if (resourceName.endsWith(".json")) { - rawServiceTemplate = - standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class); - } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) { - mediaType = APP_YAML; - rawServiceTemplate = standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName), - ToscaServiceTemplate.class); - } - - final Invocation.Builder invocationBuilder; - - invocationBuilder = sendHttpsRequest(endpoint, mediaType); - - Entity entity = Entity.entity(rawServiceTemplate, mediaType); - return invocationBuilder.post(entity); - } - - private Response readResource(String endpoint, String mediaType) throws Exception { - - final Invocation.Builder invocationBuilder; - - invocationBuilder = sendHttpsRequest(endpoint, mediaType); - - return invocationBuilder.get(); - - } - - private Response deleteResource(String endpoint, String mediaType) throws Exception { - - final Invocation.Builder invocationBuilder; - - invocationBuilder = sendHttpsRequest(endpoint, mediaType); - - return invocationBuilder.delete(); - } - - private Invocation.Builder sendHttpsRequest(final String endpoint, String mediaType) throws Exception { - - final TrustManager[] noopTrustManager = NetworkUtil.getAlwaysTrustingManager(); - - final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); - final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); - final Client client = clientBuilder.build(); - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34"); - client.register(feature); - - client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); - if (APP_JSON.equalsIgnoreCase(mediaType)) { - client.register(GsonMessageBodyHandler.class); - } else if (APP_YAML.equalsIgnoreCase(mediaType)) { - client.register(YamlMessageBodyHandler.class); - } - - final WebTarget webTarget = client.target("https://localhost:" + apiPort + "/policy/api/v1/" + endpoint); - - final Invocation.Builder invocationBuilder = webTarget.request(mediaType); - - if (!NetworkUtil.isTcpPortOpen("localhost", apiPort, 60, 1000L)) { - throw new IllegalStateException("cannot connect to port " + apiPort); - } - return invocationBuilder; - } - private void updateApiStatistics() { mgr.updateTotalApiCallCount(); mgr.updateApiCallSuccessCount(); diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java b/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java new file mode 100644 index 00000000..5244f3c9 --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java @@ -0,0 +1,223 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy API + * ================================================================================ + * Copyright (C) 2022 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.policy.api.main.PolicyApiApplication; +import org.onap.policy.api.main.rest.provider.NodeTemplateProvider; +import org.onap.policy.api.main.rest.utils.CommonTestRestController; +import org.onap.policy.common.utils.security.SelfSignedKeyStore; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Class to perform unit test of {@link NodeTemplateController}. + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class TestNodeTemplateController extends CommonTestRestController { + + private static final String TOSCA_NODE_TEMPLATE_RESOURCE = + "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; + private static final String TOSCA_INVALID_NODE_TYPE = + "nodetemplates/nodetemplates.metadatasets.invalid.nodetype.json"; + private static final String TOSCA_INVALID_TEMPLATE = + "nodetemplates/nodetemplates.metadatasets.no.nodetemplate.json"; + private static final String TOSCA_UPDATE_NODE_TEMPLATES = "nodetemplates/nodetemplates.metadatasets.update.json"; + + private static final String NODE_TEMPLATES = "nodetemplates"; + private static final String SPECIFIC_NODE_TEMPLATE = "nodetemplates/apexMetadata_adaptive/versions/1.0.0"; + private static final String INVALID_NODE_TEMPLATE_ID = "nodetemplates/invalid_template/versions/1.0.0"; + + private static final List nodeTemplateKeys = + List.of("apexMetadata_grpc", "apexMetadata_adaptive", "apexMetadata_decisionMaker"); + + protected static final String APP_JSON = "application/json"; + + private static SelfSignedKeyStore keystore; + + @LocalServerPort + private int apiPort; + + @Autowired + private NodeTemplateProvider provider; + + /** + * Initializes parameters and set up test environment. + * + * @throws IOException on I/O exceptions + * @throws InterruptedException if interrupted + */ + @BeforeClass + public static void setupParameters() throws IOException, InterruptedException { + keystore = new SelfSignedKeyStore(); + } + + /** + * Clean up the database. + * + */ + @After + public void clearDb() { + for (String name : nodeTemplateKeys) { + try { + provider.deleteToscaNodeTemplate(name, "1.0.0"); + } catch (PfModelException | PfModelRuntimeException e) { + //do nothing + } + } + } + + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("server.ssl.enabled", () -> "true"); + registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); + registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); + registry.add("server.ssl.key-store-type", () -> "PKCS12"); + registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org"); + registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD); + } + + + @Test + public void testCreateToscaNodeTemplates() throws Exception { + Response rawResponse = createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); + assertNotNull(response); + assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); + + // Send a node type with a invalid value to trigger an error + rawResponse = createResource(NODE_TEMPLATES, TOSCA_INVALID_NODE_TYPE, apiPort); + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse.getStatus()); + ErrorResponse response2 = rawResponse.readEntity(ErrorResponse.class); + assertThat(response2.getErrorMessage()) + .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); + + // Send invalid tosca template with no node templates + rawResponse = createResource(NODE_TEMPLATES, TOSCA_INVALID_TEMPLATE, apiPort); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); + response2 = rawResponse.readEntity(ErrorResponse.class); + assertEquals("node templates not present on the service template", response2.getErrorMessage()); + } + + + @Test + public void testReadNodeTemplates() throws Exception { + Response rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + List nodeTemplates = rawResponse.readEntity(List.class); + assertNotNull(nodeTemplates); + assertEquals(0, nodeTemplates.size()); + + createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); + rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + nodeTemplates = rawResponse.readEntity(List.class); + assertNotNull(nodeTemplates); + assertEquals(3, nodeTemplates.size()); + + rawResponse = readResource(SPECIFIC_NODE_TEMPLATE, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + List retrievedTemplate = + rawResponse.readEntity(new GenericType>() {}); + assertNotNull(nodeTemplates); + assertEquals(1, retrievedTemplate.size()); + String retrievedTemplateName = retrievedTemplate.get(0).getName(); + assertEquals("apexMetadata_adaptive", retrievedTemplateName); + } + + @Test + public void testUpdateNodeTemplates() throws Exception { + createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); + Response rawResponse = updateResource(NODE_TEMPLATES, TOSCA_UPDATE_NODE_TEMPLATES, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); + assertNotNull(response); + assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); + String updatedValue = "" + response.getToscaTopologyTemplate().getNodeTemplates().get("apexMetadata_grpc") + .getMetadata().get("state"); + assertEquals("passive", updatedValue); + + rawResponse = updateResource(NODE_TEMPLATES, TOSCA_INVALID_NODE_TYPE, APP_JSON, apiPort); + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse.getStatus()); + ErrorResponse response2 = rawResponse.readEntity(ErrorResponse.class); + assertThat(response2.getErrorMessage()) + .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); + + // Send invalid tosca template with no node templates + rawResponse = updateResource(NODE_TEMPLATES, TOSCA_INVALID_TEMPLATE, APP_JSON, apiPort); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); + ErrorResponse response3 = rawResponse.readEntity(ErrorResponse.class); + assertEquals("node templates not present on the service template", response3.getErrorMessage()); + } + + @Test + public void testDeleteNodeTemplates() throws Exception { + createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); + Response rawResponse = deleteResource(SPECIFIC_NODE_TEMPLATE, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); + assertNotNull(response); + assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); + + rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); + assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); + List nodeTemplates = rawResponse.readEntity(List.class); + assertNotNull(nodeTemplates); + assertEquals(2, nodeTemplates.size()); + + // Send invalid id + rawResponse = deleteResource(INVALID_NODE_TEMPLATE_ID, APP_JSON, apiPort); + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); + ErrorResponse response3 = rawResponse.readEntity(ErrorResponse.class); + assertThat(response3.getErrorMessage()).containsPattern("^node template .* not found$"); + } + +} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java b/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java new file mode 100644 index 00000000..9289adb2 --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy API + * ================================================================================ + * Copyright (C) 2022 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.utils; + +import java.security.SecureRandom; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.coder.StandardYamlCoder; +import org.onap.policy.common.utils.network.NetworkUtil; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; + +/** + * Util class to perform REST unit tests. + * + */ +public class CommonTestRestController { + + protected static final String APP_JSON = "application/json"; + protected static final String APP_YAML = "application/yaml"; + + protected static final StandardCoder standardCoder = new StandardCoder(); + protected static StandardYamlCoder standardYamlCoder = new StandardYamlCoder(); + + + protected Response createResource(String endpoint, String resourceName, int apiPort) + throws Exception { + + ToscaServiceTemplate rawServiceTemplate = getRawServiceTemplate(resourceName); + String mediaType = getMediaType(resourceName); + mediaType = mediaType == null ? APP_JSON : mediaType; + + final Invocation.Builder invocationBuilder; + invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); + Entity entity = Entity.entity(rawServiceTemplate, mediaType); + return invocationBuilder.post(entity); + } + + protected Response readResource(String endpoint, String mediaType, int apiPort) throws Exception { + + final Invocation.Builder invocationBuilder; + invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); + return invocationBuilder.get(); + } + + protected Response deleteResource(String endpoint, String mediaType, int apiPort) throws Exception { + + final Invocation.Builder invocationBuilder; + invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); + return invocationBuilder.delete(); + } + + protected Response updateResource(String endpoint, String resourceName, String mediaType, int apiPort) + throws Exception { + + ToscaServiceTemplate rawServiceTemplate = getRawServiceTemplate(resourceName); + + final Invocation.Builder invocationBuilder; + invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); + Entity entity = Entity.entity(rawServiceTemplate, mediaType); + return invocationBuilder.put(entity); + } + + protected ToscaServiceTemplate decodeJson(String resourceName) throws CoderException { + return standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class); + } + + protected ToscaServiceTemplate decodeYaml(String resourceName) throws CoderException { + return standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class); + } + + protected Invocation.Builder sendHttpsRequest(final String endpoint, String mediaType, int apiPort) + throws Exception { + + final TrustManager[] noopTrustManager = NetworkUtil.getAlwaysTrustingManager(); + + final SSLContext sc = SSLContext.getInstance("TLSv1.2"); + sc.init(null, noopTrustManager, new SecureRandom()); + final ClientBuilder clientBuilder = + ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); + final Client client = clientBuilder.build(); + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34"); + client.register(feature); + + client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); + if (APP_JSON.equalsIgnoreCase(mediaType)) { + client.register(GsonMessageBodyHandler.class); + } else if (APP_YAML.equalsIgnoreCase(mediaType)) { + client.register(YamlMessageBodyHandler.class); + } + + final WebTarget webTarget = client.target("https://localhost:" + apiPort + "/policy/api/v1/" + endpoint); + + final Invocation.Builder invocationBuilder = webTarget.request(mediaType); + + if (!NetworkUtil.isTcpPortOpen("localhost", apiPort, 60, 1000L)) { + throw new IllegalStateException("cannot connect to port " + apiPort); + } + return invocationBuilder; + } + + private ToscaServiceTemplate getRawServiceTemplate(String resourceName) throws CoderException { + ToscaServiceTemplate rawServiceTemplate = new ToscaServiceTemplate(); + if (APP_JSON.equals(getMediaType(resourceName))) { + rawServiceTemplate = decodeJson(resourceName); + } else if (APP_YAML.equals(getMediaType(resourceName))) { + rawServiceTemplate = decodeYaml(resourceName); + } + return rawServiceTemplate; + } + + private String getMediaType(String resourceName) { + if (resourceName.endsWith(".json")) { + return APP_JSON; + } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) { + return APP_YAML; + } + return null; + } + +} -- cgit 1.2.3-korg