diff options
Diffstat (limited to 'components')
35 files changed, 1693 insertions, 519 deletions
diff --git a/components/kpi-computation-ms/pom.xml b/components/kpi-computation-ms/pom.xml index 58758a2e..e9e315eb 100644 --- a/components/kpi-computation-ms/pom.xml +++ b/components/kpi-computation-ms/pom.xml @@ -53,7 +53,7 @@ <undertow.version>2.0.30.Final</undertow.version> <xml.version>2.3.1</xml.version> <jaxb.version>2.3.0.1</jaxb.version> - <docker.repository>nexus3.onap.org:10001</docker.repository> + <docker.repository>nexus3.onap.org:10003</docker.repository> <spring.version>5.2.7.RELEASE</spring.version> <junit.version>5.3.2</junit.version> <mockito.version>2.23.4</mockito.version> @@ -334,9 +334,8 @@ <include>${project.artifactId}-${project.version}.jar</include> </resource> <resource> - <targetPath>/app</targetPath> + <targetPath>/app</targetPath> <directory>${project.basedir}</directory> - <include>entry.sh</include> </resource> </resources> diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java index 94085146..930e631c 100644 --- a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java @@ -239,12 +239,6 @@ public class Configuration { }.getType(); dmaapServers = new Gson().fromJson(servers, listType); - port = jsonObject.get("mongo.port").getAsInt(); - host = jsonObject.get("mongo.host").getAsString(); -// username = jsonObject.get("mongo.username").getAsString(); -// password = jsonObject.get("mongo.password").getAsString(); - databasename = jsonObject.get("mongo.databasename").getAsString(); - if (jsonObject.get("aafUsername") == null) { aafUsername = null; } else { diff --git a/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-output.json b/components/pm-subscription-handler/dpo/data-formats/dcae-cl-output.json index 503d6ca8..b5cfa8bf 100755 --- a/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-output.json +++ b/components/pm-subscription-handler/dpo/data-formats/dcae-cl-output.json @@ -2,96 +2,42 @@ "self": { "name": "DCAE_CL_OUTPUT", "version": "1.0.0", - "description": "The output format of PM Subscription CL event to Policy" + "description": "The output format of PM Subscription CL event sent to Policy." }, "dataformatversion": "1.0.0", "jsonSchema": { "name": "PM Subscription CL event", "version": "1.0.0", "properties": { - "version": { + "name": "PM Subscription CL event", + "version": "1.0.0", + "nfName": { "type": "string", - "enum": [ - "1.0.2" - ] - }, - "closedLoopControlName": { - "type": "string", - "description" : "This is the unique ID for the Control Loop. It is created by the CLAMP platform during Control Loop design" - }, - "requestID": { - "type": "string", - "description" : "For the control loop, when an instance of the Control Loop occurs, this unique ID must be created. The same ID must be forwarded for both the ONSET and the ABATED control loop messages" - }, - "closedLoopEventStatus": { - "type": "string", - "description" : "This is the status of the closedLoopControlName/requestID pair", - "enum": [ - "ONSET", - "ABATED" - ] - }, - "closedLoopAlarmStart": { - "type": "string", - "description" : "When the alarm was first detected" - }, - "closedLoopAlarmEnd" : { - "type" : "string", - "description" : "When the alarm was cleared. This field need only be present in the ABATED message" + "description": "The name of the nf in A&AI." }, - "policyVersion": { + "ipv4Address": { "type": "string", - "description" : "The version of the Policy driving the DCAE Micro service. Should be a part of the configuration policy setup by CLAMP and passed by DCAE controller" + "description": "The ipv4address of the nf being targeted." }, "policyName": { "type": "string", - "description" : "The name of the Operational Policy driving the DCAE micro service." + "description": "The name of the Operational Policy driving the DCAE microservice." }, - "policyScope": { + "closedLoopControlName": { "type": "string", - "description" : "The scope of the Policy driving the DCAE micro service. Should be a part of the configuration policy setup by CLAMP and passed by DCAE controller" + "description": "This is the unique ID for the Control Loop. It is created by the CLAMP platform during Control Loop design." }, - "from": { + "blueprintName": { "type": "string", - "description" : "The ONAP platform component publishing this message", - "enum": [ - "DCAE" - ] + "description": "The name of the blueprint to be executed by CDS towards the nf." }, - "target_type": { + "blueprintVersion": { "type": "string", - "description" : "The type of the target: PNF or VNF", - "enum": [ - "VNF", - "PNF" - ] - }, - "target": { - "type": "string", - "description" : "This is the name of the field within the A&AI sub-tag that indicates the actual entity Node details. There should be a matching node field within the A&AI subtag holding this value", - "enum": [ - "generic-vnf.vnf-name", - "pnf.pnf-name" - ] - }, - "AAI": { - "description" : "Contains the A&AI Node-Attribute list", - "anyOf": [ - { - "generic-vnf.vnf-name": { - "type": "string" - } - }, - { - "pnf.pnf-name": { - "type": "string" - } - } - ] + "description": "The version of the blueprint to be executed by CDS towards the nf." }, "changeType": { "type": "string", - "description": "This is the change indicator that determines whether to apply/remove a PM subscription", + "description": "This is the change indicator that determines whether to apply/remove a PM subscription.", "enum": [ "CREATE", "DELETE" @@ -99,23 +45,27 @@ }, "subscription": { "type": "object", - "description": "This is the PM subscription to be applied/removed to/from an xNF", + "description": "This is the PM subscription to be applied/removed to/from an xNF.", "properties": { - "subscriptionName": { - "type": "string" - }, "administrativeState": { "type": "string", + "description": "The administrative state of the subscription object.", "enum": [ "UNLOCKED", "LOCKED" ] }, + "subscriptionName": { + "type": "string", + "description": "The unique name of the subscription object." + }, "fileBasedGP": { - "type": "integer" + "type": "integer", + "description": "The granularity period of measurement collection in minutes." }, "fileLocation": { - "type": "string" + "type": "string", + "description": "The location of the PM measurements file on the nf." }, "measurementGroups": { "type": "array", @@ -182,18 +132,15 @@ } }, "required": [ - "version", - "closedLoopControlName", - "requestID", - "closedLoopEventStatus", - "closedLoopAlarmStart", + "nfName", + "ipv4Address", "policyName", - "from", - "target_type", - "target", - "AAI", + "closedLoopControlName", + "blueprintName", + "blueprintVersion", "changeType", "subscription" ] } -}
\ No newline at end of file +} + diff --git a/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-input.json b/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-input.json index 9c1d252f..cda1a223 100755 --- a/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-input.json +++ b/components/pm-subscription-handler/dpo/data-formats/pmsh-cl-input.json @@ -1,11 +1,73 @@ -{
- "self": {
- "name": "PMSH_CL_INPUT",
- "version": "1.0.0",
- "description": "Unstructured PMSH CL INPUT"
- },
- "dataformatversion": "1.0.0",
- "unstructured": {
- "encoding": "UTF-8"
- }
+{ + "self": { + "name": "PMSH_CL_INPUT", + "version": "1.0.0", + "description": "The input format of PM Subscription CL event." + }, + "dataformatversion": "1.0.0", + "jsonSchema": { + "name": "PM Subscription CL input", + "version": "1.0.0", + "properties": { + "name": { + "type": "string" + }, + "nameSpace": { + "type": "string" + }, + "source": { + "type": "string" + }, + "target": { + "type": "string" + }, + "version": { + "type": "string" + }, + "status": { + "type": "object", + "description": "The status response from the policy framework.", + "properties": { + "subscriptionName": { + "type": "string", + "description": "The unique name of the subscription object." + }, + "nfName": { + "type": "string", + "description": "The name of the nf in A&AI." + }, + "changeType": { + "type": "string", + "description": "This is the change type action that was undertaken to create/delete a PM subscription.", + "enum": [ + "CREATE", + "DELETE" + ] + }, + "message": { + "type": "string", + "description": "The return of the change type action status taken can be success or failure", + "enum": [ + "success", + "failure" + ] + } + }, + "required": [ + "subscriptionName", + "nfName", + "changeType", + "message" + ] + } + }, + "required": [ + "name", + "nameSpace", + "source", + "target", + "version", + "status" + ] + } }
\ No newline at end of file diff --git a/components/pm-subscription-handler/pmsh_service/mod/__init__.py b/components/pm-subscription-handler/pmsh_service/mod/__init__.py index 58cd8b3c..505add06 100644 --- a/components/pm-subscription-handler/pmsh_service/mod/__init__.py +++ b/components/pm-subscription-handler/pmsh_service/mod/__init__.py @@ -93,7 +93,7 @@ def get_db_connection_url(): pg_user_pass = os.getenv('PMSH_PG_PASSWORD') pmsh_db_name = os.getenv('PMSH_DB_NAME', 'pmsh') pmsh_db_port = os.getenv('PMSH_PG_PORT', '5432') - db_url = f'postgres+psycopg2://{quote(str(pg_user), safe="")}:' \ + db_url = f'postgresql+psycopg2://{quote(str(pg_user), safe="")}:' \ f'{quote(str(pg_user_pass), safe="")}@{pg_host}:{pmsh_db_port}/{pmsh_db_name}' if 'None' in db_url: raise Exception(f'Invalid DB connection URL: {db_url} .. exiting app!') diff --git a/components/pm-subscription-handler/pmsh_service/mod/pmsh_utils.py b/components/pm-subscription-handler/pmsh_service/mod/pmsh_utils.py index 7b91a307..a5fc86e6 100755 --- a/components/pm-subscription-handler/pmsh_service/mod/pmsh_utils.py +++ b/components/pm-subscription-handler/pmsh_service/mod/pmsh_utils.py @@ -128,10 +128,7 @@ class AppConfig: sub_data = self.subscription.__dict__ validate(instance=sub_data, schema=self.sub_schema) nf_filter = sub_data["nfFilter"] - for filter_name in nf_filter: - if len(nf_filter[filter_name]) > 0: - break - else: + if not [filter_name for filter_name, val in nf_filter.items() if len(val) > 0]: raise ValidationError("At least one filter within nfFilter must not be empty") logger.debug("Subscription schema is valid.") diff --git a/components/pm-subscription-handler/pmsh_service/mod/sub_schema.json b/components/pm-subscription-handler/pmsh_service/mod/sub_schema.json index 7a1da5bb..18d48174 100644 --- a/components/pm-subscription-handler/pmsh_service/mod/sub_schema.json +++ b/components/pm-subscription-handler/pmsh_service/mod/sub_schema.json @@ -51,11 +51,12 @@ } } }, - "required":[ - "nfNames", - "modelInvariantIDs", - "modelVersionIDs", - "modelNames" + "additionalProperties": false, + "anyOf": [ + {"required" : ["nfNames"]}, + {"required" : ["modelInvariantIDs"]}, + {"required" : ["modelVersionIDs"]}, + {"required" : ["modelNames"]} ] }, "measurementGroups":{ diff --git a/components/pm-subscription-handler/setup.py b/components/pm-subscription-handler/setup.py index c8d90783..6a2ef242 100644 --- a/components/pm-subscription-handler/setup.py +++ b/components/pm-subscription-handler/setup.py @@ -36,7 +36,7 @@ setup( "flask_sqlalchemy==2.4.1", "Flask==1.1.1", "swagger-ui-bundle==0.0.6", - "psycopg2-binary==2.8.4", + "psycopg2-binary==2.8.6", "onap_dcae_cbs_docker_client==2.1.1", "onappylog==1.0.9", "ruamel.yaml==0.16.10", diff --git a/components/pm-subscription-handler/tests/test_pmsh_utils.py b/components/pm-subscription-handler/tests/test_pmsh_utils.py index 1711e013..5aab65e1 100644 --- a/components/pm-subscription-handler/tests/test_pmsh_utils.py +++ b/components/pm-subscription-handler/tests/test_pmsh_utils.py @@ -120,7 +120,7 @@ class PmshUtilsTestCase(BaseClassSetup): self.env.set('PMSH_PG_USERNAME', 'pmsh') self.env.set('PMSH_PG_PASSWORD', 'pass') db_url = get_db_connection_url() - self.assertEqual(db_url, 'postgres+psycopg2://pmsh:pass@1.2.3.4:5432/pmsh') + self.assertEqual(db_url, 'postgresql+psycopg2://pmsh:pass@1.2.3.4:5432/pmsh') def test_get_db_connection_url_fail(self): self.env = EnvironmentVarGuard() @@ -165,6 +165,44 @@ class PmshUtilsTestCase(BaseClassSetup): with self.assertRaises(ValidationError): self.app_conf.validate_sub_schema() + def test_utils_validate_config_subscription_nfFilter_not_empty(self): + self.app_conf.subscription.nfFilter = { + "nfNames": [ + + ], + "modelInvariantIDs": [ + + ], + "modelVersionIDs": [ + + ], + "modelNames": [ + + ] + } + with self.assertRaises(ValidationError): + self.app_conf.validate_sub_schema() + + @patch('mod.logger.debug') + def test_utils_validate_config_subscription_nfFilter_with_empty_property(self, mock_logger): + self.app_conf.subscription.nfFilter = { + "nfNames": [ + "^pnf.*", + "^vnf.*" + ], + "modelInvariantIDs": [ + "7129e420-d396-4efb-af02-6b83499b12f8" + ], + "modelVersionIDs": [ + + ], + "modelNames": [ + "pnf102" + ] + } + self.app_conf.validate_sub_schema() + mock_logger.assert_called_with("Subscription schema is valid.") + def test_utils_validate_config_subscription_where_measurementTypes_is_empty(self): self.app_conf.subscription.measurementGroups = [{ "measurementGroup": { diff --git a/components/slice-analysis-ms/pom.xml b/components/slice-analysis-ms/pom.xml index 88e3dce4..e3485872 100644 --- a/components/slice-analysis-ms/pom.xml +++ b/components/slice-analysis-ms/pom.xml @@ -4,7 +4,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,12 @@ <artifactId>oparent</artifactId> <version>2.0.0</version> </parent> - <groupId>org.onap.dcaegen2.services.components</groupId> <artifactId>slice-analysis-ms</artifactId> - <version>1.0.3-SNAPSHOT</version> + <version>1.0.5-SNAPSHOT</version> <name>dcaegen2-services-slice-analysis-ms</name> <description>Network slice PM analyser</description> <packaging>jar</packaging> - <properties> <java.version>11</java.version> <sdk.version>1.1.4</sdk.version> @@ -53,9 +51,7 @@ <sonar.coverage.jacoco.xmlReportPaths> ${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml </sonar.coverage.jacoco.xmlReportPaths> - </properties> - <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-util --> <dependency> @@ -110,7 +106,6 @@ <artifactId>cbs-client</artifactId> <version>${sdk.version}</version> </dependency> - <dependency> <groupId>org.onap.dcaegen2.services.sdk.security.crypt</groupId> <artifactId>crypt-password</artifactId> @@ -198,11 +193,11 @@ <version>2.21.0</version> <scope>test</scope> </dependency> - <dependency> - <groupId>com.openpojo</groupId> - <artifactId>openpojo</artifactId> - <version>0.8.10</version> - </dependency> + <dependency> + <groupId>com.openpojo</groupId> + <artifactId>openpojo</artifactId> + <version>0.8.10</version> + </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> @@ -228,19 +223,16 @@ <version>2.0.2</version> <scope>test</scope> </dependency> - <dependency> <groupId>org.functionaljava</groupId> <artifactId>functionaljava</artifactId> <version>3.0</version> - </dependency> - - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>4.5.7</version> - </dependency> - + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.7</version> + </dependency> <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> <dependency> <groupId>commons-beanutils</groupId> @@ -276,11 +268,16 @@ <artifactId>tomcat-embed-core</artifactId> <version>9.0.36</version> </dependency> + <!-- https://mvnrepository.com/artifact/nl.jqno.equalsverifier/equalsverifier --> + <dependency> + <groupId>nl.jqno.equalsverifier</groupId> + <artifactId>equalsverifier</artifactId> + <version>3.5.5</version> + <scope>test</scope> + </dependency> </dependencies> - <build> <plugins> - <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> @@ -298,7 +295,6 @@ <artifactId>docker-maven-plugin</artifactId> <configuration> <serverId>${onap.nexus.dockerregistry.daily}</serverId> - <imageName>${onap.nexus.dockerregistry.daily}/${docker.image.name}</imageName> <imageTags> <imageTag>${project.version}-${maven.build.timestamp}Z</imageTag> @@ -334,5 +330,4 @@ </plugin> </plugins> </build> - </project> diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiInterface.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiInterface.java new file mode 100644 index 00000000..68b795b5 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiInterface.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.configdb; + +import java.util.Map; + +/** + * + * Interface for AAI + * + */ +public interface AaiInterface { + + public Map<String, String> fetchServiceDetails(String snssai); + public Map<String, Integer> fetchCurrentConfigurationOfSlice(String snssai); +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiService.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiService.java new file mode 100644 index 00000000..16ff71a6 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/AaiService.java @@ -0,0 +1,179 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.configdb; + +import java.util.HashMap; +import java.util.Map; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.slice.analysis.ms.models.Configuration; +import org.onap.slice.analysis.ms.restclients.AaiRestClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Service; + +/** + * + * Service for AAI interfaces + * + */ +@Service +public class AaiService implements AaiInterface { + + private static Logger log = LoggerFactory.getLogger(Configuration.class); + + @Autowired + AaiRestClient restclient; + private static String globalSubscriberId; + private static String subscriptionServiceType; + private static String aaiBaseUrl = Configuration.getInstance().getAaiUrl(); + + /** + * Fetches the details of a subscriber + */ + public Map<String, String> fetchServiceDetails(String snssai) { + log.info("AAI fetch service: "); + Map<String, String> responseMap = new HashMap<String, String>(); + + log.info("AAI getGlobalSubscriberId: "); + String subscriberReqUrl = aaiBaseUrl + "/business/customers"; + try { + String subscriberReq = restclient + .sendGetRequest(subscriberReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject subscriberReqJson = new JSONObject(subscriberReq); + JSONArray subscriberReqJsonList = subscriberReqJson.getJSONArray("customer"); + for (int i = 0; i < subscriberReqJsonList.length(); i++) { + JSONObject subscriberReqObj = subscriberReqJsonList.getJSONObject(i); + globalSubscriberId = subscriberReqObj.getString("global-customer-id"); + responseMap.put("globalSubscriberId", globalSubscriberId); + break; + } + } catch (Exception e) { + log.info("Exception while fetching getGlobalSubscriberId: " + e); + } + + String subscriptionServiceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + + "/service-subscriptions"; + try { + String subscriptionService = restclient + .sendGetRequest(subscriptionServiceReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject subscriptionServiceJson = new JSONObject(subscriptionService); + JSONArray subscriptionServiceListJson = subscriptionServiceJson.getJSONArray("service-subscription"); + for (int i = 0; i < subscriptionServiceListJson.length(); i++) { + JSONObject subscriptionServiceObj = subscriptionServiceListJson.getJSONObject(i); + subscriptionServiceType = subscriptionServiceObj.getString("service-type"); + responseMap.put("subscriptionServiceType", subscriptionServiceType); + break; + } + } catch (Exception e) { + log.info("Exception while fetching subscriptionService: " + e); + } + + String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + + "/service-subscriptions/service-subscription/" + subscriptionServiceType + "/service-instances"; + String serviceRole = "AN-NF"; + try { + String serviceInstance = restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject serviceInstanceJson = new JSONObject(serviceInstance); + JSONArray serviceInstanceList = serviceInstanceJson.getJSONArray("service-instance"); + for (int i = 0; i < serviceInstanceList.length(); i++) { + JSONObject serviceObj = serviceInstanceList.getJSONObject(i); + if (serviceObj.getString("environment-context").equalsIgnoreCase(snssai)) { + responseMap.put("sliceProfileId", serviceObj.getString("service-instance-id")); + } + } + + String serviceRoleReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + + "/service-subscriptions/service-subscription/" + subscriptionServiceType + + "/service-instances/?service-role=nssi&depth=2"; + + String serviceInstanceForServiceRole = restclient + .sendGetRequest(serviceRoleReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject serviceInstanceForServiceRoleJson = new JSONObject(serviceInstanceForServiceRole); + JSONArray serviceInstanceListForServiceRole = serviceInstanceForServiceRoleJson + .getJSONArray("service-instance"); + for (int i = 0; i < serviceInstanceListForServiceRole.length(); i++) { + JSONObject serviceObj = serviceInstanceListForServiceRole.getJSONObject(i); + if (serviceObj.getString("workload-context").trim().equalsIgnoreCase(serviceRole)) { + responseMap.put("ranNFNSSIId", serviceObj.getString("service-instance-id")); + } + } + } catch (Exception e) { + log.info("Exception while fetching serviceDetails: " + e); + } + responseMap.put("sNSSAI", snssai); + log.info("subscriber details: " + responseMap); + return responseMap; + } + + /** + * Fetches the current configuration of an Slice from AAI + */ + public Map<String, Integer> fetchCurrentConfigurationOfSlice(String snssai) { + log.info("AAI fetch config Slice: " + aaiBaseUrl); + String serviceInstaneId = null; + String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + + "/service-subscriptions/service-subscription/" + subscriptionServiceType + "/service-instances"; + Map<String, Integer> responseMap = new HashMap<String, Integer>(); + try { + String serviceInstance = restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject serviceInstanceJson = new JSONObject(serviceInstance); + + JSONArray serviceInstanceList = serviceInstanceJson.getJSONArray("service-instance"); + for (int i = 0; i < serviceInstanceList.length(); i++) { + JSONObject serviceObj = serviceInstanceList.getJSONObject(i); + if (serviceObj.getString("environment-context").equalsIgnoreCase(snssai)) { + serviceInstaneId = serviceObj.getString("service-instance-id"); + } + } + + String sliceProfileReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + + "/service-subscriptions/service-subscription/" + subscriptionServiceType + + "/service-instances/service-instance/" + serviceInstaneId + "/slice-profiles"; + + String sliceProfile = restclient + .sendGetRequest(sliceProfileReqUrl, new ParameterizedTypeReference<String>() { + }).getBody(); + JSONObject sliceProfileJson = new JSONObject(sliceProfile); + JSONArray sliceProfileList = sliceProfileJson.getJSONArray("slice-profile"); + for (int i = 0; i < sliceProfileList.length(); i++) { + JSONObject sliceProfileObj = sliceProfileList.getJSONObject(i); + responseMap.put("dLThptPerSlice", sliceProfileObj.getInt("exp-data-rate-UL")); + responseMap.put("uLThptPerSlice", sliceProfileObj.getInt("exp-data-rate-DL")); + break; + } + log.info("Slice configuration: " + responseMap); + } catch (Exception e) { + log.info("AAI Slice: " + e); + } + return responseMap; + } +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceService.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceService.java index 8a11bdb5..5798a40f 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceService.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceService.java @@ -113,3 +113,4 @@ public class ConfigDbInterfaceService implements IConfigDbService { } } + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsInterface.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsInterface.java new file mode 100644 index 00000000..ef6211c4 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsInterface.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.configdb; + +import java.util.List; +import java.util.Map; + +/** + * + * Interface for CPS + * + */ +public interface CpsInterface { + + public Map<String, List<String>> fetchRICsOfSnssai(String snssai); + public List<String> fetchNetworkFunctionsOfSnssai(String snssai); + public Map<String, Map<String,Object>> fetchCurrentConfigurationOfRIC(String snssai); + +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsService.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsService.java new file mode 100644 index 00000000..f72c99c2 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/CpsService.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.configdb; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.slice.analysis.ms.models.Configuration; +import org.onap.slice.analysis.ms.restclients.CpsRestClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * + * Service for CPS interfaces + * + */ +@Service +public class CpsService implements CpsInterface { + + private static Logger log = LoggerFactory.getLogger(CpsService.class); + + @Autowired + CpsRestClient restclient; + private static String cpsBaseUrl = Configuration.getInstance().getCpsUrl(); + + /** + * Fetches the current configuration of RIC from CPS + */ + public Map<String, Map<String, Object>> fetchCurrentConfigurationOfRIC(String snssai) { + return null; + } + + /** + * Fetches all the network functions of an S-NSSAI from CPS + */ + public List<String> fetchNetworkFunctionsOfSnssai(String snssai) { + return null; + } + + /** + * Fetches the RICS of an S-NSSAI from CPS + */ + public Map<String, List<String>> fetchRICsOfSnssai(String snssai) { + return null; + } + +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/IConfigDbService.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/IConfigDbService.java index 7413c181..2b92b091 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/IConfigDbService.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/configdb/IConfigDbService.java @@ -37,3 +37,4 @@ public interface IConfigDbService { public Map<String, Map<String,Object>> fetchCurrentConfigurationOfRIC(String snssai); public Map<String ,String> fetchServiceDetails(String snssai); } + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/models/Configuration.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/models/Configuration.java index 91a07d4f..60f52f0f 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/models/Configuration.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/models/Configuration.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package org.onap.slice.analysis.ms.models; import java.lang.reflect.Type; import java.util.List; import java.util.Map; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +34,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; -/** +/** * Model class for the application Configuration */ public class Configuration { @@ -46,6 +47,9 @@ public class Configuration { private String pgPassword; private List<String> dmaapServers; private String configDbService; + private String cpsUrl; + private String aaiUrl; + private Boolean configDbEnabled; private String cg; private String cid; private int pollingInterval; @@ -57,221 +61,258 @@ public class Configuration { private int samples; private int minPercentageChange; private long initialDelaySeconds; + /** * Check if topic is secure. */ - public boolean isSecured() { - return (aafUsername != null); + public boolean isSecured() { + return (aafUsername != null); - } + } - public String getAafUsername() { - return aafUsername; - } + public String getAafUsername() { + return aafUsername; + } - public void setAafUsername(String aafUsername) { - this.aafUsername = aafUsername; - } + public void setAafUsername(String aafUsername) { + this.aafUsername = aafUsername; + } - public String getAafPassword() { - return aafPassword; - } + public String getAafPassword() { + return aafPassword; + } - public void setAafPassword(String aafPassword) { - this.aafPassword = aafPassword; - } + public void setAafPassword(String aafPassword) { + this.aafPassword = aafPassword; + } - public Map<String, Object> getStreamsSubscribes() { - return streamsSubscribes; - } + public Map<String, Object> getStreamsSubscribes() { + return streamsSubscribes; + } - public void setStreamsSubscribes(Map<String, Object> streamsSubscribes) { - this.streamsSubscribes = streamsSubscribes; - } + public void setStreamsSubscribes(Map<String, Object> streamsSubscribes) { + this.streamsSubscribes = streamsSubscribes; + } - public Map<String, Object> getStreamsPublishes() { - return streamsPublishes; - } + public Map<String, Object> getStreamsPublishes() { + return streamsPublishes; + } - public void setStreamsPublishes(Map<String, Object> streamsPublishes) { - this.streamsPublishes = streamsPublishes; - } + public void setStreamsPublishes(Map<String, Object> streamsPublishes) { + this.streamsPublishes = streamsPublishes; + } - protected Configuration() { + protected Configuration() { - } + } - /** - * Get instance of class. - */ - public static Configuration getInstance() { - if (instance == null) { - instance = new Configuration(); - } - return instance; - } + /** + * Get instance of class. + */ + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); + } + return instance; + } - public String getCg() { - return cg; - } + public String getCg() { + return cg; + } - public void setCg(String cg) { - this.cg = cg; - } + public void setCg(String cg) { + this.cg = cg; + } - public String getCid() { - return cid; - } - - public void setCid(String cid) { - this.cid = cid; - } - - public int getPollingInterval() { - return pollingInterval; - } - - public void setPollingInterval(int pollingInterval) { - this.pollingInterval = pollingInterval; - } + public String getCid() { + return cid; + } - public int getPollingTimeout() { - return pollingTimeout; - } + public void setCid(String cid) { + this.cid = cid; + } - public void setPollingTimeout(int pollingTimeout) { - this.pollingTimeout = pollingTimeout; - } + public int getPollingInterval() { + return pollingInterval; + } - public String getPgHost() { - return pgHost; - } + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } - public void setPgHost(String pgHost) { - this.pgHost = pgHost; - } + public int getPollingTimeout() { + return pollingTimeout; + } - public int getPgPort() { - return pgPort; - } + public void setPollingTimeout(int pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + public String getPgHost() { + return pgHost; + } + + public void setPgHost(String pgHost) { + this.pgHost = pgHost; + } + + public int getPgPort() { + return pgPort; + } + + public void setPgPort(int pgPort) { + this.pgPort = pgPort; + } + + public String getPgUsername() { + return pgUsername; + } + + public void setPgUsername(String pgUsername) { + this.pgUsername = pgUsername; + } + + public String getPgPassword() { + return pgPassword; + } + + public void setPgPassword(String pgPassword) { + this.pgPassword = pgPassword; + } + + public List<String> getDmaapServers() { + return dmaapServers; + } + + public void setDmaapServers(List<String> dmaapServers) { + this.dmaapServers = dmaapServers; + } + + public String getConfigDbService() { + return configDbService; + } + + public void setConfigDbService(String configDbService) { + this.configDbService = configDbService; + } + + public String getCpsUrl() { + return cpsUrl; + } + + public void setCpsUrl(String cpsUrl) { + this.cpsUrl = cpsUrl; + } + + public String getAaiUrl() { + return aaiUrl; + } + + public void setAaiUrl(String aaiUrl) { + this.aaiUrl = aaiUrl; + } + + public Boolean getConfigDbEnabled() { + return configDbEnabled; + } + + public void setConfigDbEnabled(Boolean configDbEnabled) { + this.configDbEnabled = configDbEnabled; + } + + public int getSamples() { + return samples; + } + + public void setSamples(int samples) { + this.samples = samples; + } + + public int getMinPercentageChange() { + return minPercentageChange; + } + + public void setMinPercentageChange(int minPercentageChange) { + this.minPercentageChange = minPercentageChange; + } + + public long getInitialDelaySeconds() { + return initialDelaySeconds; + } + + public void setInitialDelaySeconds(long initialDelaySeconds) { + this.initialDelaySeconds = initialDelaySeconds; + } + + @Override + public String toString() { + return "Configuration [pgHost=" + pgHost + ", pgPort=" + pgPort + ", pgUsername=" + pgUsername + ", pgPassword=" + + pgPassword + ", dmaapServers=" + dmaapServers + ", configDbService=" + configDbService + ", cpsUrl=" + + cpsUrl + ", aaiUrl=" + aaiUrl + ", configDbEnabled=" + configDbEnabled + ", cg=" + cg + ", cid=" + cid + ", pollingInterval=" + pollingInterval + ", pollingTimeout=" + + pollingTimeout + ", aafUsername=" + aafUsername + ", aafPassword=" + aafPassword + + ", streamsSubscribes=" + streamsSubscribes + ", streamsPublishes=" + streamsPublishes + ", samples=" + + samples + ", minPercentageChange=" + minPercentageChange + ", initialDelaySeconds=" + + initialDelaySeconds + "]"; + } - public void setPgPort(int pgPort) { - this.pgPort = pgPort; - } - - public String getPgUsername() { - return pgUsername; - } - - public void setPgUsername(String pgUsername) { - this.pgUsername = pgUsername; - } - - public String getPgPassword() { - return pgPassword; - } - - public void setPgPassword(String pgPassword) { - this.pgPassword = pgPassword; - } - - public List<String> getDmaapServers() { - return dmaapServers; - } - - public void setDmaapServers(List<String> dmaapServers) { - this.dmaapServers = dmaapServers; - } - - public String getConfigDbService() { - return configDbService; - } - - public void setConfigDbService(String configDbService) { - this.configDbService = configDbService; - } - - public int getSamples() { - return samples; - } - - public void setSamples(int samples) { - this.samples = samples; - } - - public int getMinPercentageChange() { - return minPercentageChange; - } - - public void setMinPercentageChange(int minPercentageChange) { - this.minPercentageChange = minPercentageChange; - } - - public long getInitialDelaySeconds() { - return initialDelaySeconds; - } - - public void setInitialDelaySeconds(long initialDelaySeconds) { - this.initialDelaySeconds = initialDelaySeconds; - } - - @Override - public String toString() { - return "Configuration [pgHost=" + pgHost + ", pgPort=" + pgPort + ", pgUsername=" + pgUsername + ", pgPassword=" - + pgPassword + ", dmaapServers=" + dmaapServers + ", configDbService=" + configDbService + ", cg=" + cg - + ", cid=" + cid + ", pollingInterval=" + pollingInterval + ", pollingTimeout=" + pollingTimeout - + ", aafUsername=" + aafUsername + ", aafPassword=" + aafPassword + ", streamsSubscribes=" - + streamsSubscribes + ", streamsPublishes=" + streamsPublishes + ", samples=" + samples - + ", minPercentageChange=" + minPercentageChange + ", initialDelaySeconds=" + initialDelaySeconds + "]"; - } - - /** - * updates application configuration. - */ - public void updateConfigurationFromJsonObject(JsonObject jsonObject) { - - log.info("Updating configuration from CBS"); - - Type mapType = new TypeToken<Map<String, Object>>() { - }.getType(); - - JsonObject subscribes = jsonObject.getAsJsonObject("streams_subscribes"); - streamsSubscribes = new Gson().fromJson(subscribes, mapType); - - JsonObject publishes = jsonObject.getAsJsonObject("streams_publishes"); - streamsPublishes = new Gson().fromJson(publishes, mapType); - - pgPort = jsonObject.get("postgres.port").getAsInt(); - pollingInterval = jsonObject.get("sliceanalysisms.pollingInterval").getAsInt(); - pgPassword = jsonObject.get("postgres.password").getAsString(); - pgUsername = jsonObject.get("postgres.username").getAsString(); - pgHost = jsonObject.get("postgres.host").getAsString(); - - JsonArray servers = jsonObject.getAsJsonArray("sliceanalysisms.dmaap.server"); - Type listType = new TypeToken<List<String>>() {}.getType(); - dmaapServers = new Gson().fromJson(servers, listType); - - cg = jsonObject.get("sliceanalysisms.cg").getAsString(); - cid = jsonObject.get("sliceanalysisms.cid").getAsString(); - configDbService = jsonObject.get("sliceanalysisms.configDb.service").getAsString(); - - pollingTimeout = jsonObject.get("sliceanalysisms.pollingTimeout").getAsInt(); - samples = jsonObject.get("sliceanalysisms.samples").getAsInt(); - minPercentageChange = jsonObject.get("sliceanalysisms.minPercentageChange").getAsInt(); - initialDelaySeconds = jsonObject.get("sliceanalysisms.initialDelaySeconds").getAsLong(); - - if(jsonObject.get("aafUsername") == null) { - aafUsername = null; - } - else { - aafUsername = jsonObject.get("aafUsername").getAsString(); - } - if(jsonObject.get("aafPassword") == null) { - aafPassword = null; - } - else { - aafPassword = jsonObject.get("aafPassword").getAsString(); - } - log.info("configuration from CBS {}", this); - } + /** + * updates application configuration. + */ + public void updateConfigurationFromJsonObject(JsonObject jsonObject) { + + log.info("Updating configuration from CBS"); + + Type mapType = new TypeToken<Map<String, Object>>() { + }.getType(); + + JsonObject subscribes = jsonObject.getAsJsonObject("streams_subscribes"); + streamsSubscribes = new Gson().fromJson(subscribes, mapType); + + JsonObject publishes = jsonObject.getAsJsonObject("streams_publishes"); + streamsPublishes = new Gson().fromJson(publishes, mapType); + + pgPort = jsonObject.get("postgres.port").getAsInt(); + pollingInterval = jsonObject.get("sliceanalysisms.pollingInterval").getAsInt(); + pgPassword = jsonObject.get("postgres.password").getAsString(); + pgUsername = jsonObject.get("postgres.username").getAsString(); + pgHost = jsonObject.get("postgres.host").getAsString(); + + JsonArray servers = jsonObject.getAsJsonArray("sliceanalysisms.dmaap.server"); + Type listType = new TypeToken<List<String>>() { + }.getType(); + dmaapServers = new Gson().fromJson(servers, listType); + + cg = jsonObject.get("sliceanalysisms.cg").getAsString(); + cid = jsonObject.get("sliceanalysisms.cid").getAsString(); + configDbService = jsonObject.get("sliceanalysisms.configDb.service").getAsString(); + configDbEnabled = jsonObject.get("sliceanalysisms.configDbEnabled").getAsBoolean(); + + pollingTimeout = jsonObject.get("sliceanalysisms.pollingTimeout").getAsInt(); + samples = jsonObject.get("sliceanalysisms.samples").getAsInt(); + minPercentageChange = jsonObject.get("sliceanalysisms.minPercentageChange").getAsInt(); + initialDelaySeconds = jsonObject.get("sliceanalysisms.initialDelaySeconds").getAsLong(); + + if (Objects.isNull(jsonObject.get("aafUsername"))) { + aafUsername = null; + } else { + aafUsername = jsonObject.get("aafUsername").getAsString(); + } + if (Objects.isNull(jsonObject.get("aafPassword"))) { + aafPassword = null; + } else { + aafPassword = jsonObject.get("aafPassword").getAsString(); + } + if (Objects.isNull(jsonObject.get("sliceanalysisms.aai.url"))) { + aaiUrl = null; + } else { + aaiUrl = jsonObject.get("sliceanalysisms.aai.url").getAsString(); + } + if (Objects.isNull(jsonObject.get("sliceanalysisms.cps.url"))) { + cpsUrl = null; + } else { + cpsUrl = jsonObject.get("sliceanalysisms.cps.url").getAsString(); + } + log.info("configuration from CBS {}", this); + } } + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/AaiRestClient.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/AaiRestClient.java new file mode 100644 index 00000000..62e39ad5 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/AaiRestClient.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.restclients; + +import java.util.Collections; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * This class represents rest client for AAI interfaces + */ +@Component +public class AaiRestClient extends RestClient { + + public AaiRestClient() { + super(); + } + + public <T> ResponseEntity<T> sendPostRequest(String requestUrl, String requestBody, + ParameterizedTypeReference<T> responseType) { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + return super.sendPostRequest(headers, requestUrl, requestBody, responseType); + } + + public <T> ResponseEntity<T> sendGetRequest(String requestUrl, ParameterizedTypeReference<T> responseType) { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("X-FromAppId", "AAI"); + headers.set("X-TransactionId", "get_aai_subscr"); + return super.sendGetRequest(headers, requestUrl, responseType); + } +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/CpsRestClient.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/CpsRestClient.java new file mode 100644 index 00000000..1d6e2388 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/CpsRestClient.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.restclients; + +import java.util.Collections; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * This class represents rest client for CPS interfaces + */ +@Component +public class CpsRestClient extends RestClient { + + public CpsRestClient() { + super(); + } + + /** + * Send Post Request to CPS + */ + + public <T> ResponseEntity<T> sendPostRequest(String requestUrl, String requestBody, + ParameterizedTypeReference<T> responseType) { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + return super.sendPostRequest(headers, requestUrl, requestBody, responseType); + } + + /** + * Send Get Request to CPS + */ + + public <T> ResponseEntity<T> sendGetRequest(String requestUrl, ParameterizedTypeReference<T> responseType) { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + return super.sendGetRequest(headers, requestUrl, responseType); + } +} + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/RestClient.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/RestClient.java index 65de9838..3be3fc65 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/RestClient.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/restclients/RestClient.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,22 @@ package org.onap.slice.analysis.ms.restclients; +import java.security.KeyStoreException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +import javax.net.ssl.SSLContext; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.ssl.SSLContexts; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; @@ -29,20 +45,22 @@ 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.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; -/** - * This class is for base rest client +/** + * This class is for base rest client */ @Component public class RestClient { private static final String EXCEPTION_MSG = "Exception caught during request {}"; private static final Logger log = org.slf4j.LoggerFactory.getLogger(RestClient.class); - + @Autowired private RestTemplate restTemplate; + protected RestClient() { } @@ -66,15 +84,37 @@ public class RestClient { * Get Request Template. */ - public <T> ResponseEntity<T> sendGetRequest(HttpHeaders headers, String requestUrl, ParameterizedTypeReference<T> responseType) { + public <T> ResponseEntity<T> sendGetRequest(HttpHeaders headers, String requestUrl, + ParameterizedTypeReference<T> responseType) { HttpEntity<Void> requestEntity = new HttpEntity<>(headers); try { + RestTemplate restTemplate = new RestTemplate(useApacheHttpClientWithSelfSignedSupport()); return restTemplate.exchange(requestUrl, HttpMethod.GET, requestEntity, responseType); } catch (Exception e) { - log.debug(EXCEPTION_MSG, e.getMessage()); + log.info(EXCEPTION_MSG, e.getMessage()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } + private static HttpComponentsClientHttpRequestFactory useApacheHttpClientWithSelfSignedSupport() { + + TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; + SSLContext sslContext = null; + try { + sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + log.error(EXCEPTION_MSG, e); + } + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build(); + BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager( + socketFactoryRegistry); + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf) + .setConnectionManager(connectionManager).build(); + HttpComponentsClientHttpRequestFactory useApacheHttpClient = new HttpComponentsClientHttpRequestFactory(); + useApacheHttpClient.setHttpClient(httpClient); + return useApacheHttpClient; + } } diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/MLMessageProcessor.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/MLMessageProcessor.java index 84ff3715..b67d3507 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/MLMessageProcessor.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/MLMessageProcessor.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,13 @@ package org.onap.slice.analysis.ms.service; import java.util.List; import java.util.Map; +import java.util.Objects; +import org.onap.slice.analysis.ms.configdb.AaiInterface; +import org.onap.slice.analysis.ms.configdb.CpsInterface; import org.onap.slice.analysis.ms.configdb.IConfigDbService; import org.onap.slice.analysis.ms.models.CUModel; +import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.models.MLOutputModel; import org.onap.slice.analysis.ms.models.policy.AdditionalProperties; import org.slf4j.Logger; @@ -41,28 +45,50 @@ import org.springframework.stereotype.Component; @Scope("prototype") public class MLMessageProcessor { private static Logger log = LoggerFactory.getLogger(MLMessageProcessor.class); - + @Autowired private IConfigDbService configDbService; - + @Autowired private PolicyService policyService; - + + @Autowired + private AaiInterface aaiInterface; + + @Autowired + private CpsInterface cpsInterface; + public void processMLMsg(MLOutputModel mlOutputMsg) { + Boolean isConfigDbEnabled = (Objects.isNull(Configuration.getInstance().getConfigDbEnabled())) ? true + : Configuration.getInstance().getConfigDbEnabled(); + Map<String, List<String>> ricToCellMapping = null; + Map<String, String> serviceDetails = null; String snssai = mlOutputMsg.getSnssai(); List<CUModel> cuData = mlOutputMsg.getData(); - Map<String, List<String>> ricToCellMapping = configDbService.fetchRICsOfSnssai(snssai); - log.debug("RIC to cell mapping of S-NSSAI {} is {}",snssai,ricToCellMapping); - for(CUModel cuModel: cuData) { + if (isConfigDbEnabled) { + ricToCellMapping = configDbService.fetchRICsOfSnssai(snssai); + } else { + ricToCellMapping = cpsInterface.fetchRICsOfSnssai(snssai); + } + log.debug("RIC to cell mapping of S-NSSAI {} is {}", snssai, ricToCellMapping); + for (CUModel cuModel : cuData) { String cellId = String.valueOf(cuModel.getCellCUList().get(0).getCellLocalId()); ricToCellMapping.forEach((ricId, cells) -> { - if(cells.contains(cellId)) { + if (cells.contains(cellId)) { cuModel.setNearRTRICId(ricId); } }); } AdditionalProperties<MLOutputModel> addProps = new AdditionalProperties<>(); addProps.setResourceConfig(mlOutputMsg); - policyService.sendOnsetMessageToPolicy(snssai, addProps, configDbService.fetchServiceDetails(snssai)); + + if (isConfigDbEnabled) { + serviceDetails = configDbService.fetchServiceDetails(snssai); + } else { + serviceDetails = aaiInterface.fetchServiceDetails(snssai); + + } + policyService.sendOnsetMessageToPolicy(snssai, addProps, serviceDetails); } } + diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessor.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessor.java index e8d5de3e..0c5c0eb8 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessor.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessor.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,12 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import javax.annotation.PostConstruct; +import org.onap.slice.analysis.ms.configdb.AaiInterface; +import org.onap.slice.analysis.ms.configdb.CpsInterface; import org.onap.slice.analysis.ms.configdb.IConfigDbService; import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.models.MeasurementObject; @@ -39,7 +42,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -/** +/** * This class process the measurement data of an S-NSSAI */ @Component @@ -49,25 +52,31 @@ public class SnssaiSamplesProcessor { @Autowired private PolicyService policyService; - + @Autowired private IConfigDbService configDbService; - + @Autowired private PmDataQueue pmDataQueue; - + @Autowired private AverageCalculator averageCalculator; - + + @Autowired + private AaiInterface aaiInterface; + + @Autowired + private CpsInterface cpsInterface; + private List<MeasurementObject> snssaiMeasurementList = new ArrayList<>(); private Map<String, List<String>> ricToCellMapping = new HashMap<>(); private Map<String, Map<String, Integer>> ricToPrbsMapping = new HashMap<>(); private Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); private int noOfSamples; - private List<String> pmsToCompute; - private Map<String, String> prbThroughputMapping = new HashMap<>(); + private List<String> pmsToCompute; + private Map<String, String> prbThroughputMapping = new HashMap<>(); private int minPercentageChange; - + @PostConstruct public void init() { Configuration configuration = Configuration.getInstance(); @@ -84,27 +93,39 @@ public class SnssaiSamplesProcessor { /** * process the measurement data of an S-NSSAI */ - public boolean processSamplesOfSnnsai(String snssai, List<String> networkFunctions) { + public boolean processSamplesOfSnnsai(String snssai, List<String> networkFunctions) { + Boolean isConfigDbEnabled = (Objects.isNull(Configuration.getInstance().getConfigDbEnabled())) ? true + : Configuration.getInstance().getConfigDbEnabled(); List<MeasurementObject> sample = null; List<List<MeasurementObject>> samples = null; + Map<String, String> serviceDetails =null; log.info("Network Functions {} of snssai {}", networkFunctions, snssai); - for(String nf : networkFunctions) { + for (String nf : networkFunctions) { log.debug("Average of samples for {}:", snssai); samples = pmDataQueue.getSamplesFromQueue(new SubCounter(nf, snssai), noOfSamples); - if(samples != null) { + if (samples != null) { sample = averageCalculator.findAverageOfSamples(samples); addToMeasurementList(sample); - } - else { + } else { log.info("Not enough samples present for nf {}", nf); return false; } - } + } log.info("snssai measurement list {}", snssaiMeasurementList); - ricToCellMapping = configDbService.fetchRICsOfSnssai(snssai); + Map<String, Map<String, Object>> ricConfiguration; + Map<String, Integer> sliceConfiguration; + if (isConfigDbEnabled) { + ricToCellMapping = configDbService.fetchRICsOfSnssai(snssai); + ricConfiguration = configDbService.fetchCurrentConfigurationOfRIC(snssai); + sliceConfiguration = configDbService.fetchCurrentConfigurationOfSlice(snssai); + serviceDetails = configDbService.fetchServiceDetails(snssai); + } else { + ricToCellMapping = cpsInterface.fetchRICsOfSnssai(snssai); + ricConfiguration = cpsInterface.fetchCurrentConfigurationOfRIC(snssai); + sliceConfiguration = aaiInterface.fetchCurrentConfigurationOfSlice(snssai); + serviceDetails = aaiInterface.fetchServiceDetails(snssai); + } log.info("RIC to Cell Mapping for {} S-NSSAI: {}", snssai, ricToCellMapping); - Map<String, Map<String, Object>> ricConfiguration = configDbService.fetchCurrentConfigurationOfRIC(snssai); - Map<String, Integer> sliceConfiguration = configDbService.fetchCurrentConfigurationOfSlice(snssai); log.info("RIC Configuration {} and Slice Configuration {}", ricConfiguration, sliceConfiguration); pmsToCompute.forEach(pm -> { log.debug("processing for pm {}", pm); @@ -113,11 +134,11 @@ public class SnssaiSamplesProcessor { computeThroughput(sliceConfiguration, sum, pm); calculatePercentageChange(ricConfiguration, prbThroughputMapping.get(pm)); }); - updateConfiguration(); - if(ricToThroughputMapping.size() > 0) { + updateConfiguration(); + if (ricToThroughputMapping.size() > 0) { AdditionalProperties<Map<String, Map<String, Integer>>> addProps = new AdditionalProperties<>(); addProps.setResourceConfig(ricToThroughputMapping); - policyService.sendOnsetMessageToPolicy(snssai, addProps, configDbService.fetchServiceDetails(snssai)); + policyService.sendOnsetMessageToPolicy(snssai, addProps, serviceDetails); } return true; } @@ -126,11 +147,11 @@ public class SnssaiSamplesProcessor { * process the measurement data of an S-NSSAI */ protected void updateConfiguration() { - Iterator<Map.Entry<String, Map<String,Integer>>> it = ricToThroughputMapping.entrySet().iterator(); - Map.Entry<String, Map<String,Integer>> entry = null; - while(it.hasNext()) { + Iterator<Map.Entry<String, Map<String, Integer>>> it = ricToThroughputMapping.entrySet().iterator(); + Map.Entry<String, Map<String, Integer>> entry = null; + while (it.hasNext()) { entry = it.next(); - if(entry.getValue().size() == 0) { + if (entry.getValue().size() == 0) { it.remove(); } } @@ -141,37 +162,36 @@ public class SnssaiSamplesProcessor { } /** - * Calculate the change in the configuration value and keep the configuration only if it is greater than a - * specific limit + * Calculate the change in the configuration value and keep the configuration + * only if it is greater than a specific limit */ protected void calculatePercentageChange(Map<String, Map<String, Object>> ricConfiguration, String pm) { - Iterator<Map.Entry<String, Map<String,Integer>>> it = ricToThroughputMapping.entrySet().iterator(); - Map.Entry<String, Map<String,Integer>> entry = null; + Iterator<Map.Entry<String, Map<String, Integer>>> it = ricToThroughputMapping.entrySet().iterator(); + Map.Entry<String, Map<String, Integer>> entry = null; float existing = 0; float change = 0; - while(it.hasNext()) { + while (it.hasNext()) { entry = it.next(); - existing = (float)((int)ricConfiguration.get(entry.getKey()).get(pm)); - change = ((Math.abs(entry.getValue().get(pm) - existing))/existing)*100; + existing = (float) ((int) ricConfiguration.get(entry.getKey()).get(pm)); + change = ((Math.abs(entry.getValue().get(pm) - existing)) / existing) * 100; if (change <= minPercentageChange) { ricToThroughputMapping.get(entry.getKey()).remove(pm); log.info("Removing pm data {} for RIC {}", pm, entry.getKey()); } } } - + protected void sumOfPrbsAcrossCells(String pmName) { - ricToCellMapping.forEach((ric,cells) -> { + ricToCellMapping.forEach((ric, cells) -> { int sumOfPrbs = 0; - for(String cell : cells) { + for (String cell : cells) { int index = MeasurementObject.findIndex(cell, snssaiMeasurementList); sumOfPrbs += snssaiMeasurementList.get(index).getPmData().get(pmName); } - if(ricToPrbsMapping.containsKey(ric)) { + if (ricToPrbsMapping.containsKey(ric)) { ricToPrbsMapping.get(ric).put(pmName, sumOfPrbs); - } - else { - Map<String, Integer> pmToPrbMapping = new HashMap<>(); + } else { + Map<String, Integer> pmToPrbMapping = new HashMap<>(); pmToPrbMapping.put(pmName, sumOfPrbs); ricToPrbsMapping.put(ric, pmToPrbMapping); } @@ -184,19 +204,19 @@ public class SnssaiSamplesProcessor { } protected void computeThroughput(Map<String, Integer> sliceConfiguration, int sum, String pm) { - Iterator<Map.Entry<String, Map<String,Integer>>> it = ricToPrbsMapping.entrySet().iterator(); - Map.Entry<String, Map<String,Integer>> entry = null; + Iterator<Map.Entry<String, Map<String, Integer>>> it = ricToPrbsMapping.entrySet().iterator(); + Map.Entry<String, Map<String, Integer>> entry = null; Map<String, Integer> throughtputMap = null; String ric = ""; int value = 0; - while(it.hasNext()) { + while (it.hasNext()) { entry = it.next(); ric = entry.getKey(); - value = Math.round(((float)entry.getValue().get(pm)/sum)*(float)sliceConfiguration.get(prbThroughputMapping.get(pm))); - if(ricToThroughputMapping.containsKey(ric)) { + value = Math.round(((float) entry.getValue().get(pm) / sum) + * (float) sliceConfiguration.get(prbThroughputMapping.get(pm))); + if (ricToThroughputMapping.containsKey(ric)) { ricToThroughputMapping.get(ric).put(prbThroughputMapping.get(pm), value); - } - else { + } else { throughtputMap = new HashMap<>(); throughtputMap.put(prbThroughputMapping.get(pm), value); ricToThroughputMapping.put(ric, throughtputMap); diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/AppConfig.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/AppConfig.java new file mode 100644 index 00000000..29d7d105 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/AppConfig.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class AppConfig { + + + + /** + * Rest Template bean. + */ + @Bean + public static RestTemplate initRestTemplateForPdfAsByteArrayAndSelfSignedHttps() { + RestTemplate restTemplate = new RestTemplate(useApacheHttpClientWithSelfSignedSupport()); + restTemplate.getMessageConverters().add(generateByteArrayHttpMessageConverter()); + return restTemplate; + } + + private static HttpComponentsClientHttpRequestFactory useApacheHttpClientWithSelfSignedSupport() { + CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()) + .build(); + HttpComponentsClientHttpRequestFactory useApacheHttpClient = new HttpComponentsClientHttpRequestFactory(); + useApacheHttpClient.setHttpClient(httpClient); + return useApacheHttpClient; + } + + private static ByteArrayHttpMessageConverter generateByteArrayHttpMessageConverter() { + ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); + + List<MediaType> supportedApplicationTypes = new ArrayList<>(); + supportedApplicationTypes.add(new MediaType("application", "pdf")); + byteArrayHttpMessageConverter.setSupportedMediaTypes(supportedApplicationTypes); + return byteArrayHttpMessageConverter; + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/AaiInterfaceServiceTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/AaiInterfaceServiceTest.java new file mode 100644 index 00000000..78607788 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/AaiInterfaceServiceTest.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.configdb; + +import static org.junit.Assert.assertEquals; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.onap.slice.analysis.ms.models.Configuration; +import org.onap.slice.analysis.ms.models.configdb.CellsModel; +import org.onap.slice.analysis.ms.models.configdb.NetworkFunctionModel; +import org.onap.slice.analysis.ms.restclients.AaiRestClient; +import org.onap.slice.analysis.ms.restclients.ConfigDbRestClient; +import org.onap.slice.analysis.ms.utils.BeanUtil; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(SpringRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PrepareForTest({ AaiService.class,Configuration.class }) +@SpringBootTest(classes = AaiInterfaceServiceTest.class) +public class AaiInterfaceServiceTest { + + Configuration configuration = Configuration.getInstance(); + + @InjectMocks + AaiService aaiService; + + @Mock + AaiRestClient restClient; + + @Test + public void fetchCurrentConfigurationOfSlice() { + configuration.setAaiUrl("http://aai:30233/aai/v21/business/customers/customer/"); + PowerMockito.mockStatic(AaiService.class); + PowerMockito.mockStatic(Configuration.class); + PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); + Map<String, Integer> responsemap = new HashMap<>(); + responsemap.put("dLThptPerSlice", 60); + responsemap.put("uLThptPerSlice", 54); + try { + String serviceInstance = new String( + Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); + + + } catch (Exception e) { + e.printStackTrace(); + + } + assertEquals(responsemap, aaiService.fetchCurrentConfigurationOfSlice("001-010000")); + } + + @Test + public void fetchServiceProfile() { + Map<String, String> responseMap = new HashMap<String, String>(); + responseMap.put("sNSSAI", "001-00110"); + responseMap.put("ranNFNSSIId", "4b889f2b-8ee4-4ec7-881f-5b1af8a74039"); + responseMap.put("sliceProfileId", "ab9af40f13f7219099333"); + responseMap.put("globalSubscriberId", "5GCustomer"); + responseMap.put("subscriptionServiceType", "5G"); + + try { + String serviceInstance = new String( + Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); + + } catch (Exception e) { + e.printStackTrace(); + + } + + assertEquals(responseMap, aaiService.fetchServiceDetails("001-00110")); + } +} + diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceServiceTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceServiceTest.java index 481fee6f..3cb0a3b7 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceServiceTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/configdb/ConfigDbInterfaceServiceTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,9 @@ public class ConfigDbInterfaceServiceTest { map.put("dLThptPerSlice", 45); map.put("uLThptPerSlice", 50); responsemap.put("1", map); + Mockito.when(restclient.sendGetRequest(Mockito.anyString(), Mockito.any())).thenReturn(new ResponseEntity<Object>(responsemap, HttpStatus.OK)); - assertEquals(responsemap, configdbservice.fetchCurrentConfigurationOfSlice("snssai")); + assertEquals(responsemap, configdbservice.fetchCurrentConfigurationOfRIC("snssai")); } @Test @@ -125,3 +126,4 @@ public class ConfigDbInterfaceServiceTest { assertEquals(responseMap, configdbservice.fetchServiceDetails("snssai")); } } + diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/HealthCheckTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/HealthCheckTest.java new file mode 100644 index 00000000..806eb752 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/HealthCheckTest.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.controller; +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +@RunWith(SpringRunner.class) +@SpringBootTest(classes=HealthCheck.class) +public class HealthCheckTest { + @Autowired + private HealthCheck healthcheck; + @Test + public void testHealthCheck() { + ResponseEntity<HttpStatus> response= new ResponseEntity<>(HttpStatus.OK); + assertEquals(response,healthcheck.healthCheck()); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/data/beans/PerformanceNotificationsTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/data/beans/PerformanceNotificationsTest.java index e8654003..e55fba74 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/data/beans/PerformanceNotificationsTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/data/beans/PerformanceNotificationsTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,26 +18,24 @@ * ============LICENSE_END========================================================= * *******************************************************************************/ - package org.onap.slice.analysis.ms.data.beans; - import static org.junit.Assert.*; - import java.sql.Timestamp; - import org.junit.Test; - public class PerformanceNotificationsTest { - private Timestamp createdAt; - - @Test - public void test() { - - PerformanceNotifications performanceNotifications = new PerformanceNotifications(); - performanceNotifications.setNotification("notification"); - performanceNotifications.setCreatedAt(createdAt); - assertEquals("notification", performanceNotifications.getNotification()); - assertEquals(createdAt, performanceNotifications.getCreatedAt()); } - + @Test + public void methodTest() { + PerformanceNotifications performanceNotifications = new PerformanceNotifications(); + performanceNotifications.setNotification("notification"); + performanceNotifications.setCreatedAt(createdAt); + assertEquals("notification", performanceNotifications.getNotification()); + assertEquals(createdAt, performanceNotifications.getCreatedAt()); + } + @Test + public void constructorTest(){ + PerformanceNotifications performanceNotification = new PerformanceNotifications("notifications",createdAt); + assertEquals("notifications", performanceNotification.getNotification()); + assertEquals(createdAt, performanceNotification.getCreatedAt()); +} } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigPolicyTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigPolicyTest.java index 2b137e3a..899ee0d8 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigPolicyTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigPolicyTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,26 +18,27 @@ * ============LICENSE_END========================================================= * *******************************************************************************/ - - package org.onap.slice.analysis.ms.models; - import static org.junit.Assert.assertEquals; - import java.util.HashMap; import java.util.Map; - import org.junit.Test; - - public class ConfigPolicyTest { - @Test public void configPolicyTest() { ConfigPolicy configPolicy = ConfigPolicy.getInstance(); - Map<String, Object> config = new HashMap<String, Object>(); + Map<String, Object> config = new HashMap<>(); config.put("policyName", "pcims_policy"); configPolicy.setConfig(config); assertEquals(config, configPolicy.getConfig()); } + @Test + public void toStringTest() { + ConfigPolicy configPolicy = ConfigPolicy.getInstance(); + Map<String, Object> config = new HashMap<String, Object>(); + config.put("policyName", "pcims_policy"); + configPolicy.setConfig(config); + String expected="ConfigPolicy [config={policyName=pcims_policy}]"; + assertEquals(expected,configPolicy.toString()); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigurationTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigurationTest.java index eb492800..ed583cad 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigurationTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ConfigurationTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,30 +18,20 @@ * ============LICENSE_END========================================================= * *******************************************************************************/ - - package org.onap.slice.analysis.ms.models; - import static org.junit.Assert.assertEquals; - import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collections; import java.util.List; import java.util.Map; - import org.junit.Test; - - public class ConfigurationTest { Configuration configuration = Configuration.getInstance(); - @Test public void configurationTest() { - List<String> list = new ArrayList<String>(); list.add("server"); - Map<String, Object> subscribes = new HashMap<>(); - + Map<String, Object> subscribes = Collections.emptyMap(); configuration.setStreamsSubscribes(subscribes); configuration.setStreamsPublishes(subscribes); configuration.setDmaapServers(list); @@ -56,18 +46,32 @@ public class ConfigurationTest { configuration.setPollingInterval(30); configuration.setPollingTimeout(100); configuration.setConfigDbService("sdnrService"); - - assertEquals("cg", configuration.getCg()); - assertEquals("cid", configuration.getCid()); + configuration.setCpsUrl(""); + configuration.setAaiUrl(""); + configuration.setConfigDbEnabled(true); + configuration.setSamples(10); + configuration.setMinPercentageChange(50); + configuration.setInitialDelaySeconds(1000); + assertEquals(true,configuration.isSecured()); assertEquals("user", configuration.getAafUsername()); assertEquals("password", configuration.getAafPassword()); - assertEquals("user", configuration.getPgUsername()); - assertEquals("password", configuration.getPgPassword()); - assertEquals("pg", configuration.getPgHost()); - assertEquals(5432, configuration.getPgPort()); + assertEquals(subscribes,configuration.getStreamsSubscribes()); + assertEquals(subscribes,configuration.getStreamsPublishes()); + assertEquals("cg", configuration.getCg()); + assertEquals("cid", configuration.getCid()); assertEquals(30, configuration.getPollingInterval()); assertEquals(100, configuration.getPollingTimeout()); - assertEquals("sdnrService", configuration.getConfigDbService()); + assertEquals("pg", configuration.getPgHost()); + assertEquals(5432, configuration.getPgPort()); + assertEquals("user", configuration.getPgUsername()); + assertEquals("password", configuration.getPgPassword()); assertEquals(list, configuration.getDmaapServers()); + assertEquals("sdnrService", configuration.getConfigDbService()); + assertEquals("",configuration.getCpsUrl()); + assertEquals("",configuration.getAaiUrl()); + assertEquals(true,configuration.getConfigDbEnabled()); + assertEquals(10,configuration.getSamples()); + assertEquals(50,configuration.getMinPercentageChange()); + assertEquals(1000,configuration.getInitialDelaySeconds()); } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/MLOutputModelTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/MLOutputModelTest.java new file mode 100644 index 00000000..4b656b83 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/MLOutputModelTest.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2021 Wipro Limited. + * ============================================================================== + * 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.slice.analysis.ms.models; +import static org.junit.Assert.assertEquals; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import nl.jqno.equalsverifier.EqualsVerifier; +@RunWith(SpringRunner.class) +@SpringBootTest(classes=MLOutputModelTest.class) +public class MLOutputModelTest { + @InjectMocks + private final MLOutputModel mlOutputModel =new MLOutputModel(); + @Test + public void mlOutputModelEqualHashcodeTest() { + EqualsVerifier.simple().forClass(MLOutputModel.class).verify(); + } + @Test + public void mlOutputModelMethodTest() { + List<CUModel> data = Collections.emptyList(); + mlOutputModel.setSnssai("message"); + mlOutputModel.setData(data); + assertEquals("message",mlOutputModel.getSnssai()); + assertEquals(data,mlOutputModel.getData()); + assertEquals("MLOutputModel [snssai=message, data=[]]",mlOutputModel.toString()); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ModelsTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ModelsTest.java index 582abdce..3150fb5c 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ModelsTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/ModelsTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,8 @@ * ============LICENSE_END========================================================= * *******************************************************************************/ - package org.onap.slice.analysis.ms.models; - import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.impl.PojoClassFactory; import com.openpojo.validation.Validator; @@ -32,10 +29,29 @@ import com.openpojo.validation.rule.impl.GetterMustExistRule; import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; - +import nl.jqno.equalsverifier.EqualsVerifier; public class ModelsTest { - - @Test + @Test + public void configDataEqualHashcodeTest() { + EqualsVerifier.simple().forClass(ConfigData.class).verify(); + } + @Test + public void cellCUListEqualHashcodeTest() { + EqualsVerifier.simple().forClass(CellCUList.class).verify(); + } + @Test + public void cuModelEqualHashcodeTest() { + EqualsVerifier.simple().forClass(CUModel.class).verify(); + } + @Test + public void subCounterEqualHashcodeTest() { + EqualsVerifier.simple().forClass(SubCounter.class).verify(); + } + @Test + public void measurementObjectEqualHashcodeTest() { + EqualsVerifier.simple().forClass(MeasurementObject.class).verify(); + } + @Test public void testGetterSetterSubCounter() { PojoClass pojoclass = PojoClassFactory.getPojoClass(SubCounter.class); Validator validator = ValidatorBuilder @@ -47,40 +63,29 @@ public class ModelsTest { .with(new EqualsAndHashCodeMatchRule()) .build(); validator.validate(pojoclass); - } - - @Test + } + @Test public void testGetterSetterMeasurementObject() { PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasurementObject.class); validateMd(pojoclass); } - - @Test + @Test public void testGetterSetterCellCUList() { PojoClass pojoclass = PojoClassFactory.getPojoClass(CellCUList.class); validateMd(pojoclass); } - - @Test + @Test public void testGetterSetterCUModel() { PojoClass pojoclass = PojoClassFactory.getPojoClass(CUModel.class); validateMd(pojoclass); } - - @Test + @Test public void testGetterSetterConfigData() { PojoClass pojoclass = PojoClassFactory.getPojoClass(ConfigData.class); validateMd(pojoclass); } - - @Test - public void testGetterSetterMLOutputModel() { - PojoClass pojoclass = PojoClassFactory.getPojoClass(MLOutputModel.class); - validateMd(pojoclass); - } - - public void validateMd(PojoClass pojoclass) { - Validator validator = ValidatorBuilder + public void validateMd(PojoClass pojoclass) { + Validator validator = ValidatorBuilder .create() .with(new SetterMustExistRule()) .with(new GetterMustExistRule()) @@ -88,5 +93,5 @@ public class ModelsTest { .with(new GetterTester()) .build(); validator.validate(pojoclass); - } + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/restclients/RestClientTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/restclients/RestClientTest.java index 95da3667..fe7407f8 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/restclients/RestClientTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/restclients/RestClientTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * slice-analysis-ms * ================================================================================ - * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2020-2021 Wipro Limited. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ *******************************************************************************/ package org.onap.slice.analysis.ms.restclients; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @@ -32,6 +31,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.onap.slice.analysis.ms.service.SnssaiSamplesProcessorTest; import org.onap.slice.analysis.ms.utils.BeanUtil; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -49,61 +49,60 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; - - @RunWith(SpringRunner.class) @SpringBootTest(classes = RestClientTest.class) public class RestClientTest { - + @Mock RestTemplate restTemplate; @InjectMocks RestClient restclient; - - @SuppressWarnings({ "static-access"}) + + @SuppressWarnings({ "static-access" }) @Test public void sendGetRequestTest() { - ParameterizedTypeReference<Map<String,Integer>> responseType = null; - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - headers.setContentType(MediaType.APPLICATION_JSON); + String requestUrl = ""; + ParameterizedTypeReference<String> responseType = null; + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Object> requestEntity = new HttpEntity<>( headers); - Map<String, Integer> responsemap=new HashMap<>(); - responsemap.put("dLThptPerSlice", 1); - responsemap.put("uLThptPerSlice", 2); - String requestUrl=""; - when(restTemplate.exchange(requestUrl, HttpMethod.GET,requestEntity,responseType)).thenReturn(ResponseEntity.ok(responsemap)); - ResponseEntity<Map<String,Integer>> resp = restclient.sendGetRequest(headers, requestUrl, responseType); - assertEquals(resp.getBody(),responsemap); + when(restTemplate.exchange(requestUrl, HttpMethod.GET, requestEntity, responseType)) + .thenReturn(new ResponseEntity(HttpStatus.NOT_FOUND)); + assertEquals(restclient.sendGetRequest(headers, requestUrl, responseType).getStatusCode(), HttpStatus.NOT_FOUND); } - + @SuppressWarnings({ "static-access", "unchecked", "rawtypes" }) @Test - public void sendPostRequestTest() { - ParameterizedTypeReference<String> responseType = null; - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - headers.setContentType(MediaType.APPLICATION_JSON); - String requestUrl = "Url"; String requestBody = null; - HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers); - when(restTemplate.exchange(requestUrl, HttpMethod.POST,requestEntity,responseType)).thenReturn(new ResponseEntity(HttpStatus.OK)); - ResponseEntity<String> resp = restclient.sendPostRequest(headers, requestUrl, requestBody,responseType); - assertEquals(resp.getStatusCode(), HttpStatus.OK); + public void sendPostRequestTest() { + ParameterizedTypeReference<String> responseType = null; + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + String requestUrl = "Url"; + String requestBody = null; + HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers); + when(restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity, responseType)) + .thenReturn(new ResponseEntity(HttpStatus.OK)); + ResponseEntity<String> resp = restclient.sendPostRequest(headers, requestUrl, requestBody, responseType); + assertEquals(resp.getStatusCode(), HttpStatus.OK); } - + @Test - public void sendPostRequestTest2() { - ParameterizedTypeReference<String> responseType = null; - HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - headers.setContentType(MediaType.APPLICATION_JSON); - String requestUrl = "Url"; String requestBody = null; - HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers); - when(restTemplate.exchange(requestUrl, HttpMethod.POST,requestEntity,responseType)).thenReturn(new ResponseEntity(HttpStatus.NOT_FOUND)); - ResponseEntity<String> resp = restclient.sendPostRequest(headers, requestUrl, requestBody,responseType); - assertEquals(resp.getStatusCode(), HttpStatus.NOT_FOUND); - } - - + public void sendPostRequestTest2() { + ParameterizedTypeReference<String> responseType = null; + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + String requestUrl = "Url"; + String requestBody = null; + HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers); + when(restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity, responseType)) + .thenReturn(new ResponseEntity(HttpStatus.NOT_FOUND)); + ResponseEntity<String> resp = restclient.sendPostRequest(headers, requestUrl, requestBody, responseType); + assertEquals(resp.getStatusCode(), HttpStatus.NOT_FOUND); + } + } + diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/MLMessageProcessorTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/MLMessageProcessorTest.java index d80160c9..6e0d1243 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/MLMessageProcessorTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/MLMessageProcessorTest.java @@ -37,6 +37,8 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.onap.slice.analysis.ms.configdb.IConfigDbService; +import org.onap.slice.analysis.ms.configdb.AaiService; +import org.onap.slice.analysis.ms.configdb.CpsService; import org.onap.slice.analysis.ms.models.MLOutputModel; import org.onap.slice.analysis.ms.models.policy.AdditionalProperties; import org.springframework.boot.test.context.SpringBootTest; @@ -55,7 +57,13 @@ public class MLMessageProcessorTest { @Mock private IConfigDbService configDbService; - + + @Mock + AaiService aaiService; + + @Mock + CpsService cpsService; + @Mock private PolicyService policyService; diff --git a/components/slice-analysis-ms/src/test/resources/aaiDetailsList.json b/components/slice-analysis-ms/src/test/resources/aaiDetailsList.json new file mode 100644 index 00000000..e538e220 --- /dev/null +++ b/components/slice-analysis-ms/src/test/resources/aaiDetailsList.json @@ -0,0 +1,273 @@ +{ + "service-instance":[ + { + "service-instance-id":"c77802fe-cc49-4874-b12c-03fc2d88b060", + "service-instance-name":"sliceprofile_01e56f6e-0481-4654-919f-476734ec8176", + "service-role":"slice-profile-instance", + "environment-context":"001-100001", + "workload-context":"TN-MH", + "service-instance-location-id":"[\"460-00\",\"460-01\"]", + "resource-version":"1613640076516", + "orchestration-status":"deactivated", + "service-function":"non-shared", + "relationship-list":{ + "relationship":[ + { + "related-to":"service-instance", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ab9af40f13f721b5f13539d87484098", + "relationship-data":[ + { + "relationship-key":"customer.global-customer-id", + "relationship-value":"5GCustomer" + }, + { + "relationship-key":"service-subscription.service-type", + "relationship-value":"5G" + }, + { + "relationship-key":"service-instance.service-instance-id", + "relationship-value":"ab9af40f13f721b5f13539d87484098" + } + ], + "related-to-property":[ + { + "property-key":"service-instance.service-instance-name", + "property-value":"an_sp_1" + } + ] + } + ] + } + }, + { + "service-instance-id":"ab9af40f13f7219099333", + "service-instance-name":"an_sp_1", + "service-type":"00-000", + "service-role":"slice-profile-instance", + "environment-context":"001-00110", + "workload-context":"ÁN-NF", + "service-instance-location-id":"[\"460-00\",\"460-01\"]", + "resource-version":"1613715676282", + "orchestration-status":"deactivated" + }, + { + "service-instance-id":"ab9af40f13f72176yh785", + "service-instance-name":"an_sp_1", + "service-type":"00-000", + "service-role":"slice-profile-instance", + "environment-context":"001-010000", + "workload-context":"AN-NF", + "service-instance-location-id":"[\"460-00\",\"460-01\"]", + "resource-version":"1613898735909", + "orchestration-status":"deactivated" + }, + { + "service-instance-id":"660ca85c-1a0f-4521-a559-65f23e794699", + "service-instance-name":"NSI", + "service-type":"00-001", + "service-role":"nsi", + "environment-context":"001-100001", + "workload-context":"nsi", + "resource-version":"1613666791709", + "orchestration-status":"deactivated", + "service-function":"non-shared", + "relationship-list":{ + "relationship":[ + { + "related-to":"service-instance", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/8e1bc208-e8d2-4010-8316-12469c600f1e", + "relationship-data":[ + { + "relationship-key":"customer.global-customer-id", + "relationship-value":"5GCustomer" + }, + { + "relationship-key":"service-subscription.service-type", + "relationship-value":"5G" + }, + { + "relationship-key":"service-instance.service-instance-id", + "relationship-value":"8e1bc208-e8d2-4010-8316-12469c600f1e" + } + ], + "related-to-property":[ + { + "property-key":"service-instance.service-instance-name", + "property-value":"TESTRANTOPNSST" + } + ] + } + ] + } + }, + { + "service-instance-id":"4b889f2b-8ee4-4ec7-881f-5b1af8a74039", + "service-instance-name":"TEST_RAN_NF_NSST", + "service-type":"00-000", + "service-role":"nssi", + "environment-context":"001-100001", + "workload-context":"AN-NF", + "model-invariant-id":"cc2ffa2f-722b-4ab1-a6cb-45258ebf0c7f", + "model-version-id":"ca22957d-3aa1-4c6e-ab70-666e678b8e02", + "service-instance-location-id":"[\"460-00\",\"460-01\"]", + "resource-version":"1613630576677", + "orchestration-status":"deactivated", + "service-function":"non-shared", + "relationship-list":{ + "relationship":[ + { + "related-to":"network-route", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/network/network-routes/network-route/835909aa-3163-41fe-b0aa-8964887132c9", + "relationship-data":[ + { + "relationship-key":"network-route.route-id", + "relationship-value":"835909aa-3163-41fe-b0aa-8964887132c9" + } + ] + }, + { + "related-to":"network-route", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/network/network-routes/network-route/7869350c-31c5-424b-8b0d-fb3d1f05857d", + "relationship-data":[ + { + "relationship-key":"network-route.route-id", + "relationship-value":"7869350c-31c5-424b-8b0d-fb3d1f05857d" + } + ] + }, + { + "related-to":"service-instance", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/8e1bc208-e8d2-4010-8316-12469c600f1e", + "relationship-data":[ + { + "relationship-key":"customer.global-customer-id", + "relationship-value":"5GCustomer" + }, + { + "relationship-key":"service-subscription.service-type", + "relationship-value":"5G" + }, + { + "relationship-key":"service-instance.service-instance-id", + "relationship-value":"8e1bc208-e8d2-4010-8316-12469c600f1e" + } + ], + "related-to-property":[ + { + "property-key":"service-instance.service-instance-name", + "property-value":"TESTRANTOPNSST" + } + ] + }, + { + "related-to":"network-route", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/network/network-routes/network-route/69d2251d-12fb-49c1-b68f-ffc6d1e4b903", + "relationship-data":[ + { + "relationship-key":"network-route.route-id", + "relationship-value":"69d2251d-12fb-49c1-b68f-ffc6d1e4b903" + } + ] + }, + { + "related-to":"network-route", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/network/network-routes/network-route/5568076c-0ecc-4ee7-b8cb-a2a94b3f57c5", + "relationship-data":[ + { + "relationship-key":"network-route.route-id", + "relationship-value":"5568076c-0ecc-4ee7-b8cb-a2a94b3f57c5" + } + ] + }, + { + "related-to":"service-instance", + "relationship-label":"org.onap.relationships.inventory.ComposedOf", + "related-link":"/aai/v21/business/customers/customer/5GCustomer/service-subscriptions/service-subscription/5G/service-instances/service-instance/ee81b1a6-6562-40e2-8235-122a92d651a7", + "relationship-data":[ + { + "relationship-key":"customer.global-customer-id", + "relationship-value":"5GCustomer" + }, + { + "relationship-key":"service-subscription.service-type", + "relationship-value":"5G" + }, + { + "relationship-key":"service-instance.service-instance-id", + "relationship-value":"ee81b1a6-6562-40e2-8235-122a92d651a7" + } + ], + "related-to-property":[ + { + "property-key":"service-instance.service-instance-name", + "property-value":"sliceprofile_002fcda5-ebff-4efc-b385-58d0b3f25f6f" + } + ] + } + ] + } + } + ], + "slice-profile":[ + { + "profile-id":"684hf846f-863b-4901-b202-0ahskn896", + "latency":30, + "max-number-of-UEs":200, + "coverage-area-TA-list":"[1, 2, 3, 4]", + "resource-sharing-level":"non-shared", + "exp-data-rate-UL":60, + "exp-data-rate-DL":54, + "resource-version":"1613898735909" + } + ], + "customer":[ + { + "global-customer-id":"5GCustomer", + "subscriber-name":"5GCustomer", + "subscriber-type":"INFRA", + "resource-version":"1610546339091" + } + ], + "service-subscription":[ + { + "service-type":"5G", + "resource-version":"1612775493653", + "relationship-list":{ + "relationship":[ + { + "related-to":"tenant", + "relationship-label":"org.onap.relationships.inventory.Uses", + "related-link":"/aai/v21/cloud-infrastructure/cloud-regions/cloud-region/k8scloudowner4/k8sregionfour/tenants/tenant/aaaa", + "relationship-data":[ + { + "relationship-key":"cloud-region.cloud-owner", + "relationship-value":"k8scloudowner4" + }, + { + "relationship-key":"cloud-region.cloud-region-id", + "relationship-value":"k8sregionfour" + }, + { + "relationship-key":"tenant.tenant-id", + "relationship-value":"aaaa" + } + ], + "related-to-property":[ + { + "property-key":"tenant.tenant-name", + "property-value":"k8stenant" + } + ] + } + ] + } + } + ] +} diff --git a/components/slice-analysis-ms/version.properties b/components/slice-analysis-ms/version.properties index 20c177b9..a2c346b8 100644 --- a/components/slice-analysis-ms/version.properties +++ b/components/slice-analysis-ms/version.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # slice-analysis-ms # ================================================================================ -# Copyright (C) 2020 Wipro Limited. +# Copyright (C) 2020-2021 Wipro Limited. # ============================================================================== # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ ############################################################################### major=1 minor=0 -patch=3 +patch=5 base_version=${major}.${minor}.${patch} release_version=${base_version} snapshot_version=${base_version}-SNAPSHOT |