From 76744e810f35c84ecbd1d9998e361052466e9483 Mon Sep 17 00:00:00 2001 From: "ravi.setti" Date: Thu, 20 Aug 2020 15:02:20 +0000 Subject: [PATCH] Development of NETCONF RPCs for tr-069 adapter to tr-069 adapter to support tr-069 compliant RPCs. Fixed code smell issues. Issue-Id: OAM-152 Signed-off-by: ravi.setti Change-Id: Ib9e0ed925a5c8602841a8b3ebdd009b93c187fc2 --- acs/application-booter/pom.xml | 19 + .../tr069adapter/acs/booter/ACSServiceBooter.java | 445 ++--- .../src/main/resources/schema-mariadb.sql | 5 +- .../cpe/deviceconnection/DeviceConnectTest.java | 233 +-- .../tr069adapter/acs/common/DeviceDetails.java | 3 +- .../tr069adapter/acs/common/DeviceInform.java | 3 +- .../tr069adapter/acs/common/OperationDetails.java | 3 +- .../tr069adapter/acs/common/OperationResponse.java | 3 +- .../tr069adapter/acs/common/ParameterDTO.java | 4 +- .../acs/common/dto/TR069DeviceDetails.java | 125 +- .../acs/common/exception/ACSException.java | 168 +- .../acs/common/inform/AbstractDeviceInform.java | 3 +- .../service/TR069DeviceEventHandler.java | 145 +- .../acs/common/utils/ConnectionStatusPOJO.java | 50 + .../tr069adapter/acs/cpe/CPEManagementService.java | 1163 ++++++------- .../commscope/tr069adapter/acs/cpe/TR069RPC.java | 869 +++++----- .../acs/cpe/builder/DeviceRPCBuilder.java | 354 ++-- .../acs/cpe/handler/ConnectionReqEventHandler.java | 2 + .../acs/cpe/handler/DeviceEventHandler.java | 849 +++++----- .../cpe/processor/ConnectionReqEventProcessor.java | 252 +-- .../commscope/tr069adapter/acs/cpe/rpc/Upload.java | 128 +- .../acs/nbi/impl/ACSServiceAPIImpl.java | 200 +-- .../acs/nbi/impl/DeviceInformForwarder.java | 107 +- .../acs/nbi/impl/DeviceRPCResponseForwarder.java | 105 +- .../mapper/service/MapperRequestRESTService.java | 154 +- .../TR069DeviceEventHandlerImpl.java | 450 ++--- .../custom/ConfigureMultipleObject.java | 1006 +++++------ .../requestprocessor/entity/TR069DeviceEntity.java | 305 ++-- .../handler/DeviceRPCRequestHandler.java | 137 +- .../helper/TR069RequestProcessEngineUtility.java | 345 ++-- .../acs/requestprocessor/impl/SessionManager.java | 267 +-- .../impl/TR069EventNotificationService.java | 194 +-- .../impl/TR069RequestProcessEngine.java | 1503 +++++++++-------- .../acs/requestprocessor/util/TR069NBIUtility.java | 158 +- .../util/TR069RequestProcessorUtility.java | 704 ++++---- .../common/deviceversion/DeviceVersion.java | 380 +++-- .../deviceversion/DeviceVersionManagerImpl.java | 376 ++--- config-data/pom.xml | 19 + .../controllers/ConfugurationDataController.java | 198 +-- .../config/model/ConfigFileContent.java | 195 +-- .../repository/ConfigurationDataRepository.java | 65 +- .../config/service/ConfigurationDataService.java | 479 +++--- .../tr069adapter/config/ConfigDataTestsUtils.java | 171 +- .../config/ConfugurationDataControllerTests.java | 228 ++- factory/pom.xml | 19 + mapper/pom.xml | 21 +- mapper/rpc_set_input.xml | 9 - .../mapper/MapperConfigProperties.java | 298 ++-- .../tr069adapter/mapper/acs/ACSRequestSender.java | 102 +- .../acs/impl/ACSNotificationHandlerImpl.java | 829 ++++----- .../mapper/acs/impl/PnPPreProvisioningHandler.java | 668 ++++---- .../mapper/boot/MapperServiceBooter.java | 92 +- .../mapper/entity/DeviceOperationDetails.java | 156 +- .../mapper/model/NetConfNotificationDTO.java | 6 +- .../tr069adapter/mapper/model/NetConfRequest.java | 166 +- .../mapper/model/NetConfServerDetails.java | 216 +-- .../tr069adapter/mapper/model/VESNotification.java | 17 +- .../mapper/netconf/NetConfNotificationSender.java | 687 ++++---- .../mapper/netconf/NetConfRequestHandler.java | 92 +- .../mapper/netconf/NetConfServerManager.java | 158 +- .../netconf/controller/NetConfRequestReceiver.java | 258 +-- .../netconf/impl/NetConfRequestHandlerImpl.java | 1783 ++++++++++++-------- .../mapper/sync/SynchronizedRequestHandler.java | 219 +-- .../mapper/util/FirwareUpgradeErrorCode.java | 54 +- .../tr069adapter/mapper/util/MOMetaDataUtil.java | 507 +++--- .../mapper/util/NetconfToTr069MapperUtil.java | 1409 +++++++++------- .../mapper/ves/VESNotificationSender.java | 204 ++- .../mapper/ves/impl/VesRequestHandlerImpl.java | 131 +- mapper/src/main/resources/application.properties | 1 + mapper/src/main/resources/schema-mariadb.sql | 2 +- .../mapper/ACSNotificationHandlerImplTest.java | 356 ++-- .../mapper/NetConfRequestReceiverTest.java | 560 +++--- .../mapper/NetConfServerManagerTest.java | 300 ++-- .../mapper/NetconfToTr069MapperUtilTest.java | 200 +-- .../mapper/PnPPreProvisioningHandlerTest.java | 202 +-- netconf-server/pom.xml | 19 + .../schemas/common/tr069-operations.yang | 328 ++++ .../netconf/boot/NetConfServiceBooter.java | 270 +-- .../netconf/entity/NetConfServerDetailsEntity.java | 204 +-- .../netconf/notification/NetConfSessionUtil.java | 100 +- .../netconf/notification/NotificationHandler.java | 112 +- .../operations/CustomOperationsCreator.java | 253 +-- .../restapi/NetConfServerManagerRestApi.java | 179 +- .../restapi/NotificationReceiverService.java | 58 +- .../netconf/rpc/AddObjectOperation.java | 171 ++ .../tr069adapter/netconf/rpc/ConnectionStatus.java | 172 ++ .../netconf/rpc/CreateSubscription.java | 478 +++--- .../netconf/rpc/DeleteConfigOperation.java | 238 +-- .../netconf/rpc/DeleteObjectOperation.java | 172 ++ .../netconf/rpc/DownloadOperation.java | 182 ++ .../netconf/rpc/GPAObjectOperation.java | 169 ++ .../netconf/rpc/GetConfigOperation.java | 218 +-- .../tr069adapter/netconf/rpc/GetOperation.java | 216 +-- .../tr069adapter/netconf/rpc/RebootOperation.java | 180 ++ .../tr069adapter/netconf/rpc/ResetOperation.java | 179 ++ .../netconf/rpc/SPAObjectOperation.java | 182 ++ .../netconf/rpc/SetConfigOperation.java | 240 +-- .../netconf/rpc/SoftwareActivateOperation.java | 224 +-- .../netconf/rpc/SoftwareDownloadOperation.java | 331 ++-- .../tr069adapter/netconf/rpc/XmlUtility.java | 224 +-- .../netconf/server/NetConfServerManagerImpl.java | 890 +++++----- .../netconf/server/NetconfServerStarter.java | 456 ++--- .../server/helper/ServerPortAllocationHelper.java | 322 ++-- .../error/ServerPortAllocationExceptionTest.java | 120 +- .../operations/CustomOperationsCreatorTest.java | 99 +- .../restapi/NetConfServerManagerRestApiTest.java | 210 +-- .../tr069adapter/netconf/rpc/XmlUtilityTest.java | 111 +- ves-agent/pom.xml | 19 + .../vesagent/async/AsyncRequestHandler.java | 277 ++- .../vesagent/async/AsyncThreadPoolConfig.java | 1 + .../vesagent/controller/AlarmMappingHandler.java | 410 ++--- .../controller/HeartBeatMessageHandler.java | 478 +++--- .../vesagent/controller/PnfRegMappingHandler.java | 447 ++--- .../vesagent/entity/DeviceDataEntity.java | 264 +-- .../vesagent/exception/VesAgentException.java | 159 +- .../vesagent/mapper/MapperRequestSender.java | 87 +- .../vesagent/model/CommonEventHeader.java | 439 ++--- .../tr069adapter/vesagent/model/EventMessage.java | 88 +- .../vesagent/model/HeartbeatFields.java | 55 +- .../model/PnfRegEventAdditionalFeilds.java | 275 +-- .../vesagent/model/PnfRegEventFields.java | 312 ++-- .../vesagent/service/VesAgentServiceHelper.java | 615 +++---- .../vesagent/timer/StartupTimerService.java | 139 +- .../vesagent/util/VesAgentConstants.java | 70 +- .../tr069adapter/vesagent/util/VesAgentUtils.java | 3 + 125 files changed, 18450 insertions(+), 15289 deletions(-) create mode 100644 acs/common/src/main/java/org/commscope/tr069adapter/acs/common/utils/ConnectionStatusPOJO.java delete mode 100644 mapper/rpc_set_input.xml create mode 100644 netconf-server/schemas/common/tr069-operations.yang create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/AddObjectOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ConnectionStatus.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteObjectOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DownloadOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GPAObjectOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/RebootOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ResetOperation.java create mode 100644 netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SPAObjectOperation.java diff --git a/acs/application-booter/pom.xml b/acs/application-booter/pom.xml index 16e9a56..173e8fa 100644 --- a/acs/application-booter/pom.xml +++ b/acs/application-booter/pom.xml @@ -189,6 +189,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin diff --git a/acs/application-booter/src/main/java/org/commscope/tr069adapter/acs/booter/ACSServiceBooter.java b/acs/application-booter/src/main/java/org/commscope/tr069adapter/acs/booter/ACSServiceBooter.java index ee7c1f8..16dee98 100644 --- a/acs/application-booter/src/main/java/org/commscope/tr069adapter/acs/booter/ACSServiceBooter.java +++ b/acs/application-booter/src/main/java/org/commscope/tr069adapter/acs/booter/ACSServiceBooter.java @@ -1,222 +1,223 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.booter; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_Q; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; - -import java.util.Arrays; - -import javax.jms.ConnectionFactory; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.catalina.connector.Connector; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jms.annotation.EnableJms; -import org.springframework.jms.config.DefaultJmsListenerContainerFactory; -import org.springframework.jms.config.JmsListenerContainerFactory; -import org.springframework.jms.listener.MessageListenerContainer; -import org.springframework.jms.support.converter.MappingJackson2MessageConverter; -import org.springframework.jms.support.converter.MessageConverter; -import org.springframework.jms.support.converter.MessageType; -import org.springframework.web.client.RestTemplate; - -@EnableJms -@SpringBootApplication -@ComponentScan({"org.commscope.tr069adapter.acs", "org.commscope.tr069adapter.common"}) -@EnableJpaRepositories("org.commscope.tr069adapter.acs") -@EntityScan("org.commscope.tr069adapter.acs.requestprocessor.entity") -public class ACSServiceBooter { - - public static void main(String[] args) { - SpringApplication.run(ACSServiceBooter.class, args); - } - - @Bean - public RestTemplate restTemplate(RestTemplateBuilder builder) { - return builder.build(); - } - - - /* - * JMS Configuration Defining the connection factories used in the application Setting the - * Re-delivery configuration goes here - */ - @Bean - public BrokerService broker() throws Exception { - final BrokerService broker = new BrokerService(); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://localhost"); - broker.setPersistent(false); - return broker; - } - - @Bean - public ConnectionFactory jmsConnectionFactory() { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - connectionFactory - .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter")); - connectionFactory.setMaxThreadPoolSize(7); - - ActiveMQQueue tr069nbiReqQueue = new ActiveMQQueue(TR069_NBI_REQUEST_Q); - RedeliveryPolicy tr069nbiReqQueuePolicy = new RedeliveryPolicy(); - tr069nbiReqQueuePolicy.setInitialRedeliveryDelay(30000); - tr069nbiReqQueuePolicy.setUseCollisionAvoidance(true); - tr069nbiReqQueuePolicy.setRedeliveryDelay(30000); - tr069nbiReqQueuePolicy.setUseExponentialBackOff(false); - tr069nbiReqQueuePolicy.setMaximumRedeliveries(3); - tr069nbiReqQueuePolicy.setDestination(tr069nbiReqQueue); - - ActiveMQQueue crQueue = new ActiveMQQueue(CR_REQ_Q); - RedeliveryPolicy crQueuePolicy = new RedeliveryPolicy(); - crQueuePolicy.setInitialRedeliveryDelay(18000); - crQueuePolicy.setUseCollisionAvoidance(true); - crQueuePolicy.setRedeliveryDelay(18000); - crQueuePolicy.setUseExponentialBackOff(true); - crQueuePolicy.setBackOffMultiplier(2); - crQueuePolicy.setMaximumRedeliveries(4); - crQueuePolicy.setDestination(crQueue); - - ActiveMQQueue notificationQueue = new ActiveMQQueue(NBI_NOTIFICATION_Q); - RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy(); - notificationQueuePolicy.setInitialRedeliveryDelay(30000); - notificationQueuePolicy.setUseCollisionAvoidance(true); - notificationQueuePolicy.setRedeliveryDelay(30000); - notificationQueuePolicy.setUseExponentialBackOff(false); - notificationQueuePolicy.setMaximumRedeliveries(5); - notificationQueuePolicy.setDestination(notificationQueue); - - ActiveMQQueue opResQueue = new ActiveMQQueue(NBI_OP_RESULT_Q); - RedeliveryPolicy opResQueuePolicy = new RedeliveryPolicy(); - opResQueuePolicy.setInitialRedeliveryDelay(30000); - opResQueuePolicy.setUseCollisionAvoidance(true); - opResQueuePolicy.setRedeliveryDelay(30000); - opResQueuePolicy.setUseExponentialBackOff(false); - opResQueuePolicy.setMaximumRedeliveries(3); - opResQueuePolicy.setDestination(opResQueue); - - RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap(); - rdMap.put(tr069nbiReqQueue, tr069nbiReqQueuePolicy); - rdMap.put(crQueue, crQueuePolicy); - rdMap.put(notificationQueue, notificationQueuePolicy); - rdMap.put(opResQueue, opResQueuePolicy); - - return connectionFactory; - } - // End - - @Bean - public JmsListenerContainerFactory tr069NBIRequestCF( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - return handleJMSCommonConfiguration(connectionFactory, configurer); - } - - @Bean - public JmsListenerContainerFactory tr069DeviceResponseCF( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - return handleJMSCommonConfiguration(connectionFactory, configurer); - } - - @Bean - public JmsListenerContainerFactory nbiNotificationCF( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - return handleJMSCommonConfiguration(connectionFactory, configurer); - } - - @Bean - public JmsListenerContainerFactory nbiOpResultCF( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - return handleJMSCommonConfiguration(connectionFactory, configurer); - } - - public JmsListenerContainerFactory handleJMSCommonConfiguration( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); - configurer.configure(factory, connectionFactory); - return factory; - } - - /* - * JMS Configuration ends here - */ - - /* - * JMS serializing and de-serializing used Jackson JMS message converter Serialize message content - * to json using TextMessage - */ - @Bean - public MessageConverter jacksonJmsMessageConverter() { - MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); - converter.setTargetType(MessageType.TEXT); - converter.setTypeIdPropertyName("_type"); - return converter; - } - - /* - * Exposing an addition HTTP port for Netconf mapper to access And making the default port to be - * TLS secured which shall be used in the hems url - */ - @Value("${server.additional.http.port}") - private String additionalHttpPort; - - @Value("${server.port}") - private String serverPort; - - @Bean - public ConfigurableServletWebServerFactory tomcatEmbeddedServletContainerFactory() { - final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - final Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); - connector.setScheme("https"); - connector.setPort(Integer.valueOf(this.additionalHttpPort)); - factory.addAdditionalTomcatConnectors(connector); - return factory; - } - - @Bean - public FilterRegistrationBean loggingFilter() { - FilterRegistrationBean registrationBean = - new FilterRegistrationBean<>(); - registrationBean.setFilter(new FilterInsecuredRequests(serverPort)); - registrationBean.addUrlPatterns("/CPEMgmt/*"); - return registrationBean; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.booter; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_Q; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; + +import java.util.Arrays; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.RedeliveryPolicy; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; +import org.apache.activemq.command.ActiveMQQueue; +import org.apache.catalina.connector.Connector; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jms.annotation.EnableJms; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.config.JmsListenerContainerFactory; +import org.springframework.jms.listener.MessageListenerContainer; +import org.springframework.jms.support.converter.MappingJackson2MessageConverter; +import org.springframework.jms.support.converter.MessageConverter; +import org.springframework.jms.support.converter.MessageType; +import org.springframework.web.client.RestTemplate; + +@EnableJms +@SpringBootApplication +@ComponentScan({"org.commscope.tr069adapter.acs", "org.commscope.tr069adapter.common"}) +@EnableJpaRepositories("org.commscope.tr069adapter.acs") +@EntityScan("org.commscope.tr069adapter.acs.requestprocessor.entity") +public class ACSServiceBooter { + + public static void main(String[] args) { + SpringApplication.run(ACSServiceBooter.class, args); + } + + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } + + + /* + * JMS Configuration Defining the connection factories used in the application Setting the + * Re-delivery configuration goes here + */ + @Bean + public BrokerService broker() throws Exception { + final BrokerService broker = new BrokerService(); + broker.addConnector("tcp://localhost:61616"); + broker.addConnector("vm://localhost"); + broker.setPersistent(false); + return broker; + } + + @Bean + public ConnectionFactory jmsConnectionFactory() { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory + .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter")); + connectionFactory.setMaxThreadPoolSize(7); + + ActiveMQQueue tr069nbiReqQueue = new ActiveMQQueue(TR069_NBI_REQUEST_Q); + RedeliveryPolicy tr069nbiReqQueuePolicy = new RedeliveryPolicy(); + tr069nbiReqQueuePolicy.setInitialRedeliveryDelay(30000); + tr069nbiReqQueuePolicy.setUseCollisionAvoidance(true); + tr069nbiReqQueuePolicy.setRedeliveryDelay(30000); + tr069nbiReqQueuePolicy.setUseExponentialBackOff(false); + tr069nbiReqQueuePolicy.setMaximumRedeliveries(3); + tr069nbiReqQueuePolicy.setDestination(tr069nbiReqQueue); + + ActiveMQQueue crQueue = new ActiveMQQueue(CR_REQ_Q); + RedeliveryPolicy crQueuePolicy = new RedeliveryPolicy(); + crQueuePolicy.setInitialRedeliveryDelay(10 * 1000L); + crQueuePolicy.setUseCollisionAvoidance(true); + crQueuePolicy.setRedeliveryDelay(10 * 1000L); + crQueuePolicy.setMaximumRedeliveries(2); + crQueuePolicy.setDestination(crQueue); + + ActiveMQQueue notificationQueue = new ActiveMQQueue(NBI_NOTIFICATION_Q); + RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy(); + notificationQueuePolicy.setInitialRedeliveryDelay(30000); + notificationQueuePolicy.setUseCollisionAvoidance(true); + notificationQueuePolicy.setRedeliveryDelay(30000); + notificationQueuePolicy.setUseExponentialBackOff(false); + notificationQueuePolicy.setMaximumRedeliveries(5); + notificationQueuePolicy.setDestination(notificationQueue); + + ActiveMQQueue opResQueue = new ActiveMQQueue(NBI_OP_RESULT_Q); + RedeliveryPolicy opResQueuePolicy = new RedeliveryPolicy(); + opResQueuePolicy.setInitialRedeliveryDelay(30000); + opResQueuePolicy.setUseCollisionAvoidance(true); + opResQueuePolicy.setRedeliveryDelay(30000); + opResQueuePolicy.setUseExponentialBackOff(false); + opResQueuePolicy.setMaximumRedeliveries(3); + opResQueuePolicy.setDestination(opResQueue); + + RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap(); + rdMap.put(tr069nbiReqQueue, tr069nbiReqQueuePolicy); + rdMap.put(crQueue, crQueuePolicy); + rdMap.put(notificationQueue, notificationQueuePolicy); + rdMap.put(opResQueue, opResQueuePolicy); + + return connectionFactory; + } + // End + + @Bean + public JmsListenerContainerFactory tr069NBIRequestCF( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10"); + } + + @Bean + public JmsListenerContainerFactory tr069DeviceResponseCF( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + return handleJMSCommonConfiguration(connectionFactory, configurer, "10-20"); + } + + @Bean + public JmsListenerContainerFactory nbiNotificationCF( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10"); + } + + @Bean + public JmsListenerContainerFactory nbiOpResultCF( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10"); + } + + public JmsListenerContainerFactory handleJMSCommonConfiguration( + ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer, + String threadCoutRange) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + factory.setConcurrency(threadCoutRange); + JmsListenerContainerFactory result = + (JmsListenerContainerFactory) factory; + return result; + } + + /* + * JMS Configuration ends here + */ + + /* + * JMS serializing and de-serializing used Jackson JMS message converter Serialize message content + * to json using TextMessage + */ + @Bean + public MessageConverter jacksonJmsMessageConverter() { + MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); + converter.setTargetType(MessageType.TEXT); + converter.setTypeIdPropertyName("_type"); + return converter; + } + + /* + * Exposing an addition HTTP port for Netconf mapper to access And making the default port to be + * TLS secured which shall be used in the hems url + */ + @Value("${server.additional.http.port}") + private String additionalHttpPort; + + @Value("${server.port}") + private String serverPort; + + @Bean + public ConfigurableServletWebServerFactory tomcatEmbeddedServletContainerFactory() { + final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); + final Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); + connector.setScheme("https"); + connector.setPort(Integer.valueOf(this.additionalHttpPort)); + factory.addAdditionalTomcatConnectors(connector); + return factory; + } + + @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = + new FilterRegistrationBean<>(); + registrationBean.setFilter(new FilterInsecuredRequests(serverPort)); + registrationBean.addUrlPatterns("/CPEMgmt/*"); + return registrationBean; + } + +} diff --git a/acs/application-booter/src/main/resources/schema-mariadb.sql b/acs/application-booter/src/main/resources/schema-mariadb.sql index f39500d..cdf4559 100644 --- a/acs/application-booter/src/main/resources/schema-mariadb.sql +++ b/acs/application-booter/src/main/resources/schema-mariadb.sql @@ -9,7 +9,10 @@ CREATE TABLE IF NOT EXISTS tr069_device SW_VERSION varchar(20), HW_VERSION varchar(20), CONNECTION_REQUEST_URL varchar(1024), - LAST_UPDATED_TIME Timestamp + LAST_UPDATED_TIME Timestamp, + LAST_FAILED_ATTEMPT_TIME Timestamp, + CONN_STATUS BOOLEAN, + ERROR_MESSGAE varchar(256) ); diff --git a/acs/application-booter/src/test/java/org/commscope/tr069adapter/acs/cpe/deviceconnection/DeviceConnectTest.java b/acs/application-booter/src/test/java/org/commscope/tr069adapter/acs/cpe/deviceconnection/DeviceConnectTest.java index 0907d13..29e7c26 100644 --- a/acs/application-booter/src/test/java/org/commscope/tr069adapter/acs/cpe/deviceconnection/DeviceConnectTest.java +++ b/acs/application-booter/src/test/java/org/commscope/tr069adapter/acs/cpe/deviceconnection/DeviceConnectTest.java @@ -1,103 +1,130 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe.deviceconnection; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.Serializable; - -import org.apache.activemq.broker.BrokerService; -import org.commscope.tr069adapter.acs.booter.ACSServiceBooter; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.utils.AcsConstants; -import org.commscope.tr069adapter.acs.cpe.handler.ConnectionReqEventHandler; -import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector; -import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@SpringBootTest(classes = {ACSServiceBooter.class}) -@RunWith(SpringJUnit4ClassRunner.class) -@AutoConfigureMockMvc -@ContextConfiguration -public class DeviceConnectTest { - - @Autowired - ConnectionReqEventHandler connectionReqEventHandler; - - @MockBean - private DeviceConnector deviceConnector; - - @MockBean - private TimerServiceManagerAPI timerServiceManagerAPI; - - @Autowired - BrokerService broker; - - @Test - public void deviceConnect() { - try { - Mockito.doNothing().when(timerServiceManagerAPI).startTimer(Mockito.anyString(), - Mockito.anyString(), Mockito.anyLong(), Mockito.any(Serializable.class)); - - DeviceRPCResponse response = new DeviceRPCResponse(); - OperationResponse operationResponse = new OperationResponse(); - operationResponse.setOperationCode(TR069OperationCode.INITIATE_CR); - operationResponse.setStatus(AcsConstants.HTTP_STATUS_OK); - response.setOperationResponse(operationResponse); - Mockito.when(deviceConnector.requestConnectionHttp(Mockito.any(TR069DeviceDetails.class))) - .thenReturn(response); - - TR069DeviceDetails deviceDetails = new TR069DeviceDetails(); - deviceDetails.setDeviceId("0005B9AAAA22"); - deviceDetails.setConnectionRequestURL("http://10.10.10.10:8888/connect/device"); - - connectionReqEventHandler.onMessage(deviceDetails); - - assertTrue(true); - } catch (Exception e) { - fail(e.getMessage()); - } - - } - - @After - public void stopBroker() throws Exception { - try { - System.out.println("Tearing down the broker"); - broker.stop(); - broker.waitUntilStopped(); - broker = null; - } catch (Exception e) { - e.printStackTrace(); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe.deviceconnection; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.Serializable; +import java.util.Date; + +import org.apache.activemq.broker.BrokerService; +import org.commscope.tr069adapter.acs.booter.ACSServiceBooter; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.utils.AcsConstants; +import org.commscope.tr069adapter.acs.cpe.handler.ConnectionReqEventHandler; +import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRepository; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; +import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@SpringBootTest(classes = {ACSServiceBooter.class}) +@RunWith(SpringJUnit4ClassRunner.class) +@AutoConfigureMockMvc +@ContextConfiguration +public class DeviceConnectTest { + + @Autowired + ConnectionReqEventHandler connectionReqEventHandler; + + @MockBean + private DeviceConnector deviceConnector; + + @MockBean + private TimerServiceManagerAPI timerServiceManagerAPI; + + @Autowired + BrokerService broker; + + @MockBean + private DeviceRepository deviceRepository; + + + @Test + public void deviceConnect() { + try { + Mockito.doNothing().when(timerServiceManagerAPI).startTimer(Mockito.anyString(), + Mockito.anyString(), Mockito.anyLong(), Mockito.any(Serializable.class)); + + DeviceRPCResponse response = new DeviceRPCResponse(); + OperationResponse operationResponse = new OperationResponse(); + operationResponse.setOperationCode(TR069OperationCode.INITIATE_CR); + operationResponse.setStatus(AcsConstants.HTTP_STATUS_OK); + response.setOperationResponse(operationResponse); + Mockito.when(deviceConnector.requestConnectionHttp(Mockito.any(TR069DeviceDetails.class))) + .thenReturn(response); + + TR069DeviceDetails deviceDetails = new TR069DeviceDetails(); + deviceDetails.setDeviceId("0005B9AAAA22"); + deviceDetails.setConnectionRequestURL("http://10.10.10.10:8888/connect/device"); + + TR069DeviceEntity tr069DeviceEntity = new TR069DeviceEntity(); + tr069DeviceEntity.setDeviceId(deviceDetails.getDeviceId()); + tr069DeviceEntity.setUserName(deviceDetails.getUsername()); + tr069DeviceEntity.setPassword(deviceDetails.getPassword()); + tr069DeviceEntity.setLastUpdatedTime(new Date()); + tr069DeviceEntity.setConnStatus(true); + tr069DeviceEntity.setErrorMsg(null); + + if (deviceDetails.getSoftwareVersion() != null) { + tr069DeviceEntity.setSwVersion(deviceDetails.getSoftwareVersion()); + } + if (deviceDetails.getHardwareVersion() != null) { + tr069DeviceEntity.setHwVersion(deviceDetails.getHardwareVersion()); + } + Mockito.when(deviceRepository.findByDeviceId(Mockito.anyString())) + .thenReturn(tr069DeviceEntity); + + Mockito.when(deviceRepository.save(Mockito.any(TR069DeviceEntity.class))) + .thenReturn(tr069DeviceEntity); + + connectionReqEventHandler.onMessage(deviceDetails); + + assertTrue(true); + } catch (Exception e) { + fail(e.getMessage()); + } + + } + + @After + public void stopBroker() throws Exception { + try { + System.out.println("Tearing down the broker"); + broker.stop(); + broker.waitUntilStopped(); + broker = null; + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceDetails.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceDetails.java index 8063f13..9883f46 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceDetails.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceDetails.java @@ -19,10 +19,11 @@ package org.commscope.tr069adapter.acs.common; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.io.Serializable; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class DeviceDetails implements Serializable { private static final long serialVersionUID = -2127021632952200894L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceInform.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceInform.java index 97c1a6e..ba3ebcc 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceInform.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/DeviceInform.java @@ -19,11 +19,12 @@ package org.commscope.tr069adapter.acs.common; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.io.Serializable; import java.util.List; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class DeviceInform implements Serializable { private static final long serialVersionUID = 1215967892463095850L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationDetails.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationDetails.java index 7d9c92f..8885b74 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationDetails.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationDetails.java @@ -19,11 +19,12 @@ package org.commscope.tr069adapter.acs.common; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.io.Serializable; import java.util.List; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class OperationDetails implements Serializable { private static final long serialVersionUID = -3405001463223998757L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationResponse.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationResponse.java index 2d60e1e..e5052a0 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationResponse.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/OperationResponse.java @@ -19,11 +19,12 @@ package org.commscope.tr069adapter.acs.common; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import java.io.Serializable; import java.util.List; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class OperationResponse implements Serializable { private static final long serialVersionUID = 6086073521990872907L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/ParameterDTO.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/ParameterDTO.java index f6b97f1..e829a73 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/ParameterDTO.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/ParameterDTO.java @@ -19,9 +19,11 @@ package org.commscope.tr069adapter.acs.common; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; + import java.io.Serializable; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class ParameterDTO implements Serializable { private static final long serialVersionUID = 1460021542834472410L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/dto/TR069DeviceDetails.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/dto/TR069DeviceDetails.java index 4d4ef7e..08bba0b 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/dto/TR069DeviceDetails.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/dto/TR069DeviceDetails.java @@ -1,58 +1,67 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.common.dto; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; - -public class TR069DeviceDetails extends DeviceDetails { - - private static final long serialVersionUID = 8067939584181214835L; - - // Device credentials - private String username; - private String password; - - // Device connection request URL - private String connectionRequestURL; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getConnectionRequestURL() { - return connectionRequestURL; - } - - public void setConnectionRequestURL(String connectionRequestURL) { - this.connectionRequestURL = connectionRequestURL; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.common.dto; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; + +public class TR069DeviceDetails extends DeviceDetails { + + private static final long serialVersionUID = 8067939584181214835L; + + // Device credentials + private String username; + private String password; + + // Device connection request URL + private String connectionRequestURL; + private int crRetryCount; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConnectionRequestURL() { + return connectionRequestURL; + } + + public void setConnectionRequestURL(String connectionRequestURL) { + this.connectionRequestURL = connectionRequestURL; + } + + public int getCrRetryCount() { + return crRetryCount; + } + + public void setCrRetryCount(int crRetryCount) { + this.crRetryCount = crRetryCount; + } + +} diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/exception/ACSException.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/exception/ACSException.java index e86321f..7aa4652 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/exception/ACSException.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/exception/ACSException.java @@ -1,89 +1,79 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.common.exception; - -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.common.utils.Utility; - -public class ACSException extends Exception { - - private static final long serialVersionUID = 9116478433222830454L; - - private static final String ERRORMSG_PREFIX = "TR069"; - - private ErrorCode errorCode; - - private String[] arguments; - - private String message; - - /** - * @param s - */ - public ACSException(String s) { - super(s); - } - - /** - * @param errorCode - */ - public ACSException(ErrorCode errorCode) { - super(); - this.errorCode = errorCode; - setErrorMessage(getErrorMessage()); - } - - /** - * @param errorCode - * @param args - */ - public ACSException(ErrorCode errorCode, String... args) { - super(); - this.errorCode = errorCode; - arguments = args; - setErrorMessage(getErrorMessage()); - } - - public ErrorCode getErrorCode() { - return errorCode; - } - - public void setErrorCode(ErrorCode errorCode) { - this.errorCode = errorCode; - } - - @Override - public String getMessage() { - return message; - } - - /** - * All the error messages defined in the TR069 ErrorMessage properties must have prefix "TR069" - * - * @return - */ - private String getErrorMessage() { - String key = ERRORMSG_PREFIX + "." + errorCode.getErrorCodeKey(); - return Utility.getMessage(key, arguments); - } - - private void setErrorMessage(String message) { - this.message = message; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.common.exception; + +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.common.utils.Utility; + +public class ACSException extends Exception { + + private static final long serialVersionUID = 9116478433222830454L; + + private static final String ERRORMSG_PREFIX = "TR069"; + + private final ErrorCode errorCode; + + private final String[] arguments; + + private final String message; + + /** + * @param s + */ + public ACSException(String s) { + super(s); + this.errorCode = null; + this.arguments = null; + this.message = ""; + } + + /** + * @param errorCode + */ + public ACSException(ErrorCode errorCode) { + super(); + this.errorCode = errorCode; + this.arguments = null; + this.message = getErrorMessage(); + } + + + public ACSException(ErrorCode errorCode, String... args) { + super(); + this.errorCode = errorCode; + arguments = args; + this.message = getErrorMessage(); + } + + public ErrorCode getErrorCode() { + return errorCode; + } + + + @Override + public String getMessage() { + return message; + } + + private String getErrorMessage() { + String key = ERRORMSG_PREFIX + "." + errorCode.getErrorCodeKey(); + return Utility.getMessage(key, arguments); + } + +} diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/inform/AbstractDeviceInform.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/inform/AbstractDeviceInform.java index d05d84e..4667e41 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/inform/AbstractDeviceInform.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/inform/AbstractDeviceInform.java @@ -19,10 +19,11 @@ package org.commscope.tr069adapter.acs.common.inform; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import org.commscope.tr069adapter.acs.common.DeviceInform; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public abstract class AbstractDeviceInform extends DeviceInform { private static final long serialVersionUID = -487248664548665087L; diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/requestprocessor/service/TR069DeviceEventHandler.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/requestprocessor/service/TR069DeviceEventHandler.java index d3884e2..362360b 100644 --- a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/requestprocessor/service/TR069DeviceEventHandler.java +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/requestprocessor/service/TR069DeviceEventHandler.java @@ -1,70 +1,75 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.common.requestprocessor.service; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; - -public interface TR069DeviceEventHandler { - - /** - * @param deviceNotification - * @return - */ - public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification) throws Exception; - - /** - * Return type can be null, such case Empty HTTP response to be sent to the device - * - * @param operationResult - * @return - */ - public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult) - throws Exception; - - /** - * Return type can be null, such case Empty HTTP response to be sent to the device - * - * @return - */ - public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) - throws Exception; - - /** - * @param sessionId - * @return - * @throws SessionManagerException - */ - public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) - throws SessionManagerException; - - /** - * @param deviceId - * @return - * @throws DeviceOperationException - */ - public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException; - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.common.requestprocessor.service; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; +import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; + +public interface TR069DeviceEventHandler { + + /** + * @param deviceNotification + * @return + * @throws SessionConcurrentAccessException + */ + public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification) + throws InterruptedException, SessionConcurrentAccessException; + + /** + * Return type can be null, such case Empty HTTP response to be sent to the device + * + * @param operationResult + * @return + */ + public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult) + throws SessionConcurrentAccessException, InterruptedException; + + /** + * Return type can be null, such case Empty HTTP response to be sent to the device + * + * @return + */ + public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) + throws SessionConcurrentAccessException, InterruptedException; + + /** + * @param sessionId + * @return + * @throws SessionManagerException + */ + public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) + throws SessionManagerException; + + /** + * @param deviceId + * @return + * @throws DeviceOperationException + */ + public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException; + + public void processConnectionRequest(String errorMsg, String deviceId, boolean isSuccess); + +} diff --git a/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/utils/ConnectionStatusPOJO.java b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/utils/ConnectionStatusPOJO.java new file mode 100644 index 0000000..81fa5ad --- /dev/null +++ b/acs/common/src/main/java/org/commscope/tr069adapter/acs/common/utils/ConnectionStatusPOJO.java @@ -0,0 +1,50 @@ +package org.commscope.tr069adapter.acs.common.utils; + +import java.util.Date; + +public class ConnectionStatusPOJO { + + private boolean status; + private Date lastContactTime; + private Date lastFailedAttemptTime; + private String errorMessage; + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public Date getLastContactTime() { + return lastContactTime; + } + + public void setLastContactTime(Date lastContactTime) { + this.lastContactTime = lastContactTime; + } + + public Date getLastFailedAttemptTime() { + return lastFailedAttemptTime; + } + + public void setLastFailedAttemptTime(Date lastFailedAttemptTime) { + this.lastFailedAttemptTime = lastFailedAttemptTime; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + @Override + public String toString() { + return "ConnectionStatusPOJO [status=" + status + ", lastContactTime=" + lastContactTime + + ", lastFailedAttemptTime=" + lastFailedAttemptTime + "]"; + } + +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/CPEManagementService.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/CPEManagementService.java index 6f07e36..a94d981 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/CPEManagementService.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/CPEManagementService.java @@ -1,577 +1,586 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.ACS_SESSIONID; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CWMP_VERSION; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.INFORM; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TRANSFER_COMPLETE; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.Enumeration; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Context; -import javax.xml.soap.MessageFactory; -import javax.xml.soap.MimeHeaders; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPMessage; - -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.cpe.handler.DeviceEventHandler; -import org.commscope.tr069adapter.acs.cpe.rpc.Fault; -import org.commscope.tr069adapter.acs.cpe.rpc.Inform; -import org.commscope.tr069adapter.acs.cpe.rpc.InformResponse; -import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete; -import org.commscope.tr069adapter.acs.cpe.rpc.TransferCompleteResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/CPEMgmt") -public class CPEManagementService { - - private static final String UTF_8 = "UTF-8"; - - private static final Logger logger = LoggerFactory.getLogger(CPEManagementService.class); - - private static final int MY_MAX_ENVELOPES = 1; - - @Autowired - DeviceEventHandler deviceEventHandler; - - /** - * @param request - * @param response - */ - @SuppressWarnings("static-access") - @PostMapping("/acs") - public void processDeviceEvent(@Context HttpServletRequest request, - @Context HttpServletResponse response) { - - logger.debug("A device event occurred"); - logHeaderElements(request.getHeaderNames()); - - try { - Boolean isEmptyCPERequest = true; - SOAPMessage soapMsg = null; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - String ct = request.getContentType(); - int csix = -1; - String csFrom = "ISO-8859-1"; - if (ct != null) { - csix = ct.indexOf("charset="); - response.setContentType(ct); - } else { - response.setContentType("text/xml;charset=UTF-8"); - } - - if (csix != -1) - csFrom = ct.substring(csix + 8).replaceAll("\"", ""); - - Cookie[] cookies = request.getCookies(); - String acsSessionID = getACSSessionCookieData(cookies); - String cwmpVersion = getCWMPVersionCookieData(cookies); - - XmlFilterInputStream f = - new XmlFilterInputStream(request.getInputStream(), request.getContentLength()); - MessageFactory mf = getSOAPMessageFactory(); - while (f.next()) { - isEmptyCPERequest = false; - MimeHeaders hdrs = new MimeHeaders(); - hdrs.setHeader("Content-Type", "text/xml; charset=UTF-8"); - InputStream in = getInputStream(csFrom, f); - soapMsg = mf.createMessage(hdrs, in); - - logSoapMsg(soapMsg); - - TR069RPC msg = null; - msg = TR069RPC.parse(soapMsg); - - String reqType = getRequestType(msg); - logger.info("Event notified by the device is of type: {}", reqType); - - if (reqType != null) { - if (reqType.equals(INFORM)) { - processDeviceInform(msg, request, response, out); - } else if (reqType.equals(TRANSFER_COMPLETE)) { - processTransferComplete(msg, response, out); - } else { - processOperationResult(msg, response, reqType, acsSessionID, out); - } - } - } - - if (isEmptyCPERequest.booleanValue()) { - processEmptyCPERequest(response, cwmpVersion, acsSessionID, out); - } - - if (out.size() < 1) {// To delete dm_sessionId cookie - clearCookies(cookies, response); - } - - response.setContentLength(out.size()); - response.setHeader("SOAPAction", ""); - String sout = out.toString().trim(); - logger.info(sout); - response.getOutputStream().print(sout); - response.getOutputStream().flush(); - logger.debug("End of processing"); - - } catch (Exception e) { - logger.error("An error occurred while processing device event, Exception: {}", - e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - - logger.debug("End of processing the HTTP post request"); - } - - private InputStream getInputStream(String csFrom, XmlFilterInputStream f) throws IOException { - InputStream in = null; - if (csFrom.equalsIgnoreCase(UTF_8)) { - in = new XmlFilterNS(f); - } else { - in = new CharsetConverterInputStream(csFrom, UTF_8, new XmlFilterNS(f)); - } - return in; - } - - private void processDeviceInform(TR069RPC msg, HttpServletRequest request, - HttpServletResponse response, ByteArrayOutputStream out) throws IOException { - Inform inform = (Inform) msg; - DeviceInformResponse deviceInformResponse = null; - try { - deviceInformResponse = - deviceEventHandler.processDeviceInform(inform, request.getHeader("Authorization")); - Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId()); - Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion()); - response.addCookie(cookie); - response.addCookie(cwmpVerCookie); - } catch (TR069EventProcessingException tr069ex) { - ErrorCode errorCode = tr069ex.getErrorCode(); - if (ErrorCode.OUI_OR_PC_MISMATCH.equals(errorCode)) { - sendFault(response, out, Fault.FCODE_ACS_REQUEST_DENIED, "OUIandProductClassNotValid", - inform.getId()); - } else { - int httpStatusCode = deviceEventHandler.handleException(tr069ex); - response.setStatus(httpStatusCode); - } - int httpStatusCode = deviceEventHandler.handleException(tr069ex); - response.setStatus(httpStatusCode); - } - - InformResponse resp = new InformResponse(inform.getId(), MY_MAX_ENVELOPES); - resp.setCWMPVersion(msg.getCWMPVersion()); - resp.writeTo(out); - } - - private void processTransferComplete(TR069RPC msg, HttpServletResponse response, - ByteArrayOutputStream out) { - TransferComplete tc = (TransferComplete) msg; - try { - DeviceInformResponse deviceInformResponse = deviceEventHandler.processTransferComplete(tc); - Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId()); - Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion() + ";"); - response.addCookie(cookie); - response.addCookie(cwmpVerCookie); - } catch (Exception e) { - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - TransferCompleteResponse tr = new TransferCompleteResponse(tc.getId()); - tr.setCWMPVersion(msg.getCWMPVersion()); - tr.writeTo(out); - } - - private void processOperationResult(TR069RPC msg, HttpServletResponse response, String reqType, - String acsSessionID, ByteArrayOutputStream out) { - logger.debug("Received Operation Result response {}", msg); - if (null == acsSessionID) { - logger.error("Received response without session ID, response: {}", reqType); - } else { - try { - TR069RPC message = deviceEventHandler.processRPCResponse(msg, acsSessionID); - if (null != message) { - message.setCWMPVersion(msg.getCWMPVersion()); - message.writeTo(out); - } else { - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - } - } catch (TR069EventProcessingException tr069ex) { - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - } - - private void processEmptyCPERequest(HttpServletResponse response, String cwmpVersion, - String acsSessionID, ByteArrayOutputStream out) { - if (null == acsSessionID) { - logger.error("Received empty response without session ID"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - - try { - logger.info("Received Empty Device response"); - TR069RPC message = deviceEventHandler.processEmptyRequest(acsSessionID); - if (null != message) { - message.setCWMPVersion(cwmpVersion); - message.writeTo(out); - } else { - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - } - } catch (TR069EventProcessingException tr069ex) { - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - private void clearCookies(Cookie[] cookies, HttpServletResponse response) { - Cookie cookieToDelete = null; - if (null != cookies) { - logger.debug("Clearing the cookies"); - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equals(ACS_SESSIONID) - || cookies[i].getName().equals(CWMP_VERSION)) { - cookieToDelete = cookies[i]; - cookieToDelete.setMaxAge(0); - response.addCookie(cookieToDelete); - } - } - } - } - - private static class XmlFilterInputStream extends InputStream { - - private InputStream istream; - private int lvl; - private int lastchar; - @SuppressWarnings("unused") - private int len; - private int nextchar; - private boolean intag = false; - private StringBuilder buff = new StringBuilder(16); - - /** Creates a new instance of xmlFilterInputStream */ - public XmlFilterInputStream(InputStream is, int l) { - len = l; - istream = is; - } - - @Override - public int read() throws IOException { - if (lastchar == '>' && lvl == 0) { - return -1; - } - int l = lastchar; - if (!readLastChar()) - return lastchar; - - if (!intag && lastchar == '&') { - int amppos = buff.length(); - updateBuffer(); - String s = buff.substring(amppos); - replaceSpecialChars(s, amppos); - return read(); - } - - if (l == '<') { - intag = true; - if (lastchar == '/') { - lvl--; - } else { - lvl++; - } - } - - len--; - return lastchar; - } - - public boolean next() throws IOException { - if ((nextchar = istream.read()) == -1) { - logger.debug("Next char is {}", nextchar); - lvl = 0; - lastchar = 0; - } - return (nextchar != -1); - } - - private boolean readLastChar() throws IOException { - if (nextchar != -1) { - lastchar = nextchar; - nextchar = -1; - } else { - if (buff.length() > 0) { - lastchar = buff.charAt(0); - buff.deleteCharAt(0); - return false; - } else { - lastchar = istream.read(); - } - } - - if (lastchar == '<') { - intag = true; - } else if (lastchar == '>') { - intag = false; - } - - return true; - } - - private void updateBuffer() throws IOException { - // fix up broken xml not encoding & - buff.append((char) lastchar); - for (int c = 0; c < 10; c++) { - int ch = istream.read(); - boolean breakLoop = false; - if (ch == -1) { - breakLoop = true; - } - if (ch == '&') { - nextchar = ch; - breakLoop = true; - } - if (breakLoop) - break; - - buff.append((char) ch); - } - } - - private void replaceSpecialChars(String s, int amppos) { - if (!s.startsWith("&") && !s.startsWith("<") && !s.startsWith(">") - && !s.startsWith("'") && !s.startsWith(""") && !s.startsWith("&#")) { - buff.replace(amppos, amppos + 1, "&"); - } - } - } - - private static class XmlFilterNS extends InputStream { - // Dumb class to filter out declaration of default xmlns - - private String pat = "xmlns=\"urn:dslforum-org:cwmp-1-0\""; - private String pat2 = "xmlns=\"urn:dslforum-org:cwmp-1-1\""; - private int length = 0; - private int pos = 0; - private boolean f = false; - private byte[] buff = new byte[1024]; - private InputStream is; - - @Override - public int read() throws IOException { - if (!f) { - length = is.read(buff); - if (length < buff.length) { - byte[] b2 = new byte[length]; - System.arraycopy(buff, 0, b2, 0, length); - buff = b2; - } - - String b = new String(buff, StandardCharsets.UTF_8); - b = b.replace(pat, ""); - b = b.replace(pat2, ""); - buff = b.getBytes(StandardCharsets.UTF_8); - length = buff.length; - f = true; - } - - if (pos < length) { - return buff[pos++] & 0xFF; - } - return is.read(); - } - - public XmlFilterNS(InputStream is) { - this.is = is; - } - } - - private static class CharsetConverterInputStream extends InputStream { - - @SuppressWarnings("unused") - private InputStream in; - private PipedInputStream pipein; - private OutputStream pipeout; - private Reader r; - private Writer w; - - public CharsetConverterInputStream(String csFrom, String csTo, InputStream in) - throws IOException { - this.in = in; - r = new InputStreamReader(in, csFrom); - pipein = new PipedInputStream(); - pipeout = new PipedOutputStream(pipein); - w = new OutputStreamWriter(pipeout, csTo); - } - - @Override - public int read() throws IOException { - if (pipein.available() > 0) { - return pipein.read(); - } - int c = r.read(); - if (c == -1) { - return -1; - } - w.write(c); - w.flush(); - return pipein.read(); - } - } - - /** - * @return - * @throws Exception - */ - private MessageFactory getSOAPMessageFactory() throws SOAPException { - MessageFactory mf = null; - mf = MessageFactory.newInstance(); - return mf; - } - - /** - * @param cookies - * @return - */ - private String getACSSessionCookieData(Cookie[] cookies) { - String acsSessionID = null; - if (null != cookies) { - for (Cookie cookie : cookies) { - if (cookie.getName().equals(ACS_SESSIONID)) { - acsSessionID = cookie.getValue(); - logger.debug("The session id is {}", acsSessionID); - } - } - } - return acsSessionID; - } - - /** - * @param cookies - * @return - * @throws TR069EventProcessingException - */ - private String getCWMPVersionCookieData(Cookie[] cookies) throws TR069EventProcessingException { - String cwmpVersion = null; - try { - if (null != cookies) { - for (Cookie cookie : cookies) { - if (cookie.getName().equals(CWMP_VERSION)) { - cwmpVersion = cookie.getValue(); - if (cwmpVersion != null) { - cwmpVersion = URLDecoder.decode(cwmpVersion, StandardCharsets.UTF_8.name()); - } - logger.debug("The CWMP version supported by the device is: {}", cwmpVersion); - } - } - } - } catch (UnsupportedEncodingException e) { - logger.error(e.getMessage()); - TR069EventProcessingException ex = new TR069EventProcessingException( - ErrorCode.UNSUPPORTED_CHARACTER_ENCODING, StandardCharsets.UTF_8.name()); - logger.error(ex.getMessage()); - throw ex; - } - return cwmpVersion; - } - - /** - * @param soapMsg - */ - private void logSoapMsg(SOAPMessage soapMsg) { - StringBuilder buffer = new StringBuilder(); - buffer.append(soapMsg.toString()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - soapMsg.writeTo(baos); - } catch (SOAPException | IOException e) { - logger.error("Error while writting soap message"); - } - buffer.append(baos); - String soapMessage = buffer.toString(); - logger.debug(soapMessage); - } - - /** - * @param response - * @param out - * @param fcodeAcsRequestDenied - * @param faultString - * @param id - * @throws IOException - */ - private void sendFault(HttpServletResponse response, ByteArrayOutputStream out, - String fcodeAcsRequestDenied, String faultString, String id) throws IOException { - Fault fault = new Fault(fcodeAcsRequestDenied, faultString, id); - fault.writeTo(out); - response.setContentLength(out.size()); - String sout = out.toString(UTF_8); - sout = sout.replace('\'', '"'); - response.getOutputStream().print(sout); - } - - private void logHeaderElements(Enumeration headerName) { - while (headerName.hasMoreElements()) { - String requestHeader = headerName.nextElement(); - logger.debug("Request Headers {}", requestHeader); - } - } - - private String getRequestType(TR069RPC msg) { - String requestType = msg.getName(); - if (requestType == null) - requestType = "Empty Request"; - - return requestType; - } - - /******************************************************************************************************************/ - - public DeviceEventHandler getDeviceEventHandler() { - return deviceEventHandler; - } - - public void setDeviceEventHandler(DeviceEventHandler deviceEventHandler) { - this.deviceEventHandler = deviceEventHandler; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.ACS_SESSIONID; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CWMP_VERSION; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.INFORM; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TRANSFER_COMPLETE; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Enumeration; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Context; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.MimeHeaders; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; + +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.cpe.handler.DeviceEventHandler; +import org.commscope.tr069adapter.acs.cpe.rpc.Fault; +import org.commscope.tr069adapter.acs.cpe.rpc.Inform; +import org.commscope.tr069adapter.acs.cpe.rpc.InformResponse; +import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete; +import org.commscope.tr069adapter.acs.cpe.rpc.TransferCompleteResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/CPEMgmt") +public class CPEManagementService { + + private static final String UTF_8 = "UTF-8"; + + private static final Logger logger = LoggerFactory.getLogger(CPEManagementService.class); + + private static final int MY_MAX_ENVELOPES = 1; + + @Autowired + DeviceEventHandler deviceEventHandler; + + /** + * @param request + * @param response + */ + @SuppressWarnings("static-access") + @PostMapping("/acs") + public void processDeviceEvent(@Context HttpServletRequest request, + @Context HttpServletResponse response) { + + logger.debug("A device event occurred"); + logHeaderElements(request.getHeaderNames()); + + try { + Boolean isEmptyCPERequest = true; + SOAPMessage soapMsg = null; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String ct = request.getContentType(); + int csix = -1; + String csFrom = "ISO-8859-1"; + if (ct != null) { + csix = ct.indexOf("charset="); + response.setContentType(ct); + } else { + response.setContentType("text/xml;charset=UTF-8"); + } + + if (csix != -1) + csFrom = ct.substring(csix + 8).replaceAll("\"", ""); + + Cookie[] cookies = request.getCookies(); + String acsSessionID = getACSSessionCookieData(cookies); + String cwmpVersion = getCWMPVersionCookieData(cookies); + + XmlFilterInputStream f = + new XmlFilterInputStream(request.getInputStream(), request.getContentLength()); + MessageFactory mf = getSOAPMessageFactory(); + while (f.next()) { + isEmptyCPERequest = false; + MimeHeaders hdrs = new MimeHeaders(); + hdrs.setHeader("Content-Type", "text/xml; charset=UTF-8"); + InputStream in = getInputStream(csFrom, f); + soapMsg = mf.createMessage(hdrs, in); + + logSoapMsg(soapMsg); + + TR069RPC msg = null; + msg = TR069RPC.parse(soapMsg); + + String reqType = getRequestType(msg); + logger.info("Event notified by the device is of type: {}", reqType); + + if (reqType != null) { + if (reqType.equals(INFORM)) { + processDeviceInform(msg, request, response, out); + } else if (reqType.equals(TRANSFER_COMPLETE)) { + processTransferComplete(msg, request, response, out); + } else { + processOperationResult(msg, response, reqType, acsSessionID, out); + } + } + } + + if (isEmptyCPERequest.booleanValue()) { + processEmptyCPERequest(response, cwmpVersion, acsSessionID, out); + } + + if (out.size() < 1) {// To delete dm_sessionId cookie + clearCookies(cookies, response); + } + + response.setContentLength(out.size()); + response.setHeader("SOAPAction", ""); + String sout = out.toString().trim(); + logger.info(sout); + response.getOutputStream().print(sout); + response.getOutputStream().flush(); + logger.debug("End of processing"); + + } catch (Exception e) { + logger.error("An error occurred while processing device event, Exception: {}", + e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + logger.debug("End of processing the HTTP post request"); + } + + private InputStream getInputStream(String csFrom, XmlFilterInputStream f) throws IOException { + InputStream in = null; + if (csFrom.equalsIgnoreCase(UTF_8)) { + in = new XmlFilterNS(f); + } else { + in = new CharsetConverterInputStream(csFrom, UTF_8, new XmlFilterNS(f)); + } + return in; + } + + private void processDeviceInform(TR069RPC msg, HttpServletRequest request, + HttpServletResponse response, ByteArrayOutputStream out) throws IOException { + Inform inform = (Inform) msg; + DeviceInformResponse deviceInformResponse = null; + try { + deviceInformResponse = + deviceEventHandler.processDeviceInform(inform, request.getHeader("Authorization")); + Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId()); + cookie.setSecure(request.isSecure()); + cookie.setHttpOnly(true); + Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion()); + cwmpVerCookie.setSecure(request.isSecure()); + cwmpVerCookie.setHttpOnly(true); + response.addCookie(cookie); + response.addCookie(cwmpVerCookie); + } catch (TR069EventProcessingException tr069ex) { + ErrorCode errorCode = tr069ex.getErrorCode(); + if (ErrorCode.OUI_OR_PC_MISMATCH.equals(errorCode)) { + sendFault(response, out, Fault.FCODE_ACS_REQUEST_DENIED, "OUIandProductClassNotValid", + inform.getId()); + } else { + int httpStatusCode = deviceEventHandler.handleException(tr069ex); + response.setStatus(httpStatusCode); + } + int httpStatusCode = deviceEventHandler.handleException(tr069ex); + response.setStatus(httpStatusCode); + } + + InformResponse resp = new InformResponse(inform.getId(), MY_MAX_ENVELOPES); + resp.setCWMPVersion(msg.getCWMPVersion()); + resp.writeTo(out); + } + + private void processTransferComplete(TR069RPC msg, HttpServletRequest request, + HttpServletResponse response, ByteArrayOutputStream out) { + TransferComplete tc = (TransferComplete) msg; + try { + DeviceInformResponse deviceInformResponse = deviceEventHandler.processTransferComplete(tc); + Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId()); + cookie.setSecure(request.isSecure()); + cookie.setHttpOnly(true); + Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion() + ";"); + cwmpVerCookie.setSecure(request.isSecure()); + cwmpVerCookie.setHttpOnly(true); + response.addCookie(cookie); + response.addCookie(cwmpVerCookie); + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + TransferCompleteResponse tr = new TransferCompleteResponse(tc.getId()); + tr.setCWMPVersion(msg.getCWMPVersion()); + tr.writeTo(out); + } + + private void processOperationResult(TR069RPC msg, HttpServletResponse response, String reqType, + String acsSessionID, ByteArrayOutputStream out) { + logger.debug("Received Operation Result response {}", msg); + if (null == acsSessionID) { + logger.error("Received response without session ID, response: {}", reqType); + } else { + try { + TR069RPC message = deviceEventHandler.processRPCResponse(msg, acsSessionID); + if (null != message) { + message.setCWMPVersion(msg.getCWMPVersion()); + message.writeTo(out); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + } + } catch (TR069EventProcessingException tr069ex) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + + private void processEmptyCPERequest(HttpServletResponse response, String cwmpVersion, + String acsSessionID, ByteArrayOutputStream out) { + if (null == acsSessionID) { + logger.error("Received empty response without session ID"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + + try { + logger.info("Received Empty Device response"); + TR069RPC message = deviceEventHandler.processEmptyRequest(acsSessionID); + if (null != message) { + message.setCWMPVersion(cwmpVersion); + message.writeTo(out); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + } + } catch (TR069EventProcessingException tr069ex) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + + private void clearCookies(Cookie[] cookies, HttpServletResponse response) { + Cookie cookieToDelete = null; + if (null != cookies) { + logger.debug("Clearing the cookies"); + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals(ACS_SESSIONID) + || cookies[i].getName().equals(CWMP_VERSION)) { + cookieToDelete = cookies[i]; + cookieToDelete.setMaxAge(0); + response.addCookie(cookieToDelete); + } + } + } + } + + private static class XmlFilterInputStream extends InputStream { + + private InputStream istream; + private int lvl; + private int lastchar; + @SuppressWarnings("unused") + private int len; + private int nextchar; + private boolean intag = false; + private StringBuilder buff = new StringBuilder(16); + + /** Creates a new instance of xmlFilterInputStream */ + public XmlFilterInputStream(InputStream is, int l) { + len = l; + istream = is; + } + + + @Override + public int read() throws IOException { + if (lastchar == '>' && lvl == 0) { + return -1; + } + int l = lastchar; + if (!readLastChar()) + return lastchar; + + if (!intag && lastchar == '&') { + int amppos = buff.length(); + updateBuffer(); + String s = buff.substring(amppos); + replaceSpecialChars(s, amppos); + return read(); + } + + if (l == '<') { + intag = true; + if (lastchar == '/') { + lvl--; + } else { + lvl++; + } + } + + len--; + return lastchar; + } + + public boolean next() throws IOException { + if ((nextchar = istream.read()) == -1) { + logger.debug("Next char is {}", nextchar); + lvl = 0; + lastchar = 0; + } + return (nextchar != -1); + } + + private boolean readLastChar() throws IOException { + if (nextchar != -1) { + lastchar = nextchar; + nextchar = -1; + } else { + if (buff.length() > 0) { + lastchar = buff.charAt(0); + buff.deleteCharAt(0); + return false; + } else { + lastchar = istream.read(); + } + } + + if (lastchar == '<') { + intag = true; + } else if (lastchar == '>') { + intag = false; + } + + return true; + } + + private void updateBuffer() throws IOException { + // fix up broken xml not encoding & + buff.append((char) lastchar); + for (int c = 0; c < 10; c++) { + int ch = istream.read(); + boolean breakLoop = false; + if (ch == -1) { + breakLoop = true; + } + if (ch == '&') { + nextchar = ch; + breakLoop = true; + } + if (breakLoop) + break; + + buff.append((char) ch); + } + } + + private void replaceSpecialChars(String s, int amppos) { + if (!s.startsWith("&") && !s.startsWith("<") && !s.startsWith(">") + && !s.startsWith("'") && !s.startsWith(""") && !s.startsWith("&#")) { + buff.replace(amppos, amppos + 1, "&"); + } + } + } + + private static class XmlFilterNS extends InputStream { + // Dumb class to filter out declaration of default xmlns + + private String pat = "xmlns=\"urn:dslforum-org:cwmp-1-0\""; + private String pat2 = "xmlns=\"urn:dslforum-org:cwmp-1-1\""; + private int length = 0; + private int pos = 0; + private boolean f = false; + private byte[] buff = new byte[1024]; + private InputStream is; + + @Override + public int read() throws IOException { + if (!f) { + length = is.read(buff); + if (length < buff.length) { + byte[] b2 = new byte[length]; + System.arraycopy(buff, 0, b2, 0, length); + buff = b2; + } + + String b = new String(buff, StandardCharsets.UTF_8); + b = b.replace(pat, ""); + b = b.replace(pat2, ""); + buff = b.getBytes(StandardCharsets.UTF_8); + length = buff.length; + f = true; + } + + if (pos < length) { + return buff[pos++] & 0xFF; + } + return is.read(); + } + + public XmlFilterNS(InputStream is) { + this.is = is; + } + } + + private static class CharsetConverterInputStream extends InputStream { + + @SuppressWarnings("unused") + private InputStream in; + private PipedInputStream pipein; + private OutputStream pipeout; + private Reader r; + private Writer w; + + public CharsetConverterInputStream(String csFrom, String csTo, InputStream in) + throws IOException { + this.in = in; + r = new InputStreamReader(in, csFrom); + pipein = new PipedInputStream(); + pipeout = new PipedOutputStream(pipein); + w = new OutputStreamWriter(pipeout, csTo); + } + + @Override + public int read() throws IOException { + if (pipein.available() > 0) { + return pipein.read(); + } + int c = r.read(); + if (c == -1) { + return -1; + } + w.write(c); + w.flush(); + return pipein.read(); + } + } + + /** + * @return + * @throws Exception + */ + private MessageFactory getSOAPMessageFactory() throws SOAPException { + MessageFactory mf = null; + mf = MessageFactory.newInstance(); + return mf; + } + + /** + * @param cookies + * @return + */ + private String getACSSessionCookieData(Cookie[] cookies) { + String acsSessionID = null; + if (null != cookies) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals(ACS_SESSIONID)) { + acsSessionID = cookie.getValue(); + logger.debug("The session id is {}", acsSessionID); + } + } + } + return acsSessionID; + } + + /** + * @param cookies + * @return + * @throws TR069EventProcessingException + */ + private String getCWMPVersionCookieData(Cookie[] cookies) throws TR069EventProcessingException { + String cwmpVersion = null; + try { + if (null != cookies) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals(CWMP_VERSION)) { + cwmpVersion = cookie.getValue(); + if (cwmpVersion != null) { + cwmpVersion = URLDecoder.decode(cwmpVersion, StandardCharsets.UTF_8.name()); + } + logger.debug("The CWMP version supported by the device is: {}", cwmpVersion); + } + } + } + } catch (UnsupportedEncodingException e) { + logger.error(e.getMessage()); + TR069EventProcessingException ex = new TR069EventProcessingException( + ErrorCode.UNSUPPORTED_CHARACTER_ENCODING, StandardCharsets.UTF_8.name()); + logger.error(ex.getMessage()); + throw ex; + } + return cwmpVersion; + } + + /** + * @param soapMsg + */ + private void logSoapMsg(SOAPMessage soapMsg) { + StringBuilder buffer = new StringBuilder(); + buffer.append(soapMsg.toString()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + soapMsg.writeTo(baos); + } catch (SOAPException | IOException e) { + logger.error("Error while writting soap message"); + } + buffer.append(baos); + String soapMessage = buffer.toString(); + logger.debug(soapMessage); + } + + /** + * @param response + * @param out + * @param fcodeAcsRequestDenied + * @param faultString + * @param id + * @throws IOException + */ + private void sendFault(HttpServletResponse response, ByteArrayOutputStream out, + String fcodeAcsRequestDenied, String faultString, String id) throws IOException { + Fault fault = new Fault(fcodeAcsRequestDenied, faultString, id); + fault.writeTo(out); + response.setContentLength(out.size()); + String sout = out.toString(UTF_8); + sout = sout.replace('\'', '"'); + response.getOutputStream().print(sout); + } + + private void logHeaderElements(Enumeration headerName) { + while (headerName.hasMoreElements()) { + String requestHeader = headerName.nextElement(); + logger.debug("Request Headers {}", requestHeader); + } + } + + private String getRequestType(TR069RPC msg) { + String requestType = msg.getName(); + if (requestType == null) + requestType = "Empty Request"; + + return requestType; + } + + /******************************************************************************************************************/ + + public DeviceEventHandler getDeviceEventHandler() { + return deviceEventHandler; + } + + public void setDeviceEventHandler(DeviceEventHandler deviceEventHandler) { + this.deviceEventHandler = deviceEventHandler; + } + +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/TR069RPC.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/TR069RPC.java index e3da5e9..3aa7669 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/TR069RPC.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/TR069RPC.java @@ -1,434 +1,435 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Random; - -import javax.xml.soap.MessageFactory; -import javax.xml.soap.Name; -import javax.xml.soap.Node; -import javax.xml.soap.SOAPBody; -import javax.xml.soap.SOAPBodyElement; -import javax.xml.soap.SOAPElement; -import javax.xml.soap.SOAPEnvelope; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPFactory; -import javax.xml.soap.SOAPHeader; -import javax.xml.soap.SOAPHeaderElement; -import javax.xml.soap.SOAPMessage; -import javax.xml.soap.SOAPPart; - -import org.commscope.tr069adapter.acs.cpe.rpc.Fault; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class TR069RPC implements Serializable { - - private static final String HTTP_SCHEMA_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; - - private static final long serialVersionUID = 7270475819053880884L; - - protected static final Logger logger = LoggerFactory.getLogger(TR069RPC.class); - - private Random mrandom = new Random(); - - /** Creates a new instance of Message */ - public TR069RPC() {} - - public static final String ENVELOPE_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"; - - protected abstract void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException; - - protected abstract void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException; - - protected class ArrayType { - - public ArrayType() { - super(); - } - - private String type; - - public String getType() { - return type; - } - - public Name getType(SOAPBodyElement body, SOAPFactory spf) throws SOAPException { - int i = type.indexOf(':'); - if (i == -1) { - return spf.createName(type); - } else { - String prefix = type.substring(0, i); - SOAPBody b = (SOAPBody) body.getParentElement(); - SOAPEnvelope e = (SOAPEnvelope) b.getParentElement(); - SOAPHeader h = e.getHeader(); - String uri = null; - try { - uri = h.lookupNamespaceURI(prefix); - } catch (Exception ee) { - logger.error("While geting namespace URI 1 {}", ee.toString()); - } - if (uri == null) { - try { - uri = e.lookupNamespaceURI(prefix); - } catch (Exception ee) { - logger.error("While geting namespace URI 2 {}", ee.toString()); - } - } - if (uri == null) { - try { - uri = b.lookupNamespaceURI(prefix); - } catch (Exception ee) { - logger.error("While geting namespace URI {} ", ee.toString()); - } - } - return spf.createName(type.substring(i + 1), prefix, uri); - } - } - - public void setType(String type) { - this.type = type; - } - } - - public static SOAPBodyElement getRequest(SOAPMessage msg) throws SOAPException { - SOAPBodyElement request = null; - Iterator i1 = msg.getSOAPBody().getChildElements(); - while (i1.hasNext()) { - Node n = i1.next(); - if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { - request = (SOAPBodyElement) n; - } - } - return request; - } - - private static String getRequestName(SOAPMessage msg) throws SOAPException { - if (msg.getSOAPBody().hasFault()) { - return "Fault"; - } - String name = ""; - SOAPBodyElement element = getRequest(msg); - if (element != null) { - name = element.getNodeName(); - } - if (name.startsWith("cwmp:")) { - name = name.substring(5); - } else if (name.startsWith("cwmp_x:")) { - name = name.substring(7); - } else if (name.indexOf(':') != -1) { - name = name.substring(name.indexOf(':') + 1, name.length()); - } - return name; - } - - public static TR069RPC parse(SOAPMessage soapMsg) - throws SOAPException, InstantiationException, IllegalAccessException, ClassNotFoundException { - String reqname = TR069RPC.getRequestName(soapMsg); - - TR069RPC msg = null; - try { - msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname) - .newInstance(); - } catch (Exception e) { - msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname) - .newInstance(); - } - msg = msg.parseSoapMessage(soapMsg); - return msg; - } - - @SuppressWarnings("unchecked") - private TR069RPC parseSoapMessage(SOAPMessage soapMsg) throws SOAPException { - SOAPEnvelope env = soapMsg.getSOAPPart().getEnvelope(); - - Iterator pfxs = env.getNamespacePrefixes(); - while (pfxs.hasNext()) { - String pfx = pfxs.next(); - String uri = env.getNamespaceURI(pfx); - if (uri.startsWith("urn:dslforum-org:cwmp-")) { - urnCWMP = uri; - } - } - SOAPFactory spf = SOAPFactory.newInstance(); - SOAPBodyElement soaprequest = getRequest(soapMsg); - SOAPHeader hdr = soapMsg.getSOAPHeader(); - id = "device_did_not_send_id"; // or make it null?... - if (hdr != null) { - try { - id = getHeaderElement(spf, hdr, "ID"); - } catch (Exception e) { - logger.error("While parsing the soap message {}", e.toString()); - } - } - name = getRequestName(soapMsg); - if (soaprequest != null) { - Fault fault = parseSOAPRequest(soaprequest, spf); - if (fault != null) - return fault; - } - return this; - } - - private Fault parseSOAPRequest(SOAPBodyElement soaprequest, SOAPFactory spf) - throws SOAPException { - if (soaprequest != null) { - try { - parseBody(soaprequest, spf); - } catch (Exception e) { - SOAPElement se = getRequestChildElement(spf, soaprequest, FAULT_CODE); - String fc = (se != null) ? se.getValue() : "0"; - SOAPElement se2 = getRequestChildElement(spf, soaprequest, FAULT_STRING); - String fs = (se2 != null) ? se2.getValue() : "0"; - - if (se != null || se2 != null) { - return new Fault(fc, fs, id); - } - throw e; - } - } - return null; - } - - public void writeTo(OutputStream out) { - try { - SOAPFactory spf = SOAPFactory.newInstance(); - MessageFactory factory = MessageFactory.newInstance(); - SOAPMessage soapMsg = factory.createMessage(); - SOAPPart part = soapMsg.getSOAPPart(); - - SOAPEnvelope envelope = part.getEnvelope(); - SOAPHeader header = envelope.getHeader(); - SOAPBody body = envelope.getBody(); - - String responseId = getId(); - - envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema"); - envelope.addNamespaceDeclaration("cwmp", urnCWMP); - envelope.addNamespaceDeclaration("SOAP-ENC", HTTP_SCHEMA_ENCODING); - envelope.addNamespaceDeclaration("SOAP-ENV", ENVELOPE_NAMESPACE); - envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance"); - - SOAPElement element = header.addChildElement(spf.createName("ID", "cwmp", urnCWMP)); - element.addAttribute(spf.createName("mustUnderstand", "SOAP-ENV", ENVELOPE_NAMESPACE), - responseId); - element.addTextNode("1"); - - body.setEncodingStyle(HTTP_SCHEMA_ENCODING); - SOAPBodyElement bd = body.addBodyElement(spf.createName(name, CWMP, urnCWMP)); - - if (name == null || name.equals("")) { - name = this.getClass().getSimpleName(); - } - createBody(bd, spf, id); - - soapMsg.writeTo(out); - } catch (SOAPException ex) { - logger.error("Exception occurred while constructing SOAP message: {}", ex.getMessage()); - } catch (IOException e) { - logger.error("Exception occurred while constructing SOAP message: {}", e.getMessage()); - } - } - - protected void createBody(SOAPBodyElement body, SOAPFactory spf, String key) - throws SOAPException { - logger.debug("Key element is: {}", key); - createBody(body, spf); - } - - protected SOAPElement getRequestChildElement(SOAPFactory f, SOAPElement req, String name) { - @SuppressWarnings("unchecked") - Iterator i = req.getChildElements(); - f.getClass(); - while (i.hasNext()) { - Object o = i.next(); - try { - Node nn = (Node) o; - String n = nn.getLocalName(); - if (n != null && n.equals(name)) { - return (SOAPElement) o; - } - } catch (Exception e) { - logger.debug("Exception: {}, {}", e.getMessage(), e.getClass().getName()); - } - } - return null; - } - - protected SOAPElement getRequestChildElement2(SOAPFactory f, SOAPElement req, String name) - throws SOAPException { - return (SOAPElement) req.getChildElements(f.createName(name, CWMP, urnCWMP)).next(); - } - - protected String getRequestElement(SOAPFactory f, SOAPElement req, String name) { - return getRequestChildElement(f, req, name).getValue(); - } - - protected String getRequestElement(SOAPFactory f, SOAPElement req, String name, String def) { - String v = getRequestChildElement(f, req, name).getValue(); - return (v != null) ? v : def; - } - - protected SOAPElement getRequestChildElement(SOAPElement req, Name name) { - return (SOAPElement) req.getChildElements(name).next(); - } - - protected String getRequestElement(SOAPElement req, Name name) { - return getRequestChildElement(req, name).getValue(); - } - - protected String getHeaderElement(SOAPFactory f, SOAPHeader hdr, String name) - throws SOAPException { - return ((SOAPHeaderElement) hdr.getChildElements(f.createName(name, CWMP, urnCWMP)).next()) - .getValue(); - } - - protected HashMap parseParamList(SOAPElement body, SOAPFactory spf) - throws SOAPException { - return parseParamList(body, spf, "ParameterValueStruct", "Value"); - } - - protected HashMap parseParamList(SOAPElement body, SOAPFactory spf, String sn, - String vn) throws SOAPException { - Iterator pi = - getRequestChildElement(spf, body, "ParameterList").getChildElements(spf.createName(sn)); - Name nameKey = spf.createName("Name"); - Name nameValue = spf.createName(vn); - HashMap pl = new HashMap<>(); - while (pi.hasNext()) { - SOAPElement param = pi.next(); - String key = getRequestElement(param, nameKey); - String value = getRequestElement(param, nameValue); - if (value == null) { - value = ""; - } - pl.put(key, value); - } - return pl; - } - - protected int getArrayCount(SOAPFactory spf, SOAPElement e) throws SOAPException { - return getArrayCount(spf, e, null); - } - - protected int getArrayCount(SOAPFactory spf, SOAPElement e, ArrayType type) throws SOAPException { - Name nameArray = spf.createName("arrayType", "soap-enc", HTTP_SCHEMA_ENCODING); - String attr = e.getAttributeValue(nameArray); - if (attr == null) { - return 0; - } - attr = attr.replace(" ", ""); - int i = attr.indexOf('['); - String c = attr.substring(i + 1, attr.length() - 1); - if (type != null) { - type.setType(attr.substring(0, i)); - } - return Integer.parseInt(c); - } - - public boolean isFault() { - return name.equals("Fault"); - } - - protected String b2s(boolean b) { - return (b) ? "1" : "0"; - } - - protected String name; - - public String getName() { - return name; - } - - protected String id; - - public String getId() { - if (id == null) { - id = "" + mrandom.nextInt(99999); - } - return id; - } - - protected void println(StringBuilder b, String n, String v) { - b.append(n); - b.append(": "); - b.append(v); - b.append("\n"); - } - - protected void println(StringBuilder b, String n, String n2, String v) { - b.append(n); - println(b, n2, v); - } - - public String getCWMPVersion() { - return urnCWMP; - } - - public void setCWMPVersion(String cwmpVersion) { - urnCWMP = cwmpVersion; - } - - protected String urnCWMP = "urn:dslforum-org:cwmp-1-0"; - protected static final String CWMP = "cwmp"; - protected static final String PARAMETER_KEY = "ParameterKey"; - protected static final String COMMAND_KEY = "CommandKey"; - protected static final String XSI_TYPE = "xsi:type"; - protected static final String XSD_STRING = "xsd:string"; - protected static final String XSD_UNSIGNEDINT = "xsd:unsignedInt"; - protected static final String XSD_INT = "xsd:int"; - protected static final String XSD_BOOLEAN = "xsd:boolean"; - protected static final String XSD_DATETIME = "xsd:dateTime"; - protected static final String XSD_BASE64 = "xsd:base64"; - protected static final String SOAP_ARRAY_TYPE = "SOAP-ENC:arrayType"; - public static final String FAULT_CODE = "FaultCode"; - public static final String FAULT_STRING = "FaultString"; - public static final String TYPE_OBJECT = "object"; - public static final String TYPE_STRING = "string"; - public static final String TYPE_BOOLEAN = "boolean"; - public static final String TYPE_DATETIME = "dateTime"; - public static final String TYPE_UNSIGNEDINT = "unsignedInt"; - public static final String TYPE_INT = "int"; - public static final String TYPE_BASE64 = "base64"; - - public String getXmlType(String type) { - if (type.equals(TYPE_BASE64)) { - return TR069RPC.XSD_BASE64; - } else if (type.equals(TYPE_BOOLEAN)) { - return TR069RPC.XSD_BOOLEAN; - } else if (type.equals(TYPE_DATETIME)) { - return TR069RPC.XSD_DATETIME; - } else if (type.equals(TYPE_INT)) { - return TR069RPC.XSD_INT; - } else if (type.equals(TYPE_OBJECT)) { - return ""; - } else if (type.equals(TYPE_STRING)) { - return TR069RPC.XSD_STRING; - } else if (type.equals(TYPE_UNSIGNEDINT)) { - return TR069RPC.XSD_UNSIGNEDINT; - } - return type; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Serializable; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Random; + +import javax.xml.soap.MessageFactory; +import javax.xml.soap.Name; +import javax.xml.soap.Node; +import javax.xml.soap.SOAPBody; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPElement; +import javax.xml.soap.SOAPEnvelope; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPFactory; +import javax.xml.soap.SOAPHeader; +import javax.xml.soap.SOAPHeaderElement; +import javax.xml.soap.SOAPMessage; +import javax.xml.soap.SOAPPart; + +import org.commscope.tr069adapter.acs.cpe.rpc.Fault; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class TR069RPC implements Serializable { + + private static final String HTTP_SCHEMA_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; + + private static final long serialVersionUID = 7270475819053880884L; + + protected static final Logger logger = LoggerFactory.getLogger(TR069RPC.class); + + private Random mrandom = new SecureRandom(); + + /** Creates a new instance of Message */ + public TR069RPC() {} + + public static final String ENVELOPE_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"; + + protected abstract void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException; + + protected abstract void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException; + + protected class ArrayType { + + public ArrayType() { + super(); + } + + private String type; + + public String getType() { + return type; + } + + public Name getType(SOAPBodyElement body, SOAPFactory spf) throws SOAPException { + int i = type.indexOf(':'); + if (i == -1) { + return spf.createName(type); + } else { + String prefix = type.substring(0, i); + SOAPBody b = (SOAPBody) body.getParentElement(); + SOAPEnvelope e = (SOAPEnvelope) b.getParentElement(); + SOAPHeader h = e.getHeader(); + String uri = null; + try { + uri = h.lookupNamespaceURI(prefix); + } catch (Exception ee) { + logger.error("While geting namespace URI 1 {}", ee.toString()); + } + if (uri == null) { + try { + uri = e.lookupNamespaceURI(prefix); + } catch (Exception ee) { + logger.error("While geting namespace URI 2 {}", ee.toString()); + } + } + if (uri == null) { + try { + uri = b.lookupNamespaceURI(prefix); + } catch (Exception ee) { + logger.error("While geting namespace URI {} ", ee.toString()); + } + } + return spf.createName(type.substring(i + 1), prefix, uri); + } + } + + public void setType(String type) { + this.type = type; + } + } + + public static SOAPBodyElement getRequest(SOAPMessage msg) throws SOAPException { + SOAPBodyElement request = null; + Iterator i1 = msg.getSOAPBody().getChildElements(); + while (i1.hasNext()) { + Node n = i1.next(); + if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { + request = (SOAPBodyElement) n; + } + } + return request; + } + + private static String getRequestName(SOAPMessage msg) throws SOAPException { + if (msg.getSOAPBody().hasFault()) { + return "Fault"; + } + String name = ""; + SOAPBodyElement element = getRequest(msg); + if (element != null) { + name = element.getNodeName(); + } + if (name.startsWith("cwmp:")) { + name = name.substring(5); + } else if (name.startsWith("cwmp_x:")) { + name = name.substring(7); + } else if (name.indexOf(':') != -1) { + name = name.substring(name.indexOf(':') + 1, name.length()); + } + return name; + } + + public static TR069RPC parse(SOAPMessage soapMsg) + throws SOAPException, InstantiationException, IllegalAccessException, ClassNotFoundException { + String reqname = TR069RPC.getRequestName(soapMsg); + + TR069RPC msg = null; + try { + msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname) + .newInstance(); + } catch (Exception e) { + msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname) + .newInstance(); + } + msg = msg.parseSoapMessage(soapMsg); + return msg; + } + + @SuppressWarnings("unchecked") + private TR069RPC parseSoapMessage(SOAPMessage soapMsg) throws SOAPException { + SOAPEnvelope env = soapMsg.getSOAPPart().getEnvelope(); + + Iterator pfxs = env.getNamespacePrefixes(); + while (pfxs.hasNext()) { + String pfx = pfxs.next(); + String uri = env.getNamespaceURI(pfx); + if (uri.startsWith("urn:dslforum-org:cwmp-")) { + urnCWMP = uri; + } + } + SOAPFactory spf = SOAPFactory.newInstance(); + SOAPBodyElement soaprequest = getRequest(soapMsg); + SOAPHeader hdr = soapMsg.getSOAPHeader(); + id = "device_did_not_send_id"; // or make it null?... + if (hdr != null) { + try { + id = getHeaderElement(spf, hdr, "ID"); + } catch (Exception e) { + logger.error("While parsing the soap message {}", e.toString()); + } + } + name = getRequestName(soapMsg); + if (soaprequest != null) { + Fault fault = parseSOAPRequest(soaprequest, spf); + if (fault != null) + return fault; + } + return this; + } + + private Fault parseSOAPRequest(SOAPBodyElement soaprequest, SOAPFactory spf) + throws SOAPException { + if (soaprequest != null) { + try { + parseBody(soaprequest, spf); + } catch (Exception e) { + SOAPElement se = getRequestChildElement(spf, soaprequest, FAULT_CODE); + String fc = (se != null) ? se.getValue() : "0"; + SOAPElement se2 = getRequestChildElement(spf, soaprequest, FAULT_STRING); + String fs = (se2 != null) ? se2.getValue() : "0"; + + if (se != null || se2 != null) { + return new Fault(fc, fs, id); + } + throw e; + } + } + return null; + } + + public void writeTo(OutputStream out) { + try { + SOAPFactory spf = SOAPFactory.newInstance(); + MessageFactory factory = MessageFactory.newInstance(); + SOAPMessage soapMsg = factory.createMessage(); + SOAPPart part = soapMsg.getSOAPPart(); + + SOAPEnvelope envelope = part.getEnvelope(); + SOAPHeader header = envelope.getHeader(); + SOAPBody body = envelope.getBody(); + + String responseId = getId(); + + envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema"); + envelope.addNamespaceDeclaration("cwmp", urnCWMP); + envelope.addNamespaceDeclaration("SOAP-ENC", HTTP_SCHEMA_ENCODING); + envelope.addNamespaceDeclaration("SOAP-ENV", ENVELOPE_NAMESPACE); + envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + + SOAPElement element = header.addChildElement(spf.createName("ID", "cwmp", urnCWMP)); + element.addAttribute(spf.createName("mustUnderstand", "SOAP-ENV", ENVELOPE_NAMESPACE), + responseId); + element.addTextNode("1"); + + body.setEncodingStyle(HTTP_SCHEMA_ENCODING); + SOAPBodyElement bd = body.addBodyElement(spf.createName(name, CWMP, urnCWMP)); + + if (name == null || name.equals("")) { + name = this.getClass().getSimpleName(); + } + createBody(bd, spf, id); + + soapMsg.writeTo(out); + } catch (SOAPException ex) { + logger.error("Exception occurred while constructing SOAP message: {}", ex.getMessage()); + } catch (IOException e) { + logger.error("Exception occurred while constructing SOAP message: {}", e.getMessage()); + } + } + + protected void createBody(SOAPBodyElement body, SOAPFactory spf, String key) + throws SOAPException { + logger.debug("Key element is: {}", key); + createBody(body, spf); + } + + protected SOAPElement getRequestChildElement(SOAPFactory f, SOAPElement req, String name) { + @SuppressWarnings("unchecked") + Iterator i = req.getChildElements(); + f.getClass(); + while (i.hasNext()) { + Object o = i.next(); + try { + Node nn = (Node) o; + String n = nn.getLocalName(); + if (n != null && n.equals(name)) { + return (SOAPElement) o; + } + } catch (Exception e) { + logger.debug("Exception: {}, {}", e.getMessage(), e.getClass().getName()); + } + } + return null; + } + + protected SOAPElement getRequestChildElement2(SOAPFactory f, SOAPElement req, String name) + throws SOAPException { + return (SOAPElement) req.getChildElements(f.createName(name, CWMP, urnCWMP)).next(); + } + + protected String getRequestElement(SOAPFactory f, SOAPElement req, String name) { + return getRequestChildElement(f, req, name).getValue(); + } + + protected String getRequestElement(SOAPFactory f, SOAPElement req, String name, String def) { + String v = getRequestChildElement(f, req, name).getValue(); + return (v != null) ? v : def; + } + + protected SOAPElement getRequestChildElement(SOAPElement req, Name name) { + return (SOAPElement) req.getChildElements(name).next(); + } + + protected String getRequestElement(SOAPElement req, Name name) { + return getRequestChildElement(req, name).getValue(); + } + + protected String getHeaderElement(SOAPFactory f, SOAPHeader hdr, String name) + throws SOAPException { + return ((SOAPHeaderElement) hdr.getChildElements(f.createName(name, CWMP, urnCWMP)).next()) + .getValue(); + } + + protected HashMap parseParamList(SOAPElement body, SOAPFactory spf) + throws SOAPException { + return parseParamList(body, spf, "ParameterValueStruct", "Value"); + } + + protected HashMap parseParamList(SOAPElement body, SOAPFactory spf, String sn, + String vn) throws SOAPException { + Iterator pi = + getRequestChildElement(spf, body, "ParameterList").getChildElements(spf.createName(sn)); + Name nameKey = spf.createName("Name"); + Name nameValue = spf.createName(vn); + HashMap pl = new HashMap<>(); + while (pi.hasNext()) { + SOAPElement param = pi.next(); + String key = getRequestElement(param, nameKey); + String value = getRequestElement(param, nameValue); + if (value == null) { + value = ""; + } + pl.put(key, value); + } + return pl; + } + + protected int getArrayCount(SOAPFactory spf, SOAPElement e) throws SOAPException { + return getArrayCount(spf, e, null); + } + + protected int getArrayCount(SOAPFactory spf, SOAPElement e, ArrayType type) throws SOAPException { + Name nameArray = spf.createName("arrayType", "soap-enc", HTTP_SCHEMA_ENCODING); + String attr = e.getAttributeValue(nameArray); + if (attr == null) { + return 0; + } + attr = attr.replace(" ", ""); + int i = attr.indexOf('['); + String c = attr.substring(i + 1, attr.length() - 1); + if (type != null) { + type.setType(attr.substring(0, i)); + } + return Integer.parseInt(c); + } + + public boolean isFault() { + return name.equals("Fault"); + } + + protected String b2s(boolean b) { + return (b) ? "1" : "0"; + } + + protected String name; + + public String getName() { + return name; + } + + protected String id; + + public String getId() { + if (id == null) { + id = "" + mrandom.nextInt(99999); + } + return id; + } + + protected void println(StringBuilder b, String n, String v) { + b.append(n); + b.append(": "); + b.append(v); + b.append("\n"); + } + + protected void println(StringBuilder b, String n, String n2, String v) { + b.append(n); + println(b, n2, v); + } + + public String getCWMPVersion() { + return urnCWMP; + } + + public void setCWMPVersion(String cwmpVersion) { + urnCWMP = cwmpVersion; + } + + protected String urnCWMP = "urn:dslforum-org:cwmp-1-0"; + protected static final String CWMP = "cwmp"; + protected static final String PARAMETER_KEY = "ParameterKey"; + protected static final String COMMAND_KEY = "CommandKey"; + protected static final String XSI_TYPE = "xsi:type"; + protected static final String XSD_STRING = "xsd:string"; + protected static final String XSD_UNSIGNEDINT = "xsd:unsignedInt"; + protected static final String XSD_INT = "xsd:int"; + protected static final String XSD_BOOLEAN = "xsd:boolean"; + protected static final String XSD_DATETIME = "xsd:dateTime"; + protected static final String XSD_BASE64 = "xsd:base64"; + protected static final String SOAP_ARRAY_TYPE = "SOAP-ENC:arrayType"; + public static final String FAULT_CODE = "FaultCode"; + public static final String FAULT_STRING = "FaultString"; + public static final String TYPE_OBJECT = "object"; + public static final String TYPE_STRING = "string"; + public static final String TYPE_BOOLEAN = "boolean"; + public static final String TYPE_DATETIME = "dateTime"; + public static final String TYPE_UNSIGNEDINT = "unsignedInt"; + public static final String TYPE_INT = "int"; + public static final String TYPE_BASE64 = "base64"; + + public String getXmlType(String type) { + if (type.equals(TYPE_BASE64)) { + return TR069RPC.XSD_BASE64; + } else if (type.equals(TYPE_BOOLEAN)) { + return TR069RPC.XSD_BOOLEAN; + } else if (type.equals(TYPE_DATETIME)) { + return TR069RPC.XSD_DATETIME; + } else if (type.equals(TYPE_INT)) { + return TR069RPC.XSD_INT; + } else if (type.equals(TYPE_OBJECT)) { + return ""; + } else if (type.equals(TYPE_STRING)) { + return TR069RPC.XSD_STRING; + } else if (type.equals(TYPE_UNSIGNEDINT)) { + return TR069RPC.XSD_UNSIGNEDINT; + } + return type; + } +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/builder/DeviceRPCBuilder.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/builder/DeviceRPCBuilder.java index b64b5e9..f35f864 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/builder/DeviceRPCBuilder.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/builder/DeviceRPCBuilder.java @@ -1,176 +1,178 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe.builder; - -import java.util.ArrayList; -import java.util.List; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.OperationCode; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.cpe.TR069RPC; -import org.commscope.tr069adapter.acs.cpe.rpc.AddObject; -import org.commscope.tr069adapter.acs.cpe.rpc.DeleteObject; -import org.commscope.tr069adapter.acs.cpe.rpc.Download; -import org.commscope.tr069adapter.acs.cpe.rpc.FactoryReset; -import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterAttributes; -import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterValues; -import org.commscope.tr069adapter.acs.cpe.rpc.Reboot; -import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterAttributes; -import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterValues; -import org.springframework.stereotype.Component; - -@Component -public class DeviceRPCBuilder { - - /** - * @param deviceRPCRequest - * @return - */ - public TR069RPC constructDeviceRPC(DeviceRPCRequest deviceRPCRequest) { - TR069RPC message = null; - - OperationDetails opDetails = deviceRPCRequest.getOpDetails(); - if (null == opDetails || null == opDetails.getOpCode()) { - return null; - } - - OperationCode opCode = opDetails.getOpCode(); - if (opCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) { - message = buildSetParameterValues(opDetails); - } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) { - message = buildGetParameterValues(opDetails); - } else if (opCode.equals(TR069OperationCode.SET_PARAMETER_ATTRIBUTES)) { - message = buildSetParameterAttributes(opDetails); - } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) { - message = buildGetParameterAttributes(opDetails); - } else if (opCode.equals(TR069OperationCode.ADD_OBJECT)) { - List poarameterDTOs = opDetails.getParmeters(); - for (ParameterDTO param : poarameterDTOs) { - AddObject addObject = new AddObject(param.getParamName(), String.valueOf(hashCode())); - message = addObject; - } - } else if (opCode.equals(TR069OperationCode.DELETE_OBJECT)) { - List poarameterDTOs = opDetails.getParmeters(); - for (ParameterDTO param : poarameterDTOs) { - DeleteObject deleteObject = - new DeleteObject(param.getParamName(), String.valueOf(hashCode())); - message = deleteObject; - } - } else if (opCode.equals(TR069OperationCode.DOWNLOAD)) { - String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); - List poarameterDTOs = opDetails.getParmeters(); - message = populateDownloadParams(deviceId, poarameterDTOs); - } else if (opCode.equals(TR069OperationCode.FACTORY_RESET)) { - message = new FactoryReset(); - } else if (opCode.equals(TR069OperationCode.REBOOT)) { - message = new Reboot(); - } - - return message; - } - - /** - * @param poarameterDTOs - * @return - */ - private Download populateDownloadParams(String deviceId, List poarameterDTOs) { - Download download = new Download(); - for (ParameterDTO param : poarameterDTOs) { - if (param.getParamName().equals("FileType")) { - download.setFileType(param.getParamValue()); - } else if (param.getParamName().equals("URL")) { - download.setUrl(param.getParamValue()); - } else if (param.getParamName().equals("Username")) { - download.setUserName(param.getParamValue()); - } else if (param.getParamName().equals("Password")) { - download.setPassword(param.getParamValue()); - } else if (param.getParamName().equals("FileSize")) { - download.setFileSize(Long.parseLong(param.getParamValue())); - } else if (param.getParamName().equals("TargetFileName")) { - download.setTargetFileName(param.getParamValue()); - } else if (param.getParamName().equals("DelaySeconds")) { - download.setDelaySeconds(Integer.parseInt(param.getParamValue())); - } else if (param.getParamName().equals("SuccessURL")) { - download.setSuccessUrl(param.getParamValue()); - } else if (param.getParamName().equals("FailureURL")) { - download.setFailureUrl(param.getParamValue()); - } - } - download.setCommandKey(String.valueOf(deviceId)); - - return download; - } - - private SetParameterValues buildSetParameterValues(OperationDetails opDetails) { - SetParameterValues spv = new SetParameterValues(); - List parmeters = opDetails.getParmeters(); - for (ParameterDTO param : parmeters) { - spv.addValue(param.getParamName(), param.getParamValue(), param.getDataType()); - } - - return spv; - } - - private GetParameterValues buildGetParameterValues(OperationDetails opDetails) { - GetParameterValues gpv = new GetParameterValues(); - List parmeters = opDetails.getParmeters(); - List paramNamelist = new ArrayList<>(); - for (ParameterDTO param : parmeters) { - paramNamelist.add(param.getParamName()); - } - String[] parameterNames = new String[paramNamelist.size()]; - for (int i = 0; i < paramNamelist.size(); i++) { - parameterNames[i] = paramNamelist.get(i); - } - gpv.setParameterNames(parameterNames); - return gpv; - } - - private SetParameterAttributes buildSetParameterAttributes(OperationDetails opDetails) { - SetParameterAttributes spa = new SetParameterAttributes(); - List parameterAttributes = opDetails.getParmeters(); - for (ParameterDTO parameterDTO : parameterAttributes) { - ParameterAttributeDTO parameterAttributeDTO = (ParameterAttributeDTO) parameterDTO; - spa.addAttribute(parameterAttributeDTO.getParamName(), - parameterAttributeDTO.getNotificationChange(), parameterAttributeDTO.getNotification(), - parameterAttributeDTO.getAccesslistChange(), parameterAttributeDTO.getAccessList()); - } - return spa; - } - - private GetParameterAttributes buildGetParameterAttributes(OperationDetails opDetails) { - GetParameterAttributes gpa = new GetParameterAttributes(); - List poarameterDTOs = opDetails.getParmeters(); - List paramNamelist = new ArrayList<>(); - for (ParameterDTO param : poarameterDTOs) { - paramNamelist.add(param.getParamName()); - } - String[] parameterNames = new String[paramNamelist.size()]; - for (int i = 0; i < paramNamelist.size(); i++) { - parameterNames[i] = paramNamelist.get(i); - } - gpa.setParameterNames(parameterNames); - - return gpa; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.OperationCode; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.cpe.TR069RPC; +import org.commscope.tr069adapter.acs.cpe.rpc.AddObject; +import org.commscope.tr069adapter.acs.cpe.rpc.DeleteObject; +import org.commscope.tr069adapter.acs.cpe.rpc.Download; +import org.commscope.tr069adapter.acs.cpe.rpc.FactoryReset; +import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterAttributes; +import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterValues; +import org.commscope.tr069adapter.acs.cpe.rpc.Reboot; +import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterAttributes; +import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterValues; +import org.springframework.stereotype.Component; + +@Component +public class DeviceRPCBuilder { + + /** + * @param deviceRPCRequest + * @return + */ + + + public TR069RPC constructDeviceRPC(DeviceRPCRequest deviceRPCRequest) { + TR069RPC message = null; + + OperationDetails opDetails = deviceRPCRequest.getOpDetails(); + if (null == opDetails || null == opDetails.getOpCode()) { + return null; + } + + OperationCode opCode = opDetails.getOpCode(); + if (opCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) { + message = buildSetParameterValues(opDetails); + } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) { + message = buildGetParameterValues(opDetails); + } else if (opCode.equals(TR069OperationCode.SET_PARAMETER_ATTRIBUTES)) { + message = buildSetParameterAttributes(opDetails); + } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) { + message = buildGetParameterAttributes(opDetails); + } else if (opCode.equals(TR069OperationCode.ADD_OBJECT)) { + List poarameterDTOs = opDetails.getParmeters(); + for (ParameterDTO param : poarameterDTOs) { + AddObject addObject = new AddObject(param.getParamName(), String.valueOf(hashCode())); + message = addObject; + } + } else if (opCode.equals(TR069OperationCode.DELETE_OBJECT)) { + List poarameterDTOs = opDetails.getParmeters(); + for (ParameterDTO param : poarameterDTOs) { + DeleteObject deleteObject = + new DeleteObject(param.getParamName(), String.valueOf(hashCode())); + message = deleteObject; + } + } else if (opCode.equals(TR069OperationCode.DOWNLOAD)) { + String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); + List poarameterDTOs = opDetails.getParmeters(); + message = populateDownloadParams(deviceId, poarameterDTOs); + } else if (opCode.equals(TR069OperationCode.FACTORY_RESET)) { + message = new FactoryReset(); + } else if (opCode.equals(TR069OperationCode.REBOOT)) { + message = new Reboot(); + } + + return message; + } + + /** + * @param poarameterDTOs + * @return + */ + private Download populateDownloadParams(String deviceId, List poarameterDTOs) { + Download download = new Download(); + for (ParameterDTO param : poarameterDTOs) { + if (param.getParamName().equals("FileType")) { + download.setFileType(param.getParamValue()); + } else if (param.getParamName().equals("URL")) { + download.setUrl(param.getParamValue()); + } else if (param.getParamName().equals("Username")) { + download.setUserName(param.getParamValue()); + } else if (param.getParamName().equals("Password")) { + download.setPassword(param.getParamValue()); + } else if (param.getParamName().equals("FileSize")) { + download.setFileSize(Long.parseLong(param.getParamValue())); + } else if (param.getParamName().equals("TargetFileName")) { + download.setTargetFileName(param.getParamValue()); + } else if (param.getParamName().equals("DelaySeconds")) { + download.setDelaySeconds(Integer.parseInt(param.getParamValue())); + } else if (param.getParamName().equals("SuccessURL")) { + download.setSuccessUrl(param.getParamValue()); + } else if (param.getParamName().equals("FailureURL")) { + download.setFailureUrl(param.getParamValue()); + } + } + download.setCommandKey(String.valueOf(deviceId)); + + return download; + } + + private SetParameterValues buildSetParameterValues(OperationDetails opDetails) { + SetParameterValues spv = new SetParameterValues(); + List parmeters = opDetails.getParmeters(); + for (ParameterDTO param : parmeters) { + spv.addValue(param.getParamName(), param.getParamValue(), param.getDataType()); + } + + return spv; + } + + private GetParameterValues buildGetParameterValues(OperationDetails opDetails) { + GetParameterValues gpv = new GetParameterValues(); + List parmeters = opDetails.getParmeters(); + List paramNamelist = new ArrayList<>(); + for (ParameterDTO param : parmeters) { + paramNamelist.add(param.getParamName()); + } + String[] parameterNames = new String[paramNamelist.size()]; + for (int i = 0; i < paramNamelist.size(); i++) { + parameterNames[i] = paramNamelist.get(i); + } + gpv.setParameterNames(parameterNames); + return gpv; + } + + private SetParameterAttributes buildSetParameterAttributes(OperationDetails opDetails) { + SetParameterAttributes spa = new SetParameterAttributes(); + List parameterAttributes = opDetails.getParmeters(); + for (ParameterDTO parameterDTO : parameterAttributes) { + ParameterAttributeDTO parameterAttributeDTO = (ParameterAttributeDTO) parameterDTO; + spa.addAttribute(parameterAttributeDTO.getParamName(), + parameterAttributeDTO.getNotificationChange(), parameterAttributeDTO.getNotification(), + parameterAttributeDTO.getAccesslistChange(), parameterAttributeDTO.getAccessList()); + } + return spa; + } + + private GetParameterAttributes buildGetParameterAttributes(OperationDetails opDetails) { + GetParameterAttributes gpa = new GetParameterAttributes(); + List poarameterDTOs = opDetails.getParmeters(); + List paramNamelist = new ArrayList<>(); + for (ParameterDTO param : poarameterDTOs) { + paramNamelist.add(param.getParamName()); + } + String[] parameterNames = new String[paramNamelist.size()]; + for (int i = 0; i < paramNamelist.size(); i++) { + parameterNames[i] = paramNamelist.get(i); + } + gpa.setParameterNames(parameterNames); + + return gpa; + } +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/ConnectionReqEventHandler.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/ConnectionReqEventHandler.java index afa6a3f..8f03439 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/ConnectionReqEventHandler.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/ConnectionReqEventHandler.java @@ -21,7 +21,9 @@ package org.commscope.tr069adapter.acs.cpe.handler; import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_CF; import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_Q; + import java.io.IOException; + import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; import org.commscope.tr069adapter.acs.cpe.processor.ConnectionReqEventProcessor; diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/DeviceEventHandler.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/DeviceEventHandler.java index 4597cbb..7d1fba0 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/DeviceEventHandler.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/handler/DeviceEventHandler.java @@ -1,423 +1,426 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe.handler; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletResponse; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.common.inform.AbstractDeviceInform; -import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform; -import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler; -import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.cpe.TR069RPC; -import org.commscope.tr069adapter.acs.cpe.builder.DeviceInformBuilder; -import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCBuilder; -import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCResponseBuilder; -import org.commscope.tr069adapter.acs.cpe.rpc.Fault; -import org.commscope.tr069adapter.acs.cpe.rpc.Inform; -import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete; -import org.commscope.tr069adapter.common.timer.TimerException; -import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class DeviceEventHandler { - - private static final Logger logger = LoggerFactory.getLogger(DeviceEventHandler.class); - - private static final String CLIENT_STR = "client"; - - @Autowired - private DeviceInformBuilder deviceInformBuilder; - - @Autowired - private DeviceRPCBuilder deviceRPCBuilder; - - @Autowired - private DeviceRPCResponseBuilder deviceRPCResponseBuilder; - - @Autowired - private TR069DeviceEventHandler tr069DeviceEventHandler; - - @Autowired - private TimerServiceManagerAPI timerServiceManagerAPI; - - @Autowired - private DeviceValidator deviceValidtor; - - private static Map> informParameter = null; - - static { - informParameter = new HashMap<>(); - List parameters = new ArrayList<>(); - parameters.add("InternetGatewayDevice.DeviceInfo.HardwareVersion"); - parameters.add("InternetGatewayDevice.DeviceInfo.SoftwareVersion"); - parameters.add("InternetGatewayDevice.DeviceInfo.ProvisioningCode"); - parameters.add("InternetGatewayDevice.ManagementServer.ConnectionRequestURL"); - parameters.add("InternetGatewayDevice.ManagementServer.ParameterKey"); - informParameter.put("InternetGatewayDevice", parameters); - - List deviceParameters = new ArrayList<>(); - deviceParameters.add("Device.DeviceInfo.HardwareVersion"); - deviceParameters.add("Device.DeviceInfo.SoftwareVersion"); - deviceParameters.add("Device.DeviceInfo.ProvisioningCode"); - deviceParameters.add("Device.ManagementServer.ConnectionRequestURL"); - deviceParameters.add("Device.ManagementServer.ParameterKey"); - informParameter.put("Device", deviceParameters); - } - - /** - * @param inform - * @param authorizationHeader - * @return - * @throws TR069EventProcessingException - */ - public DeviceInformResponse processDeviceInform(Inform inform, String authorizationHeader) - throws TR069EventProcessingException { - - DeviceInformResponse deviceInformResponse = null; - try { - String deviceId = inform.getSn(); - MDC.put(CLIENT_STR, deviceId); - - logger.info("Processing the device Inform event"); - - logger.debug("Authorization header received in the request -> {}", authorizationHeader); - Boolean isAuthorized = deviceValidtor.isDeviceAuthorized(inform, authorizationHeader); - logger.info("Is device authentication successful: {}", isAuthorized); - if (!isAuthorized.booleanValue()) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.UNAUTHORIZED_EVENT, "Authorization failed"); - logger.error(ex.getMessage()); - throw ex; - } - - logger.debug("The root element is: {}", inform.getRoot()); - // Canceling any connection initiator timer running, due to inform event - stopConnectionInitiatorTimer(inform.getSn()); - - if (!deviceValidtor.validateDevice(inform.getSn(), inform.getOui(), inform.getProductClass()) - .booleanValue()) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.OUI_OR_PC_MISMATCH); - logger.error(ex.getMessage()); - throw ex; - } - - if (!validateInformParameters(inform)) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM); - logger.error(ex.getMessage()); - throw ex; - } - - AbstractDeviceInform deviceInform = deviceInformBuilder.constructDeviceInform(inform); - if (deviceInform == null) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM); - logger.error(ex.getMessage()); - throw ex; - } - - logger.debug("Sending the device inform to TR069 Request Processor to process"); - deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(deviceInform); - - } catch (TR069EventProcessingException tr069Ex) { - throw tr069Ex; - } catch (Exception e) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage()); - logger.error(ex.getMessage()); - throw ex; - } finally { - MDC.remove(CLIENT_STR); - } - - return deviceInformResponse; - - } - - /** - * @param tc - * @return - * @throws TR069EventProcessingException - */ - public DeviceInformResponse processTransferComplete(TransferComplete tc) - throws TR069EventProcessingException { - - logger.debug("Processing Transfer Complete"); - - String startTime = tc.getStartTime(); - String completeTime = tc.getCompleteTime(); - int faultCode = tc.getFaultCode(); - String faultString = tc.getFaultString(); - String commandKey = tc.getCommandKey(); - - DeviceInformResponse deviceInformResponse = null; - - try { - MDC.put(CLIENT_STR, commandKey); - TransferCompleteInform transferCompleteInform = new TransferCompleteInform(); - transferCompleteInform.setCommandKey(tc.getCommandKey()); - transferCompleteInform.setCompleteTime(completeTime); - transferCompleteInform.setFaultCode(faultCode); - transferCompleteInform.setFaultString(faultString); - transferCompleteInform.setStartTime(startTime); - - logger.debug("TransferComplete inform received with Start time"); - - transferCompleteInform.setDeviceDetails(tr069DeviceEventHandler.getDeviceDetails(commandKey)); - deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(transferCompleteInform); - logger.debug("Successfully processed the TRANSFER COMPLETE Inform"); - - } catch (Exception e) { - throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - - return deviceInformResponse; - } - - /** - * @param msg - * @param sessionId - * @return - * @throws TR069EventProcessingException - */ - public TR069RPC processRPCResponse(TR069RPC msg, String sessionId) - throws TR069EventProcessingException { - DeviceOperationRequestDetails deviceOperationRequestDetails = null; - try { - deviceOperationRequestDetails = - tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId); - if (null == deviceOperationRequestDetails - || null == deviceOperationRequestDetails.getDeviceDetails()) { - logger.error("Response with invalid session ID: {}", sessionId); - return null; - } - - String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId(); - MDC.put(CLIENT_STR, deviceId); - DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse(); - deviceRPCResponse.setDeviceDetails(deviceOperationRequestDetails.getDeviceDetails()); - deviceRPCResponse.setOperationId(deviceOperationRequestDetails.getOperationId()); - OperationResponse operationResponse = null; - if (msg instanceof Fault) { - Fault values = (Fault) msg; - logger.info("{} ID->{} faultCode->{} faultString->{}", values.getName(), values.getId(), - values.getCwmpFaultCode(), values.getFaultStringCwmp()); - deviceRPCResponse.setFaultKey(values.getCwmpFaultCode()); - deviceRPCResponse.setFaultString( - values.getFaultStringCwmp() + ": Error code: " + values.getCwmpFaultCode()); - - TR069OperationCode operationCode = - (TR069OperationCode) deviceOperationRequestDetails.getOpCode(); - operationResponse = constructResponseForFault(operationCode); - if (operationResponse != null) { - operationResponse.setStatus(1); - operationResponse.setParameterDTOs(new ArrayList()); - } - } else { - operationResponse = deviceRPCResponseBuilder.constructDeviceRPCResponse(msg); - } - deviceRPCResponse.setOperationResponse(operationResponse); - - DeviceRPCRequest deviceRPCRequest = - tr069DeviceEventHandler.processDeviceRPCResponse(deviceRPCResponse); - if (null != deviceRPCRequest) { - return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest); - } - } catch (SessionManagerException e) { - logger.error("Error while getting device detail for the session id: {}", sessionId); - } catch (Exception e) { - throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_RPC_RESPONSE, - msg.getName(), e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - - return null; - } - - /** - * @param sessionId - * @return - * @throws TR069EventProcessingException - */ - public TR069RPC processEmptyRequest(String sessionId) throws TR069EventProcessingException { - try { - DeviceOperationRequestDetails deviceOperationRequestDetails = - tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId); - DeviceRPCRequest deviceRPCRequest = null; - String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId(); - MDC.put(CLIENT_STR, deviceId); - deviceRPCRequest = tr069DeviceEventHandler - .processEmptyDeviceRequest(deviceOperationRequestDetails.getDeviceDetails()); - if (null == deviceRPCRequest) { - return null; - } else { - logger.debug("There exists a NBI request to process."); - return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest); - } - } catch (SessionManagerException e) { - logger.error("Error while processing empty request, reason: {}", e.getMessage()); - } catch (Exception e) { - throw new TR069EventProcessingException(ErrorCode.EMPTY_REQUEST_PROCESSING_ERROR, - e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - return null; - } - - /** - * @param operationCode - * @return - */ - private OperationResponse constructResponseForFault(TR069OperationCode operationCode) { - OperationResponse operationResponse = null; - if (operationCode.equals(TR069OperationCode.ADD_OBJECT)) { - operationResponse = new org.commscope.tr069adapter.acs.common.response.AddObjectResponse(); - } else if (operationCode.equals(TR069OperationCode.DELETE_OBJECT)) { - operationResponse = new org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse(); - } else if (operationCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) { - operationResponse = - new org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse(); - } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) { - operationResponse = - new org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse(); - } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) { - operationResponse = - new org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse(); - } - return operationResponse; - } - - /** - * @param serialNumber - */ - public void stopConnectionInitiatorTimer(String serialNumber) { - String timerId = serialNumber + SEPERATOR + CONNECTION_REQUEST; - try { - logger - .debug("Canceling the Connection initiation timer, as Inform is been sent by the device"); - timerServiceManagerAPI.stopTimer(timerId); - } catch (TimerException e) { - logger.error( - "An exception occurred while stopping the connection initiator session timer, Reason: {}", - e.getMessage()); - } - } - - /** - * @param lastInform - * @return - */ - private boolean validateInformParameters(Inform lastInform) { - boolean validate = false; - String root = lastInform.getRoot(); - if (!informParameter.containsKey(root)) - return validate; - List params = informParameter.get(root); - Set keySet = lastInform.getParams().keySet(); - validate = true; - for (String param : params) { - if (!keySet.contains(param)) { - logger.warn("This param Not found in the inform {}", param); - validate = false; - break; - } - } - return validate; - } - - /** - * @param tr069ex - * @return - */ - public int handleException(TR069EventProcessingException tr069ex) { - - int errorresponseCode = 0; - - ErrorCode errorCode = tr069ex.getErrorCode(); - switch (errorCode) { - case UNSUPPORTED_CHARACTER_ENCODING: - case INVALID_PARAMS_IN_INFORM: - case FAILED_PROCESSING_INFORM: - errorresponseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - break; - case UNAUTHORIZED_EVENT: - errorresponseCode = HttpServletResponse.SC_UNAUTHORIZED; - break; - default: - break; - } - - return errorresponseCode; - } - - /***************************************************************************************************************************/ - - public void setDeviceInformBuilder(DeviceInformBuilder deviceInformBuilder) { - this.deviceInformBuilder = deviceInformBuilder; - } - - public void setDeviceRPCBuilder(DeviceRPCBuilder deviceRPCBuilder) { - this.deviceRPCBuilder = deviceRPCBuilder; - } - - public void setDeviceRPCResponseBuilder(DeviceRPCResponseBuilder deviceRPCResponseBuilder) { - this.deviceRPCResponseBuilder = deviceRPCResponseBuilder; - } - - public void setTr069DeviceEventHandler(TR069DeviceEventHandler tr069DeviceEventHandler) { - this.tr069DeviceEventHandler = tr069DeviceEventHandler; - } - - public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) { - this.timerServiceManagerAPI = timerServiceManagerAPI; - } - - public void setDeviceAuthenticator(DeviceValidator deviceAuthenticator) { - this.deviceValidtor = deviceAuthenticator; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe.handler; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletResponse; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.common.inform.AbstractDeviceInform; +import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform; +import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler; +import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.cpe.TR069RPC; +import org.commscope.tr069adapter.acs.cpe.builder.DeviceInformBuilder; +import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCBuilder; +import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCResponseBuilder; +import org.commscope.tr069adapter.acs.cpe.rpc.Fault; +import org.commscope.tr069adapter.acs.cpe.rpc.Inform; +import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete; +import org.commscope.tr069adapter.common.timer.TimerException; +import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class DeviceEventHandler { + + private static final Logger logger = LoggerFactory.getLogger(DeviceEventHandler.class); + public static final String PATTERN = "[\n|\r|\t]"; + + private static final String CLIENT_STR = "client"; + + @Autowired + private DeviceInformBuilder deviceInformBuilder; + + @Autowired + private DeviceRPCBuilder deviceRPCBuilder; + + @Autowired + private DeviceRPCResponseBuilder deviceRPCResponseBuilder; + + @Autowired + private TR069DeviceEventHandler tr069DeviceEventHandler; + + @Autowired + private TimerServiceManagerAPI timerServiceManagerAPI; + + @Autowired + private DeviceValidator deviceValidtor; + + private static Map> informParameter = null; + + static { + informParameter = new HashMap<>(); + List parameters = new ArrayList<>(); + parameters.add("InternetGatewayDevice.DeviceInfo.HardwareVersion"); + parameters.add("InternetGatewayDevice.DeviceInfo.SoftwareVersion"); + parameters.add("InternetGatewayDevice.DeviceInfo.ProvisioningCode"); + parameters.add("InternetGatewayDevice.ManagementServer.ConnectionRequestURL"); + parameters.add("InternetGatewayDevice.ManagementServer.ParameterKey"); + informParameter.put("InternetGatewayDevice", parameters); + + List deviceParameters = new ArrayList<>(); + deviceParameters.add("Device.DeviceInfo.HardwareVersion"); + deviceParameters.add("Device.DeviceInfo.SoftwareVersion"); + deviceParameters.add("Device.DeviceInfo.ProvisioningCode"); + deviceParameters.add("Device.ManagementServer.ConnectionRequestURL"); + deviceParameters.add("Device.ManagementServer.ParameterKey"); + informParameter.put("Device", deviceParameters); + } + + /** + * @param inform + * @param authorizationHeader + * @return + * @throws TR069EventProcessingException + */ + public DeviceInformResponse processDeviceInform(Inform inform, String authorizationHeader) + throws TR069EventProcessingException { + + DeviceInformResponse deviceInformResponse = null; + try { + String deviceId = inform.getSn(); + MDC.put(CLIENT_STR, deviceId); + + logger.info("Processing the device Inform event"); + + logger.debug("Authorization header received in the request -> {}", authorizationHeader); + Boolean isAuthorized = deviceValidtor.isDeviceAuthorized(inform, authorizationHeader); + logger.info("Is device authentication successful: {}", isAuthorized); + if (!isAuthorized.booleanValue()) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.UNAUTHORIZED_EVENT, "Authorization failed"); + String exceptionMessage = ex.getMessage().replaceAll(PATTERN, "_"); + logger.error(exceptionMessage); + throw ex; + } + + logger.debug("The root element is: {}", inform.getRoot()); + // Canceling any connection initiator timer running, due to inform event + stopConnectionInitiatorTimer(inform.getSn()); + + if (!deviceValidtor.validateDevice(inform.getSn(), inform.getOui(), inform.getProductClass()) + .booleanValue()) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.OUI_OR_PC_MISMATCH); + logger.error(ex.getMessage()); + throw ex; + } + + if (!validateInformParameters(inform)) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM); + logger.error(ex.getMessage()); + throw ex; + } + + AbstractDeviceInform deviceInform = deviceInformBuilder.constructDeviceInform(inform); + if (deviceInform == null) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM); + logger.error(ex.getMessage()); + throw ex; + } + + logger.debug("Sending the device inform to TR069 Request Processor to process"); + deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(deviceInform); + + } catch (TR069EventProcessingException tr069Ex) { + throw tr069Ex; + } catch (Exception e) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage()); + String exceptionMessage = ex.getMessage().replaceAll(PATTERN, "_"); + logger.error(exceptionMessage); + throw ex; + } finally { + MDC.remove(CLIENT_STR); + } + + return deviceInformResponse; + + } + + /** + * @param tc + * @return + * @throws TR069EventProcessingException + */ + public DeviceInformResponse processTransferComplete(TransferComplete tc) + throws TR069EventProcessingException { + + logger.debug("Processing Transfer Complete"); + + String startTime = tc.getStartTime(); + String completeTime = tc.getCompleteTime(); + int faultCode = tc.getFaultCode(); + String faultString = tc.getFaultString(); + String commandKey = tc.getCommandKey(); + + DeviceInformResponse deviceInformResponse = null; + + try { + MDC.put(CLIENT_STR, commandKey); + TransferCompleteInform transferCompleteInform = new TransferCompleteInform(); + transferCompleteInform.setCommandKey(tc.getCommandKey()); + transferCompleteInform.setCompleteTime(completeTime); + transferCompleteInform.setFaultCode(faultCode); + transferCompleteInform.setFaultString(faultString); + transferCompleteInform.setStartTime(startTime); + + logger.debug("TransferComplete inform received with Start time"); + + transferCompleteInform.setDeviceDetails(tr069DeviceEventHandler.getDeviceDetails(commandKey)); + deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(transferCompleteInform); + logger.debug("Successfully processed the TRANSFER COMPLETE Inform"); + + } catch (Exception e) { + throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + + return deviceInformResponse; + } + + /** + * @param msg + * @param sessionId + * @return + * @throws TR069EventProcessingException + */ + public TR069RPC processRPCResponse(TR069RPC msg, String sessionId) + throws TR069EventProcessingException { + DeviceOperationRequestDetails deviceOperationRequestDetails = null; + try { + deviceOperationRequestDetails = + tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId); + if (null == deviceOperationRequestDetails + || null == deviceOperationRequestDetails.getDeviceDetails()) { + sessionId = sessionId.replaceAll(PATTERN, "_"); + logger.error("Response with invalid session ID: {}", sessionId); + return null; + } + + String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId(); + MDC.put(CLIENT_STR, deviceId); + DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse(); + deviceRPCResponse.setDeviceDetails(deviceOperationRequestDetails.getDeviceDetails()); + deviceRPCResponse.setOperationId(deviceOperationRequestDetails.getOperationId()); + OperationResponse operationResponse = null; + if (msg instanceof Fault) { + Fault values = (Fault) msg; + logger.info("{} ID->{} faultCode->{} faultString->{}", values.getName(), values.getId(), + values.getCwmpFaultCode(), values.getFaultStringCwmp()); + deviceRPCResponse.setFaultKey(values.getCwmpFaultCode()); + deviceRPCResponse.setFaultString( + values.getFaultStringCwmp() + ": Error code: " + values.getCwmpFaultCode()); + + TR069OperationCode operationCode = + (TR069OperationCode) deviceOperationRequestDetails.getOpCode(); + operationResponse = constructResponseForFault(operationCode); + if (operationResponse != null) { + operationResponse.setStatus(1); + operationResponse.setParameterDTOs(new ArrayList<>()); + } + } else { + operationResponse = deviceRPCResponseBuilder.constructDeviceRPCResponse(msg); + } + deviceRPCResponse.setOperationResponse(operationResponse); + + DeviceRPCRequest deviceRPCRequest = + tr069DeviceEventHandler.processDeviceRPCResponse(deviceRPCResponse); + if (null != deviceRPCRequest) { + return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest); + } + } catch (SessionManagerException e) { + logger.error("Error while getting device detail for the session id: {}", sessionId); + } catch (Exception e) { + throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_RPC_RESPONSE, + msg.getName(), e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + + return null; + } + + /** + * @param sessionId + * @return + * @throws TR069EventProcessingException + */ + public TR069RPC processEmptyRequest(String sessionId) throws TR069EventProcessingException { + try { + DeviceOperationRequestDetails deviceOperationRequestDetails = + tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId); + DeviceRPCRequest deviceRPCRequest = null; + String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId(); + MDC.put(CLIENT_STR, deviceId); + deviceRPCRequest = tr069DeviceEventHandler + .processEmptyDeviceRequest(deviceOperationRequestDetails.getDeviceDetails()); + if (null == deviceRPCRequest) { + return null; + } else { + logger.debug("There exists a NBI request to process."); + return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest); + } + } catch (SessionManagerException e) { + logger.error("Error while processing empty request, reason: {}", e.getMessage()); + } catch (Exception e) { + throw new TR069EventProcessingException(ErrorCode.EMPTY_REQUEST_PROCESSING_ERROR, + e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + return null; + } + + /** + * @param operationCode + * @return + */ + private OperationResponse constructResponseForFault(TR069OperationCode operationCode) { + OperationResponse operationResponse = null; + if (operationCode.equals(TR069OperationCode.ADD_OBJECT)) { + operationResponse = new org.commscope.tr069adapter.acs.common.response.AddObjectResponse(); + } else if (operationCode.equals(TR069OperationCode.DELETE_OBJECT)) { + operationResponse = new org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse(); + } else if (operationCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) { + operationResponse = + new org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse(); + } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) { + operationResponse = + new org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse(); + } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) { + operationResponse = + new org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse(); + } + return operationResponse; + } + + /** + * @param serialNumber + */ + public void stopConnectionInitiatorTimer(String serialNumber) { + String timerId = serialNumber + SEPERATOR + CONNECTION_REQUEST; + try { + logger + .debug("Canceling the Connection initiation timer, as Inform is been sent by the device"); + timerServiceManagerAPI.stopTimer(timerId); + } catch (TimerException e) { + logger.error( + "An exception occurred while stopping the connection initiator session timer, Reason: {}", + e.getMessage()); + } + } + + /** + * @param lastInform + * @return + */ + private boolean validateInformParameters(Inform lastInform) { + boolean validate = false; + String root = lastInform.getRoot(); + if (!informParameter.containsKey(root)) + return validate; + List params = informParameter.get(root); + Set keySet = lastInform.getParams().keySet(); + validate = true; + for (String param : params) { + if (!keySet.contains(param)) { + logger.warn("This param Not found in the inform {}", param); + validate = false; + break; + } + } + return validate; + } + + /** + * @param tr069ex + * @return + */ + public int handleException(TR069EventProcessingException tr069ex) { + + int errorresponseCode = 0; + + ErrorCode errorCode = tr069ex.getErrorCode(); + switch (errorCode) { + case UNSUPPORTED_CHARACTER_ENCODING: + case INVALID_PARAMS_IN_INFORM: + case FAILED_PROCESSING_INFORM: + errorresponseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + break; + case UNAUTHORIZED_EVENT: + errorresponseCode = HttpServletResponse.SC_UNAUTHORIZED; + break; + default: + break; + } + + return errorresponseCode; + } + + /***************************************************************************************************************************/ + + public void setDeviceInformBuilder(DeviceInformBuilder deviceInformBuilder) { + this.deviceInformBuilder = deviceInformBuilder; + } + + public void setDeviceRPCBuilder(DeviceRPCBuilder deviceRPCBuilder) { + this.deviceRPCBuilder = deviceRPCBuilder; + } + + public void setDeviceRPCResponseBuilder(DeviceRPCResponseBuilder deviceRPCResponseBuilder) { + this.deviceRPCResponseBuilder = deviceRPCResponseBuilder; + } + + public void setTr069DeviceEventHandler(TR069DeviceEventHandler tr069DeviceEventHandler) { + this.tr069DeviceEventHandler = tr069DeviceEventHandler; + } + + public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) { + this.timerServiceManagerAPI = timerServiceManagerAPI; + } + + public void setDeviceAuthenticator(DeviceValidator deviceAuthenticator) { + this.deviceValidtor = deviceAuthenticator; + } + +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/processor/ConnectionReqEventProcessor.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/processor/ConnectionReqEventProcessor.java index f43e938..1bee058 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/processor/ConnectionReqEventProcessor.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/processor/ConnectionReqEventProcessor.java @@ -1,126 +1,126 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe.processor; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_RETRY_SLEEP_TIME; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT_CALLBACK; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.HTTP_OP_FAILED; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAX_CONNECT_RETRY_COUNT; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR; - -import java.io.IOException; - -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector; -import org.commscope.tr069adapter.common.timer.TimerException; -import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ConnectionReqEventProcessor { - - private static final Logger logger = LoggerFactory.getLogger(ConnectionReqEventProcessor.class); - - @Autowired - private DeviceConnector deviceConnector; - - @Autowired - private TimerServiceManagerAPI timerServiceManagerAPI; - - public void initiateConnectionRequest(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry) - throws SessionManagerException, IOException { - DeviceRPCResponse deviceRPCResponse = null; - - for (int retryCount = 0; retryCount < MAX_CONNECT_RETRY_COUNT; retryCount++) { - logger.info("Initiating connection request on the device. Connection request URL is : {}", - tr069DeviceDetails.getConnectionRequestURL()); - deviceRPCResponse = deviceConnector.requestConnectionHttp(tr069DeviceDetails); - - if (deviceRPCResponse.getOperationResponse().getStatus() == HTTP_OP_FAILED) { - onFailedHTTPGetOperation(deviceRPCResponse); - logger.debug("Connection Request Retry attempt - {}", retryCount + 1); - - if ((retryCount + 1) == MAX_CONNECT_RETRY_COUNT) { - SessionManagerException e = new SessionManagerException( - ErrorCode.SESSION_INITIATION_FAILED, tr069DeviceDetails.getDeviceId()); - logger.error(e.getMessage()); - throw e; - } - } else { - onSuccessHTTPGetOperation(tr069DeviceDetails, isRetry); - break; - } - } - } - - private void onFailedHTTPGetOperation(DeviceRPCResponse deviceRPCResponse) { - logger.warn("Connection request failed with device, Error: {}", - deviceRPCResponse.getFaultString()); - logger.debug("Waiting for " + CONNECTION_RETRY_SLEEP_TIME + " millisec before retry"); - try { - Thread.sleep(CONNECTION_RETRY_SLEEP_TIME); - } catch (InterruptedException e1) { - logger.error("Interrupted exception while waiting for CR retry"); - Thread.currentThread().interrupt(); - } - } - - private void onSuccessHTTPGetOperation(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry) { - try { - String timerId = tr069DeviceDetails.getDeviceId() + SEPERATOR + CONNECTION_REQUEST; - if (isRetry.booleanValue()) { - timerServiceManagerAPI.modifyTimer(timerId, CR_TIMEOUT, tr069DeviceDetails); - } else { - timerServiceManagerAPI.startTimer(timerId, CR_TIMEOUT_CALLBACK, CR_TIMEOUT, - tr069DeviceDetails); - } - logger.debug( - "Successfully started the timer task for connection request initiation on device : {}", - tr069DeviceDetails.getDeviceId()); - } catch (TimerException e) { - logger.error("Couldn't start the timer task for connection request initiation on device : {}", - tr069DeviceDetails.getDeviceId()); - } - } - - public DeviceConnector getDeviceConnector() { - return deviceConnector; - } - - public void setDeviceConnector(DeviceConnector deviceConnector) { - this.deviceConnector = deviceConnector; - } - - public TimerServiceManagerAPI getTimerServiceManagerAPI() { - return timerServiceManagerAPI; - } - - public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) { - this.timerServiceManagerAPI = timerServiceManagerAPI; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe.processor; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT_CALLBACK; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.HTTP_OP_FAILED; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR; + +import java.io.IOException; + +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector; +import org.commscope.tr069adapter.common.timer.TimerException; +import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ConnectionReqEventProcessor { + + private static final Logger logger = LoggerFactory.getLogger(ConnectionReqEventProcessor.class); + + @Autowired + private DeviceConnector deviceConnector; + + @Autowired + private TimerServiceManagerAPI timerServiceManagerAPI; + + @Autowired + TR069DeviceEventHandler tr069EventHandler; + + public void initiateConnectionRequest(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry) + throws SessionManagerException, IOException { + DeviceRPCResponse deviceRPCResponse = null; + + logger.info("Initiating connection request on the device. Connection request URL is : {}", + tr069DeviceDetails.getConnectionRequestURL()); + boolean isConnectionFailed = true; + try { + deviceRPCResponse = deviceConnector.requestConnectionHttp(tr069DeviceDetails); + } catch (Exception e) { + logger.error("Connection Failed with the Device: {}", e.getMessage()); + isConnectionFailed = false; + } + + if (!isConnectionFailed + || deviceRPCResponse.getOperationResponse().getStatus() == HTTP_OP_FAILED) { + tr069DeviceDetails.setCrRetryCount(tr069DeviceDetails.getCrRetryCount() + 1); + String faultStr = ""; + if (deviceRPCResponse != null) { + faultStr = deviceRPCResponse.getFaultString(); + } + logger.warn("Connection request failed with device, Error: {}, on attempt- {}", faultStr, + tr069DeviceDetails.getCrRetryCount()); + if (tr069DeviceDetails.getCrRetryCount() == 1) { + logger.error("CONNECT request is failed, not retrying the CR to device"); + } else { + SessionManagerException e = new SessionManagerException(ErrorCode.SESSION_INITIATION_FAILED, + tr069DeviceDetails.getDeviceId()); + logger.error(e.getMessage()); + throw e; + } + } else { + onSuccessHTTPGetOperation(tr069DeviceDetails, isRetry); + } + } + + private void onSuccessHTTPGetOperation(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry) { + try { + String timerId = tr069DeviceDetails.getDeviceId() + SEPERATOR + CONNECTION_REQUEST; + if (isRetry.booleanValue()) { + timerServiceManagerAPI.modifyTimer(timerId, CR_TIMEOUT, tr069DeviceDetails); + } else { + timerServiceManagerAPI.startTimer(timerId, CR_TIMEOUT_CALLBACK, CR_TIMEOUT, + tr069DeviceDetails); + } + logger.debug( + "Successfully started the timer task for connection request initiation on device : {}", + tr069DeviceDetails.getDeviceId()); + } catch (TimerException e) { + logger.error("Couldn't start the timer task for connection request initiation on device : {}", + tr069DeviceDetails.getDeviceId()); + } + } + + public DeviceConnector getDeviceConnector() { + return deviceConnector; + } + + public void setDeviceConnector(DeviceConnector deviceConnector) { + this.deviceConnector = deviceConnector; + } + + public TimerServiceManagerAPI getTimerServiceManagerAPI() { + return timerServiceManagerAPI; + } + + public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) { + this.timerServiceManagerAPI = timerServiceManagerAPI; + } + +} diff --git a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/rpc/Upload.java b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/rpc/Upload.java index 09ba567..8659321 100644 --- a/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/rpc/Upload.java +++ b/acs/cpe/src/main/java/org/commscope/tr069adapter/acs/cpe/rpc/Upload.java @@ -1,64 +1,64 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.cpe.rpc; - -import javax.xml.soap.SOAPBodyElement; -import javax.xml.soap.SOAPException; -import javax.xml.soap.SOAPFactory; - -import org.commscope.tr069adapter.acs.cpe.TR069RPC; - -public class Upload extends TR069RPC { - - private static final long serialVersionUID = -3096728959585163928L; - - /** Creates a new instance of Upload */ - public Upload() { - name = "Upload"; - username = ""; - password = ""; - delaySeconds = 0; - fileType = FT_CONFIG; - url = "http://192.168.1.1:8080/acs-war/upload/tst.cfg"; - commandKey = "default.command.key"; - } - - protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException { - body.addChildElement(COMMAND_KEY).setValue(commandKey); - body.addChildElement("FileType").setValue(fileType); - - body.addChildElement("URL").setValue(url); - body.addChildElement("Username").setValue(username); - body.addChildElement("Password").setValue(password); - body.addChildElement("DelaySeconds").setValue(String.valueOf(delaySeconds)); - } - - protected void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException { - logger.isDebugEnabled(); - } - - private String commandKey; - private String fileType; - private String url; - private String username; - private String password; - private int delaySeconds; - public static final String FT_CONFIG = "1 Vendor Configuration File"; - public static final String FT_LOG = "2 Vendor Log File"; -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.cpe.rpc; + +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPFactory; + +import org.commscope.tr069adapter.acs.cpe.TR069RPC; + +public class Upload extends TR069RPC { + + private static final long serialVersionUID = -3096728959585163928L; + + /** Creates a new instance of Upload */ + public Upload() { + name = "Upload"; + username = ""; + password = ""; + delaySeconds = 0; + fileType = FT_CONFIG; + url = "http://localhost:8080/acs-war/upload/tst.cfg"; + commandKey = "default.command.key"; + } + + protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException { + body.addChildElement(COMMAND_KEY).setValue(commandKey); + body.addChildElement("FileType").setValue(fileType); + + body.addChildElement("URL").setValue(url); + body.addChildElement("Username").setValue(username); + body.addChildElement("Password").setValue(password); + body.addChildElement("DelaySeconds").setValue(String.valueOf(delaySeconds)); + } + + protected void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException { + logger.isDebugEnabled(); + } + + private String commandKey; + private String fileType; + private String url; + private String username; + private String password; + private int delaySeconds; + public static final String FT_CONFIG = "1 Vendor Configuration File"; + public static final String FT_LOG = "2 Vendor Log File"; +} diff --git a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/ACSServiceAPIImpl.java b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/ACSServiceAPIImpl.java index 835f24c..1e1ff1a 100644 --- a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/ACSServiceAPIImpl.java +++ b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/ACSServiceAPIImpl.java @@ -1,100 +1,100 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.nbi.impl; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.exception.MapperServiceException; -import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI; -import org.commscope.tr069adapter.acs.nbi.util.OperationIdGenerator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.stereotype.Component; - -@Component(MAPPER_SERVICE_QUALILFIER) -public class ACSServiceAPIImpl implements ACSServiceAPI { - - private static final Logger logger = LoggerFactory.getLogger(ACSServiceAPIImpl.class); - - private static final String CLIENT_STR = "client"; - - @Autowired - private OperationIdGenerator opIdGenerator; - - @Autowired - private JmsTemplate jmsTemplate; - - /* - * (non-Javadoc) - * - * @see org.commscope.tr069adapter.acs.mapper.ACSServiceAPI#performDeviceOperation(org.commscope. - * tr069adapter.acs.DeviceRPCRequest) - */ - @Override - public long performDeviceOperation(DeviceRPCRequest deviceRPCRequest) - throws MapperServiceException { - - Long opId = 0l; - try { - if (deviceRPCRequest != null && deviceRPCRequest.getDeviceDetails() != null) { - MDC.put(CLIENT_STR, deviceRPCRequest.getDeviceDetails().getDeviceId()); - } - - // validate the request and reject if not valid. - if (null == deviceRPCRequest) { - logger.error("Received null Mapper Request."); - throw new MapperServiceException("Received null Mapper Request."); - } else if (null == deviceRPCRequest.getOpDetails()) { - logger.error("Received null operation details."); - throw new MapperServiceException("Received null operation details."); - } else if (null == deviceRPCRequest.getOpDetails().getOpCode()) { - logger.error("Received null operation code."); - throw new MapperServiceException("Received null operation code."); - } - - logger.info("Received request to perform device operation. OperationCode: {}", - deviceRPCRequest.getOpDetails().getOpCode()); - opId = opIdGenerator.generateOpId(); - logger.debug("The operation ID generated for processing the Device RPC request is - {}", - opId); - // set opId and forward the request - deviceRPCRequest.setOperationId(opId); - jmsTemplate.convertAndSend(TR069_NBI_REQUEST_Q, deviceRPCRequest); - - logger.debug( - "Successfully posted the Mapper Request to Queue with OperationId : {} OperationCode : {}", - deviceRPCRequest.getOperationId(), deviceRPCRequest.getOpDetails().getOpCode()); - } catch (Exception ex) { - MapperServiceException mapperEx = - new MapperServiceException("ACS Internal Error. Unknown Exception. Details :", ex); - logger.error(mapperEx.getMessage()); - throw mapperEx; - } finally { - MDC.remove(CLIENT_STR); - } - - return opId; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.nbi.impl; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.OperationCode; +import org.commscope.tr069adapter.acs.common.exception.MapperServiceException; +import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI; +import org.commscope.tr069adapter.acs.nbi.util.OperationIdGenerator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.stereotype.Component; + +@Component(MAPPER_SERVICE_QUALILFIER) +public class ACSServiceAPIImpl implements ACSServiceAPI { + + private static final Logger logger = LoggerFactory.getLogger(ACSServiceAPIImpl.class); + + private static final String CLIENT_STR = "client"; + + @Autowired + private OperationIdGenerator opIdGenerator; + + @Autowired + private JmsTemplate jmsTemplate; + + /* + * (non-Javadoc) + * + * @see org.commscope.tr069adapter.acs.mapper.ACSServiceAPI#performDeviceOperation(org.commscope. + * tr069adapter.acs.DeviceRPCRequest) + */ + @Override + public long performDeviceOperation(DeviceRPCRequest deviceRPCRequest) + throws MapperServiceException { + + Long opId = 0l; + try { + if (deviceRPCRequest != null && deviceRPCRequest.getDeviceDetails() != null) { + MDC.put(CLIENT_STR, deviceRPCRequest.getDeviceDetails().getDeviceId()); + } + + // validate the request and reject if not valid. + if (null == deviceRPCRequest) { + logger.error("Received null Mapper Request."); + throw new MapperServiceException("Received null Mapper Request."); + } else if (null == deviceRPCRequest.getOpDetails()) { + logger.error("Received null operation details."); + throw new MapperServiceException("Received null operation details."); + } else if (null == deviceRPCRequest.getOpDetails().getOpCode()) { + logger.error("Received null operation code."); + throw new MapperServiceException("Received null operation code."); + } + OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode(); + logger.info("Received request to perform device operation. OperationCode: {}", opCode); + opId = opIdGenerator.generateOpId(); + logger.debug("The operation ID generated for processing the Device RPC request is - {}", + opId); + // set opId and forward the request + deviceRPCRequest.setOperationId(opId); + jmsTemplate.convertAndSend(TR069_NBI_REQUEST_Q, deviceRPCRequest); + + logger.debug( + "Successfully posted the Mapper Request to Queue with OperationId : {} OperationCode : {}", + deviceRPCRequest.getOperationId(), deviceRPCRequest.getOpDetails().getOpCode()); + } catch (Exception ex) { + MapperServiceException mapperEx = + new MapperServiceException("ACS Internal Error. Unknown Exception. Details :", ex); + logger.error(mapperEx.getMessage()); + throw mapperEx; + } finally { + MDC.remove(CLIENT_STR); + } + + return opId; + } + +} diff --git a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceInformForwarder.java b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceInformForwarder.java index 2833f4a..b62e61a 100644 --- a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceInformForwarder.java +++ b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceInformForwarder.java @@ -1,53 +1,54 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.nbi.impl; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_CF; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.annotation.JmsListener; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -@Component -public class DeviceInformForwarder { - - private static final Logger logger = LoggerFactory.getLogger(DeviceInformForwarder.class); - - @Autowired - private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService; - - @JmsListener(destination = NBI_NOTIFICATION_Q, containerFactory = NBI_NOTIFICATION_CF) - @Transactional(rollbackFor = Exception.class) - public void onMessage(DeviceInform notification) { - if (null != notification) { - logger.debug( - "DeviceNotification message is received for deviceId : {} , Notification Type(s): {}", - notification.getDeviceDetails().getDeviceId(), notification.getInformTypeList()); - deviceEventsMapperNotificationService.processDeviceNotification(notification); - logger.debug("Successfully processed device notification."); - } else { - logger.error("Null device response is received!!!"); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.nbi.impl; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_CF; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +public class DeviceInformForwarder { + + private static final Logger logger = LoggerFactory.getLogger(DeviceInformForwarder.class); + + @Autowired + private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService; + + @JmsListener(destination = NBI_NOTIFICATION_Q, containerFactory = NBI_NOTIFICATION_CF) + @Transactional(rollbackFor = Exception.class) + public void onMessage(DeviceInform notification) { + if (null != notification) { + logger.debug( + "DeviceNotification message is received for deviceId : {} , Notification Type(s): {}", + notification.getDeviceDetails().getDeviceId(), notification.getInformTypeList()); + deviceEventsMapperNotificationService.processDeviceNotification(notification); + logger.debug("Successfully processed device notification."); + } else { + logger.error("Null device response is received!!!"); + } + } +} diff --git a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceRPCResponseForwarder.java b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceRPCResponseForwarder.java index 4971056..156b420 100644 --- a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceRPCResponseForwarder.java +++ b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/impl/DeviceRPCResponseForwarder.java @@ -1,52 +1,53 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.nbi.impl; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_CF; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.annotation.JmsListener; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -@Component -public class DeviceRPCResponseForwarder { - - private static final Logger logger = LoggerFactory.getLogger(DeviceRPCResponseForwarder.class); - - @Autowired - private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService; - - @JmsListener(destination = NBI_OP_RESULT_Q, containerFactory = NBI_OP_RESULT_CF) - @Transactional(rollbackFor = Exception.class) - public void onMessage(DeviceRPCResponse opResult) { - if (null != opResult) { - logger.debug("NBIOperationResult message is received for deviceId : {}, , OprationId: {}", - opResult.getDeviceDetails().getDeviceId(), opResult.getOperationId()); - deviceEventsMapperNotificationService.processOperationResponse(opResult); - logger.debug("Successfully processed NBI operation result."); - } else { - logger.error("Null device response is received!!!"); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.nbi.impl; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_CF; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; + +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +public class DeviceRPCResponseForwarder { + + private static final Logger logger = LoggerFactory.getLogger(DeviceRPCResponseForwarder.class); + + @Autowired + private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService; + + @JmsListener(destination = NBI_OP_RESULT_Q, containerFactory = NBI_OP_RESULT_CF) + @Transactional(rollbackFor = Exception.class) + public void onMessage(DeviceRPCResponse opResult) { + if (null != opResult) { + logger.debug("NBIOperationResult message is received for deviceId : {}, , OprationId: {}", + opResult.getDeviceDetails().getDeviceId(), opResult.getOperationId()); + deviceEventsMapperNotificationService.processOperationResponse(opResult); + logger.debug("Successfully processed NBI operation result."); + } else { + logger.error("Null device response is received!!!"); + } + } +} diff --git a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/mapper/service/MapperRequestRESTService.java b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/mapper/service/MapperRequestRESTService.java index 9ea4eec..5b417a0 100644 --- a/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/mapper/service/MapperRequestRESTService.java +++ b/acs/nbi/src/main/java/org/commscope/tr069adapter/acs/nbi/mapper/service/MapperRequestRESTService.java @@ -1,62 +1,92 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.nbi.mapper.service; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.exception.MapperServiceException; -import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/MapperService") -public class MapperRequestRESTService { - - private static final Logger logger = LoggerFactory.getLogger(MapperRequestRESTService.class); - - @Qualifier(value = MAPPER_SERVICE_QUALILFIER) - @Autowired - ACSServiceAPI acsServiceAPI; - - @PostMapping("/initiateDeviceOperation") - public Long initiateDeviceOperation(@RequestBody DeviceRPCRequest deviceRPCRequest) { - logger.debug("Received a Device operation request from Mapper"); - Long operationId = 0l; - try { - operationId = acsServiceAPI.performDeviceOperation(deviceRPCRequest); - logger.debug( - "Successfully initiated device operation, The operation id for the request is: {}", - operationId); - } catch (MapperServiceException e) { - logger.error("An exception occurred while calling the device operation, Reason: {}", - e.getMessage()); - } - - return operationId; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.nbi.mapper.service; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; +import org.commscope.tr069adapter.acs.common.exception.MapperServiceException; +import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI; +import org.commscope.tr069adapter.acs.common.utils.ConnectionStatusPOJO; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRepository; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/MapperService") +public class MapperRequestRESTService { + + private static final Logger logger = LoggerFactory.getLogger(MapperRequestRESTService.class); + + @Qualifier(value = MAPPER_SERVICE_QUALILFIER) + @Autowired + ACSServiceAPI acsServiceAPI; + + @Autowired + private DeviceRepository deviceRepository; + + @PostMapping("/initiateDeviceOperation") + public Long initiateDeviceOperation(@RequestBody DeviceRPCRequest deviceRPCRequest) { + logger.debug("Received a Device operation request from Mapper"); + Long operationId = 0l; + try { + operationId = acsServiceAPI.performDeviceOperation(deviceRPCRequest); + logger.debug( + "Successfully initiated device operation, The operation id for the request is: {}", + operationId); + } catch (MapperServiceException e) { + logger.error("An exception occurred while calling the device operation, Reason: {}", + e.getMessage()); + } + + return operationId; + } + + @PostMapping("/connectionStatusOperation") + public ConnectionStatusPOJO connectionStatusOperation(@RequestBody String deviceId) + throws DeviceOperationException { + logger.debug("Received a Connection Status operation request from Mapper"); + ConnectionStatusPOJO connStatusPOJO = new ConnectionStatusPOJO(); + try { + TR069DeviceEntity tr069DeviceEntity = deviceRepository.findByDeviceId(deviceId); + if (tr069DeviceEntity == null) { + throw new DeviceOperationException(ErrorCode.DEVICE_NOT_EXISTS, deviceId); + } + connStatusPOJO.setStatus(tr069DeviceEntity.isConnStatus()); + connStatusPOJO.setLastContactTime(tr069DeviceEntity.getLastUpdatedTime()); + connStatusPOJO.setLastFailedAttemptTime(tr069DeviceEntity.getLastFailedAttemptTime()); + connStatusPOJO.setErrorMessage(tr069DeviceEntity.getErrorMsg()); + logger.info("connectionStatusOperation:: ConnectionStatusPOJO: {}", connStatusPOJO); + return connStatusPOJO; + } catch (DeviceOperationException doe) { + logger.error(doe.getMessage()); + throw doe; + } + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/TR069DeviceEventHandlerImpl.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/TR069DeviceEventHandlerImpl.java index 0936fcd..58569a5 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/TR069DeviceEventHandlerImpl.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/TR069DeviceEventHandlerImpl.java @@ -1,212 +1,238 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.*; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; -import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler; -import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; -import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -@Component -public class TR069DeviceEventHandlerImpl implements TR069DeviceEventHandler { - - private static final String RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST = - "Retry limit reached and failing the device unregister request"; - - private static final Logger logger = LoggerFactory.getLogger(TR069DeviceEventHandlerImpl.class); - - private static final String CLIENT_STR = "client"; - - @Autowired - private TR069RequestProcessEngine tr069RequestProcessEngine; - - public TR069RequestProcessEngine getProcessEngine() { - return tr069RequestProcessEngine; - } - - public void setProcessEngine(TR069RequestProcessEngine processEngine) { - this.tr069RequestProcessEngine = processEngine; - } - - @Override - @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, - rollbackFor = RuntimeException.class) - public DeviceInformResponse processDeviceInform(final DeviceInform deviceNotification) - throws Exception { - DeviceInformResponse deviceNotificationResponse = null; - try { - String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); - MDC.put(CLIENT_STR, deviceId); - deviceNotificationResponse = - processDeviceInformWithRetryOnConcurrentAccess(deviceNotification); - } finally { - MDC.remove(CLIENT_STR); - } - - return deviceNotificationResponse; - } - - @Override - @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, - rollbackFor = RuntimeException.class) - public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult) - throws Exception { - DeviceRPCRequest deviceRPCRequest = null; - try { - String deviceId = operationResult.getDeviceDetails().getDeviceId(); - MDC.put(CLIENT_STR, deviceId); - deviceRPCRequest = processDeviceRPCResponseWithRetryOnConcurrentAccess(operationResult); - } finally { - MDC.remove(CLIENT_STR); - } - return deviceRPCRequest; - } - - @Override - @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, - rollbackFor = RuntimeException.class) - public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) - throws Exception { - DeviceRPCRequest deviceRPCRequest = null; - try { - String deviceId = deviceDetails.getDeviceId(); - MDC.put(CLIENT_STR, deviceId); - deviceRPCRequest = processEmptyDeviceRequestWithRetryOnConcurrentAccess(deviceDetails); - } finally { - MDC.remove(CLIENT_STR); - } - return deviceRPCRequest; - } - - @Override - @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, - rollbackFor = RuntimeException.class) - public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) - throws SessionManagerException { - return tr069RequestProcessEngine.getOpRequestDetailsBySessionId(sessionId); - } - - @Override - @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, - rollbackFor = RuntimeException.class) - public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException { - return tr069RequestProcessEngine.getDeviceDetails(deviceId); - } - - /** - * @param deviceNotification - * @return - * @throws InterruptedException - */ - private DeviceInformResponse processDeviceInformWithRetryOnConcurrentAccess( - DeviceInform deviceNotification) - throws SessionConcurrentAccessException, InterruptedException { - logger.debug("Processing Device Inform Event"); - DeviceInformResponse deviceNotificationResponse = null; - for (int i = 0; i < MAX_RETRY_LIMIT; i++) { - try { - deviceNotificationResponse = - tr069RequestProcessEngine.processDeviceInform(deviceNotification); - logger.debug("Successfully processed Device Inform Event"); - break; - } catch (SessionConcurrentAccessException scae) { - if ((i + 1) == MAX_RETRY_LIMIT) { - logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); - throw scae; - } - Long delay = (i == 0) ? DELAY : DELAY * i; - Thread.sleep(delay); - } - } - return deviceNotificationResponse; - } - - /** - * @param operationResult - * @return - * @throws InterruptedException - * @throws Exception - */ - private DeviceRPCRequest processDeviceRPCResponseWithRetryOnConcurrentAccess( - DeviceRPCResponse operationResult) - throws SessionConcurrentAccessException, InterruptedException { - DeviceRPCRequest deviceRPCRequest = null; - logger.debug("Processing Device operation response"); - for (int i = 0; i < MAX_RETRY_LIMIT; i++) { - try { - deviceRPCRequest = tr069RequestProcessEngine.processDeviceRPCResponse(operationResult); - logger.debug("Successfully processed Device operation response"); - break; - } catch (SessionConcurrentAccessException scae) { - if ((i + 1) == MAX_RETRY_LIMIT) { - logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); - throw scae; - } - Long delay = (i == 0) ? DELAY : DELAY * i; - Thread.sleep(delay); - } - } - return deviceRPCRequest; - } - - /** - * @param deviceDetails - * @return - * @throws InterruptedException - * @throws Exception - */ - private DeviceRPCRequest processEmptyDeviceRequestWithRetryOnConcurrentAccess( - TR069DeviceDetails deviceDetails) - throws SessionConcurrentAccessException, InterruptedException { - DeviceRPCRequest deviceRPCRequest = null; - logger.debug("Processing Empty request"); - for (int i = 0; i < MAX_RETRY_LIMIT; i++) { - try { - deviceRPCRequest = tr069RequestProcessEngine.processEmptyDeviceRequest(deviceDetails); - logger.debug("Successfully processed Empty request"); - break; - } catch (SessionConcurrentAccessException scae) { - if ((i + 1) == MAX_RETRY_LIMIT) { - logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); - throw scae; - } - Long delay = (i == 0) ? DELAY : DELAY * i; - Thread.sleep(delay); - } - } - return deviceRPCRequest; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.*; + +import java.util.Date; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; +import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler; +import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRepository; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; +import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +@Component +public class TR069DeviceEventHandlerImpl implements TR069DeviceEventHandler { + + private static final String RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST = + "Retry limit reached and failing the device unregister request"; + + private static final Logger logger = LoggerFactory.getLogger(TR069DeviceEventHandlerImpl.class); + + private static final String CLIENT_STR = "client"; + + @Autowired + private TR069RequestProcessEngine tr069RequestProcessEngine; + + @Autowired + private DeviceRepository deviceRepository; + + public TR069RequestProcessEngine getProcessEngine() { + return tr069RequestProcessEngine; + } + + public void setProcessEngine(TR069RequestProcessEngine processEngine) { + this.tr069RequestProcessEngine = processEngine; + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRES_NEW, + timeout = 300, rollbackFor = RuntimeException.class) + public void processConnectionRequest(String errorMsg, String deviceId, boolean isSuccess) { + TR069DeviceEntity tr069DeviceEntity = deviceRepository.findByDeviceId(deviceId); + + if (isSuccess) { + logger.debug("processConnectionRequest success case"); + tr069DeviceEntity.setConnStatus(true); + tr069DeviceEntity.setLastUpdatedTime(new Date()); + } else { + logger.debug("processConnectionRequest failed case"); + tr069DeviceEntity.setConnStatus(false); + tr069DeviceEntity.setLastFailedAttemptTime(new Date()); + } + tr069DeviceEntity.setErrorMsg(errorMsg); + deviceRepository.save(tr069DeviceEntity); + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, + rollbackFor = RuntimeException.class) + public DeviceInformResponse processDeviceInform(final DeviceInform deviceNotification) + throws SessionConcurrentAccessException, InterruptedException { + DeviceInformResponse deviceNotificationResponse = null; + try { + String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); + MDC.put(CLIENT_STR, deviceId); + deviceNotificationResponse = + processDeviceInformWithRetryOnConcurrentAccess(deviceNotification); + } finally { + MDC.remove(CLIENT_STR); + } + + return deviceNotificationResponse; + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, + rollbackFor = RuntimeException.class) + public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult) + throws SessionConcurrentAccessException, InterruptedException { + DeviceRPCRequest deviceRPCRequest = null; + try { + String deviceId = operationResult.getDeviceDetails().getDeviceId(); + MDC.put(CLIENT_STR, deviceId); + deviceRPCRequest = processDeviceRPCResponseWithRetryOnConcurrentAccess(operationResult); + } finally { + MDC.remove(CLIENT_STR); + } + return deviceRPCRequest; + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, + rollbackFor = RuntimeException.class) + public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) + throws SessionConcurrentAccessException, InterruptedException { + DeviceRPCRequest deviceRPCRequest = null; + try { + String deviceId = deviceDetails.getDeviceId(); + MDC.put(CLIENT_STR, deviceId); + deviceRPCRequest = processEmptyDeviceRequestWithRetryOnConcurrentAccess(deviceDetails); + } finally { + MDC.remove(CLIENT_STR); + } + return deviceRPCRequest; + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, + rollbackFor = RuntimeException.class) + public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) + throws SessionManagerException { + return tr069RequestProcessEngine.getOpRequestDetailsBySessionId(sessionId); + } + + @Override + @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300, + rollbackFor = RuntimeException.class) + public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException { + return tr069RequestProcessEngine.getDeviceDetails(deviceId); + } + + /** + * @param deviceNotification + * @return + * @throws InterruptedException + */ + private DeviceInformResponse processDeviceInformWithRetryOnConcurrentAccess( + DeviceInform deviceNotification) + throws SessionConcurrentAccessException, InterruptedException { + logger.debug("Processing Device Inform Event"); + DeviceInformResponse deviceNotificationResponse = null; + for (int i = 0; i < MAX_RETRY_LIMIT; i++) { + try { + deviceNotificationResponse = + tr069RequestProcessEngine.processDeviceInform(deviceNotification); + logger.debug("Successfully processed Device Inform Event"); + break; + } catch (SessionConcurrentAccessException scae) { + if ((i + 1) == MAX_RETRY_LIMIT) { + logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); + throw scae; + } + Long delay = (i == 0) ? DELAY : DELAY * i; + Thread.sleep(delay); + } + } + return deviceNotificationResponse; + } + + /** + * @param operationResult + * @return + * @throws InterruptedException + * @throws Exception + */ + private DeviceRPCRequest processDeviceRPCResponseWithRetryOnConcurrentAccess( + DeviceRPCResponse operationResult) + throws SessionConcurrentAccessException, InterruptedException { + DeviceRPCRequest deviceRPCRequest = null; + logger.debug("Processing Device operation response"); + for (int i = 0; i < MAX_RETRY_LIMIT; i++) { + try { + deviceRPCRequest = tr069RequestProcessEngine.processDeviceRPCResponse(operationResult); + logger.debug("Successfully processed Device operation response"); + break; + } catch (SessionConcurrentAccessException scae) { + if ((i + 1) == MAX_RETRY_LIMIT) { + logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); + throw scae; + } + Long delay = (i == 0) ? DELAY : DELAY * i; + Thread.sleep(delay); + } + } + return deviceRPCRequest; + } + + /** + * @param deviceDetails + * @return + * @throws InterruptedException + * @throws Exception + */ + private DeviceRPCRequest processEmptyDeviceRequestWithRetryOnConcurrentAccess( + TR069DeviceDetails deviceDetails) + throws SessionConcurrentAccessException, InterruptedException { + DeviceRPCRequest deviceRPCRequest = null; + logger.debug("Processing Empty request"); + for (int i = 0; i < MAX_RETRY_LIMIT; i++) { + try { + deviceRPCRequest = tr069RequestProcessEngine.processEmptyDeviceRequest(deviceDetails); + logger.debug("Successfully processed Empty request"); + break; + } catch (SessionConcurrentAccessException scae) { + if ((i + 1) == MAX_RETRY_LIMIT) { + logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST); + throw scae; + } + Long delay = (i == 0) ? DELAY : DELAY * i; + Thread.sleep(delay); + } + } + return deviceRPCRequest; + } +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/custom/ConfigureMultipleObject.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/custom/ConfigureMultipleObject.java index 5b36b88..cdf98eb 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/custom/ConfigureMultipleObject.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/custom/ConfigureMultipleObject.java @@ -1,502 +1,504 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.custom; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NUMBER_REGEX; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SUCCESS; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.common.response.AddObjectResponse; -import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse; -import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse; -import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; -import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper; -import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData; -import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; -import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; -import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component("ConfigureMultipleObject") -public class ConfigureMultipleObject implements CustomOperation { - - private static final Logger logger = LoggerFactory.getLogger(ConfigureMultipleObject.class); - - @Autowired - TR069RequestProcessEngine tr069ProcessEngine; - - @Autowired - protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper; - - public CustomOperationData executeCustomLogic(CustomOperationData customOperationData) - throws TR069EventProcessingException { - - TR069DeviceDetails deviceDetails = customOperationData.getDeviceDetails(); - DeviceRPCResponse deviceRPCResponse = customOperationData.getDeviceRPCResponse(); - DeviceRPCRequest nbiDeviceOperationRequest = customOperationData.getDeviceRPCRequest(); - - logger.debug("Started processing Configure multiple object"); - DeviceRPCRequest operRequest = null; - Long responseOperationId = null; - if (deviceRPCResponse != null && deviceRPCResponse.getOperationId() != null) { - responseOperationId = deviceRPCResponse.getOperationId(); - if (deviceRPCResponse.getFaultKey() != null && responseOperationId != null - && responseOperationId.equals(nbiDeviceOperationRequest.getOperationId())) { - logger.error("The Configure Multiple Object operation has failed, Reason: {}", - deviceRPCResponse.getFaultString()); - - logger.debug( - "Deleting the NBI operation request for custom operation configureMultipleObjects with operation ID: {}", - responseOperationId); - List tr069DeviceRPCRequestEntityList = - deviceRPCRequestRepositoryHelper - .findByDeviceIdAndOperationId(deviceDetails.getDeviceId(), responseOperationId); - for (TR069DeviceRPCRequestEntity tr069DeviceRPCRequestEntity : tr069DeviceRPCRequestEntityList) { - tr069DeviceRPCRequestEntity.setIsProcessed(Integer.valueOf(1)); - } - deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); - - OperationResponse operationResponse = new GetParameterValueResponse(); - operationResponse.setParameterDTOs(new ArrayList()); - operationResponse.setStatus(1); - deviceRPCResponse.setOperationResponse(operationResponse); - - customOperationData.setDeviceRPCResponse(deviceRPCResponse); - customOperationData.setDeviceRPCRequest(null); - logger.debug("Finished processing Configure multiple object"); - return customOperationData; - } - } - - TR069OperationDetails tr069OperationDetails = - (TR069OperationDetails) nbiDeviceOperationRequest.getOpDetails(); - List tr069deleteParamList = tr069OperationDetails.getDeleteParamList(); - List tr069modifyParamList = tr069OperationDetails.getModifyParamList(); - List tr069setParamList = tr069OperationDetails.getSetParamList(); - - OperationOrder nextOperation = null; - boolean isPendingOperationExists = true; - final String NXT_OPERATION = "Next operation to be executed is : "; - - if ((responseOperationId == null) || (responseOperationId != null - && !responseOperationId.equals(nbiDeviceOperationRequest.getOperationId()))) { - // Must be called from Empty HTTP request, First operation to be called - - // Must be called from a different user operation, First operation to be called - // if response operation id is different from current - // nbiDevOperRequest operation id then first step is deleteObject - - nextOperation = OperationOrder.DELETE_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - } else { - // Since the responseOperation is not null and equivalent, find the - // response type and the take next action - OperationResponse opResponse = deviceRPCResponse.getOperationResponse(); - if (opResponse instanceof DeleteObjectResponse) { - logger.debug("Received delete object response"); - if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) { - int i = 0; - for (ParameterDTO deleteParam : tr069deleteParamList) { - i++; - if (!deleteParam.isProcessed()) { - deleteParam.setProcessed(true); - } else { - continue; - } - logger.debug("Persisting the NBI request for deleteObject"); - // Update the existing NBI request - List entityList = - deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId( - deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId()); - List tr069DeviceRPCRequestEntityList = - TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); - for (int j = 0; j < entityList.size(); j++) { - tr069DeviceRPCRequestEntityList.get(j).setId(entityList.get(j).getId()); - } - deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); - - if (tr069deleteParamList.size() > i) { - nextOperation = OperationOrder.DELETE_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - break; - } else { - nextOperation = OperationOrder.ADD_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - } - } - } else { - nextOperation = OperationOrder.ADD_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - } - } else if (opResponse instanceof AddObjectResponse) { - logger.debug("Received Add object response"); - if (null != tr069setParamList && !tr069setParamList.isEmpty()) { - long instanceNumber; - boolean addParamExist = false; - AddObjectResponse addObjResponse = - (AddObjectResponse) deviceRPCResponse.getOperationResponse(); - List modifyParamList = new ArrayList<>(); - List removeParamList = new ArrayList<>(); - ParameterDTO addParam = null; - - if (null != addObjResponse) { - instanceNumber = addObjResponse.getInstanceNumber(); - String replaceIndex = null; - String replaceParam = null; - - for (ParameterDTO setParam : tr069setParamList) { - if (!setParam.isProcessed()) { - String paramName = setParam.getParamName(); - final Matcher matcher = Pattern.compile(NUMBER_REGEX).matcher(paramName); - String index = null; - String modifyParamName = null; - String subString = null; - while (matcher.find()) { - index = matcher.group().substring(1, matcher.group().length() - 1); - StringBuilder sb = new StringBuilder(paramName); - int lastIndex = paramName.lastIndexOf(matcher.group()); - modifyParamName = (sb.replace(lastIndex, lastIndex + matcher.group().length(), - "." + instanceNumber + ".")).toString(); - subString = paramName.substring(0, matcher.start()) + "."; - } - if (null == replaceIndex) - replaceIndex = index; - if (null == replaceParam) - replaceParam = subString; - if (null != replaceIndex && null != index && replaceIndex.equals(index) - && replaceParam.equalsIgnoreCase(subString)) { - setParam.setProcessed(true); - modifyParamList.add(prepareParamDTO(modifyParamName, null, setParam)); - removeParamList.add(prepareParamDTO(null, null, setParam)); - } else { - addParamExist = true; - } - if (null == addParam) { - logger.debug( - "The device index chosen is {} for adding the NBI tab parameter with index {}", - instanceNumber, replaceIndex); - addParam = prepareParamDTO(subString + replaceIndex, - String.valueOf(instanceNumber), setParam); - } - } - } - } - // Replace index with instance number and add in modify param list - if (!modifyParamList.isEmpty()) { - tr069modifyParamList.addAll(modifyParamList); - } - // Prepare add object param and add in set param list - if (null != addParam) { - addParam.setDataType("1"); - tr069setParamList.add(addParam); - } - // Remove all processed set params from set param list - if (!removeParamList.isEmpty()) { - tr069setParamList.removeAll(removeParamList); - } - - logger.debug("Persisting the NBI request for addObject"); - List entityList = - deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId( - deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId()); - List tr069DeviceRPCRequestEntityList = - TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); - for (int i = 0; i < entityList.size(); i++) { - tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId()); - } - deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); - - if (addParamExist) { - nextOperation = OperationOrder.ADD_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - } else { - nextOperation = OperationOrder.SET_PARAMETER_VALUE; - logger.debug(NXT_OPERATION, nextOperation); - } - } else { - nextOperation = OperationOrder.SET_PARAMETER_VALUE; - logger.debug(NXT_OPERATION, nextOperation); - } - } else if (opResponse instanceof SetParameterValueResponse) { - logger.debug("Received Set parameter value response"); - isPendingOperationExists = false; - for (ParameterDTO setParam : tr069modifyParamList) { - if (Boolean.TRUE.equals(setParam.isInitiated()) - && Boolean.FALSE.equals(setParam.isProcessed())) { - setParam.setInitiated(Boolean.FALSE); - setParam.setProcessed(Boolean.TRUE); - } else if (Boolean.FALSE.equals(setParam.isInitiated()) - && Boolean.FALSE.equals(setParam.isProcessed())) { - isPendingOperationExists = true; - nextOperation = OperationOrder.SET_PARAMETER_VALUE; - } - } - - updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); - logger.debug("Next operation to be executed is : {}", nextOperation); - } - } - - if (isPendingOperationExists) { - boolean checkForNextoperation = true; - while (checkForNextoperation) { - switch (nextOperation) { - case DELETE_OBJECT: - if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) { - logger.debug("Started executing delete object request"); - checkForNextoperation = false; - DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); - List deleteParamList = new ArrayList<>(); - // Just take the first not processed delete object from the list - for (ParameterDTO deleteParam : tr069deleteParamList) { - if (!deleteParam.isProcessed()) { - deleteParamList.add(deleteParam); - break; - } - } - clonedOpRequest.setOpDetails(null); - OperationDetails opDetails = new OperationDetails(); - opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT); - opDetails.setParmeters(deleteParamList); - clonedOpRequest.setOpDetails(opDetails); - operRequest = clonedOpRequest; - } else { - nextOperation = OperationOrder.ADD_OBJECT; - logger.debug(NXT_OPERATION, nextOperation); - } - break; - case ADD_OBJECT: - if (null != tr069setParamList && !tr069setParamList.isEmpty()) { - logger.debug("Started executing Add object request"); - checkForNextoperation = false; - DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); - List addParamList = new ArrayList<>(); - // Just take the first not processed delete object from the list - for (ParameterDTO addParam : tr069setParamList) { - if (!addParam.isProcessed()) { - String addParamMO = null; - final Matcher matcher = - Pattern.compile(NUMBER_REGEX).matcher(addParam.getParamName()); - while (matcher.find()) { - addParamMO = addParam.getParamName().substring(0, matcher.start()) + "."; - } - if (null != addParamMO) { - addParamList.add(prepareParamDTO(addParamMO, null, addParam)); - } - break; - } - } - clonedOpRequest.setOpDetails(null); - OperationDetails opDetails = new OperationDetails(); - opDetails.setOpCode(TR069OperationCode.ADD_OBJECT); - opDetails.setParmeters(addParamList); - clonedOpRequest.setOpDetails(opDetails); - operRequest = clonedOpRequest; - } else { - nextOperation = OperationOrder.SET_PARAMETER_VALUE; - logger.debug(NXT_OPERATION, nextOperation); - } - break; - case SET_PARAMETER_VALUE: - checkForNextoperation = false; - if (null != tr069modifyParamList && !tr069modifyParamList.isEmpty()) { - logger.debug("Started executing SPV request"); - DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); - clonedOpRequest.setOpDetails(null); - OperationDetails opDetails = new OperationDetails(); - opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES); - List unprocessedParamList = new ArrayList<>(); - ParameterDTO adminStateParam = null; - for (ParameterDTO paramDTO : tr069modifyParamList) { - if (!paramDTO.isProcessed()) { - if (isAdminStateExists(paramDTO)) { - adminStateParam = paramDTO; - } else { - unprocessedParamList.add(paramDTO); - } - } - } - - if (null != adminStateParam && isAdminStateFalse(adminStateParam.getParamValue())) { - List adminStateParamList = new ArrayList<>(); - adminStateParam.setInitiated(Boolean.TRUE); - adminStateParamList.add(adminStateParam); - opDetails.setParmeters(adminStateParamList); - updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); - } else if (!unprocessedParamList.isEmpty()) { - setInititedFlagTrue(unprocessedParamList); - opDetails.setParmeters(unprocessedParamList); - updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); - } else if (null != adminStateParam - && isAdminStateTrue(adminStateParam.getParamValue())) { - List paramList = new ArrayList<>(); - adminStateParam.setInitiated(Boolean.TRUE); - paramList.add(adminStateParam); - opDetails.setParmeters(paramList); - updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); - } else { - isPendingOperationExists = false; - } - - clonedOpRequest.setOpDetails(opDetails); - operRequest = clonedOpRequest; - } else { - isPendingOperationExists = false; - operRequest = null; - } - break; - default: - isPendingOperationExists = false; - operRequest = null; - } - } - } - - if (!isPendingOperationExists) { - logger.debug( - "No pending operation exists, hence marking the operation as processed with id {} " - + "and sending GetParameterValueResponse for ConfigureMultipleObjects", - responseOperationId); - List responseParamList = new ArrayList<>(); - - if (tr069deleteParamList != null) { - for (ParameterDTO delete : tr069deleteParamList) { - delete.setParamValue(SUCCESS); - delete.setDataType("2"); - responseParamList.add(delete); - } - } - - if (tr069modifyParamList != null) { - for (ParameterDTO modify : tr069modifyParamList) { - modify.setParamValue(SUCCESS); - modify.setDataType("4"); - responseParamList.add(modify); - } - } - - responseParamList.addAll(tr069setParamList); - - OperationResponse operationResponse = new GetParameterValueResponse(); - operationResponse.setParameterDTOs(responseParamList); - if (deviceRPCResponse != null) { - deviceRPCResponse.setDeviceDetails(deviceDetails); - deviceRPCResponse.setOperationResponse(operationResponse); - deviceRPCResponse.setOperationId(responseOperationId); - } - - logger.debug( - "Prepared operation result for custom operation Configure Multiple Objects, hence marking as processed the corresponding NBI Operation request record"); - deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceDetails.getDeviceId(), - responseOperationId); - } - - customOperationData.setDeviceRPCResponse(deviceRPCResponse); - customOperationData.setDeviceRPCRequest(operRequest); - logger.debug("Finished processing Configure multiple object"); - return customOperationData; - } - - - enum OperationOrder { - - SET_PARAMETER_VALUE(null), ADD_OBJECT(SET_PARAMETER_VALUE), DELETE_OBJECT(ADD_OBJECT); - - OperationOrder nextOperation; - - OperationOrder(OperationOrder nextOperation) { - this.nextOperation = nextOperation; - } - - public OperationOrder getNextOperation() { - return nextOperation; - } - - } - - private DeviceRPCRequest cloneNBIRequest(DeviceRPCRequest nbiDeviceOperationRequest) { - return new DeviceRPCRequest(nbiDeviceOperationRequest); - } - - private ParameterDTO prepareParamDTO(String name, String value, ParameterDTO paramDTO) { - ParameterDTO parameterDTO = new ParameterDTO(); - if (null != name) { - parameterDTO.setParamName(name); - } else { - parameterDTO.setParamName(paramDTO.getParamName()); - } - if (null != value) { - parameterDTO.setParamValue(value); - } else { - parameterDTO.setParamValue(paramDTO.getParamValue()); - } - parameterDTO.setDataType(paramDTO.getDataType()); - parameterDTO.setProcessed(paramDTO.isProcessed()); - - return parameterDTO; - } - - private boolean isAdminStateExists(ParameterDTO paramDTO) { - return (paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATE) - || paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATUS)); - } - - private void updateParamChangedFlagInDb(String deviceId, - DeviceRPCRequest nbiDeviceOperationRequest) throws TR069EventProcessingException { - List entityList = deviceRPCRequestRepositoryHelper - .findByDeviceIdAndOperationId(deviceId, nbiDeviceOperationRequest.getOperationId()); - List tr069DeviceRPCRequestEntityList = - TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); - for (int i = 0; i < entityList.size(); i++) { - tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId()); - } - deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); - } - - private void setInititedFlagTrue(List unprocessedParamList) { - for (ParameterDTO paramDTO : unprocessedParamList) { - paramDTO.setInitiated(Boolean.TRUE); - } - } - - private boolean isAdminStateFalse(String adminState) { - return (null != adminState && (adminState.equalsIgnoreCase(Boolean.FALSE.toString()) - || adminState.equalsIgnoreCase("0"))); - } - - private boolean isAdminStateTrue(String adminState) { - return (null != adminState && (adminState.equalsIgnoreCase(Boolean.TRUE.toString()) - || adminState.equalsIgnoreCase("1"))); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.custom; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NUMBER_REGEX; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SUCCESS; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.common.response.AddObjectResponse; +import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse; +import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse; +import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper; +import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; +import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; +import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("ConfigureMultipleObject") +public class ConfigureMultipleObject implements CustomOperation { + + private static final Logger logger = LoggerFactory.getLogger(ConfigureMultipleObject.class); + + @Autowired + TR069RequestProcessEngine tr069ProcessEngine; + + @Autowired + protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper; + + public CustomOperationData executeCustomLogic(CustomOperationData customOperationData) + throws TR069EventProcessingException { + + TR069DeviceDetails deviceDetails = customOperationData.getDeviceDetails(); + DeviceRPCResponse deviceRPCResponse = customOperationData.getDeviceRPCResponse(); + DeviceRPCRequest nbiDeviceOperationRequest = customOperationData.getDeviceRPCRequest(); + + logger.debug("Started processing Configure multiple object"); + DeviceRPCRequest operRequest = null; + Long responseOperationId = null; + if (deviceRPCResponse != null && deviceRPCResponse.getOperationId() != null) { + responseOperationId = deviceRPCResponse.getOperationId(); + if (deviceRPCResponse.getFaultKey() != null && responseOperationId != null + && responseOperationId.equals(nbiDeviceOperationRequest.getOperationId())) { + logger.error("The Configure Multiple Object operation has failed, Reason: {}", + deviceRPCResponse.getFaultString()); + + logger.debug( + "Deleting the NBI operation request for custom operation configureMultipleObjects with operation ID: {}", + responseOperationId); + List tr069DeviceRPCRequestEntityList = + deviceRPCRequestRepositoryHelper + .findByDeviceIdAndOperationId(deviceDetails.getDeviceId(), responseOperationId); + for (TR069DeviceRPCRequestEntity tr069DeviceRPCRequestEntity : tr069DeviceRPCRequestEntityList) { + tr069DeviceRPCRequestEntity.setIsProcessed(Integer.valueOf(1)); + } + deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); + + OperationResponse operationResponse = new GetParameterValueResponse(); + operationResponse.setParameterDTOs(new ArrayList<>()); + operationResponse.setStatus(1); + deviceRPCResponse.setOperationResponse(operationResponse); + + customOperationData.setDeviceRPCResponse(deviceRPCResponse); + customOperationData.setDeviceRPCRequest(null); + logger.debug("Finished processing Configure multiple object"); + return customOperationData; + } + } + + TR069OperationDetails tr069OperationDetails = + (TR069OperationDetails) nbiDeviceOperationRequest.getOpDetails(); + List tr069deleteParamList = tr069OperationDetails.getDeleteParamList(); + List tr069modifyParamList = tr069OperationDetails.getModifyParamList(); + List tr069setParamList = tr069OperationDetails.getSetParamList(); + + OperationOrder nextOperation = null; + boolean isPendingOperationExists = true; + final String NXT_OPERATION = "Next operation to be executed is : "; + + if ((responseOperationId == null) || (responseOperationId != null + && !responseOperationId.equals(nbiDeviceOperationRequest.getOperationId()))) { + // Must be called from Empty HTTP request, First operation to be called + + // Must be called from a different user operation, First operation to be called + // if response operation id is different from current + // nbiDevOperRequest operation id then first step is deleteObject + + nextOperation = OperationOrder.DELETE_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + } else { + // Since the responseOperation is not null and equivalent, find the + // response type and the take next action + OperationResponse opResponse = deviceRPCResponse.getOperationResponse(); + if (opResponse instanceof DeleteObjectResponse) { + logger.debug("Received delete object response"); + if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) { + int i = 0; + for (ParameterDTO deleteParam : tr069deleteParamList) { + i++; + if (!deleteParam.isProcessed()) { + deleteParam.setProcessed(true); + } else { + continue; + } + logger.debug("Persisting the NBI request for deleteObject"); + // Update the existing NBI request + List entityList = + deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId( + deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId()); + List tr069DeviceRPCRequestEntityList = + TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); + for (int j = 0; j < entityList.size(); j++) { + tr069DeviceRPCRequestEntityList.get(j).setId(entityList.get(j).getId()); + } + deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); + + if (tr069deleteParamList.size() > i) { + nextOperation = OperationOrder.DELETE_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + break; + } else { + nextOperation = OperationOrder.ADD_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + } + } + } else { + nextOperation = OperationOrder.ADD_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + } + } else if (opResponse instanceof AddObjectResponse) { + logger.debug("Received Add object response"); + if (null != tr069setParamList && !tr069setParamList.isEmpty()) { + long instanceNumber; + boolean addParamExist = false; + AddObjectResponse addObjResponse = + (AddObjectResponse) deviceRPCResponse.getOperationResponse(); + List modifyParamList = new ArrayList<>(); + List removeParamList = new ArrayList<>(); + ParameterDTO addParam = null; + + if (null != addObjResponse) { + instanceNumber = addObjResponse.getInstanceNumber(); + String replaceIndex = null; + String replaceParam = null; + + for (ParameterDTO setParam : tr069setParamList) { + if (!setParam.isProcessed()) { + String paramName = setParam.getParamName(); + final Matcher matcher = Pattern.compile(NUMBER_REGEX).matcher(paramName); + String index = null; + String modifyParamName = null; + String subString = null; + while (matcher.find()) { + index = matcher.group().substring(1, matcher.group().length() - 1); + StringBuilder sb = new StringBuilder(paramName); + int lastIndex = paramName.lastIndexOf(matcher.group()); + modifyParamName = (sb.replace(lastIndex, lastIndex + matcher.group().length(), + "." + instanceNumber + ".")).toString(); + subString = paramName.substring(0, matcher.start()) + "."; + } + if (null == replaceIndex) + replaceIndex = index; + if (null == replaceParam) + replaceParam = subString; + if (null != replaceIndex && null != index && replaceIndex.equals(index) + && replaceParam.equalsIgnoreCase(subString)) { + setParam.setProcessed(true); + modifyParamList.add(prepareParamDTO(modifyParamName, null, setParam)); + removeParamList.add(prepareParamDTO(null, null, setParam)); + } else { + addParamExist = true; + } + if (null == addParam) { + logger.debug( + "The device index chosen is {} for adding the NBI tab parameter with index {}", + instanceNumber, replaceIndex); + addParam = prepareParamDTO(subString + replaceIndex, + String.valueOf(instanceNumber), setParam); + } + } + } + } + // Replace index with instance number and add in modify param list + if (!modifyParamList.isEmpty()) { + tr069modifyParamList.addAll(modifyParamList); + } + // Prepare add object param and add in set param list + if (null != addParam) { + addParam.setDataType("1"); + tr069setParamList.add(addParam); + } + // Remove all processed set params from set param list + if (!removeParamList.isEmpty()) { + tr069setParamList.removeAll(removeParamList); + } + + logger.debug("Persisting the NBI request for addObject"); + List entityList = + deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId( + deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId()); + List tr069DeviceRPCRequestEntityList = + TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); + for (int i = 0; i < entityList.size(); i++) { + tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId()); + } + deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); + + if (addParamExist) { + nextOperation = OperationOrder.ADD_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + } else { + nextOperation = OperationOrder.SET_PARAMETER_VALUE; + logger.debug(NXT_OPERATION, nextOperation); + } + } else { + nextOperation = OperationOrder.SET_PARAMETER_VALUE; + logger.debug(NXT_OPERATION, nextOperation); + } + } else if (opResponse instanceof SetParameterValueResponse) { + logger.debug("Received Set parameter value response"); + isPendingOperationExists = false; + for (ParameterDTO setParam : tr069modifyParamList) { + if (Boolean.TRUE.equals(setParam.isInitiated()) + && Boolean.FALSE.equals(setParam.isProcessed())) { + setParam.setInitiated(Boolean.FALSE); + setParam.setProcessed(Boolean.TRUE); + } else if (Boolean.FALSE.equals(setParam.isInitiated()) + && Boolean.FALSE.equals(setParam.isProcessed())) { + isPendingOperationExists = true; + nextOperation = OperationOrder.SET_PARAMETER_VALUE; + } + } + + updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); + logger.debug("Next operation to be executed is : {}", nextOperation); + } + } + + if (isPendingOperationExists) { + boolean checkForNextoperation = true; + while (checkForNextoperation) { + switch (nextOperation) { + case DELETE_OBJECT: + if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) { + logger.debug("Started executing delete object request"); + checkForNextoperation = false; + DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); + List deleteParamList = new ArrayList<>(); + // Just take the first not processed delete object from the list + for (ParameterDTO deleteParam : tr069deleteParamList) { + if (!deleteParam.isProcessed()) { + deleteParamList.add(deleteParam); + break; + } + } + clonedOpRequest.setOpDetails(null); + OperationDetails opDetails = new OperationDetails(); + opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT); + opDetails.setParmeters(deleteParamList); + clonedOpRequest.setOpDetails(opDetails); + operRequest = clonedOpRequest; + } else { + nextOperation = OperationOrder.ADD_OBJECT; + logger.debug(NXT_OPERATION, nextOperation); + } + break; + case ADD_OBJECT: + if (null != tr069setParamList && !tr069setParamList.isEmpty()) { + logger.debug("Started executing Add object request"); + checkForNextoperation = false; + DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); + List addParamList = new ArrayList<>(); + // Just take the first not processed delete object from the list + for (ParameterDTO addParam : tr069setParamList) { + if (!addParam.isProcessed()) { + String addParamMO = null; + final Matcher matcher = + Pattern.compile(NUMBER_REGEX).matcher(addParam.getParamName()); + while (matcher.find()) { + addParamMO = addParam.getParamName().substring(0, matcher.start()) + "."; + } + if (null != addParamMO) { + addParamList.add(prepareParamDTO(addParamMO, null, addParam)); + } + break; + } + } + clonedOpRequest.setOpDetails(null); + OperationDetails opDetails = new OperationDetails(); + opDetails.setOpCode(TR069OperationCode.ADD_OBJECT); + opDetails.setParmeters(addParamList); + clonedOpRequest.setOpDetails(opDetails); + operRequest = clonedOpRequest; + } else { + nextOperation = OperationOrder.SET_PARAMETER_VALUE; + logger.debug(NXT_OPERATION, nextOperation); + } + break; + case SET_PARAMETER_VALUE: + checkForNextoperation = false; + if (null != tr069modifyParamList && !tr069modifyParamList.isEmpty()) { + logger.debug("Started executing SPV request"); + DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest); + clonedOpRequest.setOpDetails(null); + OperationDetails opDetails = new OperationDetails(); + opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES); + List unprocessedParamList = new ArrayList<>(); + ParameterDTO adminStateParam = null; + for (ParameterDTO paramDTO : tr069modifyParamList) { + if (!paramDTO.isProcessed()) { + if (isAdminStateExists(paramDTO)) { + adminStateParam = paramDTO; + } else { + unprocessedParamList.add(paramDTO); + } + } + } + + if (null != adminStateParam && isAdminStateFalse(adminStateParam.getParamValue())) { + List adminStateParamList = new ArrayList<>(); + adminStateParam.setInitiated(Boolean.TRUE); + adminStateParamList.add(adminStateParam); + opDetails.setParmeters(adminStateParamList); + updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); + } else if (!unprocessedParamList.isEmpty()) { + setInititedFlagTrue(unprocessedParamList); + opDetails.setParmeters(unprocessedParamList); + updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); + } else if (null != adminStateParam + && isAdminStateTrue(adminStateParam.getParamValue())) { + List paramList = new ArrayList<>(); + adminStateParam.setInitiated(Boolean.TRUE); + paramList.add(adminStateParam); + opDetails.setParmeters(paramList); + updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest); + } else { + isPendingOperationExists = false; + } + + clonedOpRequest.setOpDetails(opDetails); + operRequest = clonedOpRequest; + } else { + isPendingOperationExists = false; + operRequest = null; + } + break; + default: + isPendingOperationExists = false; + operRequest = null; + } + } + } + + if (!isPendingOperationExists) { + logger.debug( + "No pending operation exists, hence marking the operation as processed with id {} " + + "and sending GetParameterValueResponse for ConfigureMultipleObjects", + responseOperationId); + List responseParamList = new ArrayList<>(); + + if (tr069deleteParamList != null) { + for (ParameterDTO delete : tr069deleteParamList) { + delete.setParamValue(SUCCESS); + delete.setDataType("2"); + responseParamList.add(delete); + } + } + + if (tr069modifyParamList != null) { + for (ParameterDTO modify : tr069modifyParamList) { + modify.setParamValue(SUCCESS); + modify.setDataType("4"); + responseParamList.add(modify); + } + } + + responseParamList.addAll(tr069setParamList); + + OperationResponse operationResponse = new GetParameterValueResponse(); + operationResponse.setParameterDTOs(responseParamList); + if (deviceRPCResponse != null) { + deviceRPCResponse.setDeviceDetails(deviceDetails); + deviceRPCResponse.setOperationResponse(operationResponse); + deviceRPCResponse.setOperationId(responseOperationId); + } + + logger.debug( + "Prepared operation result for custom operation Configure Multiple Objects, hence marking as processed the corresponding NBI Operation request record"); + deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceDetails.getDeviceId(), + responseOperationId); + } + + customOperationData.setDeviceRPCResponse(deviceRPCResponse); + customOperationData.setDeviceRPCRequest(operRequest); + logger.debug("Finished processing Configure multiple object"); + return customOperationData; + } + + + enum OperationOrder { + + SET_PARAMETER_VALUE(null), ADD_OBJECT(SET_PARAMETER_VALUE), DELETE_OBJECT(ADD_OBJECT); + + OperationOrder nextOperation; + + OperationOrder(OperationOrder nextOperation) { + this.nextOperation = nextOperation; + } + + public OperationOrder getNextOperation() { + return nextOperation; + } + + } + + private DeviceRPCRequest cloneNBIRequest(DeviceRPCRequest nbiDeviceOperationRequest) { + return new DeviceRPCRequest(nbiDeviceOperationRequest); + } + + private ParameterDTO prepareParamDTO(String name, String value, ParameterDTO paramDTO) { + ParameterDTO parameterDTO = new ParameterDTO(); + if (null != name) { + parameterDTO.setParamName(name); + } else { + parameterDTO.setParamName(paramDTO.getParamName()); + } + if (null != value) { + parameterDTO.setParamValue(value); + } else { + parameterDTO.setParamValue(paramDTO.getParamValue()); + } + parameterDTO.setDataType(paramDTO.getDataType()); + parameterDTO.setProcessed(paramDTO.isProcessed()); + + return parameterDTO; + } + + private boolean isAdminStateExists(ParameterDTO paramDTO) { + return (paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATE) + || paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATUS)); + } + + private void updateParamChangedFlagInDb(String deviceId, + DeviceRPCRequest nbiDeviceOperationRequest) throws TR069EventProcessingException { + List entityList = deviceRPCRequestRepositoryHelper + .findByDeviceIdAndOperationId(deviceId, nbiDeviceOperationRequest.getOperationId()); + List tr069DeviceRPCRequestEntityList = + TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest); + for (int i = 0; i < entityList.size(); i++) { + tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId()); + } + deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList); + } + + private void setInititedFlagTrue(List unprocessedParamList) { + for (ParameterDTO paramDTO : unprocessedParamList) { + paramDTO.setInitiated(Boolean.TRUE); + } + } + + private boolean isAdminStateFalse(String adminState) { + return (null != adminState && (adminState.equalsIgnoreCase(Boolean.FALSE.toString()) + || adminState.equalsIgnoreCase("0"))); + } + + private boolean isAdminStateTrue(String adminState) { + return (null != adminState && (adminState.equalsIgnoreCase(Boolean.TRUE.toString()) + || adminState.equalsIgnoreCase("1"))); + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/entity/TR069DeviceEntity.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/entity/TR069DeviceEntity.java index 2193f5a..a7ae38d 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/entity/TR069DeviceEntity.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/entity/TR069DeviceEntity.java @@ -1,136 +1,169 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.entity; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -/** - * The persistent class for the TR069_DEVICE_ database table. - * - */ -@Entity -@Table(name = "TR069_DEVICE", uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"})) -public class TR069DeviceEntity implements Serializable { - - private static final long serialVersionUID = -2696584252283707720L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ID") - private Long id; - - @Column(name = "DEVICE_ID", length = 30) - private String deviceId; - - @Column(name = "USER_NAME", length = 256) - private String userName; - - @Column(name = "PASSWORD", length = 256) - private String password; - - @Column(name = "HW_VERSION", length = 20) - private String hwVersion; - - @Column(name = "SW_VERSION", length = 20) - private String swVersion; - - @Column(name = "CONNECTION_REQUEST_URL", length = 1024) - private String connectionReqURL; - - @Column(name = "LAST_UPDATED_TIME") - private Date lastUpdatedTime; - - public TR069DeviceEntity() { - super(); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceID) { - this.deviceId = deviceID; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public String getConnectionReqURL() { - return connectionReqURL; - } - - public void setConnectionReqURL(String connectionReqURL) { - this.connectionReqURL = connectionReqURL; - } - - public Date getLastUpdatedTime() { - return lastUpdatedTime; - } - - public void setLastUpdatedTime(Date rowUpdatedTime) { - this.lastUpdatedTime = rowUpdatedTime; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.entity; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +/** + * The persistent class for the TR069_DEVICE_ database table. + * + */ +@Entity +@Table(name = "TR069_DEVICE", uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"})) +public class TR069DeviceEntity implements Serializable { + + private static final long serialVersionUID = -2696584252283707720L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + + @Column(name = "DEVICE_ID", length = 30) + private String deviceId; + + @Column(name = "USER_NAME", length = 256) + private String userName; + + @Column(name = "PASSWORD", length = 256) + private String password; + + @Column(name = "HW_VERSION", length = 20) + private String hwVersion; + + @Column(name = "SW_VERSION", length = 20) + private String swVersion; + + @Column(name = "CONNECTION_REQUEST_URL", length = 1024) + private String connectionReqURL; + + @Column(name = "LAST_UPDATED_TIME") + private Date lastUpdatedTime; + + @Column(name = "LAST_FAILED_ATTEMPT_TIME") + private Date lastFailedAttemptTime; + + @Column(name = "CONN_STATUS") + private boolean connStatus; + + @Column(name = "ERROR_MESSGAE") + private String errorMsg; + + public TR069DeviceEntity() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceID) { + this.deviceId = deviceID; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public String getConnectionReqURL() { + return connectionReqURL; + } + + public void setConnectionReqURL(String connectionReqURL) { + this.connectionReqURL = connectionReqURL; + } + + public Date getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(Date rowUpdatedTime) { + this.lastUpdatedTime = rowUpdatedTime; + } + + public Date getLastFailedAttemptTime() { + return lastFailedAttemptTime; + } + + public void setLastFailedAttemptTime(Date lastFailedAttemptTime) { + this.lastFailedAttemptTime = lastFailedAttemptTime; + } + + public boolean isConnStatus() { + return connStatus; + } + + public void setConnStatus(boolean connStatus) { + this.connStatus = connStatus; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/handler/DeviceRPCRequestHandler.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/handler/DeviceRPCRequestHandler.java index 0f98e60..ddd41b7 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/handler/DeviceRPCRequestHandler.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/handler/DeviceRPCRequestHandler.java @@ -1,68 +1,69 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.handler; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_CF; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.annotation.JmsListener; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -@Component -public class DeviceRPCRequestHandler { - - private static final Logger logger = LoggerFactory.getLogger(DeviceRPCRequestHandler.class); - - private static final String CLIENT_STR = "client"; - - @Autowired - private TR069RequestProcessEngine tr069RequestProcessEngine; - - @JmsListener(destination = TR069_NBI_REQUEST_Q, containerFactory = TR069_NBI_REQUEST_CF) - @Transactional(rollbackFor = Exception.class) - public void onMessage(DeviceRPCRequest mapperDeviceOperationRequest) - throws SessionConcurrentAccessException, TR069EventProcessingException { - logger.debug("Received a JMS message from Mapper for TR069 Device RPC operation"); - try { - if (mapperDeviceOperationRequest != null) { - MDC.put(CLIENT_STR, mapperDeviceOperationRequest.getDeviceDetails().getDeviceId()); - logger.debug("Received a TR069 operation request from Mapper with operation ID: {} ", - mapperDeviceOperationRequest.getOperationId()); - tr069RequestProcessEngine.processDeviceRPCRequest(mapperDeviceOperationRequest); - logger.debug("Processed a TR069 operation request from Mapper with operation ID: {} ", - mapperDeviceOperationRequest.getOperationId()); - - } - } finally { - MDC.remove(CLIENT_STR); - } - logger.debug("Processed JMS message from Mapper for TR069 Device RPC operation"); - - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.handler; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_CF; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +public class DeviceRPCRequestHandler { + + private static final Logger logger = LoggerFactory.getLogger(DeviceRPCRequestHandler.class); + + private static final String CLIENT_STR = "client"; + + @Autowired + private TR069RequestProcessEngine tr069RequestProcessEngine; + + @JmsListener(destination = TR069_NBI_REQUEST_Q, containerFactory = TR069_NBI_REQUEST_CF) + @Transactional(rollbackFor = Exception.class) + public void onMessage(DeviceRPCRequest mapperDeviceOperationRequest) + throws SessionConcurrentAccessException, TR069EventProcessingException { + logger.debug("Received a JMS message from Mapper for TR069 Device RPC operation"); + try { + if (mapperDeviceOperationRequest != null) { + MDC.put(CLIENT_STR, mapperDeviceOperationRequest.getDeviceDetails().getDeviceId()); + logger.debug("Received a TR069 operation request from Mapper with operation ID: {} ", + mapperDeviceOperationRequest.getOperationId()); + tr069RequestProcessEngine.processDeviceRPCRequest(mapperDeviceOperationRequest); + logger.debug("Processed a TR069 operation request from Mapper with operation ID: {} ", + mapperDeviceOperationRequest.getOperationId()); + + } + } finally { + MDC.remove(CLIENT_STR); + } + logger.debug("Processed JMS message from Mapper for TR069 Device RPC operation"); + + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/helper/TR069RequestProcessEngineUtility.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/helper/TR069RequestProcessEngineUtility.java index 9cc7b54..4471779 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/helper/TR069RequestProcessEngineUtility.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/helper/TR069RequestProcessEngineUtility.java @@ -1,173 +1,172 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.helper; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.OPERATION_EXPIRATION_TIMEOUT; - -import java.util.ArrayList; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode; -import org.commscope.tr069adapter.acs.common.response.AddObjectResponse; -import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse; -import org.commscope.tr069adapter.acs.common.response.DownloadResponse; -import org.commscope.tr069adapter.acs.common.response.FactoryResetResponse; -import org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse; -import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse; -import org.commscope.tr069adapter.acs.common.response.RebootResponse; -import org.commscope.tr069adapter.acs.common.response.SetParameterAttributeResponse; -import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class TR069RequestProcessEngineUtility { - - private static final Logger logger = - LoggerFactory.getLogger(TR069RequestProcessEngineUtility.class); - - /** - * Builds a operation aborted operation request - * - * @param deviceDetails - * @param nbiDeviceOperationrequest - * @param acsFaultCode - * @return - */ - public DeviceRPCResponse buildAbortedOperationresult(DeviceDetails deviceDetails, - DeviceRPCRequest nbiDeviceOperationrequest, AcsFaultCode acsFaultCode) { - Long operationId = nbiDeviceOperationrequest.getOperationId(); - - TR069OperationCode operationCode = null; - if (nbiDeviceOperationrequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { - operationCode = TR069OperationCode.GET_PARAMETER_VALUES; - } else { - operationCode = (TR069OperationCode) nbiDeviceOperationrequest.getOpDetails().getOpCode(); - } - - return buildOperationresult(deviceDetails, operationId, operationCode, acsFaultCode); - - } - - /** - * @param deviceDetails - * @param operationId - * @param operationCode - * @return - */ - public DeviceRPCResponse buildTimedOutOperationResult(DeviceDetails deviceDetails, - DeviceRPCRequest deviceRPCRequest) { - Long operationId = deviceRPCRequest.getOperationId(); - - TR069OperationCode operationCode = null; - if (deviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { - CustomOperationCode customOperationCode = - (CustomOperationCode) deviceRPCRequest.getOpDetails().getOpCode(); - if (CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS.equals(customOperationCode)) { - operationCode = TR069OperationCode.GET_PARAMETER_VALUES; - } else if (CustomOperationCode.CONNECT.equals(customOperationCode)) { - operationCode = TR069OperationCode.INITIATE_CR; - } - } else { - operationCode = (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode(); - } - DeviceRPCResponse deviceRPCResponse = buildOperationresult(deviceDetails, operationId, - operationCode, AcsFaultCode.FAULT_CODE_8003); - OperationResponse operationResponse = deviceRPCResponse.getOperationResponse(); - operationResponse.setStatus(OPERATION_EXPIRATION_TIMEOUT); - return deviceRPCResponse; - } - - /** - * Builds a operation aborted operation request - * - * @param deviceDetails - * @param nbiDeviceOperationrequest - * @param acsFaultCode - * @return - */ - private DeviceRPCResponse buildOperationresult(DeviceDetails deviceDetails, Long operationId, - TR069OperationCode operationCode, AcsFaultCode acsFaultCode) { - DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse(); - deviceRPCResponse.setDeviceDetails(deviceDetails); - deviceRPCResponse.setOperationId(operationId); - - deviceRPCResponse.setFaultKey(acsFaultCode.getFaultKey()); - deviceRPCResponse.setFaultString(acsFaultCode.getFaultString()); - - OperationResponse opResponse = null; - switch (operationCode) { - case GET_RPC_METHODS: - case GET_PARAMETER_NAMES: - break; - case SET_PARAMETER_VALUES: - opResponse = new SetParameterValueResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case GET_PARAMETER_VALUES: - case INITIATE_CR: - opResponse = new GetParameterValueResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case SET_PARAMETER_ATTRIBUTES: - opResponse = new SetParameterAttributeResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case GET_PARAMETER_ATTRIBUTES: - opResponse = new GetParameterAttributeResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case ADD_OBJECT: - opResponse = new AddObjectResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case DELETE_OBJECT: - opResponse = new DeleteObjectResponse(); - opResponse.setParameterDTOs(new ArrayList()); - break; - case REBOOT: - opResponse = new RebootResponse(); - break; - case DOWNLOAD: - opResponse = new DownloadResponse(); - break; - case SCHEDULE_DOWNLOAD: - case UPLOAD: - case FACTORY_RESET: - opResponse = new FactoryResetResponse(); - break; - default: - String operationCodeName = operationCode.name(); - logger.debug("An unsupported operation: {}, hence returning without response object", - operationCodeName); - break; - } - deviceRPCResponse.setOperationResponse(opResponse); - - return deviceRPCResponse; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.helper; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.OPERATION_EXPIRATION_TIMEOUT; + +import java.util.ArrayList; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode; +import org.commscope.tr069adapter.acs.common.response.AddObjectResponse; +import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse; +import org.commscope.tr069adapter.acs.common.response.DownloadResponse; +import org.commscope.tr069adapter.acs.common.response.FactoryResetResponse; +import org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse; +import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse; +import org.commscope.tr069adapter.acs.common.response.RebootResponse; +import org.commscope.tr069adapter.acs.common.response.SetParameterAttributeResponse; +import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class TR069RequestProcessEngineUtility { + + private static final Logger logger = + LoggerFactory.getLogger(TR069RequestProcessEngineUtility.class); + + /** + * Builds a operation aborted operation request + * + * @param deviceDetails + * @param nbiDeviceOperationrequest + * @param acsFaultCode + * @return + */ + public DeviceRPCResponse buildAbortedOperationresult(DeviceDetails deviceDetails, + DeviceRPCRequest nbiDeviceOperationrequest, AcsFaultCode acsFaultCode) { + Long operationId = nbiDeviceOperationrequest.getOperationId(); + + TR069OperationCode operationCode = null; + if (nbiDeviceOperationrequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { + operationCode = TR069OperationCode.GET_PARAMETER_VALUES; + } else { + operationCode = (TR069OperationCode) nbiDeviceOperationrequest.getOpDetails().getOpCode(); + } + + return buildOperationresult(deviceDetails, operationId, operationCode, acsFaultCode); + + } + + /** + * @param deviceDetails + * @param operationId + * @param operationCode + * @return + */ + public DeviceRPCResponse buildTimedOutOperationResult(DeviceDetails deviceDetails, + DeviceRPCRequest deviceRPCRequest) { + Long operationId = deviceRPCRequest.getOperationId(); + + TR069OperationCode operationCode = null; + if (deviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { + CustomOperationCode customOperationCode = + (CustomOperationCode) deviceRPCRequest.getOpDetails().getOpCode(); + if (CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS.equals(customOperationCode)) { + operationCode = TR069OperationCode.GET_PARAMETER_VALUES; + } else if (CustomOperationCode.CONNECT.equals(customOperationCode)) { + operationCode = TR069OperationCode.INITIATE_CR; + } + } else { + operationCode = (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode(); + } + DeviceRPCResponse deviceRPCResponse = buildOperationresult(deviceDetails, operationId, + operationCode, AcsFaultCode.FAULT_CODE_8003); + OperationResponse operationResponse = deviceRPCResponse.getOperationResponse(); + operationResponse.setStatus(OPERATION_EXPIRATION_TIMEOUT); + return deviceRPCResponse; + } + + /** + * Builds a operation aborted operation request + * + * @param deviceDetails + * @param nbiDeviceOperationrequest + * @param acsFaultCode + * @return + */ + private DeviceRPCResponse buildOperationresult(DeviceDetails deviceDetails, Long operationId, + TR069OperationCode operationCode, AcsFaultCode acsFaultCode) { + DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse(); + deviceRPCResponse.setDeviceDetails(deviceDetails); + deviceRPCResponse.setOperationId(operationId); + + deviceRPCResponse.setFaultKey(acsFaultCode.getFaultKey()); + deviceRPCResponse.setFaultString(acsFaultCode.getFaultString()); + + OperationResponse opResponse = null; + switch (operationCode) { + case GET_RPC_METHODS: + case GET_PARAMETER_NAMES: + break; + case SET_PARAMETER_VALUES: + opResponse = new SetParameterValueResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case GET_PARAMETER_VALUES: + case INITIATE_CR: + opResponse = new GetParameterValueResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case SET_PARAMETER_ATTRIBUTES: + opResponse = new SetParameterAttributeResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case GET_PARAMETER_ATTRIBUTES: + opResponse = new GetParameterAttributeResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case ADD_OBJECT: + opResponse = new AddObjectResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case DELETE_OBJECT: + opResponse = new DeleteObjectResponse(); + opResponse.setParameterDTOs(new ArrayList<>()); + break; + case REBOOT: + opResponse = new RebootResponse(); + break; + case DOWNLOAD: + opResponse = new DownloadResponse(); + break; + case SCHEDULE_DOWNLOAD: + case UPLOAD: + case FACTORY_RESET: + opResponse = new FactoryResetResponse(); + break; + default: + String operationCodeName = operationCode.name(); + logger.debug("An unsupported operation: {}, hence returning without response object", + operationCodeName); + break; + } + deviceRPCResponse.setOperationResponse(opResponse); + + return deviceRPCResponse; + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/SessionManager.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/SessionManager.java index b9de828..43f7386 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/SessionManager.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/SessionManager.java @@ -1,133 +1,134 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; - -import com.fasterxml.uuid.EthernetAddress; -import com.fasterxml.uuid.Generators; -import com.fasterxml.uuid.impl.TimeBasedGenerator; - -import java.util.Optional; -import java.util.UUID; - -import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.requestprocessor.dao.SessionRepository; -import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO; -import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState; -import org.commscope.tr069adapter.acs.requestprocessor.entity.SessionManagerEntity; -import org.commscope.tr069adapter.acs.requestprocessor.util.SessionManagerUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class SessionManager { - - private static final Logger logger = LoggerFactory.getLogger(SessionManager.class); - - @Autowired - SessionRepository sessionRepository; - - /** - * @param deviceId - * @return - * @throws SessionManagerException - */ - public SessionDTO getSession(String deviceId) { - SessionManagerEntity session = null; - Optional optionalSessionData = sessionRepository.findById(deviceId); - if (optionalSessionData.isPresent()) { - session = optionalSessionData.get(); - } - return SessionManagerUtility.convertToDTO(session); - } - - /** - * @param sessionId - * @return - * @throws SessionManagerException - */ - public SessionDTO getSessionBySessionId(String sessionId) throws SessionManagerException { - - SessionManagerEntity sessionManagerEntity = sessionRepository.findBySessionId(sessionId); - if (sessionManagerEntity == null || SessionState.TERMINATED - .equals(SessionState.getByValue(sessionManagerEntity.getState()))) { - throw new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); - } - return SessionManagerUtility.convertToDTO(sessionManagerEntity); - } - - /** - * @param session - * @return - * @throws SessionManagerException - */ - public SessionDTO createSession(SessionDTO session) throws SessionManagerException { - if (session == null) { - SessionManagerException sme = new SessionManagerException(ErrorCode.SESSION_CREATION_ERROR, - "Session object cannot be null"); - logger.error(sme.getMessage()); - throw sme; - } - logger.debug("Creating a new session for the device"); - return SessionManagerUtility - .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(session))); - } - - /** - * @param dto - * @return - * @throws SessionManagerException - */ - public SessionDTO updateSession(SessionDTO dto) { - return SessionManagerUtility - .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(dto))); - } - - /** - * @param deviceId - * @throws SessionConcurrentAccessException - */ - public void deleteSession(String deviceId) { - sessionRepository.deleteById(deviceId); - } - - /** - * @param deviceId - * @return - * @throws SessionManagerException - */ - public SessionDTO getLockedSession(String deviceId) { - logger.debug("Acquiring the session lock for the device"); - return SessionManagerUtility.convertToDTO(sessionRepository.findByDeviceId(deviceId)); - } - - /** - * @return - */ - public String generateUniqueSessionID() { - EthernetAddress addr = EthernetAddress.fromInterface(); - TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(addr); - UUID uuid = uuidGenerator.generate(); - return uuid.toString(); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; + +import com.fasterxml.uuid.EthernetAddress; +import com.fasterxml.uuid.Generators; +import com.fasterxml.uuid.impl.TimeBasedGenerator; + +import java.util.Optional; +import java.util.UUID; + +import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.requestprocessor.dao.SessionRepository; +import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO; +import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState; +import org.commscope.tr069adapter.acs.requestprocessor.entity.SessionManagerEntity; +import org.commscope.tr069adapter.acs.requestprocessor.util.SessionManagerUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SessionManager { + + private static final Logger logger = LoggerFactory.getLogger(SessionManager.class); + + @Autowired + SessionRepository sessionRepository; + + /** + * @param deviceId + * @return + * @throws SessionManagerException + */ + public SessionDTO getSession(String deviceId) { + SessionManagerEntity session = null; + Optional optionalSessionData = sessionRepository.findById(deviceId); + if (optionalSessionData.isPresent()) { + session = optionalSessionData.get(); + } + return SessionManagerUtility.convertToDTO(session); + } + + /** + * @param sessionId + * @return + * @throws SessionManagerException + */ + public SessionDTO getSessionBySessionId(String sessionId) throws SessionManagerException { + + SessionManagerEntity sessionManagerEntity = sessionRepository.findBySessionId(sessionId); + if (sessionManagerEntity == null || SessionState.TERMINATED + .equals(SessionState.getByValue(sessionManagerEntity.getState()))) { + throw new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); + } + return SessionManagerUtility.convertToDTO(sessionManagerEntity); + } + + /** + * @param session + * @return + * @throws SessionManagerException + */ + public SessionDTO createSession(SessionDTO session) throws SessionManagerException { + if (session == null) { + SessionManagerException sme = new SessionManagerException(ErrorCode.SESSION_CREATION_ERROR, + "Session object cannot be null"); + String smeMessage = sme.getMessage().replaceAll("[\n|\r|\t]", "_"); + logger.error(smeMessage); + throw sme; + } + logger.debug("Creating a new session for the device"); + return SessionManagerUtility + .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(session))); + } + + /** + * @param dto + * @return + * @throws SessionManagerException + */ + public SessionDTO updateSession(SessionDTO dto) { + return SessionManagerUtility + .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(dto))); + } + + /** + * @param deviceId + * @throws SessionConcurrentAccessException + */ + public void deleteSession(String deviceId) { + sessionRepository.deleteById(deviceId); + } + + /** + * @param deviceId + * @return + * @throws SessionManagerException + */ + public SessionDTO getLockedSession(String deviceId) { + logger.debug("Acquiring the session lock for the device"); + return SessionManagerUtility.convertToDTO(sessionRepository.findByDeviceId(deviceId)); + } + + /** + * @return + */ + public String generateUniqueSessionID() { + EthernetAddress addr = EthernetAddress.fromInterface(); + TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(addr); + UUID uuid = uuidGenerator.generate(); + return uuid.toString(); + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069EventNotificationService.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069EventNotificationService.java index 634f9df..2f1ac6f 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069EventNotificationService.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069EventNotificationService.java @@ -1,95 +1,99 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069InformType; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.stereotype.Component; - -@Component -public class TR069EventNotificationService { - - private static final Logger logger = LoggerFactory.getLogger(TR069EventNotificationService.class); - - private static final String CLIENT_STR = "client"; - - @Autowired - private JmsTemplate jmsTemplate; - - /** - * @param deviceNotification - */ - public void sendDeviceInformToNBI(DeviceInform deviceNotification) { - String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); - try { - MDC.put(CLIENT_STR, deviceId); - TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType(); - - logger.debug("Device Inform Event received: '{}'", notificationType.getNotificationCode()); - jmsTemplate.convertAndSend(NBI_NOTIFICATION_Q, deviceNotification); - logger.debug("Successfully posted the device inform event to DM to forward to NBI"); - } catch (Exception e) { - logger.error("Posting Device Inform event to mapper failed, Reason: {}", e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - } - - /** - * @param deviceRPCResponse - */ - public void sendOperationResultToNBI(DeviceRPCResponse deviceRPCResponse) { - String deviceId = deviceRPCResponse.getDeviceDetails().getDeviceId(); - try { - MDC.put(CLIENT_STR, deviceId); - if (deviceRPCResponse.getOperationResponse() - .getOperationCode() instanceof TR069OperationCode) { - TR069OperationCode operCode = - (TR069OperationCode) deviceRPCResponse.getOperationResponse().getOperationCode(); - logger.debug("Device RPC Response received for operation: '" + operCode.name() - + "' with operation ID:" + deviceRPCResponse.getOperationId()); - } else if (deviceRPCResponse.getOperationResponse() - .getOperationCode() instanceof CustomOperationCode) { - CustomOperationCode operCode = - (CustomOperationCode) deviceRPCResponse.getOperationResponse().getOperationCode(); - logger.debug("Device RPC Response received for operation: '" + operCode.getJndiName() - + "' with operation ID:" + deviceRPCResponse.getOperationId()); - } - jmsTemplate.convertAndSend(NBI_OP_RESULT_Q, deviceRPCResponse); - logger.debug("Successfully posted the operation result event to DM to forward to NBI"); - } catch (Exception e) { - logger.error("Posting Device RPC response event to mapper failed, Reason: {}", - e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q; +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069InformType; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.stereotype.Component; + +@Component +public class TR069EventNotificationService { + + private static final Logger logger = LoggerFactory.getLogger(TR069EventNotificationService.class); + + private static final String CLIENT_STR = "client"; + + @Autowired + private JmsTemplate jmsTemplate; + + /** + * @param deviceNotification + */ + public void sendDeviceInformToNBI(DeviceInform deviceNotification) { + String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); + try { + MDC.put(CLIENT_STR, deviceId); + TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType(); + + logger.debug("Device Inform Event received: '{}'", notificationType.getNotificationCode()); + jmsTemplate.convertAndSend(NBI_NOTIFICATION_Q, deviceNotification); + logger.debug("Successfully posted the device inform event to DM to forward to NBI"); + } catch (Exception e) { + logger.error("Posting Device Inform event to mapper failed, Reason: {}", e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + } + + /** + * @param deviceRPCResponse + */ + public void sendOperationResultToNBI(DeviceRPCResponse deviceRPCResponse) { + String deviceId = deviceRPCResponse.getDeviceDetails().getDeviceId(); + try { + MDC.put(CLIENT_STR, deviceId); + String opercode; + if (deviceRPCResponse.getOperationResponse() + .getOperationCode() instanceof TR069OperationCode) { + TR069OperationCode operCode = + (TR069OperationCode) deviceRPCResponse.getOperationResponse().getOperationCode(); + opercode = operCode.name(); + logger.debug("Device RPC Response received for operation: {} with operation ID: {}", + opercode, deviceRPCResponse.getOperationId()); + + } else if (deviceRPCResponse.getOperationResponse() + .getOperationCode() instanceof CustomOperationCode) { + CustomOperationCode operCode = + (CustomOperationCode) deviceRPCResponse.getOperationResponse().getOperationCode(); + opercode = operCode.name(); + logger.debug("Device RPC Response received for operation: {} with operation ID: {}", + opercode, deviceRPCResponse.getOperationId()); + } + jmsTemplate.convertAndSend(NBI_OP_RESULT_Q, deviceRPCResponse); + logger.debug("Successfully posted the operation result event to DM to forward to NBI"); + } catch (Exception e) { + logger.error("Posting Device RPC response event to mapper failed, Reason: {}", + e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069RequestProcessEngine.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069RequestProcessEngine.java index 91dacb3..5689a31 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069RequestProcessEngine.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/impl/TR069RequestProcessEngine.java @@ -1,742 +1,761 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SESSION_ID; - -import java.util.List; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationCode; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069InformType; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; -import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; -import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode; -import org.commscope.tr069adapter.acs.common.inform.BootInform; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.requestprocessor.DeviceOperationInterface; -import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper; -import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData; -import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO; -import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState; -import org.commscope.tr069adapter.acs.requestprocessor.dto.TR069RequestProcessorData; -import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; -import org.commscope.tr069adapter.acs.requestprocessor.helper.TR069RequestProcessEngineHelper; -import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class TR069RequestProcessEngine extends TR069RequestProcessEngineHelper { - - private static final String PENDING_RPC_CHECK = - "Checking if any pending Device RPC requests exists for the device"; - - private static final Logger logger = LoggerFactory.getLogger(TR069RequestProcessEngine.class); - - @Autowired - TR069EventNotificationService tr069EventNotificationService; - - @Autowired - DeviceOperationInterface deviceOperationInterface; - - @Autowired - protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper; - - /** - * @param deviceRPCRequest - * @throws TR069EventProcessingException - * @throws SessionConcurrentAccessException - */ - public void processDeviceRPCRequest(DeviceRPCRequest deviceRPCRequest) - throws TR069EventProcessingException, SessionConcurrentAccessException { - - DeviceRPCResponse deviceRPCResponse = null; - String deviceId = null; - - try { - if (deviceRPCRequest == null) { - TR069EventProcessingException ex = - new TR069EventProcessingException(ErrorCode.INVALID_NBI_REQUEST); - logger.error(ex.getMessage()); - throw ex; - } - - Long operationId = deviceRPCRequest.getOperationId(); - logger.info("A Mapper request is received with operationID: {}", operationId); - TR069DeviceDetails tr069DeviceDetails = null; - deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); - try { - tr069DeviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); - deviceRPCResponse = checkForDeviceAvailabilityRequest(deviceRPCRequest, tr069DeviceDetails); - if (null != deviceRPCResponse) { - return; - } - } catch (DeviceOperationException | SessionManagerException deo) { - logger.error(deo.getMessage()); - deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( - tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8000); - return; - } - - try { - SessionDTO sessionDTO = acquireSessionLockWithRetryOnFailure(deviceId, operationId); - - logger.debug("Persisting the Device RPC request, with operation ID: {}", operationId); - List tr069DeviceRPCRequestEntities = - TR069RequestProcessorUtility.convertToEntity(deviceRPCRequest); - deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntities); - logger.info("Successfully persisted the Device RPC request"); - - if (sessionDTO != null) { - if (SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { - logger.debug("No active session exists, hence requesting for Connection request"); - requestForConnectionRequestInform(tr069DeviceDetails); - - // Start Request Timer - startDeviceRPCRequestTimer(deviceId, deviceRPCRequest.getOperationId(), - deviceRPCRequest.getOptions().getExecutionTimeout()); - } else { - logger.debug( - "Session is in processing state, Will be notified to session manager to pick the request on session availability"); - } - } else { - logger.warn( - "The device is not activated yet, hence the NBI Operation result cannot be processed!"); - deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( - tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8001); - } - } catch (SessionConcurrentAccessException scae) { - throw scae; - } catch (Exception e) { - logger.error("An unknown exception occurred while processing the NBI request, Reason: {}", - e.getMessage()); - deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( - tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8004); - } - } finally { - if (deviceRPCResponse != null) { - logger.debug("Sending failed operation result for this NBI request"); - tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); - // Marking the NBI Request as processed - deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, - deviceRPCRequest.getOperationId()); - } - } - } - - private DeviceRPCResponse checkForDeviceAvailabilityRequest(DeviceRPCRequest deviceRPCRequest, - TR069DeviceDetails tr069DeviceDetails) throws SessionManagerException { - DeviceRPCResponse deviceRPCResponse = null; - - if (!deviceRPCRequest.getOpDetails().getOpCode().equals(CustomOperationCode.CONNECT)) { - return deviceRPCResponse; - } - - SessionDTO sessionDTO = getSession(tr069DeviceDetails.getDeviceId()); - - if (null != sessionDTO && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { - logger.debug("Device is reachable as device tr069 session is in {} state.", - sessionDTO.getSessionState()); - - deviceRPCResponse = new DeviceRPCResponse(); - deviceRPCResponse.setDeviceDetails(tr069DeviceDetails); - deviceRPCResponse.setOperationId(deviceRPCRequest.getOperationId()); - - OperationResponse operationResponse = new OperationResponse(); - // device reachable...change value 1 to some constant or enum - operationResponse.setStatus(TR069RequestProcessorUtility.DEVICE_REACHABLE_STATUS_CODE); - operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode()); - - deviceRPCResponse.setOperationResponse(operationResponse); - } - - return deviceRPCResponse; - } - - /** - * Common Step 1. Since there can exist only one Inform from any device, which will be the - * initiator of the session, following steps to be followed a. Stop the session timer for this - * device if any running. b. Get the lock by reading the session record for this device from DB - * and load the session object in Thread Local Cache c. Create a new session id from - * SessionManager, and update the session object with new Session id and change the state to - * PROCESSING. 2. Read the Device record from the DB, and load the device DTO also in the - * ThreadLocalCache - * - * Common Notification Specific Step 1. Take the connection request URL from the - * deviceNotification object 2. Update the Device DTO object with connection request URL, - * swVersion, hwVersion if there is a difference. Update the last updated time if updated 3. Send - * this Inform to the NBI, by calling the ProcessDeviceInform method on TR069NBIService module. 4. - * Create the Inform response Object and update the sessionID used for this transaction in the - * response which will be used in the cookie of the HTTP response 5. Post the message into - * Response Queue 6. Change the session state to LOCKED 7. Save the Session and device records - * with the values in ThreadLocalCache 8. Start the session timer and default request timer (As - * configured for all the requests from device) 8. All the above steps to be executed in a single - * transaction. - * - * @param deviceNotification - * @return - * @throws SessionConcurrentAccessException - */ - public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification) - throws SessionConcurrentAccessException { - - String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); - TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType(); - logger.info("Processing the Device Inform Event: '{}'", notificationType.getNotificationCode()); - String newSessionId = null; - SessionDTO session = null; - TR069DeviceDetails deviceDetails = null; - DeviceInformResponse informResponse = null; - - try { - - SessionDTO sessionDTO = getSession(deviceId); - if (sessionDTO != null && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { - String sessionId = sessionDTO.getSessionId(); - logger.debug( - "The session with session id {} is not terminated, hence stopping the associated timer", - sessionId); - stopSessionTimer(sessionDTO.getSessionId()); - } - - // To stop the request timer if any running for this device, and send failed operation - // result for any such pending cases. Requests pending in DB should not be cleared - - /* - * Read any pending records in TR069_NBI_REQUEST table for this device. Send abort operation - * result for all the pending requests Delete the records from the TR069_NBI_Request table for - * this device. - */ - if (deviceNotification instanceof BootstrapInform - || deviceNotification instanceof BootInform) { - sendAbortedOperationResultForPendingRPCRequests(deviceNotification.getDeviceDetails(), - notificationType); - } - - session = acquireSessionLock(deviceId, notificationType, true); - deviceDetails = getPersistedDeviceDetails(deviceId, deviceNotification); - - newSessionId = session.getSessionId(); - logger.debug("The session id generated to process the device notification request is: {} ", - newSessionId); - - initThreadLocalCache(deviceDetails, session); - TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); - updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); - - logger.debug("Sending the Device Inform Event to the Mapper"); - tr069EventNotificationService.sendDeviceInformToNBI(deviceNotification); - - updateDeviceDetailsFromInform(tr069RequestProcessorData, deviceNotification); - - logger.debug("Updating the session for the device with newly generated session id"); - changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); - updateSession(session); - - // Start session timer - Get a default timeout for session. - startSessionTimer(session.getSessionId()); - - informResponse = - new DeviceInformResponse(newSessionId, deviceNotification.getDeviceDetails()); - } catch ( - - DeviceOperationException doe) { - logger.error(doe.getMessage()); - } catch (SessionConcurrentAccessException scae) { - throw scae; - } catch (Exception e) { - throw new SessionConcurrentAccessException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); - } - return informResponse; - } - - /** - * - * 1. Stop the request timer for this device using the session ID received in the cookie of the - * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the - * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check - * if any pending request being notified for the device using in memory cache - Not planned for - * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request - * is pending. - * - * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the - * response object and update the sessionID used for this transaction in the response which will - * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4. - * Change the session state to LOCKED and update the OPERATION_ID in the session table with the - * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6. - * Start the session timer and request timer (available in the request) } else { 1. Move the - * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record - * with the values in ThreadLocalCache. 3. Start the session timer. } - * - * 6. All the above steps to be executed in a single transaction - * - * @param deviceRPCResponse - * @return - * @throws SessionConcurrentAccessException - */ - public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse deviceRPCResponse) - throws SessionConcurrentAccessException { - TR069DeviceDetails deviceDetails = (TR069DeviceDetails) deviceRPCResponse.getDeviceDetails(); - String deviceId = deviceDetails.getDeviceId(); - logger.info("Processing the operation response from device"); - - SessionDTO session; - DeviceRPCRequest deviceRPCRequest = null; - try { - session = acquireSessionLock(deviceId, null, false); - String newSessionId = session.getSessionId(); - logger.debug("The session id used to process the device RPC response is: {}", newSessionId); - - initThreadLocalCache(deviceDetails, session); - TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); - updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); - - Long operationId = deviceRPCResponse.getOperationId(); - - deviceRPCRequest = getNextRPCRequest(deviceId, operationId); - - if (deviceRPCRequest != null) { - OperationDetails opDetails = deviceRPCRequest.getOpDetails(); - if (opDetails != null) { - OperationCode opCode = opDetails.getOpCode(); - if (opCode instanceof CustomOperationCode) { - CustomOperationCode customOperationCode = (CustomOperationCode) opCode; - String customOperationCodeName = customOperationCode.name(); - logger.info( - "The Device RPC request is of custom type, the custom operation to be performed is: {}", - customOperationCodeName); - String jndiName = customOperationCode.getJndiName(); - CustomOperationData customOperationData = - new CustomOperationData(deviceDetails, deviceRPCResponse, deviceRPCRequest); - customOperationData = executeCustomOperation(jndiName, customOperationData); - - DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest(); - deviceRPCResponse = customOperationData.getDeviceRPCResponse(); - if (operationRequest != null) { - return handleOperationRequest(deviceRPCResponse, session, deviceRPCRequest, - newSessionId, tr069RequestProcessorData, operationRequest); - } else { - logger.debug(PENDING_RPC_CHECK); - deviceRPCRequest = - deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); - } - } - } - } - - if (deviceRPCRequest != null) { - logger.info("A pending Device RPC request exists for the device with operation ID: {}", - deviceRPCRequest.getOperationId()); - updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId()); - changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); - - deviceRPCRequest.addContextParam(SESSION_ID, newSessionId); - - } else { - logger.info( - "No pending Device RPC request exists for the device, hence empty response will be sent to the device"); - logger.debug("Updating the session to terminated state"); - // To stop the session timer if any running for this device. - stopSessionTimer(newSessionId); - changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED); - } - - // To stop the request timer if any running for this operation. - stopDeviceRPCRequestTimer(deviceId, deviceRPCResponse.getOperationId()); - - // Sending the operation response to NBI - logger.debug("Sending the Device RPC Response to the Mapper"); - tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); - - updateSession(session); - } catch (DeviceOperationException doe) { - logger.error(doe.getMessage()); - } catch (SessionConcurrentAccessException scae) { - throw scae; - } - - return deviceRPCRequest; - } - - private DeviceRPCRequest handleOperationRequest(DeviceRPCResponse deviceRPCResponse, - SessionDTO session, DeviceRPCRequest deviceRPCRequest, String newSessionId, - TR069RequestProcessorData tr069RequestProcessorData, DeviceRPCRequest operationRequest) { - operationRequest.addContextParam(SESSION_ID, newSessionId); - updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId()); - changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); - updateSession(session); - if (deviceRPCResponse != null && operationRequest.getOperationId() != null - && !operationRequest.getOperationId().equals(deviceRPCResponse.getOperationId())) { - logger - .debug("Sending the Device RPC response for a configure Multiple object prior operation"); - // Sending the operation response to NBI - tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); - } - return operationRequest; - } - - /** - * - * 1. Stop the request timer for this device using the session ID received in the cookie of the - * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the - * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check - * if any pending request being notified for the device using in memory cache - Not planned for - * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request - * is pending. - * - * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the - * response object and update the sessionID used for this transaction in the response which will - * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4. - * Change the session state to LOCKED and update the OPERATION_ID in the session table with the - * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6. - * Start the session timer and request timer (available in the request) } else { 1. Move the - * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record - * with the values in ThreadLocalCache. 3. Start the session timer. } - * - * 6. All the above steps to be executed in a single transaction - * - * @param deviceDetails - * @return - * @throws SessionConcurrentAccessException - */ - public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) - throws SessionConcurrentAccessException { - String deviceId = deviceDetails.getDeviceId(); - logger.info("Processing the empty request from device"); - - SessionDTO session; - DeviceRPCRequest nbiDeviceOperationRequest = null; - try { - session = acquireSessionLock(deviceId, null, false); - String newSessionId = session.getSessionId(); - logger.debug("The session id used to process the empty device request is: {}", newSessionId); - - initThreadLocalCache(deviceDetails, session); - TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); - updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); - - logger.debug(PENDING_RPC_CHECK); - nbiDeviceOperationRequest = - deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); - if (nbiDeviceOperationRequest != null) { - Long operationId = nbiDeviceOperationRequest.getOperationId(); - OperationDetails opDetails = nbiDeviceOperationRequest.getOpDetails(); - if (opDetails != null) { - OperationCode opCode = opDetails.getOpCode(); - if (opCode instanceof CustomOperationCode) { - CustomOperationCode customOperationCode = (CustomOperationCode) opCode; - String customOperationCodeName = customOperationCode.name(); - logger.info( - "The Device RPC operation request is of custom type, the custom operation to be performed is: {}", - customOperationCodeName); - String jndiName = customOperationCode.getJndiName(); - CustomOperationData customOperationData = - new CustomOperationData(deviceDetails, null, nbiDeviceOperationRequest); - customOperationData = executeCustomOperation(jndiName, customOperationData); - - DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest(); - if (operationRequest != null) { - operationRequest.addContextParam(SESSION_ID, newSessionId); - updateSessionCurOpId(tr069RequestProcessorData, operationId); - changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); - updateSession(session); - return operationRequest; - } else { - logger.debug(PENDING_RPC_CHECK); - nbiDeviceOperationRequest = - deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); - } - } - } - } - - if (nbiDeviceOperationRequest != null) { - Long operationId = nbiDeviceOperationRequest.getOperationId(); - logger.info("A pending Device RPC request exists for the device with operation ID: {}", - operationId); - updateSessionCurOpId(tr069RequestProcessorData, operationId); - changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); - - nbiDeviceOperationRequest.addContextParam(SESSION_ID, newSessionId); - - } else { - logger.info( - "No pending Device RPC request exists for the device, hence empty device response will be sent to the device"); - logger.debug("Updating the session to terminated state"); - // To stop the session timer if any running for this device. - stopSessionTimer(newSessionId); - changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED); - } - - updateSession(session); - } catch (DeviceOperationException doe) { - logger.error(doe.getMessage()); - } catch (SessionConcurrentAccessException scae) { - throw scae; - } - - return nbiDeviceOperationRequest; - } - - /** - * @param sessionId - * @return - * @throws SessionManagerException - */ - public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) - throws SessionManagerException { - DeviceOperationRequestDetails deviceOperationRequestDetails = - new DeviceOperationRequestDetails(); - - logger.debug("Fetching Operation request details for session: {}", sessionId); - SessionDTO session = getSessionBySessionId(sessionId); - String deviceId = session.getDeviceId(); - TR069DeviceDetails deviceDetails = null; - try { - deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); - if (session.getCurrentOperationId() == null) { - logger.debug("There exists no pending operation request for the session: {}", sessionId); - } else { - logger.debug("There exists pending operation request for the session: {}", sessionId); - List tr069DeviceRPCRequestEntityList = - deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId, - session.getCurrentOperationId()); - if (tr069DeviceRPCRequestEntityList == null) { - SessionManagerException ex = - new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); - logger.error(ex.getMessage()); - throw ex; - } - DeviceRPCRequest deviceRPCRequest = - TR069RequestProcessorUtility.convertToDTO(tr069DeviceRPCRequestEntityList); - OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode(); - - String operationName = null; - - if (opCode instanceof TR069OperationCode) { - operationName = ((TR069OperationCode) opCode).name(); - } else { - operationName = ((CustomOperationCode) opCode).name(); - TR069OperationDetails tr069OperationDetails = - (TR069OperationDetails) deviceRPCRequest.getOpDetails(); - opCode = getCustomOperationCode(tr069OperationDetails); - } - logger.info("The pending operation request for the session is of operation {}", - operationName); - deviceOperationRequestDetails.setOpCode(opCode); - deviceOperationRequestDetails.setOperationId(deviceRPCRequest.getOperationId()); - } - deviceOperationRequestDetails.setDeviceDetails(deviceDetails); - } catch (DeviceOperationException e) { - SessionManagerException ex = - new SessionManagerException(ErrorCode.DEVICE_NOT_EXISTS, deviceId); - logger.error(ex.getMessage()); - throw ex; - } catch (Exception e) { - logger.error(e.getMessage()); - SessionManagerException ex = - new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); - logger.error(ex.getMessage()); - throw ex; - } - return deviceOperationRequestDetails; - } - - /** - * @param deviceId - * @return - * @throws DeviceOperationException - */ - public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException { - return deviceOperationInterface.getDeviceDetails(deviceId); - } - - /** - * @param deviceId - * @param operationId - * @return - * @throws DeviceOperationException - * @throws SessionConcurrentAccessException - * @throws InterruptedException - */ - private SessionDTO acquireSessionLockWithRetryOnFailure(String deviceId, Long operationId) - throws DeviceOperationException, SessionConcurrentAccessException, InterruptedException { - int sessionLockAcquireRetryCount = 0; - SessionDTO sessionDTO = null; - do { - try { - sessionDTO = acquireSessionLock(deviceId, null, false); - logger.info( - "Successfully acquired the session lock for processing NBI request with operation ID: {}", - operationId); - break; - } catch (SessionConcurrentAccessException ex) { - sessionLockAcquireRetryCount++; - if (sessionLockAcquireRetryCount == 3) { - logger.error("Failed acquiring the lock after retry, rolling back the transaction"); - throw ex; - } - logger.warn( - "Session lock acquiring failed with SessionConcurrentAccessException, hence retrying"); - Thread.sleep(1000L); - } - } while (sessionLockAcquireRetryCount < 3); - - return sessionDTO; - } - - /** - * @param deviceId - * @param deviceNotification - * @return - * @throws DeviceOperationException - */ - private TR069DeviceDetails getPersistedDeviceDetails(String deviceId, - DeviceInform deviceNotification) throws DeviceOperationException { - TR069DeviceDetails deviceDetails = null; - try { - deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); - } catch (DeviceOperationException doe) { - if (ErrorCode.DEVICE_NOT_EXISTS.equals(doe.getErrorCode())) { - logger.info( - "Creating the device record in TR069_DEVICE_ table, as the device is authenticated successfully."); - createDevice(deviceNotification.getDeviceDetails()); - deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); - } - } - - return deviceDetails; - } - - /** - * @param deviceDetails - * @param notificationType - * @throws TR069EventProcessingException - */ - private void sendAbortedOperationResultForPendingRPCRequests(DeviceDetails deviceDetails, - TR069InformType notificationType) throws TR069EventProcessingException { - String deviceId = deviceDetails.getDeviceId(); - String notificationName = notificationType.name(); - logger.debug( - "Device Inform event received is {}, hence aborting all the pending operations if any exists", - notificationName); - - List deviceRPCRequestList = - deviceRPCRequestRepositoryHelper.findAllDeviceRPCRequests(deviceId); - - for (DeviceRPCRequest pendingDeviceRPCRequest : deviceRPCRequestList) { - DeviceRPCResponse deviceOpResult = - tr069RequestProcessEngineUtility.buildAbortedOperationresult(deviceDetails, - pendingDeviceRPCRequest, AcsFaultCode.FAULT_CODE_8002); - String operationName = null; - if (pendingDeviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { - CustomOperationCode operationCode = - (CustomOperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode(); - operationName = operationCode.name(); - } else { - TR069OperationCode operationCode = - (TR069OperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode(); - operationName = operationCode.name(); - } - Long operationId = pendingDeviceRPCRequest.getOperationId(); - logger.debug("Aborting the NBI Operation request with operation Id : {} for operation: {}", - operationId, operationName); - tr069EventNotificationService.sendOperationResultToNBI(deviceOpResult); - // Marking the NBI Request as processed - deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId); - stopDeviceRPCRequestTimer(deviceId, operationId); - } - } - - /** - * @param tr069RequestProcessorData - * @param deviceNotification - */ - private void updateDeviceDetailsFromInform(TR069RequestProcessorData tr069RequestProcessorData, - DeviceInform deviceNotification) { - Boolean isDeviceDataChanged = - isDeviceUpdateExists(tr069RequestProcessorData, deviceNotification); - if (isDeviceDataChanged.booleanValue()) { - updateDeviceDetails(tr069RequestProcessorData, deviceNotification); - try { - logger.info( - "The device data like connection request URL/ Device SW/HW version has changed, hence updating the device details"); - deviceOperationInterface - .updateDeviceDetails(tr069RequestProcessorData.getTr069DeviceDetails()); - } catch (DeviceOperationException e) { - logger.error("Updating the device details with the notification details failed, Reason: {}", - e.getMessage()); - logger.error(e.getMessage()); - } - } - } - - /** - * @param deviceId - * @param operationId - * @return - */ - private DeviceRPCRequest getNextRPCRequest(String deviceId, Long operationId) { - DeviceRPCRequest deviceRPCRequest = null; - try { - List entityList = - deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId, operationId); - Integer operationCode = entityList.get(0).getOpCode(); - if (CustomOperationCode.getByOperationCode(operationCode) == null) { - logger.info("Marking the Device RPC request with operation id - {} as processed.", - operationId); - deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId); - } - logger.debug(PENDING_RPC_CHECK); - deviceRPCRequest = deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); - } catch (TR069EventProcessingException e) { - logger.error("An unknown exception occurred while fetching the NBI request, Reason: {}", - e.getMessage()); - } - - return deviceRPCRequest; - } - - /** - * Creates the device in the DM module if factory imported already - * - * @param deviceDetails - * @throws DeviceOperationException - */ - private void createDevice(DeviceDetails deviceDetails) throws DeviceOperationException { - deviceOperationInterface.updateDeviceDetails(deviceDetails); - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.impl; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SESSION_ID; + +import java.util.Date; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationCode; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069InformType; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException; +import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException; +import org.commscope.tr069adapter.acs.common.exception.SessionManagerException; +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode; +import org.commscope.tr069adapter.acs.common.inform.BootInform; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.requestprocessor.DeviceOperationInterface; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper; +import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRepository; +import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData; +import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO; +import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState; +import org.commscope.tr069adapter.acs.requestprocessor.dto.TR069RequestProcessorData; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; +import org.commscope.tr069adapter.acs.requestprocessor.helper.TR069RequestProcessEngineHelper; +import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class TR069RequestProcessEngine extends TR069RequestProcessEngineHelper { + + private static final String PENDING_RPC_CHECK = + "Checking if any pending Device RPC requests exists for the device"; + + private static final Logger logger = LoggerFactory.getLogger(TR069RequestProcessEngine.class); + + @Autowired + TR069EventNotificationService tr069EventNotificationService; + + @Autowired + DeviceOperationInterface deviceOperationInterface; + + @Autowired + protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper; + + @Autowired + private DeviceRepository deviceRepository; + + /** + * @param deviceRPCRequest + * @throws TR069EventProcessingException + * @throws SessionConcurrentAccessException + */ + public void processDeviceRPCRequest(DeviceRPCRequest deviceRPCRequest) + throws TR069EventProcessingException, SessionConcurrentAccessException { + + DeviceRPCResponse deviceRPCResponse = null; + String deviceId = null; + + try { + if (deviceRPCRequest == null) { + TR069EventProcessingException ex = + new TR069EventProcessingException(ErrorCode.INVALID_NBI_REQUEST); + logger.error(ex.getMessage()); + throw ex; + } + + Long operationId = deviceRPCRequest.getOperationId(); + logger.info("A Mapper request is received with operationID: {}", operationId); + TR069DeviceDetails tr069DeviceDetails = null; + deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); + try { + tr069DeviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); + deviceRPCResponse = checkForDeviceAvailabilityRequest(deviceRPCRequest, tr069DeviceDetails); + if (null != deviceRPCResponse) { + return; + } + } catch (DeviceOperationException | SessionManagerException deo) { + logger.error(deo.getMessage()); + deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( + tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8000); + return; + } + + try { + SessionDTO sessionDTO = acquireSessionLockWithRetryOnFailure(deviceId, operationId); + + logger.debug("Persisting the Device RPC request, with operation ID: {}", operationId); + List tr069DeviceRPCRequestEntities = + TR069RequestProcessorUtility.convertToEntity(deviceRPCRequest); + deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntities); + logger.info("Successfully persisted the Device RPC request"); + + if (sessionDTO != null) { + if (SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { + logger.debug("No active session exists, hence requesting for Connection request"); + requestForConnectionRequestInform(tr069DeviceDetails); + + // Start Request Timer + startDeviceRPCRequestTimer(deviceId, deviceRPCRequest.getOperationId(), + deviceRPCRequest.getOptions().getExecutionTimeout()); + } else { + logger.debug( + "Session is in processing state, Will be notified to session manager to pick the request on session availability"); + } + } else { + logger.warn( + "The device is not activated yet, hence the NBI Operation result cannot be processed!"); + deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( + tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8001); + } + } catch (SessionConcurrentAccessException scae) { + throw scae; + } catch (Exception e) { + logger.error("An unknown exception occurred while processing the NBI request, Reason: {}", + e.getMessage()); + deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult( + tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8004); + } + } finally { + if (deviceRPCResponse != null) { + logger.debug("Sending failed operation result for this NBI request"); + tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); + // Marking the NBI Request as processed + deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, + deviceRPCRequest.getOperationId()); + } + } + } + + private DeviceRPCResponse checkForDeviceAvailabilityRequest(DeviceRPCRequest deviceRPCRequest, + TR069DeviceDetails tr069DeviceDetails) throws SessionManagerException { + DeviceRPCResponse deviceRPCResponse = null; + + if (!deviceRPCRequest.getOpDetails().getOpCode().equals(CustomOperationCode.CONNECT)) { + return deviceRPCResponse; + } + + SessionDTO sessionDTO = getSession(tr069DeviceDetails.getDeviceId()); + tr069DeviceDetails.setCrRetryCount(1); + if (null != sessionDTO && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { + logger.debug("Device is reachable as device tr069 session is in {} state.", + sessionDTO.getSessionState()); + + deviceRPCResponse = new DeviceRPCResponse(); + deviceRPCResponse.setDeviceDetails(tr069DeviceDetails); + deviceRPCResponse.setOperationId(deviceRPCRequest.getOperationId()); + + OperationResponse operationResponse = new OperationResponse(); + // device reachable...change value 1 to some constant or enum + operationResponse.setStatus(TR069RequestProcessorUtility.DEVICE_REACHABLE_STATUS_CODE); + operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode()); + + deviceRPCResponse.setOperationResponse(operationResponse); + } + + return deviceRPCResponse; + } + + /** + * Common Step 1. Since there can exist only one Inform from any device, which will be the + * initiator of the session, following steps to be followed a. Stop the session timer for this + * device if any running. b. Get the lock by reading the session record for this device from DB + * and load the session object in Thread Local Cache c. Create a new session id from + * SessionManager, and update the session object with new Session id and change the state to + * PROCESSING. 2. Read the Device record from the DB, and load the device DTO also in the + * ThreadLocalCache + * + * Common Notification Specific Step 1. Take the connection request URL from the + * deviceNotification object 2. Update the Device DTO object with connection request URL, + * swVersion, hwVersion if there is a difference. Update the last updated time if updated 3. Send + * this Inform to the NBI, by calling the ProcessDeviceInform method on TR069NBIService module. 4. + * Create the Inform response Object and update the sessionID used for this transaction in the + * response which will be used in the cookie of the HTTP response 5. Post the message into + * Response Queue 6. Change the session state to LOCKED 7. Save the Session and device records + * with the values in ThreadLocalCache 8. Start the session timer and default request timer (As + * configured for all the requests from device) 8. All the above steps to be executed in a single + * transaction. + * + * @param deviceNotification + * @return + * @throws SessionConcurrentAccessException + */ + public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification) + throws SessionConcurrentAccessException { + + String deviceId = deviceNotification.getDeviceDetails().getDeviceId(); + TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType(); + logger.info("Processing the Device Inform Event: '{}'", notificationType.getNotificationCode()); + String newSessionId = null; + SessionDTO session = null; + TR069DeviceDetails deviceDetails = null; + DeviceInformResponse informResponse = null; + + try { + + SessionDTO sessionDTO = getSession(deviceId); + if (sessionDTO != null && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) { + String sessionId = sessionDTO.getSessionId(); + logger.debug( + "The session with session id {} is not terminated, hence stopping the associated timer", + sessionId); + stopSessionTimer(sessionDTO.getSessionId()); + } + + // To stop the request timer if any running for this device, and send failed operation + // result for any such pending cases. Requests pending in DB should not be cleared + + /* + * Read any pending records in TR069_NBI_REQUEST table for this device. Send abort operation + * result for all the pending requests Delete the records from the TR069_NBI_Request table for + * this device. + */ + if (deviceNotification instanceof BootstrapInform + || deviceNotification instanceof BootInform) { + sendAbortedOperationResultForPendingRPCRequests(deviceNotification.getDeviceDetails(), + notificationType); + } + + session = acquireSessionLock(deviceId, notificationType, true); + deviceDetails = getPersistedDeviceDetails(deviceId, deviceNotification); + + newSessionId = session.getSessionId(); + logger.debug("The session id generated to process the device notification request is: {} ", + newSessionId); + + initThreadLocalCache(deviceDetails, session); + TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); + updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); + + logger.debug("Sending the Device Inform Event to the Mapper"); + tr069EventNotificationService.sendDeviceInformToNBI(deviceNotification); + + updateDeviceDetailsFromInform(tr069RequestProcessorData, deviceNotification); + + logger.debug("Updating the session for the device with newly generated session id"); + changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); + updateSession(session); + + // Start session timer - Get a default timeout for session. + startSessionTimer(session.getSessionId()); + + informResponse = + new DeviceInformResponse(newSessionId, deviceNotification.getDeviceDetails()); + } catch ( + + DeviceOperationException doe) { + logger.error(doe.getMessage()); + } catch (SessionConcurrentAccessException scae) { + throw scae; + } catch (Exception e) { + throw new SessionConcurrentAccessException(ErrorCode.UNKNOWN_ERROR, e.getMessage()); + } + return informResponse; + } + + /** + * + * 1. Stop the request timer for this device using the session ID received in the cookie of the + * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the + * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check + * if any pending request being notified for the device using in memory cache - Not planned for + * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request + * is pending. + * + * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the + * response object and update the sessionID used for this transaction in the response which will + * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4. + * Change the session state to LOCKED and update the OPERATION_ID in the session table with the + * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6. + * Start the session timer and request timer (available in the request) } else { 1. Move the + * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record + * with the values in ThreadLocalCache. 3. Start the session timer. } + * + * 6. All the above steps to be executed in a single transaction + * + * @param deviceRPCResponse + * @return + * @throws SessionConcurrentAccessException + */ + public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse deviceRPCResponse) + throws SessionConcurrentAccessException { + TR069DeviceDetails deviceDetails = (TR069DeviceDetails) deviceRPCResponse.getDeviceDetails(); + String deviceId = deviceDetails.getDeviceId(); + logger.info("Processing the operation response from device"); + + SessionDTO session; + DeviceRPCRequest deviceRPCRequest = null; + try { + session = acquireSessionLock(deviceId, null, false); + String newSessionId = session.getSessionId(); + logger.debug("The session id used to process the device RPC response is: {}", newSessionId); + + initThreadLocalCache(deviceDetails, session); + TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); + updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); + + Long operationId = deviceRPCResponse.getOperationId(); + + deviceRPCRequest = getNextRPCRequest(deviceId, operationId); + + if (deviceRPCRequest != null) { + OperationDetails opDetails = deviceRPCRequest.getOpDetails(); + if (opDetails != null) { + OperationCode opCode = opDetails.getOpCode(); + if (opCode instanceof CustomOperationCode) { + CustomOperationCode customOperationCode = (CustomOperationCode) opCode; + String customOperationCodeName = customOperationCode.name(); + logger.info( + "The Device RPC request is of custom type, the custom operation to be performed is: {}", + customOperationCodeName); + String jndiName = customOperationCode.getJndiName(); + CustomOperationData customOperationData = + new CustomOperationData(deviceDetails, deviceRPCResponse, deviceRPCRequest); + customOperationData = executeCustomOperation(jndiName, customOperationData); + + DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest(); + deviceRPCResponse = customOperationData.getDeviceRPCResponse(); + if (operationRequest != null) { + return handleOperationRequest(deviceRPCResponse, session, deviceRPCRequest, + newSessionId, tr069RequestProcessorData, operationRequest); + } else { + logger.debug(PENDING_RPC_CHECK); + deviceRPCRequest = + deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); + } + } + } + } + + if (deviceRPCRequest != null) { + logger.info("A pending Device RPC request exists for the device with operation ID: {}", + deviceRPCRequest.getOperationId()); + updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId()); + changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); + + deviceRPCRequest.addContextParam(SESSION_ID, newSessionId); + + } else { + logger.info( + "No pending Device RPC request exists for the device, hence empty response will be sent to the device"); + logger.debug("Updating the session to terminated state"); + // To stop the session timer if any running for this device. + stopSessionTimer(newSessionId); + changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED); + } + + // To stop the request timer if any running for this operation. + stopDeviceRPCRequestTimer(deviceId, deviceRPCResponse.getOperationId()); + + // Sending the operation response to NBI + logger.debug("Sending the Device RPC Response to the Mapper"); + tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); + + updateSession(session); + } catch (DeviceOperationException doe) { + logger.error(doe.getMessage()); + } catch (SessionConcurrentAccessException scae) { + throw scae; + } + + return deviceRPCRequest; + } + + private DeviceRPCRequest handleOperationRequest(DeviceRPCResponse deviceRPCResponse, + SessionDTO session, DeviceRPCRequest deviceRPCRequest, String newSessionId, + TR069RequestProcessorData tr069RequestProcessorData, DeviceRPCRequest operationRequest) { + operationRequest.addContextParam(SESSION_ID, newSessionId); + updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId()); + changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); + updateSession(session); + if (deviceRPCResponse != null && operationRequest.getOperationId() != null + && !operationRequest.getOperationId().equals(deviceRPCResponse.getOperationId())) { + logger + .debug("Sending the Device RPC response for a configure Multiple object prior operation"); + // Sending the operation response to NBI + tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse); + } + return operationRequest; + } + + /** + * + * 1. Stop the request timer for this device using the session ID received in the cookie of the + * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the + * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check + * if any pending request being notified for the device using in memory cache - Not planned for + * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request + * is pending. + * + * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the + * response object and update the sessionID used for this transaction in the response which will + * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4. + * Change the session state to LOCKED and update the OPERATION_ID in the session table with the + * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6. + * Start the session timer and request timer (available in the request) } else { 1. Move the + * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record + * with the values in ThreadLocalCache. 3. Start the session timer. } + * + * 6. All the above steps to be executed in a single transaction + * + * @param deviceDetails + * @return + * @throws SessionConcurrentAccessException + */ + public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails) + throws SessionConcurrentAccessException { + String deviceId = deviceDetails.getDeviceId(); + logger.info("Processing the empty request from device"); + + SessionDTO session; + DeviceRPCRequest nbiDeviceOperationRequest = null; + try { + session = acquireSessionLock(deviceId, null, false); + String newSessionId = session.getSessionId(); + logger.debug("The session id used to process the empty device request is: {}", newSessionId); + + initThreadLocalCache(deviceDetails, session); + TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData(); + updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId); + + logger.debug(PENDING_RPC_CHECK); + nbiDeviceOperationRequest = + deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); + if (nbiDeviceOperationRequest != null) { + Long operationId = nbiDeviceOperationRequest.getOperationId(); + OperationDetails opDetails = nbiDeviceOperationRequest.getOpDetails(); + if (opDetails != null) { + OperationCode opCode = opDetails.getOpCode(); + if (opCode instanceof CustomOperationCode) { + CustomOperationCode customOperationCode = (CustomOperationCode) opCode; + String customOperationCodeName = customOperationCode.name(); + logger.info( + "The Device RPC operation request is of custom type, the custom operation to be performed is: {}", + customOperationCodeName); + String jndiName = customOperationCode.getJndiName(); + CustomOperationData customOperationData = + new CustomOperationData(deviceDetails, null, nbiDeviceOperationRequest); + customOperationData = executeCustomOperation(jndiName, customOperationData); + + DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest(); + if (operationRequest != null) { + operationRequest.addContextParam(SESSION_ID, newSessionId); + updateSessionCurOpId(tr069RequestProcessorData, operationId); + changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); + updateSession(session); + return operationRequest; + } else { + logger.debug(PENDING_RPC_CHECK); + nbiDeviceOperationRequest = + deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); + } + } + } + } + + if (nbiDeviceOperationRequest != null) { + Long operationId = nbiDeviceOperationRequest.getOperationId(); + logger.info("A pending Device RPC request exists for the device with operation ID: {}", + operationId); + updateSessionCurOpId(tr069RequestProcessorData, operationId); + changeSessionState(tr069RequestProcessorData, SessionState.LOCKED); + + nbiDeviceOperationRequest.addContextParam(SESSION_ID, newSessionId); + + } else { + logger.info( + "No pending Device RPC request exists for the device, hence empty device response will be sent to the device"); + logger.debug("Updating the session to terminated state"); + // To stop the session timer if any running for this device. + stopSessionTimer(newSessionId); + changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED); + } + + updateSession(session); + } catch (DeviceOperationException doe) { + logger.error(doe.getMessage()); + } catch (SessionConcurrentAccessException scae) { + throw scae; + } + + return nbiDeviceOperationRequest; + } + + /** + * @param sessionId + * @return + * @throws SessionManagerException + */ + public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId) + throws SessionManagerException { + DeviceOperationRequestDetails deviceOperationRequestDetails = + new DeviceOperationRequestDetails(); + + logger.debug("Fetching Operation request details for session: {}", sessionId); + SessionDTO session = getSessionBySessionId(sessionId); + String deviceId = session.getDeviceId(); + TR069DeviceDetails deviceDetails = null; + try { + deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); + if (session.getCurrentOperationId() == null) { + logger.debug("There exists no pending operation request for the session: {}", sessionId); + } else { + sessionId = sessionId.replaceAll("[\n|\r|\t]", "_"); + logger.debug("There exists pending operation request for the session: {}", sessionId); + List tr069DeviceRPCRequestEntityList = + deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId, + session.getCurrentOperationId()); + if (tr069DeviceRPCRequestEntityList == null) { + SessionManagerException ex = + new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); + logger.error(ex.getMessage()); + throw ex; + } + DeviceRPCRequest deviceRPCRequest = + TR069RequestProcessorUtility.convertToDTO(tr069DeviceRPCRequestEntityList); + OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode(); + + String operationName = null; + + if (opCode instanceof TR069OperationCode) { + operationName = ((TR069OperationCode) opCode).name(); + } else { + operationName = ((CustomOperationCode) opCode).name(); + TR069OperationDetails tr069OperationDetails = + (TR069OperationDetails) deviceRPCRequest.getOpDetails(); + opCode = getCustomOperationCode(tr069OperationDetails); + } + logger.info("The pending operation request for the session is of operation {}", + operationName); + deviceOperationRequestDetails.setOpCode(opCode); + deviceOperationRequestDetails.setOperationId(deviceRPCRequest.getOperationId()); + } + deviceOperationRequestDetails.setDeviceDetails(deviceDetails); + } catch (DeviceOperationException e) { + SessionManagerException ex = + new SessionManagerException(ErrorCode.DEVICE_NOT_EXISTS, deviceId); + String exceptionMessage = ex.getMessage().replaceAll("[\n|\r|\t]", "_"); + logger.error(exceptionMessage); + throw ex; + } catch (Exception e) { + logger.error(e.getMessage()); + SessionManagerException ex = + new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId); + logger.error(ex.getMessage()); + throw ex; + } + return deviceOperationRequestDetails; + } + + /** + * @param deviceId + * @return + * @throws DeviceOperationException + */ + public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException { + return deviceOperationInterface.getDeviceDetails(deviceId); + } + + /** + * @param deviceId + * @param operationId + * @return + * @throws DeviceOperationException + * @throws SessionConcurrentAccessException + * @throws InterruptedException + */ + private SessionDTO acquireSessionLockWithRetryOnFailure(String deviceId, Long operationId) + throws DeviceOperationException, SessionConcurrentAccessException, InterruptedException { + int sessionLockAcquireRetryCount = 0; + SessionDTO sessionDTO = null; + do { + try { + sessionDTO = acquireSessionLock(deviceId, null, false); + logger.info( + "Successfully acquired the session lock for processing NBI request with operation ID: {}", + operationId); + break; + } catch (SessionConcurrentAccessException ex) { + sessionLockAcquireRetryCount++; + if (sessionLockAcquireRetryCount == 3) { + logger.error("Failed acquiring the lock after retry, rolling back the transaction"); + throw ex; + } + logger.warn( + "Session lock acquiring failed with SessionConcurrentAccessException, hence retrying"); + Thread.sleep(1000L); + } + } while (sessionLockAcquireRetryCount < 3); + + return sessionDTO; + } + + /** + * @param deviceId + * @param deviceNotification + * @return + * @throws DeviceOperationException + */ + private TR069DeviceDetails getPersistedDeviceDetails(String deviceId, + DeviceInform deviceNotification) throws DeviceOperationException { + TR069DeviceDetails deviceDetails = null; + try { + deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); + } catch (DeviceOperationException doe) { + if (ErrorCode.DEVICE_NOT_EXISTS.equals(doe.getErrorCode())) { + logger.info( + "Creating the device record in TR069_DEVICE_ table, as the device is authenticated successfully."); + createDevice(deviceNotification.getDeviceDetails()); + deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId); + } + } + + return deviceDetails; + } + + /** + * @param deviceDetails + * @param notificationType + * @throws TR069EventProcessingException + */ + private void sendAbortedOperationResultForPendingRPCRequests(DeviceDetails deviceDetails, + TR069InformType notificationType) throws TR069EventProcessingException { + String deviceId = deviceDetails.getDeviceId(); + String notificationName = notificationType.name(); + logger.debug( + "Device Inform event received is {}, hence aborting all the pending operations if any exists", + notificationName); + + List deviceRPCRequestList = + deviceRPCRequestRepositoryHelper.findAllDeviceRPCRequests(deviceId); + + for (DeviceRPCRequest pendingDeviceRPCRequest : deviceRPCRequestList) { + DeviceRPCResponse deviceOpResult = + tr069RequestProcessEngineUtility.buildAbortedOperationresult(deviceDetails, + pendingDeviceRPCRequest, AcsFaultCode.FAULT_CODE_8002); + String operationName = null; + if (pendingDeviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) { + CustomOperationCode operationCode = + (CustomOperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode(); + operationName = operationCode.name(); + } else { + TR069OperationCode operationCode = + (TR069OperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode(); + operationName = operationCode.name(); + } + Long operationId = pendingDeviceRPCRequest.getOperationId(); + logger.debug("Aborting the NBI Operation request with operation Id : {} for operation: {}", + operationId, operationName); + tr069EventNotificationService.sendOperationResultToNBI(deviceOpResult); + // Marking the NBI Request as processed + deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId); + stopDeviceRPCRequestTimer(deviceId, operationId); + } + } + + /** + * @param tr069RequestProcessorData + * @param deviceNotification + */ + private void updateDeviceDetailsFromInform(TR069RequestProcessorData tr069RequestProcessorData, + DeviceInform deviceNotification) { + Boolean isDeviceDataChanged = + isDeviceUpdateExists(tr069RequestProcessorData, deviceNotification); + if (isDeviceDataChanged.booleanValue()) { + updateDeviceDetails(tr069RequestProcessorData, deviceNotification); + try { + logger.info( + "The device data like connection request URL/ Device SW/HW version has changed, hence updating the device details"); + deviceOperationInterface + .updateDeviceDetails(tr069RequestProcessorData.getTr069DeviceDetails()); + } catch (DeviceOperationException e) { + logger.error("Updating the device details with the notification details failed, Reason: {}", + e.getMessage()); + logger.error(e.getMessage()); + } + } else { + TR069DeviceDetails tr069DeviceDetails = + (TR069DeviceDetails) tr069RequestProcessorData.getTr069DeviceDetails(); + TR069DeviceEntity tr069DeviceEntity = + deviceRepository.findByDeviceId(tr069DeviceDetails.getDeviceId()); + logger.info("Setting connection status as true for device: {}", + tr069DeviceDetails.getDeviceId()); + tr069DeviceEntity.setConnStatus(true); + tr069DeviceEntity.setLastUpdatedTime(new Date()); + tr069DeviceEntity.setErrorMsg(null); + deviceRepository.save(tr069DeviceEntity); + } + } + + /** + * @param deviceId + * @param operationId + * @return + */ + private DeviceRPCRequest getNextRPCRequest(String deviceId, Long operationId) { + DeviceRPCRequest deviceRPCRequest = null; + try { + List entityList = + deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId, operationId); + Integer operationCode = entityList.get(0).getOpCode(); + if (CustomOperationCode.getByOperationCode(operationCode) == null) { + logger.info("Marking the Device RPC request with operation id - {} as processed.", + operationId); + deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId); + } + logger.debug(PENDING_RPC_CHECK); + deviceRPCRequest = deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId); + } catch (TR069EventProcessingException e) { + logger.error("An unknown exception occurred while fetching the NBI request, Reason: {}", + e.getMessage()); + } + + return deviceRPCRequest; + } + + /** + * Creates the device in the DM module if factory imported already + * + * @param deviceDetails + * @throws DeviceOperationException + */ + private void createDevice(DeviceDetails deviceDetails) throws DeviceOperationException { + deviceOperationInterface.updateDeviceDetails(deviceDetails); + } +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069NBIUtility.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069NBIUtility.java index 50c3ab2..3d0d42f 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069NBIUtility.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069NBIUtility.java @@ -1,78 +1,80 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.util; - -import java.util.Date; - -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; - -public class TR069NBIUtility { - - private TR069NBIUtility() { - super(); - } - - /** - * A utility method to convert the DTO to Domain object - * - * @param tr069DeviceDetails - * @return - */ - - public static TR069DeviceEntity convertToEntity(TR069DeviceDetails tr069DeviceDetails) { - TR069DeviceEntity tr069DeviceEntity = new TR069DeviceEntity(); - tr069DeviceEntity.setDeviceId(tr069DeviceDetails.getDeviceId()); - tr069DeviceEntity.setUserName(tr069DeviceDetails.getUsername()); - tr069DeviceEntity.setPassword(tr069DeviceDetails.getPassword()); - tr069DeviceEntity.setLastUpdatedTime(new Date()); - - if (tr069DeviceDetails.getConnectionRequestURL() != null) { - tr069DeviceEntity.setConnectionReqURL(tr069DeviceDetails.getConnectionRequestURL()); - } - if (tr069DeviceDetails.getSoftwareVersion() != null) { - tr069DeviceEntity.setSwVersion(tr069DeviceDetails.getSoftwareVersion()); - } - if (tr069DeviceDetails.getHardwareVersion() != null) { - tr069DeviceEntity.setHwVersion(tr069DeviceDetails.getHardwareVersion()); - } - - return tr069DeviceEntity; - } - - /** - * A utility method to convert the Domain object to DTO - * - * @param entity - * @return - */ - public static TR069DeviceDetails convertToDTO(TR069DeviceEntity entity) { - TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); - - tr069DeviceDetails.setDeviceId(entity.getDeviceId()); - tr069DeviceDetails.setUsername(entity.getUserName()); - tr069DeviceDetails.setPassword(entity.getPassword()); - tr069DeviceDetails.setSoftwareVersion(entity.getSwVersion()); - tr069DeviceDetails.setHardwareVersion(entity.getHwVersion()); - tr069DeviceDetails.setConnectionRequestURL(entity.getConnectionReqURL()); - - return tr069DeviceDetails; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.util; + +import java.util.Date; + +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity; + +public class TR069NBIUtility { + + private TR069NBIUtility() { + super(); + } + + /** + * A utility method to convert the DTO to Domain object + * + * @param tr069DeviceDetails + * @return + */ + + public static TR069DeviceEntity convertToEntity(TR069DeviceDetails tr069DeviceDetails) { + TR069DeviceEntity tr069DeviceEntity = new TR069DeviceEntity(); + tr069DeviceEntity.setDeviceId(tr069DeviceDetails.getDeviceId()); + tr069DeviceEntity.setUserName(tr069DeviceDetails.getUsername()); + tr069DeviceEntity.setPassword(tr069DeviceDetails.getPassword()); + tr069DeviceEntity.setLastUpdatedTime(new Date()); + tr069DeviceEntity.setConnStatus(true); + tr069DeviceEntity.setErrorMsg(null); + + if (tr069DeviceDetails.getConnectionRequestURL() != null) { + tr069DeviceEntity.setConnectionReqURL(tr069DeviceDetails.getConnectionRequestURL()); + } + if (tr069DeviceDetails.getSoftwareVersion() != null) { + tr069DeviceEntity.setSwVersion(tr069DeviceDetails.getSoftwareVersion()); + } + if (tr069DeviceDetails.getHardwareVersion() != null) { + tr069DeviceEntity.setHwVersion(tr069DeviceDetails.getHardwareVersion()); + } + + return tr069DeviceEntity; + } + + /** + * A utility method to convert the Domain object to DTO + * + * @param entity + * @return + */ + public static TR069DeviceDetails convertToDTO(TR069DeviceEntity entity) { + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + + tr069DeviceDetails.setDeviceId(entity.getDeviceId()); + tr069DeviceDetails.setUsername(entity.getUserName()); + tr069DeviceDetails.setPassword(entity.getPassword()); + tr069DeviceDetails.setSoftwareVersion(entity.getSwVersion()); + tr069DeviceDetails.setHardwareVersion(entity.getHwVersion()); + tr069DeviceDetails.setConnectionRequestURL(entity.getConnectionReqURL()); + + return tr069DeviceDetails; + } + +} diff --git a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069RequestProcessorUtility.java b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069RequestProcessorUtility.java index 1ce4a44..5268908 100644 --- a/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069RequestProcessorUtility.java +++ b/acs/requestprocessor/src/main/java/org/commscope/tr069adapter/acs/requestprocessor/util/TR069RequestProcessorUtility.java @@ -1,352 +1,352 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.acs.requestprocessor.util; - -import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.OperationCode; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.OperationOptions; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; -import org.commscope.tr069adapter.acs.common.utils.ErrorCode; -import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; - -public class TR069RequestProcessorUtility { - - protected static final int BLOCK_SIZE = 3999; - protected static final int MAX_SIZE = 11998; - public static final int DEVICE_REACHABLE_STATUS_CODE = 100; - public static final String ADMIN_STATE = "FAPControl.LTE.AdminState"; - public static final String ADMIN_STATUS = "FAPControl.LTE.AdminStatus"; - - - private TR069RequestProcessorUtility() { - super(); - } - - /** - * Converts entity object to DTO - * - * @param entityList - * @return - */ - public static DeviceRPCRequest convertToDTO(List entityList) { - DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); - OperationDetails operationDetails = new TR069OperationDetails(); - - boolean isCustomOperation = true; - OperationCode opCode = null; - - TR069DeviceRPCRequestEntity entity = entityList.get(0); - if (CustomOperationCode.getByOperationCode(entity.getOpCode()) != null) { - opCode = CustomOperationCode.getByOperationCode(entity.getOpCode()); - } else { - opCode = TR069OperationCode.getByOperationCode(entity.getOpCode()); - isCustomOperation = false; - } - - operationDetails.setOpCode(opCode); - dtoFromEntityJson(operationDetails, entityList, isCustomOperation); - deviceRPCRequest.setOpDetails(operationDetails); - - OperationOptions opOptions = new OperationOptions(); - opOptions.setExecutionTimeout(entity.getRequestTimeOut()); - deviceRPCRequest.setOptions(opOptions); - - TR069DeviceDetails deviceDetails = new TR069DeviceDetails(); - deviceDetails.setDeviceId(entity.getDeviceId()); - - deviceRPCRequest.setDeviceDetails(deviceDetails); - deviceRPCRequest.setOperationId(entity.getOperationId()); - return deviceRPCRequest; - } - - /** - * Converts DTO to entity object - * - * @param deviceRPCRequest - * @return - * @throws TR069EventProcessingException - */ - public static List convertToEntity(DeviceRPCRequest deviceRPCRequest) - throws TR069EventProcessingException { - - if (deviceRPCRequest.getOpDetails() == null - || deviceRPCRequest.getOpDetails().getOpCode() == null) { - throw new TR069EventProcessingException(ErrorCode.MISSING_OPERATION_DETAILS); - } - - Integer opCode = null; - boolean isCustomOperation = true; - OperationCode operationCode = deviceRPCRequest.getOpDetails().getOpCode(); - if (CustomOperationCode.getByOperationCode(operationCode.getOperationCode()) != null) { - CustomOperationCode customOperationCode = - CustomOperationCode.getByOperationCode(operationCode.getOperationCode()); - opCode = customOperationCode.getOperationCode(); - } else { - TR069OperationCode tr069OperationCode = - (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode(); - opCode = tr069OperationCode.getOperationCode(); - isCustomOperation = false; - } - - String paramListJSON = paramListToJson(deviceRPCRequest, isCustomOperation); - List tr069DeviceRPCRequestEntities = - getTR069DeviceRPCRequestEntities(paramListJSON); - - for (TR069DeviceRPCRequestEntity entity : tr069DeviceRPCRequestEntities) { - entity.setOpCode(opCode); - entity.setCreateTime(new Date()); - entity.setDeviceId(deviceRPCRequest.getDeviceDetails().getDeviceId()); - entity.setOperationId(deviceRPCRequest.getOperationId()); - entity.setIsProcessed(0); - if (deviceRPCRequest.getOptions() != null - && deviceRPCRequest.getOptions().getExecutionTimeout() != 0L) { - entity.setRequestTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout()); - } else { - entity.setRequestTimeOut(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS); - OperationOptions options = new OperationOptions(); - options.setExecutionTimeout(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS); - deviceRPCRequest.setOptions(options); - } - } - - return tr069DeviceRPCRequestEntities; - } - - /** - * @param entity - * @param dto - * @param isCustomOperation - */ - private static String paramListToJson(DeviceRPCRequest dto, boolean isCustomOperation) { - String attrJsonString = null; - if (isCustomOperation) { - TR069OperationDetails operationDetails = (TR069OperationDetails) dto.getOpDetails(); - StringBuilder buffer = new StringBuilder(); - - List deletParamList = operationDetails.getDeleteParamList(); - List modifyParamList = operationDetails.getModifyParamList(); - List setParamList = operationDetails.getSetParamList(); - - if (deletParamList != null && !deletParamList.isEmpty()) { - convertBooleanValues(deletParamList); - buffer.append(toJson(deletParamList)); - } else { - buffer.append(toJson(new ArrayList<>())); - } - - if (modifyParamList != null && !modifyParamList.isEmpty()) { - convertBooleanValues(modifyParamList); - buffer.append(toJson(modifyParamList)); - } else { - buffer.append(toJson(new ArrayList<>())); - } - - if (setParamList != null && !setParamList.isEmpty()) { - convertBooleanValues(setParamList); - buffer.append(toJson(setParamList)); - } else { - buffer.append(toJson(new ArrayList<>())); - } - - attrJsonString = buffer.toString(); - } else { - List parameterDTOs = dto.getOpDetails().getParmeters(); - attrJsonString = toJson(parameterDTOs); - } - - return attrJsonString; - } - - /** - * @param paramListJSON - * @return - */ - private static List getTR069DeviceRPCRequestEntities( - String paramListJSON) { - List tr069DeviceRPCRequestEntities = new ArrayList<>(); - - if (paramListJSON.length() < MAX_SIZE) { - TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity(); - entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, 0)); - entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, 1)); - entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, 2)); - - tr069DeviceRPCRequestEntities.add(entity); - } else { - int noOfEntities = 0; - while (true) { - int i = 3 * noOfEntities; - TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity(); - entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, i)); - entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, ++i)); - entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, ++i)); - - if (entity.getAttributeJson1() != null) { - tr069DeviceRPCRequestEntities.add(entity); - } - - if (entity.getAttributeJson1() == null || entity.getAttributeJson2() == null - || entity.getAttributeJson3() == null) { - break; - } - - noOfEntities++; - } - - } - return tr069DeviceRPCRequestEntities; - } - - /** - * @param eventData - * @param blockNum - * @return - */ - private static String getAttriuteJsonData(String eventData, int blockNum) { - int eventDataSize = eventData.length(); - int startIndex = blockNum * BLOCK_SIZE; - if (startIndex > eventDataSize) { - return null; - } - int endIndex = startIndex + BLOCK_SIZE; - endIndex = endIndex < eventDataSize ? endIndex : eventDataSize; - return eventData.substring(startIndex, endIndex); - } - - /** - * @param opDetails - * @param entity - * @param isCustomOperation - */ - private static void dtoFromEntityJson(OperationDetails opDetails, - List entityList, boolean isCustomOperation) { - StringBuilder sb = new StringBuilder(); - for (TR069DeviceRPCRequestEntity entity : entityList) { - append(sb, entity.getAttributeJson1()); - append(sb, entity.getAttributeJson2()); - append(sb, entity.getAttributeJson3()); - } - - if (isCustomOperation) { - String[] splitStringArray = sb.toString().split("]\\["); - List deleteParamList = new ArrayList<>(); - List modifyParamList = new ArrayList<>(); - List setParamList = new ArrayList<>(); - for (int i = 0; i < splitStringArray.length; i++) { - String data = splitStringArray[i]; - if (i == 0) { - data = data + "]"; - deleteParamList.addAll(fromJson(data)); - } else if ((i + 1) == splitStringArray.length) { - data = "[" + data; - setParamList.addAll(fromJson(data)); - } else { - data = "[" + data + "]"; - modifyParamList.addAll(fromJson(data)); - } - } - TR069OperationDetails tr069OperationDetails = (TR069OperationDetails) opDetails; - tr069OperationDetails.setDeleteParamList(deleteParamList); - tr069OperationDetails.setModifyParamList(modifyParamList); - tr069OperationDetails.setSetParamList(setParamList); - } else { - if (TR069OperationCode.SET_PARAMETER_ATTRIBUTES.equals(opDetails.getOpCode())) { - List list = fromJsonToParameterAttribute(sb.toString()); - opDetails.setParmeters(list); - } else { - List list = fromJson(sb.toString()); - opDetails.setParmeters(list); - } - } - } - - /** - * @param sb - * @param temp - */ - private static void append(StringBuilder sb, String temp) { - if (temp != null && !temp.isEmpty()) { - sb.append(temp); - } - } - - /** - * @param jsonString - * @return - */ - private static List fromJson(String jsonString) { - Gson gson = new Gson(); - Type collectionType = new TypeToken>() {}.getType(); - return gson.fromJson(jsonString, collectionType); - } - - /** - * @param jsonString - * @return - */ - private static List fromJsonToParameterAttribute(String jsonString) { - Gson gson = new Gson(); - Type collectionType = new TypeToken>() {}.getType(); - return gson.fromJson(jsonString, collectionType); - } - - /** - * @param entity - * @return - */ - private static String toJson(T entity) { - Gson gson = new Gson(); - return gson.toJson(entity); - } - - /** - * @param parameterDTOs - */ - private static void convertBooleanValues(List parameterDTOs) { - for (ParameterDTO param : parameterDTOs) { - if (param.getDataType() != null && param.getDataType().equalsIgnoreCase("boolean")) { - if (param.getParamValue() != null && (param.getParamValue().equalsIgnoreCase("true") - || param.getParamValue().equalsIgnoreCase("1"))) { - param.setParamValue("1"); - } else { - param.setParamValue("0"); - } - } - } - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.acs.requestprocessor.util; + +import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.OperationCode; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.OperationOptions; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException; +import org.commscope.tr069adapter.acs.common.utils.ErrorCode; +import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity; + +public class TR069RequestProcessorUtility { + + protected static final int BLOCK_SIZE = 3999; + protected static final int MAX_SIZE = 11998; + public static final int DEVICE_REACHABLE_STATUS_CODE = 100; + public static final String ADMIN_STATE = "FAPControl.LTE.AdminState"; + public static final String ADMIN_STATUS = "FAPControl.LTE.AdminStatus"; + + + private TR069RequestProcessorUtility() { + super(); + } + + /** + * Converts entity object to DTO + * + * @param entityList + * @return + */ + public static DeviceRPCRequest convertToDTO(List entityList) { + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + OperationDetails operationDetails = new TR069OperationDetails(); + + boolean isCustomOperation = true; + OperationCode opCode = null; + + TR069DeviceRPCRequestEntity entity = entityList.get(0); + if (CustomOperationCode.getByOperationCode(entity.getOpCode()) != null) { + opCode = CustomOperationCode.getByOperationCode(entity.getOpCode()); + } else { + opCode = TR069OperationCode.getByOperationCode(entity.getOpCode()); + isCustomOperation = false; + } + + operationDetails.setOpCode(opCode); + dtoFromEntityJson(operationDetails, entityList, isCustomOperation); + deviceRPCRequest.setOpDetails(operationDetails); + + OperationOptions opOptions = new OperationOptions(); + opOptions.setExecutionTimeout(entity.getRequestTimeOut()); + deviceRPCRequest.setOptions(opOptions); + + TR069DeviceDetails deviceDetails = new TR069DeviceDetails(); + deviceDetails.setDeviceId(entity.getDeviceId()); + + deviceRPCRequest.setDeviceDetails(deviceDetails); + deviceRPCRequest.setOperationId(entity.getOperationId()); + return deviceRPCRequest; + } + + /** + * Converts DTO to entity object + * + * @param deviceRPCRequest + * @return + * @throws TR069EventProcessingException + */ + public static List convertToEntity(DeviceRPCRequest deviceRPCRequest) + throws TR069EventProcessingException { + + if (deviceRPCRequest.getOpDetails() == null + || deviceRPCRequest.getOpDetails().getOpCode() == null) { + throw new TR069EventProcessingException(ErrorCode.MISSING_OPERATION_DETAILS); + } + + Integer opCode = null; + boolean isCustomOperation = true; + OperationCode operationCode = deviceRPCRequest.getOpDetails().getOpCode(); + if (CustomOperationCode.getByOperationCode(operationCode.getOperationCode()) != null) { + CustomOperationCode customOperationCode = + CustomOperationCode.getByOperationCode(operationCode.getOperationCode()); + opCode = customOperationCode.getOperationCode(); + } else { + TR069OperationCode tr069OperationCode = + (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode(); + opCode = tr069OperationCode.getOperationCode(); + isCustomOperation = false; + } + + String paramListJSON = paramListToJson(deviceRPCRequest, isCustomOperation); + List tr069DeviceRPCRequestEntities = + getTR069DeviceRPCRequestEntities(paramListJSON); + + for (TR069DeviceRPCRequestEntity entity : tr069DeviceRPCRequestEntities) { + entity.setOpCode(opCode); + entity.setCreateTime(new Date()); + entity.setDeviceId(deviceRPCRequest.getDeviceDetails().getDeviceId()); + entity.setOperationId(deviceRPCRequest.getOperationId()); + entity.setIsProcessed(0); + if (deviceRPCRequest.getOptions() != null + && deviceRPCRequest.getOptions().getExecutionTimeout() != 0L) { + entity.setRequestTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout()); + } else { + entity.setRequestTimeOut(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS); + deviceRPCRequest.setOptions(options); + } + } + + return tr069DeviceRPCRequestEntities; + } + + /** + * @param entity + * @param dto + * @param isCustomOperation + */ + private static String paramListToJson(DeviceRPCRequest dto, boolean isCustomOperation) { + String attrJsonString = null; + if (isCustomOperation) { + TR069OperationDetails operationDetails = (TR069OperationDetails) dto.getOpDetails(); + StringBuilder buffer = new StringBuilder(); + + List deletParamList = operationDetails.getDeleteParamList(); + List modifyParamList = operationDetails.getModifyParamList(); + List setParamList = operationDetails.getSetParamList(); + + if (deletParamList != null && !deletParamList.isEmpty()) { + convertBooleanValues(deletParamList); + buffer.append(toJson(deletParamList)); + } else { + buffer.append(toJson(new ArrayList<>())); + } + + if (modifyParamList != null && !modifyParamList.isEmpty()) { + convertBooleanValues(modifyParamList); + buffer.append(toJson(modifyParamList)); + } else { + buffer.append(toJson(new ArrayList<>())); + } + + if (setParamList != null && !setParamList.isEmpty()) { + convertBooleanValues(setParamList); + buffer.append(toJson(setParamList)); + } else { + buffer.append(toJson(new ArrayList<>())); + } + + attrJsonString = buffer.toString(); + } else { + List parameterDTOs = dto.getOpDetails().getParmeters(); + attrJsonString = toJson(parameterDTOs); + } + + return attrJsonString; + } + + /** + * @param paramListJSON + * @return + */ + private static List getTR069DeviceRPCRequestEntities( + String paramListJSON) { + List tr069DeviceRPCRequestEntities = new ArrayList<>(); + + if (paramListJSON.length() < MAX_SIZE) { + TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity(); + entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, 0)); + entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, 1)); + entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, 2)); + + tr069DeviceRPCRequestEntities.add(entity); + } else { + int noOfEntities = 0; + while (true) { + int i = 3 * noOfEntities; + TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity(); + entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, i)); + entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, ++i)); + entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, ++i)); + + if (entity.getAttributeJson1() != null) { + tr069DeviceRPCRequestEntities.add(entity); + } + + if (entity.getAttributeJson1() == null || entity.getAttributeJson2() == null + || entity.getAttributeJson3() == null) { + break; + } + + noOfEntities++; + } + + } + return tr069DeviceRPCRequestEntities; + } + + /** + * @param eventData + * @param blockNum + * @return + */ + private static String getAttriuteJsonData(String eventData, int blockNum) { + int eventDataSize = eventData.length(); + int startIndex = blockNum * BLOCK_SIZE; + if (startIndex > eventDataSize) { + return null; + } + int endIndex = startIndex + BLOCK_SIZE; + endIndex = endIndex < eventDataSize ? endIndex : eventDataSize; + return eventData.substring(startIndex, endIndex); + } + + /** + * @param opDetails + * @param entity + * @param isCustomOperation + */ + private static void dtoFromEntityJson(OperationDetails opDetails, + List entityList, boolean isCustomOperation) { + StringBuilder sb = new StringBuilder(); + for (TR069DeviceRPCRequestEntity entity : entityList) { + append(sb, entity.getAttributeJson1()); + append(sb, entity.getAttributeJson2()); + append(sb, entity.getAttributeJson3()); + } + + if (isCustomOperation) { + String[] splitStringArray = sb.toString().split("]\\["); + List deleteParamList = new ArrayList<>(); + List modifyParamList = new ArrayList<>(); + List setParamList = new ArrayList<>(); + for (int i = 0; i < splitStringArray.length; i++) { + String data = splitStringArray[i]; + if (i == 0) { + data = data + "]"; + deleteParamList.addAll(fromJson(data)); + } else if ((i + 1) == splitStringArray.length) { + data = "[" + data; + setParamList.addAll(fromJson(data)); + } else { + data = "[" + data + "]"; + modifyParamList.addAll(fromJson(data)); + } + } + TR069OperationDetails tr069OperationDetails = (TR069OperationDetails) opDetails; + tr069OperationDetails.setDeleteParamList(deleteParamList); + tr069OperationDetails.setModifyParamList(modifyParamList); + tr069OperationDetails.setSetParamList(setParamList); + } else { + if (TR069OperationCode.SET_PARAMETER_ATTRIBUTES.equals(opDetails.getOpCode())) { + List list = fromJsonToParameterAttribute(sb.toString()); + opDetails.setParmeters(list); + } else { + List list = fromJson(sb.toString()); + opDetails.setParmeters(list); + } + } + } + + /** + * @param sb + * @param temp + */ + private static void append(StringBuilder sb, String temp) { + if (temp != null && !temp.isEmpty()) { + sb.append(temp); + } + } + + /** + * @param jsonString + * @return + */ + private static List fromJson(String jsonString) { + Gson gson = new Gson(); + Type collectionType = new TypeToken>() {}.getType(); + return gson.fromJson(jsonString, collectionType); + } + + /** + * @param jsonString + * @return + */ + private static List fromJsonToParameterAttribute(String jsonString) { + Gson gson = new Gson(); + Type collectionType = new TypeToken>() {}.getType(); + return gson.fromJson(jsonString, collectionType); + } + + /** + * @param entity + * @return + */ + private static String toJson(T entity) { + Gson gson = new Gson(); + return gson.toJson(entity); + } + + /** + * @param parameterDTOs + */ + private static void convertBooleanValues(List parameterDTOs) { + for (ParameterDTO param : parameterDTOs) { + if (param.getDataType() != null && param.getDataType().equalsIgnoreCase("boolean")) { + if (param.getParamValue() != null && (param.getParamValue().equalsIgnoreCase("true") + || param.getParamValue().equalsIgnoreCase("1"))) { + param.setParamValue("1"); + } else { + param.setParamValue("0"); + } + } + } + } + +} diff --git a/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersion.java b/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersion.java index df4d068..b7b057b 100644 --- a/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersion.java +++ b/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersion.java @@ -1,171 +1,209 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.common.deviceversion; - -import java.io.Serializable; -import java.util.Comparator; - -public class DeviceVersion implements Serializable, Comparable { - - /** - * - */ - private static final long serialVersionUID = -7251276716604249440L; - private int svMajorVersion = 0; - private int svMinorVersion = 0; - private int svPatchVersion = 0; - private String swVersion; - private boolean isGenericVersion = false; - private boolean isHwRegex = false; - private boolean isSwRegex = false; - - public DeviceVersion(String swVersion, String hwVersion) { - super(); - setSwVersion(swVersion); - this.hwVersion = hwVersion; - } - - public DeviceVersion(String swVersion, String hwVersion, boolean isSwRegex, - boolean isHwRegex) { - super(); - this.hwVersion = hwVersion; - this.swVersion = swVersion; - this.isHwRegex = isHwRegex; - this.isSwRegex = isSwRegex; - if (!isSwRegex) { - setSwVersion(swVersion); - } - } - - public String getSwVersion() { - if (!isSwRegex) - return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion; - else - return this.swVersion; - } - - public boolean isHwRegex() { - return isHwRegex; - } - - public boolean isSwRegex() { - return isSwRegex; - } - - private void setSwVersion(String swVersion) { - if (swVersion.indexOf(".") > 0) { - String[] verArray = swVersion.split("\\."); - - for (int i = 0; i < verArray.length; i++) { - - if (verArray[i].equals("*")) { - verArray[i] = "0"; - } - } - try { - svMajorVersion = Integer.parseInt(verArray[0]); - svMinorVersion = Integer.parseInt(verArray[1]); - svPatchVersion = Integer.parseInt(verArray[2]); - } catch (Exception e) { - // TODO: handle exception - } - - } else if (swVersion.indexOf("x") > 0) { - swVersion = "*"; - } else if (swVersion.equals("*")) { - isGenericVersion = true; - } - - } - - public String getHwVersion() { - return hwVersion; - } - - private String hwVersion; - - public int getSvMajorVersion() { - return svMajorVersion; - } - - public int getSvMinorVersion() { - return svMinorVersion; - } - - public int getSvPatchVersion() { - return svPatchVersion; - } - - private long deviceTypeId; - - public long getDeviceTypeId() { - return deviceTypeId; - } - - public boolean isGenericVersion() { - return isGenericVersion; - } - - public static Comparator softwareComparator = new Comparator() { - @Override - public int compare(DeviceVersion d1, DeviceVersion d2) { - if (d1.getSvMajorVersion() != d2.getSvMajorVersion()) { - return (d1.getSvMajorVersion() - d2.getSvMajorVersion()); - } else if (d1.getSvMinorVersion() != d2.getSvMinorVersion()) { - return d1.getSvMinorVersion() - d2.getSvMinorVersion(); - } else - return d1.getSvPatchVersion() - d2.getSvPatchVersion(); - } - }; - - @Override - public int compareTo(DeviceVersion o) { - if (deviceTypeId != o.deviceTypeId) - return -1; - - if (isSwRegex) { - return this.hashCode() - o.hashCode(); - } else { - if (svMajorVersion != o.svMajorVersion) { - return (svMajorVersion - o.svMajorVersion); - } else if (svMinorVersion != o.svMinorVersion) { - return svMinorVersion - o.svMinorVersion; - } else if (svPatchVersion != o.svPatchVersion) { - return svPatchVersion - o.svPatchVersion; - } else { - return hwVersion.compareToIgnoreCase(o.hwVersion); - } - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (deviceTypeId ^ (deviceTypeId >>> 32)); - result = prime * result + ((hwVersion == null) ? 0 : hwVersion.hashCode()); - result = prime * result + (isGenericVersion ? 1231 : 1237); - result = prime * result + (isHwRegex ? 1231 : 1237); - result = prime * result + (isSwRegex ? 1241 : 1247); - result = prime * result + svMajorVersion; - result = prime * result + svMinorVersion; - result = prime * result + svPatchVersion; - return result; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.common.deviceversion; + +import java.io.Serializable; +import java.util.Comparator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DeviceVersion implements Serializable, Comparable { + + /** + * + */ + private static final Logger LOG = LoggerFactory.getLogger(DeviceVersion.class); + private static final long serialVersionUID = -7251276716604249440L; + private int svMajorVersion = 0; + private int svMinorVersion = 0; + private int svPatchVersion = 0; + private String swVersion; + private boolean isGenericVersion = false; + private boolean isHwRegex = false; + private boolean isSwRegex = false; + + public DeviceVersion(String swVersion, String hwVersion) { + super(); + setSwVersion(swVersion); + this.hwVersion = hwVersion; + } + + public DeviceVersion(String swVersion, String hwVersion, boolean isSwRegex, boolean isHwRegex) { + super(); + this.hwVersion = hwVersion; + this.swVersion = swVersion; + this.isHwRegex = isHwRegex; + this.isSwRegex = isSwRegex; + if (!isSwRegex) { + setSwVersion(swVersion); + } + } + + public String getSwVersion() { + if (!isSwRegex) + return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion; + else + return this.swVersion; + } + + public boolean isHwRegex() { + return isHwRegex; + } + + public boolean isSwRegex() { + return isSwRegex; + } + + private void setSwVersion(String swVersion) { + if (swVersion.indexOf(".") > 0) { + String[] verArray = swVersion.split("\\."); + + for (int i = 0; i < verArray.length; i++) { + + if (verArray[i].equals("*")) { + verArray[i] = "0"; + } + } + try { + svMajorVersion = Integer.parseInt(verArray[0]); + svMinorVersion = Integer.parseInt(verArray[1]); + svPatchVersion = Integer.parseInt(verArray[2]); + } catch (Exception e) { + LOG.error("Software Version setting has failed. {}", e.toString()); + } + + } else if (swVersion.indexOf("x") > 0) { + swVersion = "*"; + } else if (swVersion.equals("*")) { + isGenericVersion = true; + } + + } + + public String getHwVersion() { + return hwVersion; + } + + private String hwVersion; + + public int getSvMajorVersion() { + return svMajorVersion; + } + + public int getSvMinorVersion() { + return svMinorVersion; + } + + public int getSvPatchVersion() { + return svPatchVersion; + } + + private long deviceTypeId; + + public long getDeviceTypeId() { + return deviceTypeId; + } + + public boolean isGenericVersion() { + return isGenericVersion; + } + + public static final Comparator softwareComparator = + new Comparator() { + @Override + public int compare(DeviceVersion d1, DeviceVersion d2) { + if (d1.getSvMajorVersion() != d2.getSvMajorVersion()) { + return (d1.getSvMajorVersion() - d2.getSvMajorVersion()); + } else if (d1.getSvMinorVersion() != d2.getSvMinorVersion()) { + return d1.getSvMinorVersion() - d2.getSvMinorVersion(); + } else { + return d1.getSvPatchVersion() - d2.getSvPatchVersion(); + } + } + }; + + @Override + public int compareTo(DeviceVersion o) { + if (deviceTypeId != o.deviceTypeId) + return -1; + + if (isSwRegex) { + return this.hashCode() - o.hashCode(); + } else { + if (svMajorVersion != o.svMajorVersion) { + return (svMajorVersion - o.svMajorVersion); + } else if (svMinorVersion != o.svMinorVersion) { + return svMinorVersion - o.svMinorVersion; + } else if (svPatchVersion != o.svPatchVersion) { + return svPatchVersion - o.svPatchVersion; + } else { + return hwVersion.compareToIgnoreCase(o.hwVersion); + } + } + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + DeviceVersion other = (DeviceVersion) obj; + if (deviceTypeId != other.deviceTypeId) + return false; + if (hwVersion == null && other.hwVersion != null) { + return false; + } + if (isGenericVersion != other.isGenericVersion) + return false; + if (isHwRegex != other.isHwRegex) + return false; + if (isSwRegex != other.isSwRegex) + return false; + if (svMajorVersion != other.svMajorVersion) + return false; + if (svMinorVersion != other.svMinorVersion) + return false; + if (svPatchVersion != other.svPatchVersion) + return false; + if (swVersion == null) { + if (other.swVersion != null) + return false; + } + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (deviceTypeId ^ (deviceTypeId >>> 32)); + result = prime * result + ((hwVersion == null) ? 0 : hwVersion.hashCode()); + result = prime * result + (isGenericVersion ? 1231 : 1237); + result = prime * result + (isHwRegex ? 1231 : 1237); + result = prime * result + (isSwRegex ? 1241 : 1247); + result = prime * result + svMajorVersion; + result = prime * result + svMinorVersion; + result = prime * result + svPatchVersion; + return result; + } +} diff --git a/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersionManagerImpl.java b/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersionManagerImpl.java index 4b76ae4..0c712c5 100644 --- a/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersionManagerImpl.java +++ b/common/src/main/java/org/commscope/tr069adapter/common/deviceversion/DeviceVersionManagerImpl.java @@ -1,192 +1,184 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.common.deviceversion; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.TreeMap; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import org.springframework.stereotype.Component; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Component -public class DeviceVersionManagerImpl implements DeviceVersionManager { - - TreeMap deviceVersionMap = new TreeMap<>(); - TreeMap profileDefinitionMap = new TreeMap<>(); - - @PostConstruct - public void loadProfileConfiguration() throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - String contents; - try ( - InputStream inputStream = - getClass().getResourceAsStream("/profile-definition-mapping.json"); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { - contents = reader.lines().collect(Collectors.joining(System.lineSeparator())); - } - - ProfileDefinitions versions; - try { - versions = objectMapper.readValue(contents, ProfileDefinitions.class); - - List definitionList = versions.getProfileDefinition(); - for (ProfileDefinition definition : definitionList) { - DeviceVersion versionDTO = - new DeviceVersion(definition.getSoftwareVersion(), definition.getHardwareVersion()); - String profileId = definition.getProfileId(); - deviceVersionMap.put(versionDTO, profileId); - profileDefinitionMap.put(profileId, definition); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static void main(String[] args) { - System.out.println("started loading the json file"); - DeviceVersionManagerImpl impl = new DeviceVersionManagerImpl(); - try { - impl.loadProfileConfiguration(); - System.out.println(impl.getAssociatedProfileId("4.3.0.0", "*")); - } catch (Exception e) { - System.out.println("Exception While loading the file"); - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println("File loading is completed"); - } - - @Override - public String getNetconfYangSchemaPath(String swVersion, String hwVersion) { - String profileId = getAssociatedProfileId(swVersion, hwVersion); - ProfileDefinition profileDefinition = profileDefinitionMap.get(profileId); - return profileDefinition.getNetConfSchemaPath(); - } - - @Override - public String getBaseNetconfYangSchemaPath() { - return profileDefinitionMap.firstEntry().getValue().getNetConfSchemaPath(); - } - - @Override - public ProfileDefinition getProfileDefinition(String swVersion, String hwVersion) { - String profileId = getAssociatedProfileId(swVersion, hwVersion); - return profileDefinitionMap.get(profileId); - } - - @Override - public List getSupportedProfileDefinitions() { - List proDeflist = new ArrayList<>(); - for (Iterator iterator = profileDefinitionMap.keySet().iterator(); iterator - .hasNext();) { - String key = iterator.next(); - proDeflist.add(profileDefinitionMap.get(key)); - } - return proDeflist; - } - - @Override - public String getAssociatedProfileId(String swVersion, String hwVersion) { - String profileId = null; - if (null != swVersion) // TODO: Consider hardware version also. - profileId = getProfileName(deviceVersionMap, swVersion, hwVersion); - - if (profileId == null) { - profileId = profileDefinitionMap.firstEntry().getValue().getProfileId(); - } - - return profileId; - } - - private String getProfileName(TreeMap deviceVersionMap, String swVersion, - String hwVersion) { - DeviceVersion deviceVersion = new DeviceVersion(swVersion, hwVersion, false, false); - ArrayList mSoftwareList = new ArrayList<>(); - - for (Iterator> iterator = - deviceVersionMap.entrySet().iterator(); iterator.hasNext();) { - Entry entry = iterator.next(); - DeviceVersion profileVersion = entry.getKey(); - if (profileVersion.isHwRegex() || profileVersion.isSwRegex()) { - if (profileVersion.isSwRegex()) { - if (deviceVersion.getSwVersion().equalsIgnoreCase(profileVersion.getSwVersion()) - || deviceVersion.getSwVersion().matches(profileVersion.getSwVersion())) { - if (profileVersion.isHwRegex()) { - if (deviceVersion.getHwVersion() != null) { - - if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) { - return entry.getValue(); - } - } else { - - } - } else { - // Check Strict match of Hardware - if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) { - return entry.getValue(); - } - } - } - } else if (profileVersion.isHwRegex()) { - if (deviceVersion.getHwVersion() != null) { - if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) { - // Add all software version which matching - if (profileVersion.getSwVersion() - .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) { - mSoftwareList.add(profileVersion); - } - } - } - } - } else { - // Check Strict match of Hardware - if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) - || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) { - if (profileVersion.getSwVersion() - .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) { - mSoftwareList.add(profileVersion); - } - } - } - } - - if (mSoftwareList.size() > 0) { - // return the least matched software version profile - Collections.sort(mSoftwareList, DeviceVersion.softwareComparator); - return deviceVersionMap.get(mSoftwareList.get(mSoftwareList.size() - 1)); - } - - return null; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.common.deviceversion; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class DeviceVersionManagerImpl implements DeviceVersionManager { + private static final Logger LOG = LoggerFactory.getLogger(DeviceVersionManagerImpl.class); + + TreeMap deviceVersionMap = new TreeMap<>(); + TreeMap profileDefinitionMap = new TreeMap<>(); + + @PostConstruct + public void loadProfileConfiguration() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + String contents; + try ( + InputStream inputStream = + getClass().getResourceAsStream("/profile-definition-mapping.json"); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + contents = reader.lines().collect(Collectors.joining(System.lineSeparator())); + } + + ProfileDefinitions versions; + try { + versions = objectMapper.readValue(contents, ProfileDefinitions.class); + + List definitionList = versions.getProfileDefinition(); + for (ProfileDefinition definition : definitionList) { + DeviceVersion versionDTO = + new DeviceVersion(definition.getSoftwareVersion(), definition.getHardwareVersion()); + String profileId = definition.getProfileId(); + deviceVersionMap.put(versionDTO, profileId); + profileDefinitionMap.put(profileId, definition); + } + } catch (IOException e) { + LOG.info("context", e); + + } + } + + + + @Override + public String getNetconfYangSchemaPath(String swVersion, String hwVersion) { + String profileId = getAssociatedProfileId(swVersion, hwVersion); + ProfileDefinition profileDefinition = profileDefinitionMap.get(profileId); + return profileDefinition.getNetConfSchemaPath(); + } + + @Override + public String getBaseNetconfYangSchemaPath() { + return profileDefinitionMap.firstEntry().getValue().getNetConfSchemaPath(); + } + + @Override + public ProfileDefinition getProfileDefinition(String swVersion, String hwVersion) { + String profileId = getAssociatedProfileId(swVersion, hwVersion); + return profileDefinitionMap.get(profileId); + } + + @Override + public List getSupportedProfileDefinitions() { + List proDeflist = new ArrayList<>(); + for (Iterator iterator = profileDefinitionMap.keySet().iterator(); iterator + .hasNext();) { + String key = iterator.next(); + proDeflist.add(profileDefinitionMap.get(key)); + } + return proDeflist; + } + + @Override + public String getAssociatedProfileId(String swVersion, String hwVersion) { + String profileId = null; + if (null != swVersion) // TODO: Consider hardware version also. + profileId = getProfileName(deviceVersionMap, swVersion, hwVersion); + + if (profileId == null) { + profileId = profileDefinitionMap.firstEntry().getValue().getProfileId(); + } + + return profileId; + } + + private String getProfileName(TreeMap deviceVersionMap, String swVersion, + String hwVersion) { + DeviceVersion deviceVersion = new DeviceVersion(swVersion, hwVersion, false, false); + ArrayList mSoftwareList = new ArrayList<>(); + + for (Iterator> iterator = + deviceVersionMap.entrySet().iterator(); iterator.hasNext();) { + Entry entry = iterator.next(); + DeviceVersion profileVersion = entry.getKey(); + if (profileVersion.isHwRegex() || profileVersion.isSwRegex()) { + if (profileVersion.isSwRegex()) { + if (deviceVersion.getSwVersion().equalsIgnoreCase(profileVersion.getSwVersion()) + || deviceVersion.getSwVersion().matches(profileVersion.getSwVersion())) { + if (profileVersion.isHwRegex()) { + if (deviceVersion.getHwVersion() != null) { + + if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) { + return entry.getValue(); + } + } + } else { + // Check Strict match of Hardware + if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) { + return entry.getValue(); + } + } + } + } else if (profileVersion.isHwRegex()) { + if (deviceVersion.getHwVersion() != null) { + if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) { + // Add all software version which matching + if (profileVersion.getSwVersion() + .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) { + mSoftwareList.add(profileVersion); + } + } + } + } + } else { + // Check Strict match of Hardware + if ("*".equalsIgnoreCase(profileVersion.getHwVersion()) + || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) { + if (profileVersion.getSwVersion() + .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) { + mSoftwareList.add(profileVersion); + } + } + } + } + + if (!mSoftwareList.isEmpty()) { + // return the least matched software version profile + Collections.sort(mSoftwareList, DeviceVersion.softwareComparator); + return deviceVersionMap.get(mSoftwareList.get(mSoftwareList.size() - 1)); + } + + return null; + } +} diff --git a/config-data/pom.xml b/config-data/pom.xml index 830ffa7..b5e618e 100644 --- a/config-data/pom.xml +++ b/config-data/pom.xml @@ -139,6 +139,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin diff --git a/config-data/src/main/java/org/commscope/tr069adapter/config/controllers/ConfugurationDataController.java b/config-data/src/main/java/org/commscope/tr069adapter/config/controllers/ConfugurationDataController.java index 44bd394..5a33363 100644 --- a/config-data/src/main/java/org/commscope/tr069adapter/config/controllers/ConfugurationDataController.java +++ b/config-data/src/main/java/org/commscope/tr069adapter/config/controllers/ConfugurationDataController.java @@ -1,98 +1,100 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config.controllers; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; -import org.commscope.tr069adapter.config.constants.ConfigurationServiceConstant; -import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException; -import org.commscope.tr069adapter.config.service.ConfigurationDataService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -@RestController -public class ConfugurationDataController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ConfigurationDataService configDataService; - - @GetMapping("/isActive") - public String getMessage() { - return "Application is running"; - } - - @PostMapping("/getConfig") - public ConfigurationData viewConfigurationData(@RequestParam String macId, - @RequestParam String swVersion, @RequestParam String hwVersion) - throws InvalidConfigurationServiceException { - logger.info("Processing request to get configuration data for device {}", macId); - Optional configData = configDataService.getConfigurationData(macId, swVersion, hwVersion); - if (configData.isPresent()) { - return configData.get(); - } - - logger.info("Configuration data doesn't exist for device {}", macId); - return null; - } - - @PostMapping("/importConfig") - public String uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) - throws InvalidConfigurationServiceException { - - if (null == files || files.length == 0) { - logger.info("No file given for import"); - return "No file given for import"; - } - - List fileList = Arrays.asList(files); - - MultipartFile file = fileList.get(0); - String fileName = StringUtils.cleanPath(file.getOriginalFilename()); - - logger.debug("Importing file {}", fileName); - if (!fileName.endsWith(ConfigurationServiceConstant.CONFIG_FILE_EXTENSION)) { - throw new InvalidConfigurationServiceException("Unsupported file format for file " + fileName - + ". Only XML file is supported. Ignoring file import for file " + fileName); - } - - try { - configDataService.saveConfigFileContents(file); - } catch (InvalidConfigurationServiceException ex) { - throw new InvalidConfigurationServiceException( - "Error occurred while import file " + fileName + ". Cause : " + ex.getMessage()); - } catch (Exception ex) { - throw new InvalidConfigurationServiceException( - "UNKNOWN error occurred while import file " + fileName + ". Cause : " + ex.getMessage()); - } - - return "File " + fileName + " imported successfully"; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config.controllers; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; +import org.commscope.tr069adapter.config.constants.ConfigurationServiceConstant; +import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException; +import org.commscope.tr069adapter.config.service.ConfigurationDataService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +public class ConfugurationDataController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + ConfigurationDataService configDataService; + + @GetMapping("/isActive") + public String getMessage() { + return "Application is running"; + } + + @PostMapping("/getConfig") + public ConfigurationData viewConfigurationData(@RequestParam String macId, + @RequestParam String swVersion, @RequestParam String hwVersion) + throws InvalidConfigurationServiceException { + macId = macId.replaceAll("[\n|\r|\t]", "_"); + logger.info("Processing request to get configuration data for device {}", macId); + Optional configData = + configDataService.getConfigurationData(macId, swVersion, hwVersion); + if (configData.isPresent()) { + return configData.get(); + } + logger.info("Configuration data doesn't exist for device {}", macId); + return null; + } + + @PostMapping("/importConfig") + public String uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) + throws InvalidConfigurationServiceException { + + if (null == files || files.length == 0) { + logger.info("No file given for import"); + return "No file given for import"; + } + + List fileList = Arrays.asList(files); + + MultipartFile file = fileList.get(0); + String fileName = StringUtils.cleanPath(file.getOriginalFilename()); + + logger.debug("Importing file {}", fileName); + if (!fileName.endsWith(ConfigurationServiceConstant.CONFIG_FILE_EXTENSION)) { + throw new InvalidConfigurationServiceException("Unsupported file format for file " + fileName + + ". Only XML file is supported. Ignoring file import for file " + fileName); + } + + try { + configDataService.saveConfigFileContents(file); + } catch (InvalidConfigurationServiceException ex) { + throw new InvalidConfigurationServiceException( + "Error occurred while import file " + fileName + ". Cause : " + ex.getMessage()); + } catch (Exception ex) { + throw new InvalidConfigurationServiceException( + "UNKNOWN error occurred while import file " + fileName + ". Cause : " + ex.getMessage()); + } + + return "File " + fileName + " imported successfully"; + } + +} diff --git a/config-data/src/main/java/org/commscope/tr069adapter/config/model/ConfigFileContent.java b/config-data/src/main/java/org/commscope/tr069adapter/config/model/ConfigFileContent.java index 1b6482c..b00622b 100644 --- a/config-data/src/main/java/org/commscope/tr069adapter/config/model/ConfigFileContent.java +++ b/config-data/src/main/java/org/commscope/tr069adapter/config/model/ConfigFileContent.java @@ -1,97 +1,98 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config.model; - -import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -@Entity -@Table(name = "config_file_content", - uniqueConstraints = @UniqueConstraint(columnNames = {"MACID", "SW_VERSION", "HW_VERSION"})) -public class ConfigFileContent implements Serializable { - private static final long serialVersionUID = -5435735270835950132L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ID") - private Long id; - - @Column(name = "MACID", length = 255) - private String macId; - - @Column(name = "FILE_CONTENT", columnDefinition = "MEDIUMTEXT") - private String fileContent; - - @Column(name = "SW_VERSION", length = 64) - private String swVersion; - - @Column(name = "HW_VERSION", length = 64) - private String hwVersion; - - public ConfigFileContent() { - super(); - } - - public String getMacId() { - return macId; - } - - public void setMacId(String macId) { - this.macId = macId; - } - - public String getFileContent() { - return fileContent; - } - - public void setFileContent(String fileContent) { - this.fileContent = fileContent; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +@Entity +@Table(name = "config_file_content", + uniqueConstraints = @UniqueConstraint(columnNames = {"MACID", "SW_VERSION", "HW_VERSION"})) +public class ConfigFileContent implements Serializable { + private static final long serialVersionUID = -5435735270835950132L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + + @Column(name = "MACID", length = 255) + private String macId; + + @Column(name = "FILE_CONTENT", columnDefinition = "MEDIUMTEXT") + private String fileContent; + + @Column(name = "SW_VERSION", length = 64) + private String swVersion; + + @Column(name = "HW_VERSION", length = 64) + private String hwVersion; + + public ConfigFileContent() { + super(); + } + + public String getMacId() { + return macId; + } + + public void setMacId(String macId) { + this.macId = macId; + } + + public String getFileContent() { + return fileContent; + } + + public void setFileContent(String fileContent) { + this.fileContent = fileContent; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } +} diff --git a/config-data/src/main/java/org/commscope/tr069adapter/config/repository/ConfigurationDataRepository.java b/config-data/src/main/java/org/commscope/tr069adapter/config/repository/ConfigurationDataRepository.java index e116e7d..1e55df5 100644 --- a/config-data/src/main/java/org/commscope/tr069adapter/config/repository/ConfigurationDataRepository.java +++ b/config-data/src/main/java/org/commscope/tr069adapter/config/repository/ConfigurationDataRepository.java @@ -1,32 +1,33 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config.repository; - -import java.util.List; -import org.commscope.tr069adapter.config.model.ConfigFileContent; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface ConfigurationDataRepository extends CrudRepository { - public List findByMacId(String macId); - - public ConfigFileContent findByMacIdAndSwVersionAndHwVersion(String macId, String swVersion, - String hwVersion); -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config.repository; + +import java.util.List; + +import org.commscope.tr069adapter.config.model.ConfigFileContent; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ConfigurationDataRepository extends CrudRepository { + public List findByMacId(String macId); + + public ConfigFileContent findByMacIdAndSwVersionAndHwVersion(String macId, String swVersion, + String hwVersion); +} diff --git a/config-data/src/main/java/org/commscope/tr069adapter/config/service/ConfigurationDataService.java b/config-data/src/main/java/org/commscope/tr069adapter/config/service/ConfigurationDataService.java index 0ce8aef..49225a7 100644 --- a/config-data/src/main/java/org/commscope/tr069adapter/config/service/ConfigurationDataService.java +++ b/config-data/src/main/java/org/commscope/tr069adapter/config/service/ConfigurationDataService.java @@ -1,238 +1,241 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config.service; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.TreeMap; -import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; -import org.commscope.tr069adapter.config.constants.Utility; -import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException; -import org.commscope.tr069adapter.config.model.ConfigFileContent; -import org.commscope.tr069adapter.config.parser.ConfigurationXMLDataParser; -import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -@Service -public class ConfigurationDataService { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ConfigurationDataRepository configDataRepository; - - @Autowired - ConfigurationXMLDataParser configurationXMLDataParser; - - public void saveConfigFileContent(ConfigFileContent configFileContent) { - configDataRepository.save(configFileContent); - } - - public Iterable getAllConfigFileContent() { - return configDataRepository.findAll(); - } - - public Optional getConfigFileContent(String macId) { - return configDataRepository.findById(macId); - } - - public Optional getConfigurationData(String macId, String swVersion, - String hwVersion) throws InvalidConfigurationServiceException { - ConfigurationData configurationData = null; - List configFileContentList = configDataRepository.findByMacId(macId); - TreeMap configDataMap = new TreeMap<>(); - if (!configFileContentList.isEmpty()) { - logger.debug("Parsing configuration file for device {}", macId); - for (ConfigFileContent configFileContent : configFileContentList) { - ConfigurationData cfgData = configurationXMLDataParser.parseFile(configFileContent); - DeviceVersion dVersion = - new DeviceVersion(cfgData.getSoftwareVersion(), cfgData.getHardwareVersion()); - configDataMap.put(dVersion, cfgData); - } - DeviceVersion inputVersion = new DeviceVersion(swVersion, hwVersion); - Entry floorEntry = configDataMap.floorEntry(inputVersion); - - if (null == floorEntry) { - logger.error("Configuration file is not available for device {}", macId); - return Optional.ofNullable(configurationData); - } - - DeviceVersion floor = floorEntry.getKey(); - configurationData = configDataMap.get(floor); - logger.debug("Parsing of device configuration file is completed"); - } else { - logger.error("Configuration file is not available for device {}", macId); - return Optional.ofNullable(configurationData); - } - return Optional.ofNullable(configurationData); - } - - public void saveConfigFileContents(MultipartFile file) - throws InvalidConfigurationServiceException { - String fileName = StringUtils.cleanPath(file.getOriginalFilename()); - - if (fileName.contains("..")) { - throw new InvalidConfigurationServiceException( - "Filename contains invalid path sequence " + fileName); - } - - ConfigFileContent configFileContent = new ConfigFileContent(); - - try { - configFileContent.setFileContent(new String(file.getBytes(), StandardCharsets.UTF_8)); - configFileContent.setMacId(Utility.getMacId(fileName)); - - if (!configFileContent.getFileContent().contains("")) { - logger.error( - "File {} is not a valid configuration file as it doesn't contain tag \"\"", - fileName); - throw new InvalidConfigurationServiceException( - "File is not a valid configuration file as it doesn't contain tag \"\""); - } - - } catch (Exception e) { - throw new InvalidConfigurationServiceException( - "Error occurred while reading file content. Reason: " + e.getMessage()); - } - - configurationXMLDataParser.validateFile(configFileContent); - - ConfigurationData configurationData = configurationXMLDataParser.parseFile(configFileContent); - configFileContent.setSwVersion(configurationData.getSoftwareVersion()); - configFileContent.setHwVersion(configurationData.getHardwareVersion()); - - logger.debug("Saving configuration file {} content for device of macId {}", fileName, - Utility.getMacId(fileName)); - ConfigFileContent configFileContentEntity = - configDataRepository.findByMacIdAndSwVersionAndHwVersion(configFileContent.getMacId(), - configFileContent.getSwVersion(), configFileContent.getHwVersion()); - - if (configFileContentEntity != null) { - configFileContentEntity.setFileContent(configFileContent.getFileContent()); - saveConfigFileContent(configFileContentEntity); - } else { - saveConfigFileContent(configFileContent); - } - - logger.debug("Configuration file content saved successfully"); - } - - class DeviceVersion implements Comparable { - private static final long serialVersionUID = -7251276716604249440L; - private int svMajorVersion = 0; - private int svMinorVersion = 0; - private int svPatchVersion = 0; - private boolean isGenericVersion = false; - - public DeviceVersion(String swVersion, String hwVersion) { - super(); - setSwVersion(swVersion); - this.hwVersion = hwVersion; - } - - public String getSwVersion() { - return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion; - } - - public void setSwVersion(String swVersion) { - // TODO: conversion to integers - - if (swVersion.indexOf(".") > 0) { - String[] verArray = swVersion.split("\\."); - - - for (int i = 0; i < verArray.length; i++) { - - if (verArray[i].equals("*")) { - verArray[i] = "0"; - } - } - svMajorVersion = Integer.parseInt(verArray[0]); - svMinorVersion = Integer.parseInt(verArray[1]); - svPatchVersion = Integer.parseInt(verArray[2]); - - } else if (swVersion.indexOf("x") > 0) { - swVersion = "*"; - } else if (swVersion.equals("*")) { - isGenericVersion = true; - } - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } - - private String hwVersion; - - public int getSvMajorVersion() { - return svMajorVersion; - } - - public void setSvMajorVersion(int svMajorVersion) { - this.svMajorVersion = svMajorVersion; - } - - public int getSvMinorVersion() { - return svMinorVersion; - } - - public void setSvMinorVersion(int svMinorVersion) { - this.svMinorVersion = svMinorVersion; - } - - public int getSvPatchVersion() { - return svPatchVersion; - } - - public void setSvPatchVersion(int svPatchVersion) { - this.svPatchVersion = svPatchVersion; - } - - public boolean isGenericVersion() { - return isGenericVersion; - } - - public void setGenericVersion(boolean isGenericVersion) { - this.isGenericVersion = isGenericVersion; - } - - @Override - public int compareTo(DeviceVersion o) { - - if (svMajorVersion != o.svMajorVersion) { - return (svMajorVersion - o.svMajorVersion); - } else if (svMinorVersion != o.svMinorVersion) { - return svMinorVersion - o.svMinorVersion; - } else { - return svPatchVersion - o.svPatchVersion; - } - } - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config.service; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.TreeMap; + +import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; +import org.commscope.tr069adapter.config.constants.Utility; +import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException; +import org.commscope.tr069adapter.config.model.ConfigFileContent; +import org.commscope.tr069adapter.config.parser.ConfigurationXMLDataParser; +import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +@Service +public class ConfigurationDataService { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + ConfigurationDataRepository configDataRepository; + + @Autowired + ConfigurationXMLDataParser configurationXMLDataParser; + + public void saveConfigFileContent(ConfigFileContent configFileContent) { + configDataRepository.save(configFileContent); + } + + public Iterable getAllConfigFileContent() { + return configDataRepository.findAll(); + } + + public Optional getConfigFileContent(String macId) { + return configDataRepository.findById(macId); + } + + public Optional getConfigurationData(String macId, String swVersion, + String hwVersion) throws InvalidConfigurationServiceException { + ConfigurationData configurationData = null; + List configFileContentList = configDataRepository.findByMacId(macId); + TreeMap configDataMap = new TreeMap<>(); + if (!configFileContentList.isEmpty()) { + logger.debug("Parsing configuration file for device {}", macId); + for (ConfigFileContent configFileContent : configFileContentList) { + ConfigurationData cfgData = configurationXMLDataParser.parseFile(configFileContent); + DeviceVersion dVersion = + new DeviceVersion(cfgData.getSoftwareVersion(), cfgData.getHardwareVersion()); + configDataMap.put(dVersion, cfgData); + } + DeviceVersion inputVersion = new DeviceVersion(swVersion, hwVersion); + Entry floorEntry = configDataMap.floorEntry(inputVersion); + + if (null == floorEntry) { + macId = macId.replaceAll("[\n|\r|\t]", "_"); + logger.error("Configuration file is not available for device {}", macId); + return Optional.ofNullable(configurationData); + } + + DeviceVersion floor = floorEntry.getKey(); + configurationData = configDataMap.get(floor); + logger.debug("Parsing of device configuration file is completed"); + } else { + macId = macId.replaceAll("[\n|\r|\t]", "_"); + logger.error("Configuration file is not available for device {}", macId); + return Optional.ofNullable(configurationData); + } + return Optional.ofNullable(configurationData); + } + + public void saveConfigFileContents(MultipartFile file) + throws InvalidConfigurationServiceException { + String fileName = StringUtils.cleanPath(file.getOriginalFilename()); + + if (fileName.contains("..")) { + throw new InvalidConfigurationServiceException( + "Filename contains invalid path sequence " + fileName); + } + + ConfigFileContent configFileContent = new ConfigFileContent(); + + try { + configFileContent.setFileContent(new String(file.getBytes(), StandardCharsets.UTF_8)); + configFileContent.setMacId(Utility.getMacId(fileName)); + + if (!configFileContent.getFileContent().contains("")) { + logger.error( + "File {} is not a valid configuration file as it doesn't contain tag \"\"", + fileName); + throw new InvalidConfigurationServiceException( + "File is not a valid configuration file as it doesn't contain tag \"\""); + } + + } catch (Exception e) { + throw new InvalidConfigurationServiceException( + "Error occurred while reading file content. Reason: " + e.getMessage()); + } + + configurationXMLDataParser.validateFile(configFileContent); + + ConfigurationData configurationData = configurationXMLDataParser.parseFile(configFileContent); + configFileContent.setSwVersion(configurationData.getSoftwareVersion()); + configFileContent.setHwVersion(configurationData.getHardwareVersion()); + + logger.debug("Saving configuration file {} content for device of macId {}", fileName, + Utility.getMacId(fileName)); + ConfigFileContent configFileContentEntity = + configDataRepository.findByMacIdAndSwVersionAndHwVersion(configFileContent.getMacId(), + configFileContent.getSwVersion(), configFileContent.getHwVersion()); + + if (configFileContentEntity != null) { + configFileContentEntity.setFileContent(configFileContent.getFileContent()); + saveConfigFileContent(configFileContentEntity); + } else { + saveConfigFileContent(configFileContent); + } + + logger.debug("Configuration file content saved successfully"); + } + + class DeviceVersion implements Comparable { + private static final long serialVersionUID = -7251276716604249440L; + private int svMajorVersion = 0; + private int svMinorVersion = 0; + private int svPatchVersion = 0; + private boolean isGenericVersion = false; + + public DeviceVersion(String swVersion, String hwVersion) { + super(); + setSwVersion(swVersion); + this.hwVersion = hwVersion; + } + + public String getSwVersion() { + return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion; + } + + public void setSwVersion(String swVersion) { + // TODO: conversion to integers + + if (swVersion.indexOf(".") > 0) { + String[] verArray = swVersion.split("\\."); + + + for (int i = 0; i < verArray.length; i++) { + + if (verArray[i].equals("*")) { + verArray[i] = "0"; + } + } + svMajorVersion = Integer.parseInt(verArray[0]); + svMinorVersion = Integer.parseInt(verArray[1]); + svPatchVersion = Integer.parseInt(verArray[2]); + + } else if (swVersion.indexOf("x") > 0) { + swVersion = "*"; + } else if (swVersion.equals("*")) { + isGenericVersion = true; + } + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } + + private String hwVersion; + + public int getSvMajorVersion() { + return svMajorVersion; + } + + public void setSvMajorVersion(int svMajorVersion) { + this.svMajorVersion = svMajorVersion; + } + + public int getSvMinorVersion() { + return svMinorVersion; + } + + public void setSvMinorVersion(int svMinorVersion) { + this.svMinorVersion = svMinorVersion; + } + + public int getSvPatchVersion() { + return svPatchVersion; + } + + public void setSvPatchVersion(int svPatchVersion) { + this.svPatchVersion = svPatchVersion; + } + + public boolean isGenericVersion() { + return isGenericVersion; + } + + public void setGenericVersion(boolean isGenericVersion) { + this.isGenericVersion = isGenericVersion; + } + + @Override + public int compareTo(DeviceVersion o) { + + if (svMajorVersion != o.svMajorVersion) { + return (svMajorVersion - o.svMajorVersion); + } else if (svMinorVersion != o.svMinorVersion) { + return svMinorVersion - o.svMinorVersion; + } else { + return svPatchVersion - o.svPatchVersion; + } + } + } + +} diff --git a/config-data/src/test/java/org/commscope/tr069adapter/config/ConfigDataTestsUtils.java b/config-data/src/test/java/org/commscope/tr069adapter/config/ConfigDataTestsUtils.java index d9b8ec2..de7b523 100644 --- a/config-data/src/test/java/org/commscope/tr069adapter/config/ConfigDataTestsUtils.java +++ b/config-data/src/test/java/org/commscope/tr069adapter/config/ConfigDataTestsUtils.java @@ -1,85 +1,86 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config; - -import java.util.ArrayList; -import java.util.List; -import org.commscope.tr069adapter.config.model.ConfigFileContent; - -public class ConfigDataTestsUtils { - - private ConfigDataTestsUtils() {} - - public static final String SERVER_URI = "http://localhost:9000/"; - public static final String macId = "testMacId"; - public static final String OUI = "0005B9"; - public static final String PRODUCT_CLASS = "LTE_Enterprise_C-RANSC_Cntrl"; - public static final String HAEDWARE_VERSION = "1.1.1.1"; - public static final String SW_VERSION = "4.5.00.001"; - - public static final String CONFIG_FILE_NAME = macId + ".xml"; - - // public static ConfigurationData getConfigurationData() { - // ConfigurationData configData = new ConfigurationData(); - // - // configData.setHardwareVersion(HAEDWARE_VERSION); - // configData.setSoftwareVersion(SW_VERSION); - // configData.setLocalDn(macId); - // configData.setOUI(OUI); - // configData.setProductClass(PRODUCT_CLASS); - // - //// Map map = new HashMap(); - //// map.put(", value) - //// configData.set - // return configData; - // } - - - public static List getConfigFileContent() { - List data = new ArrayList<>(); - - for (int i = 0; i < 5; i++) { - ConfigFileContent configFileContent = new ConfigFileContent(); - configFileContent.setFileContent(getFileContent()); - configFileContent.setMacId(macId); - configFileContent.setSwVersion("4." + i); - } - - return data; - } - - - public static String getFileContent() { - String fileContent = "\r\n" + "\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" + " \r\n" + " \r\n" - + " \r\n" + " 1\r\n" - + " dmsuser\r\n" - + " 7001\r\n" - + " NONE\r\n" - + " dmsuser\r\n" + " \r\n" - + " 0\r\n" + " \r\n" + " \r\n" - + " \r\n" + " \r\n" - + " \r\n" + ""; - - return fileContent; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config; + +import java.util.ArrayList; +import java.util.List; + +import org.commscope.tr069adapter.config.model.ConfigFileContent; + +public class ConfigDataTestsUtils { + + private ConfigDataTestsUtils() {} + + public static final String SERVER_URI = "http://localhost:9000/"; + public static final String macId = "testMacId"; + public static final String OUI = "0005B9"; + public static final String PRODUCT_CLASS = "LTE_Enterprise_C-RANSC_Cntrl"; + public static final String HAEDWARE_VERSION = "1.1.1.1"; + public static final String SW_VERSION = "4.5.00.001"; + + public static final String CONFIG_FILE_NAME = macId + ".xml"; + + // public static ConfigurationData getConfigurationData() { + // ConfigurationData configData = new ConfigurationData(); + // + // configData.setHardwareVersion(HAEDWARE_VERSION); + // configData.setSoftwareVersion(SW_VERSION); + // configData.setLocalDn(macId); + // configData.setOUI(OUI); + // configData.setProductClass(PRODUCT_CLASS); + // + //// Map map = new HashMap(); + //// map.put(", value) + //// configData.set + // return configData; + // } + + + public static List getConfigFileContent() { + List data = new ArrayList<>(); + + for (int i = 0; i < 5; i++) { + ConfigFileContent configFileContent = new ConfigFileContent(); + configFileContent.setFileContent(getFileContent()); + configFileContent.setMacId(macId); + configFileContent.setSwVersion("4." + i); + } + + return data; + } + + + public static String getFileContent() { + String fileContent = "\r\n" + "\r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + " \r\n" + " \r\n" + + " \r\n" + " 1\r\n" + + " dmsuser\r\n" + + " 7001\r\n" + + " NONE\r\n" + + " dmsuser\r\n" + " \r\n" + + " 0\r\n" + " \r\n" + " \r\n" + + " \r\n" + " \r\n" + + " \r\n" + ""; + + return fileContent; + } +} diff --git a/config-data/src/test/java/org/commscope/tr069adapter/config/ConfugurationDataControllerTests.java b/config-data/src/test/java/org/commscope/tr069adapter/config/ConfugurationDataControllerTests.java index 38634d0..acfe5fe 100644 --- a/config-data/src/test/java/org/commscope/tr069adapter/config/ConfugurationDataControllerTests.java +++ b/config-data/src/test/java/org/commscope/tr069adapter/config/ConfugurationDataControllerTests.java @@ -1,115 +1,113 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository; -import org.hamcrest.CoreMatchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.RequestBuilder; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {ConfigDataServiceApplication.class}) // , args = "--schemas-dir - // test-schemas --debug true - // --starting-port 17830") -@AutoConfigureMockMvc -public class ConfugurationDataControllerTests { - - @Autowired - private MockMvc mockMvc; - - @MockBean - ConfigurationDataRepository configDataRepository; - - @Test - public void getMessageTest() { - RequestBuilder requestBuilder = - MockMvcRequestBuilders.get("/isActive").accept(MediaType.APPLICATION_JSON); - - MvcResult result = null; - String resultString = null; - try { - result = mockMvc.perform(requestBuilder).andReturn(); - resultString = result.getResponse().getContentAsString(); - } catch (Exception e) { - fail(e.getMessage()); - } - - assertEquals("Application is running", resultString); - } - - @Test - public void uploadMultipleFilesTest() { - MockMultipartFile multiFile = - new MockMultipartFile("files", ConfigDataTestsUtils.CONFIG_FILE_NAME, - MediaType.APPLICATION_XML_VALUE, ConfigDataTestsUtils.getFileContent().getBytes()); - MockHttpServletRequestBuilder requestBuilder = - MockMvcRequestBuilders.multipart("/importConfig").file(multiFile);// .contentType(MediaType.MULTIPART_FORM_DATA_VALUE); - - MvcResult result = null; - String resultString = null; - try { - result = mockMvc.perform(requestBuilder).andReturn(); - MockHttpServletResponse response = result.getResponse(); - resultString = response.getContentAsString(); - } catch (Exception e) { - fail(e.getMessage()); - } - - String expectedResult = - "File " + ConfigDataTestsUtils.CONFIG_FILE_NAME + " imported successfully"; - assertEquals(expectedResult, resultString); - } - - @Test - public void viewConfigurationDataTest() { - Mockito.when(configDataRepository.findByMacId(ConfigDataTestsUtils.macId)) - .thenReturn(ConfigDataTestsUtils.getConfigFileContent()); - - MockHttpServletRequestBuilder requestBuilder = - MockMvcRequestBuilders.post("/getConfig").param("macId", "0005B95196D0") - .param("swVersion", "4.5").param("hwVersion", "1.1").accept(MediaType.APPLICATION_JSON); - - MvcResult result = null; - try { - result = mockMvc.perform(requestBuilder).andReturn(); - MockHttpServletResponse response = result.getResponse(); - assertEquals(200, response.getStatus()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.config; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ConfigDataServiceApplication.class}) // , args = "--schemas-dir + // test-schemas --debug true + // --starting-port 17830") +@AutoConfigureMockMvc +public class ConfugurationDataControllerTests { + + @Autowired + private MockMvc mockMvc; + + @MockBean + ConfigurationDataRepository configDataRepository; + + @Test + public void getMessageTest() { + RequestBuilder requestBuilder = + MockMvcRequestBuilders.get("/isActive").accept(MediaType.APPLICATION_JSON); + + MvcResult result = null; + String resultString = null; + try { + result = mockMvc.perform(requestBuilder).andReturn(); + resultString = result.getResponse().getContentAsString(); + } catch (Exception e) { + fail(e.getMessage()); + } + + assertEquals("Application is running", resultString); + } + + @Test + public void uploadMultipleFilesTest() { + MockMultipartFile multiFile = + new MockMultipartFile("files", ConfigDataTestsUtils.CONFIG_FILE_NAME, + MediaType.APPLICATION_XML_VALUE, ConfigDataTestsUtils.getFileContent().getBytes()); + MockHttpServletRequestBuilder requestBuilder = + MockMvcRequestBuilders.multipart("/importConfig").file(multiFile);// .contentType(MediaType.MULTIPART_FORM_DATA_VALUE); + + MvcResult result = null; + String resultString = null; + try { + result = mockMvc.perform(requestBuilder).andReturn(); + MockHttpServletResponse response = result.getResponse(); + resultString = response.getContentAsString(); + } catch (Exception e) { + fail(e.getMessage()); + } + + String expectedResult = + "File " + ConfigDataTestsUtils.CONFIG_FILE_NAME + " imported successfully"; + assertEquals(expectedResult, resultString); + } + + @Test + public void viewConfigurationDataTest() { + Mockito.when(configDataRepository.findByMacId(ConfigDataTestsUtils.macId)) + .thenReturn(ConfigDataTestsUtils.getConfigFileContent()); + + MockHttpServletRequestBuilder requestBuilder = + MockMvcRequestBuilders.post("/getConfig").param("macId", "0005B95196D0") + .param("swVersion", "4.5").param("hwVersion", "1.1").accept(MediaType.APPLICATION_JSON); + + MvcResult result = null; + try { + result = mockMvc.perform(requestBuilder).andReturn(); + MockHttpServletResponse response = result.getResponse(); + assertEquals(200, response.getStatus()); + } catch (Exception e) { + fail(e.getMessage()); + } + } +} diff --git a/factory/pom.xml b/factory/pom.xml index 4876f27..e9ffb70 100644 --- a/factory/pom.xml +++ b/factory/pom.xml @@ -116,6 +116,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin diff --git a/mapper/pom.xml b/mapper/pom.xml index 648a73f..126942a 100644 --- a/mapper/pom.xml +++ b/mapper/pom.xml @@ -193,6 +193,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin @@ -269,4 +288,4 @@ JIRA https://jira.o-ran-sc.org/ - + \ No newline at end of file diff --git a/mapper/rpc_set_input.xml b/mapper/rpc_set_input.xml deleted file mode 100644 index ddbe4cf..0000000 --- a/mapper/rpc_set_input.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - sftp://root@10.208.224.201/root/vishal/BCRP_OneImage_4.3.00.158.signed.bin - - airvana123 - - - \ No newline at end of file diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/MapperConfigProperties.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/MapperConfigProperties.java index 3ccf919..c58ecf8 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/MapperConfigProperties.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/MapperConfigProperties.java @@ -1,144 +1,154 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "config") -public class MapperConfigProperties { - - private String requesTimeout; - - private String preConfigureOnPNP; - - private String sbiUri; - - private String configDBUri; - - private String nbiNotificationUri; - private String nbiServerManagerUri; - private String vesUri; - - private String netConfServerIP; - private String netConfServerPort; - - private String alarmMORegex; - - private String verConfigUri; - private String vendorName; - - public String getRequesTimeout() { - return requesTimeout; - } - - public void setRequesTimeout(String requesTimeout) { - this.requesTimeout = requesTimeout; - } - - public String getPreConfigureOnPNP() { - return preConfigureOnPNP; - } - - public void setPreConfigureOnPNP(String preConfigureOnPNP) { - this.preConfigureOnPNP = preConfigureOnPNP; - } - - public String getSbiUri() { - return sbiUri; - } - - public void setSbiUri(String sbiUri) { - this.sbiUri = sbiUri; - } - - public String getConfigDBUri() { - return configDBUri; - } - - public void setConfigDBUri(String configDBUri) { - this.configDBUri = configDBUri; - } - - public String getNbiNotificationUri() { - return nbiNotificationUri; - } - - public void setNbiNotificationUri(String nbiNotificationUri) { - this.nbiNotificationUri = nbiNotificationUri; - } - - public String getNbiServerManagerUri() { - return nbiServerManagerUri; - } - - public void setNbiServerManagerUri(String nbiServerManagerUri) { - this.nbiServerManagerUri = nbiServerManagerUri; - } - - public String getVesUri() { - return vesUri; - } - - public void setVesUri(String vesUri) { - this.vesUri = vesUri; - } - - public String getNetConfServerIP() { - return netConfServerIP; - } - - public void setNetConfServerIP(String netConfServerIP) { - this.netConfServerIP = netConfServerIP; - } - - public String getNetConfServerPort() { - return netConfServerPort; - } - - public void setNetConfServerPort(String netConfServerPort) { - this.netConfServerPort = netConfServerPort; - } - - public String getAlarmMORegex() { - return alarmMORegex; - } - - public void setAlarmMORegex(String alarmMORegex) { - this.alarmMORegex = alarmMORegex; - } - - public String getVerConfigUri() { - return verConfigUri; - } - - public void setVerConfigUri(String verConfigUri) { - this.verConfigUri = verConfigUri; - } - - public String getVendorName() { - return vendorName; - } - - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "config") +public class MapperConfigProperties { + + private String requesTimeout; + + private String preConfigureOnPNP; + + private String sbiUri; + + private String connStatusUri; + + private String configDBUri; + + private String nbiNotificationUri; + private String nbiServerManagerUri; + private String vesUri; + + private String netConfServerIP; + private String netConfServerPort; + + private String alarmMORegex; + + private String verConfigUri; + private String vendorName; + + public String getRequesTimeout() { + return requesTimeout; + } + + public void setRequesTimeout(String requesTimeout) { + this.requesTimeout = requesTimeout; + } + + public String getPreConfigureOnPNP() { + return preConfigureOnPNP; + } + + public void setPreConfigureOnPNP(String preConfigureOnPNP) { + this.preConfigureOnPNP = preConfigureOnPNP; + } + + public String getSbiUri() { + return sbiUri; + } + + public void setSbiUri(String sbiUri) { + this.sbiUri = sbiUri; + } + + public String getConfigDBUri() { + return configDBUri; + } + + public void setConfigDBUri(String configDBUri) { + this.configDBUri = configDBUri; + } + + public String getNbiNotificationUri() { + return nbiNotificationUri; + } + + public void setNbiNotificationUri(String nbiNotificationUri) { + this.nbiNotificationUri = nbiNotificationUri; + } + + public String getNbiServerManagerUri() { + return nbiServerManagerUri; + } + + public void setNbiServerManagerUri(String nbiServerManagerUri) { + this.nbiServerManagerUri = nbiServerManagerUri; + } + + public String getVesUri() { + return vesUri; + } + + public void setVesUri(String vesUri) { + this.vesUri = vesUri; + } + + public String getNetConfServerIP() { + return netConfServerIP; + } + + public void setNetConfServerIP(String netConfServerIP) { + this.netConfServerIP = netConfServerIP; + } + + public String getNetConfServerPort() { + return netConfServerPort; + } + + public void setNetConfServerPort(String netConfServerPort) { + this.netConfServerPort = netConfServerPort; + } + + public String getAlarmMORegex() { + return alarmMORegex; + } + + public void setAlarmMORegex(String alarmMORegex) { + this.alarmMORegex = alarmMORegex; + } + + public String getVerConfigUri() { + return verConfigUri; + } + + public void setVerConfigUri(String verConfigUri) { + this.verConfigUri = verConfigUri; + } + + public String getConnStatusUri() { + return connStatusUri; + } + + public void setConnStatusUri(String connStatusUri) { + this.connStatusUri = connStatusUri; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/ACSRequestSender.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/ACSRequestSender.java index 01ed76a..c3fe629 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/ACSRequestSender.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/ACSRequestSender.java @@ -1,44 +1,58 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.acs; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -@Component -public class ACSRequestSender { - - private RestTemplate restTemplate = new RestTemplate(); - - @Autowired - MapperConfigProperties config; - - public Long sendRequest(DeviceRPCRequest deviceRPCRequest) { - String uri = getUri(); - return restTemplate.postForObject(uri, deviceRPCRequest, Long.class); - } - - private String getUri() { - return config.getSbiUri(); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.acs; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.utils.ConnectionStatusPOJO; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +public class ACSRequestSender { + + private RestTemplate restTemplate = new RestTemplate(); + + @Autowired + MapperConfigProperties config; + + public Long sendRequest(DeviceRPCRequest deviceRPCRequest) { + String uri = getUri(); + return restTemplate.postForObject(uri, deviceRPCRequest, Long.class); + } + + public ConnectionStatusPOJO sendConnectionStatusReq(String deviceId) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(deviceId, headers); + return restTemplate.postForObject(getUriForConnStatus(), entity, ConnectionStatusPOJO.class); + } + + private String getUri() { + return config.getSbiUri(); + } + + private String getUriForConnStatus() { + return config.getConnStatusUri(); + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/ACSNotificationHandlerImpl.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/ACSNotificationHandlerImpl.java index 4d39d57..f761c90 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/ACSNotificationHandlerImpl.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/ACSNotificationHandlerImpl.java @@ -1,413 +1,416 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.acs.impl; - -import java.util.ArrayList; -import java.util.List; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.InformType; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069InformType; -import org.commscope.tr069adapter.acs.common.inform.BootInform; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.acs.common.inform.ConnectionRequestInform; -import org.commscope.tr069adapter.acs.common.inform.PeriodicInform; -import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform; -import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform; -import org.commscope.tr069adapter.mapper.MOMetaData; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.acs.ACSNotificationHandler; -import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO; -import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; -import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender; -import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; -import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; -import org.commscope.tr069adapter.mapper.util.FirwareUpgradeErrorCode; -import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus; -import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; -import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ACSNotificationHandlerImpl implements ACSNotificationHandler { - - private static final Logger logger = LoggerFactory.getLogger(ACSNotificationHandlerImpl.class); - private static final String SOFT_MGMT_NS_URI = "urn:o-ran:software-management:1.0"; - - @Autowired - SynchronizedRequestHandler syncHandler; - - @Autowired - MOMetaDataUtil metaDataUtil; - - @Autowired - PnPPreProvisioningHandler pnpPreProvisioningHandler; - - @Autowired - VESNotificationSender vesnotiSender; - - @Autowired - NetConfNotificationSender notiSender; - - @Autowired - MapperConfigProperties config; - - @Autowired - NetConfServerManager netconfManager; - - @Autowired - DeviceOperationsDAO deviceOperDAO; - - @Override - public void handleOperationResponse(DeviceRPCResponse opResult) { - opResult.getOperationResponse().setParameterDTOs( - filterUnsupportedParameters(opResult.getOperationResponse().getParameterDTOs(), - opResult.getDeviceDetails().getSoftwareVersion(), - opResult.getDeviceDetails().getHardwareVersion())); - syncHandler.notifyResult(opResult); - } - - @Override - public void handleNotification(DeviceInform notification) { - boolean isAlarmVC = isAlarmVC(notification); - - if (notification instanceof BootstrapInform) { - logger.info("BootStrap notification received"); - BootstrapInform bootstrapNotification = (BootstrapInform) notification; - - DeviceOperationDetails deviceDetails = - deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); - if (deviceDetails == null) { - deviceDetails = new DeviceOperationDetails(); - deviceDetails.setDeviceId(notification.getDeviceDetails().getDeviceId()); - deviceDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion()); - deviceOperDAO.save(deviceDetails); - } - - checkForActivateNotification(notification); - - // send request to create the netconf server instance for the bootstrap device - // id - NetConfServerDetails serverInfo = createNtConfServer(bootstrapNotification); - if (serverInfo == null) - return; - - vesnotiSender.sendNotification(bootstrapNotification, serverInfo); - BootstrapInform bsInform = - getDeviceBootStrapNotification(bootstrapNotification, TR069InformType.BOOTSTRAP); - ValueChangeInform vcInform = null; - if (bootstrapNotification.getValueChangeNotification() != null) { - logger.info("Bootstrap notification received along with VC"); - vcInform = - getDeviceValueChangeNotification(bootstrapNotification, TR069InformType.VALUECHANGE); - processVCNotification(vcInform, isAlarmVC); - } - notiSender.sendNotification(bsInform); - if (vcInform != null) - processVCNotification(vcInform, isAlarmVC); - } else if (notification instanceof BootInform) { - logger.info("Boot notification received"); - - NetConfServerDetails serverInfo = createNtConfServer(notification); - if (serverInfo == null) - return; - - checkForActivateNotification(notification); - BootInform bootNotification = (BootInform) notification; - BootInform bInform = getDeviceBootNotification(bootNotification, TR069InformType.BOOT); - ValueChangeInform vcInform = null; - if (bootNotification.getValueChangeNotification() != null) { - logger.info("Boot notification received along with VC"); - vcInform = getDeviceValueChangeNotification(bootNotification, TR069InformType.VALUECHANGE); - } - notiSender.sendNotification(bInform); - processVCNotification(vcInform, isAlarmVC); - } else if (notification instanceof PeriodicInform) { - PeriodicInform pINotificaiton = (PeriodicInform) notification; - vesnotiSender.sendNotification(pINotificaiton, null); - notiSender.sendNotification(pINotificaiton); - logger.info("PI notification received"); - } else if (notification instanceof ConnectionRequestInform) { - ConnectionRequestInform crNotificaiton = (ConnectionRequestInform) notification; - vesnotiSender.sendNotification(crNotificaiton, null); - logger.info("ConnectionRequestInform notification received"); - } else if (notification instanceof ValueChangeInform) { - ValueChangeInform valueChgNotificaiton = (ValueChangeInform) notification; - processVCNotification(valueChgNotificaiton, isAlarmVC); - } else if (notification instanceof TransferCompleteInform) { - TransferCompleteInform tfNotificaiton = (TransferCompleteInform) notification; - if (tfNotificaiton.getCommandKey() != null && tfNotificaiton.getCommandKey() - .equalsIgnoreCase(tfNotificaiton.getDeviceDetails().getDeviceId())) { - logger.debug("TransferCompleteInform is recevied at mapper"); - processTransferCompleteInform(tfNotificaiton); - logger.debug("TransferCompleteInform processing completed at mapper"); - } - } - - pnpPreProvisioningHandler.onDeviceNotification(notification); - } - - private NetConfServerDetails createNtConfServer(DeviceInform inform) { - String eNodeBName = pnpPreProvisioningHandler.getEnodeBName( - inform.getDeviceDetails().getDeviceId(), inform.getDeviceDetails().getSoftwareVersion(), - inform.getDeviceDetails().getHardwareVersion()); - if (eNodeBName == null) - eNodeBName = inform.getDeviceDetails().getDeviceId(); - NetConfServerDetails serverInfo = - netconfManager.createNetconfServer(inform.getDeviceDetails().getDeviceId(), eNodeBName, - inform.getDeviceDetails().getSoftwareVersion(), - inform.getDeviceDetails().getHardwareVersion()); - if (serverInfo != null && !NetconfServerManagementError.SUCCESS.equals(serverInfo.getError())) { - logger.error("Failed to handle boot/bootstrap notification. Server INFO: {}", serverInfo); - logger.error("Failed to create the netconf server for device ID: {} Error: {}", - inform.getDeviceDetails().getDeviceId(), serverInfo.getError()); - return null; - } else if (serverInfo == null) { - logger.error( - "Failed to handle bootstrap notification. Failed to create netconf server. serverInfo is null"); - return null; - } - return serverInfo; - } - - private void processVCNotification(ValueChangeInform valueChgNotificaiton, boolean isAlarmVC) { - if (isAlarmVC) { - logger.debug("Alarm VC received forwarding to VES Collector"); - vesnotiSender.sendNotification(valueChgNotificaiton, null); - } else { - logger.info("VC notification received"); - notiSender.sendNotification(valueChgNotificaiton); - } - } - - private boolean isAlarmVC(DeviceInform notification) { - if (null != notification && null != notification.getParameters()) { - for (ParameterDTO param : notification.getParameters()) { - if (param.getParamName().matches(config.getAlarmMORegex())) { - logger.debug("This VC contains alarm MOs"); - return true; - } - } - } - return false; - } - - public List filterUnsupportedParameters(List parameters, - String swVersion, String hwVersion) { - List result = new ArrayList<>(); - if (null != parameters) { - for (ParameterDTO param : parameters) { - MOMetaData metaData = - metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); - if (null != metaData) { - result.add(param); - } - } - } - return result; - } - - public static BootstrapInform getDeviceBootStrapNotification(DeviceInform devNotification, - TR069InformType notificationType) { - BootstrapInform bsInform = new BootstrapInform(); - List informTypeList = new ArrayList<>(); - informTypeList.add(notificationType); - bsInform.setDeviceDetails(devNotification.getDeviceDetails()); - bsInform.setInformTypeList(informTypeList); - List paramList = new ArrayList<>(); - for (ParameterDTO param : devNotification.getParameters()) { - paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); - } - bsInform.setParameters(paramList); - return bsInform; - } - - public static BootInform getDeviceBootNotification(DeviceInform devNotification, - TR069InformType notificationType) { - BootInform bInform = new BootInform(); - List informTypeList = new ArrayList<>(); - informTypeList.add(notificationType); - bInform.setDeviceDetails(devNotification.getDeviceDetails()); - bInform.setInformTypeList(informTypeList); - List paramList = new ArrayList<>(); - for (ParameterDTO param : devNotification.getParameters()) { - paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); - } - bInform.setParameters(paramList); - return bInform; - } - - public static ValueChangeInform getDeviceValueChangeNotification(DeviceInform devNotification, - TR069InformType notificationType) { - ValueChangeInform devValChangeNotif = new ValueChangeInform(); - List informTypeList = new ArrayList<>(); - informTypeList.add(notificationType); - devValChangeNotif.setDeviceDetails(devNotification.getDeviceDetails()); - devValChangeNotif.setInformTypeList(informTypeList); - List paramList = new ArrayList<>(); - for (ParameterDTO param : devNotification.getParameters()) { - paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); - } - devValChangeNotif.setParameters(paramList); - devValChangeNotif.setExternalIPAddress(getExternalIPAddress(devNotification.getParameters())); - return devValChangeNotif; - } - - private static String getExternalIPAddress(List params) { - ParameterDTO[] nbiParam = params.toArray(new ParameterDTO[params.size()]); - String externalIpAddress = ""; - boolean isIPv6 = isIPv6Enabled(nbiParam); - - for (int index1 = 0; index1 < nbiParam.length; index1++) { - - if (isIPv6) { - if (nbiParam[index1].getParamName().contains("IPv6Address") - || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) { - externalIpAddress = nbiParam[index1].getParamValue(); - logger.debug("device communicating is with IPV6 address"); - } - } else { - if (nbiParam[index1].getParamName().contains("IPv4Address") - || nbiParam[index1].getParamName().contains("ExternalIPAddress") - || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) { - externalIpAddress = nbiParam[index1].getParamValue(); - } - } - if (externalIpAddress.trim().length() > 0) - break; - } - return externalIpAddress; - } - - private static boolean isIPv6Enabled(ParameterDTO[] nbiParam) { - boolean isIPv6 = false; - for (int index1 = 0; index1 < nbiParam.length; index1++) { - if (nbiParam[index1].getParamName().contains("IPv6Enable") - && nbiParam[index1].getParamValue().equalsIgnoreCase("1")) { - isIPv6 = true; - break; - } - } - return isIPv6; - } - - private void processTransferCompleteInform(TransferCompleteInform notification) { - - try { - ArrayList paramList = new ArrayList(); - DeviceOperationDetails fwDetails = - deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); - if (fwDetails == null || fwDetails.getFileName() == null) { - logger.debug( - "TransferCompleteInform recevied for invaild device, there is no entry exist in the database"); - return; - } - if (fwDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) { - paramList.add(new ParameterDTO("download-event.file-name", fwDetails.getFileName())); - - String status = FirwareUpgradeErrorCode.getErrorCodeMapping(notification.getFaultCode()); - paramList.add(new ParameterDTO("download-event.status", status)); - if (notification.getFaultCode() != 0) { - fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_FAILED.getStatus()); - paramList - .add(new ParameterDTO("download-event.error-message", notification.getFaultString())); - } else { - fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()); - logger.debug("downloading file completed on the device successfully."); - } - deviceOperDAO.save(fwDetails); - - logger.debug("sending download-event notification to netconfserver"); - - if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(), - paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) { - logger.debug("sending download-event notification to netconfserver sucess"); - } else { - logger.error("sending download-event notification to netconfserver failed"); - } - } else { - logger.debug( - "TransferCompleteInform recevied after boot is received; already software is activated"); - } - } catch (Exception e) { - logger.debug("Exception occured while processing TransferCompleteInform " + e.toString()); - } - } - - private void checkForActivateNotification(DeviceInform notification) { - - try { - ArrayList paramList = new ArrayList(); - DeviceOperationDetails devDetails = - deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); - - if (devDetails == null - || devDetails.getDownLoadStatus() == FirwareUpgradeStatus.NOT_STARTED.getStatus()) { - logger.debug("firmware upgrade is not in progress"); - return; - } - - if (!notification.getDeviceDetails().getSoftwareVersion() - .equalsIgnoreCase(devDetails.getSwVersion()) - && devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) { - logger.debug("received the boot/bootstrap before the transfer complete recevied"); - TransferCompleteInform inform = new TransferCompleteInform(); - inform.setDeviceDetails(notification.getDeviceDetails()); - inform.setFaultCode(0); - processTransferCompleteInform(inform); - } - - devDetails = deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); - if (devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) { - paramList.add(new ParameterDTO("activation-event.slot-name", "Active-Partion")); - // check for software change - if (notification.getDeviceDetails().getSoftwareVersion() - .equalsIgnoreCase(devDetails.getSwVersion())) { - paramList.add(new ParameterDTO("activation-event.status", "APPLICATION_ERROR")); - paramList.add(new ParameterDTO("activation-event.error-message", - "Same Software Version is reported after upgrade")); - devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_ERROR.getStatus()); - } else { - devDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion()); - devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_COMPLETED.getStatus()); - paramList.add(new ParameterDTO("activation-event.status", "COMPLETED")); - } - deviceOperDAO.save(devDetails); - - logger.debug("sending activation-event notification to netconfserver"); - - if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(), - paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) { - logger.debug("sending activation-event notification to netconfserver sucess"); - } else { - logger.error("sending activation-event notification to netconfserver failed"); - } - } - } catch (Exception e) { - logger.debug( - "Exception occured while processing ProcessFirmWareActivateNotification " + e.toString()); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.acs.impl; + +import java.util.ArrayList; +import java.util.List; +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.InformType; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069InformType; +import org.commscope.tr069adapter.acs.common.inform.BootInform; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.acs.common.inform.ConnectionRequestInform; +import org.commscope.tr069adapter.acs.common.inform.PeriodicInform; +import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform; +import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform; +import org.commscope.tr069adapter.mapper.MOMetaData; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.acs.ACSNotificationHandler; +import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO; +import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; +import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender; +import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; +import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; +import org.commscope.tr069adapter.mapper.util.FirwareUpgradeErrorCode; +import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus; +import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; +import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ACSNotificationHandlerImpl implements ACSNotificationHandler { + + private static final Logger logger = LoggerFactory.getLogger(ACSNotificationHandlerImpl.class); + private static final String SOFT_MGMT_NS_URI = "urn:o-ran:software-management:1.0"; + + @Autowired + SynchronizedRequestHandler syncHandler; + + @Autowired + MOMetaDataUtil metaDataUtil; + + @Autowired + PnPPreProvisioningHandler pnpPreProvisioningHandler; + + @Autowired + VESNotificationSender vesnotiSender; + + @Autowired + NetConfNotificationSender notiSender; + + @Autowired + MapperConfigProperties config; + + @Autowired + NetConfServerManager netconfManager; + + @Autowired + DeviceOperationsDAO deviceOperDAO; + + @Override + public void handleOperationResponse(DeviceRPCResponse opResult) { + opResult.getOperationResponse().setParameterDTOs( + filterUnsupportedParameters(opResult.getOperationResponse().getParameterDTOs(), + opResult.getDeviceDetails().getSoftwareVersion(), + opResult.getDeviceDetails().getHardwareVersion())); + syncHandler.notifyResult(opResult); + } + + @Override + public void handleNotification(DeviceInform notification) { + boolean isAlarmVC = isAlarmVC(notification); + + if (notification instanceof BootstrapInform) { + logger.info("BootStrap notification received"); + BootstrapInform bootstrapNotification = (BootstrapInform) notification; + + DeviceOperationDetails deviceDetails = + deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); + if (deviceDetails == null) { + deviceDetails = new DeviceOperationDetails(); + deviceDetails.setDeviceId(notification.getDeviceDetails().getDeviceId()); + deviceDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion()); + deviceOperDAO.save(deviceDetails); + } + + checkForActivateNotification(notification); + + // send request to create the netconf server instance for the bootstrap device + // id + NetConfServerDetails serverInfo = createNtConfServer(bootstrapNotification); + if (serverInfo == null) + return; + + vesnotiSender.sendNotification(bootstrapNotification, serverInfo); + BootstrapInform bsInform = + getDeviceBootStrapNotification(bootstrapNotification, TR069InformType.BOOTSTRAP); + ValueChangeInform vcInform = null; + if (bootstrapNotification.getValueChangeNotification() != null) { + logger.info("Bootstrap notification received along with VC"); + vcInform = + getDeviceValueChangeNotification(bootstrapNotification, TR069InformType.VALUECHANGE); + processVCNotification(vcInform, isAlarmVC); + } + notiSender.sendNotification(bsInform); + if (vcInform != null) + processVCNotification(vcInform, isAlarmVC); + } else if (notification instanceof BootInform) { + logger.info("Boot notification received"); + + NetConfServerDetails serverInfo = createNtConfServer(notification); + if (serverInfo == null) + return; + + checkForActivateNotification(notification); + BootInform bootNotification = (BootInform) notification; + BootInform bInform = getDeviceBootNotification(bootNotification, TR069InformType.BOOT); + ValueChangeInform vcInform = null; + if (bootNotification.getValueChangeNotification() != null) { + logger.info("Boot notification received along with VC"); + vcInform = getDeviceValueChangeNotification(bootNotification, TR069InformType.VALUECHANGE); + } + notiSender.sendNotification(bInform); + processVCNotification(vcInform, isAlarmVC); + } else if (notification instanceof PeriodicInform) { + PeriodicInform pINotificaiton = (PeriodicInform) notification; + vesnotiSender.sendNotification(pINotificaiton, null); + notiSender.sendNotification(pINotificaiton); + logger.info("PI notification received"); + } else if (notification instanceof ConnectionRequestInform) { + ConnectionRequestInform crNotificaiton = (ConnectionRequestInform) notification; + vesnotiSender.sendNotification(crNotificaiton, null); + logger.info("ConnectionRequestInform notification received"); + } else if (notification instanceof ValueChangeInform) { + ValueChangeInform valueChgNotificaiton = (ValueChangeInform) notification; + processVCNotification(valueChgNotificaiton, isAlarmVC); + } else if (notification instanceof TransferCompleteInform) { + TransferCompleteInform tfNotificaiton = (TransferCompleteInform) notification; + if (tfNotificaiton.getCommandKey() != null && tfNotificaiton.getCommandKey() + .equalsIgnoreCase(tfNotificaiton.getDeviceDetails().getDeviceId())) { + logger.debug("TransferCompleteInform is recevied at mapper"); + processTransferCompleteInform(tfNotificaiton); + logger.debug("TransferCompleteInform processing completed at mapper"); + } + } + + pnpPreProvisioningHandler.onDeviceNotification(notification); + } + + private NetConfServerDetails createNtConfServer(DeviceInform inform) { + String eNodeBName = pnpPreProvisioningHandler.getEnodeBName( + inform.getDeviceDetails().getDeviceId(), inform.getDeviceDetails().getSoftwareVersion(), + inform.getDeviceDetails().getHardwareVersion()); + if (eNodeBName == null) + eNodeBName = inform.getDeviceDetails().getDeviceId(); + NetConfServerDetails serverInfo = + netconfManager.createNetconfServer(inform.getDeviceDetails().getDeviceId(), eNodeBName, + inform.getDeviceDetails().getSoftwareVersion(), + inform.getDeviceDetails().getHardwareVersion()); + if (serverInfo != null && !NetconfServerManagementError.SUCCESS.equals(serverInfo.getError())) { + logger.error("Failed to handle boot/bootstrap notification. Server INFO: {}", serverInfo); + logger.error("Failed to create the netconf server for device ID: {} Error: {}", + inform.getDeviceDetails().getDeviceId(), serverInfo.getError()); + return null; + } else if (serverInfo == null) { + logger.error( + "Failed to handle bootstrap notification. Failed to create netconf server. serverInfo is null"); + return null; + } + return serverInfo; + } + + private void processVCNotification(ValueChangeInform valueChgNotificaiton, boolean isAlarmVC) { + if (isAlarmVC) { + logger.debug("Alarm VC received forwarding to VES Collector"); + vesnotiSender.sendNotification(valueChgNotificaiton, null); + } + logger.info("VC notification received"); + notiSender.sendNotification(valueChgNotificaiton); + } + + private boolean isAlarmVC(DeviceInform notification) { + if (null != notification && null != notification.getParameters()) { + for (ParameterDTO param : notification.getParameters()) { + if (param.getParamName().matches(config.getAlarmMORegex())) { + logger.debug("This VC contains alarm MOs"); + return true; + } + } + } + return false; + } + + public List filterUnsupportedParameters(List parameters, + String swVersion, String hwVersion) { + List result = new ArrayList<>(); + if (null != parameters) { + for (ParameterDTO param : parameters) { + MOMetaData metaData = + metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); + if (null != metaData) { + result.add(param); + } + } + } + return result; + } + + public static BootstrapInform getDeviceBootStrapNotification(DeviceInform devNotification, + TR069InformType notificationType) { + BootstrapInform bsInform = new BootstrapInform(); + List informTypeList = new ArrayList<>(); + informTypeList.add(notificationType); + bsInform.setDeviceDetails(devNotification.getDeviceDetails()); + bsInform.setInformTypeList(informTypeList); + List paramList = new ArrayList<>(); + for (ParameterDTO param : devNotification.getParameters()) { + paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); + } + bsInform.setParameters(paramList); + return bsInform; + } + + public static BootInform getDeviceBootNotification(DeviceInform devNotification, + TR069InformType notificationType) { + BootInform bInform = new BootInform(); + List informTypeList = new ArrayList<>(); + informTypeList.add(notificationType); + bInform.setDeviceDetails(devNotification.getDeviceDetails()); + bInform.setInformTypeList(informTypeList); + List paramList = new ArrayList<>(); + for (ParameterDTO param : devNotification.getParameters()) { + paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); + } + bInform.setParameters(paramList); + return bInform; + } + + public static ValueChangeInform getDeviceValueChangeNotification(DeviceInform devNotification, + TR069InformType notificationType) { + ValueChangeInform devValChangeNotif = new ValueChangeInform(); + List informTypeList = new ArrayList<>(); + informTypeList.add(notificationType); + devValChangeNotif.setDeviceDetails(devNotification.getDeviceDetails()); + devValChangeNotif.setInformTypeList(informTypeList); + List paramList = new ArrayList<>(); + for (ParameterDTO param : devNotification.getParameters()) { + paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue())); + } + devValChangeNotif.setParameters(paramList); + devValChangeNotif.setExternalIPAddress(getExternalIPAddress(devNotification.getParameters())); + return devValChangeNotif; + } + + private static String getExternalIPAddress(List params) { + ParameterDTO[] nbiParam = params.toArray(new ParameterDTO[params.size()]); + String externalIpAddress = ""; + boolean isIPv6 = isIPv6Enabled(nbiParam); + + for (int index1 = 0; index1 < nbiParam.length; index1++) { + + if (isIPv6) { + if (nbiParam[index1].getParamName().contains("IPv6Address") + || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) { + externalIpAddress = nbiParam[index1].getParamValue(); + logger.debug("device communicating is with IPV6 address"); + } + } else { + if (nbiParam[index1].getParamName().contains("IPv4Address") + || nbiParam[index1].getParamName().contains("ExternalIPAddress") + || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) { + externalIpAddress = nbiParam[index1].getParamValue(); + } + } + if (externalIpAddress.trim().length() > 0) + break; + } + return externalIpAddress; + } + + private static boolean isIPv6Enabled(ParameterDTO[] nbiParam) { + boolean isIPv6 = false; + for (int index1 = 0; index1 < nbiParam.length; index1++) { + if (nbiParam[index1].getParamName().contains("IPv6Enable") + && nbiParam[index1].getParamValue().equalsIgnoreCase("1")) { + isIPv6 = true; + break; + } + } + return isIPv6; + } + + private void processTransferCompleteInform(TransferCompleteInform notification) { + + try { + ArrayList paramList = new ArrayList<>(); + DeviceOperationDetails fwDetails = + deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); + if (fwDetails == null || fwDetails.getFileName() == null) { + logger.debug( + "TransferCompleteInform recevied for invaild device, there is no entry exist in the database"); + return; + } + if (fwDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) { + paramList.add(new ParameterDTO("download-event.file-name", fwDetails.getFileName())); + + String status = FirwareUpgradeErrorCode.getErrorCodeMapping(notification.getFaultCode()); + paramList.add(new ParameterDTO("download-event.status", status)); + if (notification.getFaultCode() != 0) { + fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_FAILED.getStatus()); + paramList + .add(new ParameterDTO("download-event.error-message", notification.getFaultString())); + } else { + fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()); + logger.debug("downloading file completed on the device successfully."); + } + deviceOperDAO.save(fwDetails); + + if(fwDetails.getOrigin().equals("csem")) + { + logger.debug("sending transferComplete-event notification to netconfserver"); + notiSender.sendTransferCompleteNotification(notification); + } + logger.debug("sending download-event notification to netconfserver"); + if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(), + paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) { + logger.debug("sending download-event notification to netconfserver sucess"); + } else { + logger.error("sending download-event notification to netconfserver failed"); + } + } else { + logger.debug( + "TransferCompleteInform recevied after boot is received; already software is activated"); + } + } catch (Exception e) { + logger.debug("Exception occured while processing TransferCompleteInform: {}" , e.getMessage()); + } + } + + private void checkForActivateNotification(DeviceInform notification) { + + try { + ArrayList paramList = new ArrayList<>(); + DeviceOperationDetails devDetails = + deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); + + if (devDetails == null + || devDetails.getDownLoadStatus() == FirwareUpgradeStatus.NOT_STARTED.getStatus()) { + logger.debug("firmware upgrade is not in progress"); + return; + } + + if (!notification.getDeviceDetails().getSoftwareVersion() + .equalsIgnoreCase(devDetails.getSwVersion()) + && devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) { + logger.debug("received the boot/bootstrap before the transfer complete recevied"); + TransferCompleteInform inform = new TransferCompleteInform(); + inform.setDeviceDetails(notification.getDeviceDetails()); + inform.setFaultCode(0); + processTransferCompleteInform(inform); + } + + devDetails = deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId()); + if (devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) { + paramList.add(new ParameterDTO("activation-event.slot-name", "Active-Partion")); + // check for software change + if (notification.getDeviceDetails().getSoftwareVersion() + .equalsIgnoreCase(devDetails.getSwVersion())) { + paramList.add(new ParameterDTO("activation-event.status", "APPLICATION_ERROR")); + paramList.add(new ParameterDTO("activation-event.error-message", + "Same Software Version is reported after upgrade")); + devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_ERROR.getStatus()); + } else { + devDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion()); + devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_COMPLETED.getStatus()); + paramList.add(new ParameterDTO("activation-event.status", "COMPLETED")); + } + deviceOperDAO.save(devDetails); + + logger.debug("sending activation-event notification to netconfserver"); + + if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(), + paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) { + logger.debug("sending activation-event notification to netconfserver sucess"); + } else { + logger.error("sending activation-event notification to netconfserver failed"); + } + } + } catch (Exception e) { + logger.debug( + "Exception occured while processing ProcessFirmWareActivateNotification {}" , e.getMessage()); + } + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/PnPPreProvisioningHandler.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/PnPPreProvisioningHandler.java index a3a1fd5..6cc9d7e 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/PnPPreProvisioningHandler.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/acs/impl/PnPPreProvisioningHandler.java @@ -1,333 +1,335 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.acs.impl; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.acs.common.inform.BootInform; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.mapper.MOMetaData; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; -import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; -import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; - -@Component -public class PnPPreProvisioningHandler { - - private static final Logger logger = LoggerFactory.getLogger(PnPPreProvisioningHandler.class); - - private static String clientString = "client"; - private static final String ADMIN_STATE = "AdminState"; - private static final String ENODEB_NAME = "X_0005B9_eNBName"; - - @Autowired - SynchronizedRequestHandler syncHandler; - - @Autowired - MOMetaDataUtil moMetaDataUtil; - - @Autowired - MapperConfigProperties config; - - private RestTemplate restTemplate = new RestTemplate(); - - /** - * @param notification - */ - public void onDeviceNotification(DeviceInform notification) { - String deviceId = null; - try { - if (notification instanceof BootstrapInform || notification instanceof BootInform) { - logger.debug("Checking whether the PnP pre-configuration is enabled"); - if (isPreConfigureOnPnPEnabled()) { - logger.info( - "Pre-configuration during Bootstrap or Boot is enabled, hence the configuration imported in Config DB shall be provisioned to the device"); - } else { - logger.debug("Pre-configuration on PnP is disabled!!!"); - return; - } - } - - if (notification instanceof BootstrapInform) { - BootstrapInform bootstrapNotification = (BootstrapInform) notification; - deviceId = bootstrapNotification.getDeviceDetails().getDeviceId(); - MDC.put(clientString, deviceId); - logger.info("Bootstrap notification received"); - performPreProvisioning(deviceId, - bootstrapNotification.getDeviceDetails().getSoftwareVersion(), - bootstrapNotification.getDeviceDetails().getHardwareVersion(), false); - - } else if (notification instanceof BootInform) { - BootInform bootNotification = (BootInform) notification; - deviceId = bootNotification.getDeviceDetails().getDeviceId(); - MDC.put(clientString, deviceId); - logger.info("Boot notification received"); - - performPreProvisioning(deviceId, bootNotification.getDeviceDetails().getSoftwareVersion(), - bootNotification.getDeviceDetails().getHardwareVersion(), true); - } - - logger.debug("Successfully completed provisioning of PnP mandatory parameters"); - } finally { - MDC.remove(clientString); - } - } - - /** - * @param deviceId - * @param isBoot - */ - private void performPreProvisioning(String deviceId, String swVersion, String hwVersion, - boolean isBoot) { - List deviceRPCRequestList = - prepareNBIDeviceOperationrequest(deviceId, swVersion, hwVersion, isBoot); - if (deviceRPCRequestList.isEmpty()) { - logger.debug("No Operation requests exists to perform pre provision on the device"); - return; - } - - boolean isMandatoryProvFailed = false; - for (DeviceRPCRequest deviceRPCRequest : deviceRPCRequestList) { - logger.info("Performing PROVISION operation"); - DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest); - logger.debug("Received Provisioning Operation result"); - if (deviceRPCResponse != null && !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) { - logger.error("Device operation failed, Reason: {}", deviceRPCResponse.getFaultString()); - isMandatoryProvFailed = true; - break; - } - - logger.debug("Provisioning is successful"); - } - - if (isMandatoryProvFailed) { - logger - .debug("Mandatory provisioning has failed, hence provisioning Admin down on the device"); - provisionAdminDown(deviceRPCRequestList); - logger.debug("AdminDown Provisioning is successful"); - } - } - - private void provisionAdminDown(List deviceRPCRequestList) { - DeviceRPCRequest adminDownOpRequest = null; - for (DeviceRPCRequest nbiDeviceOperationRequest : deviceRPCRequestList) { - ParameterDTO param = nbiDeviceOperationRequest.getOpDetails().getParmeters().get(0); - if (param.getParamName().endsWith(ADMIN_STATE)) { - adminDownOpRequest = nbiDeviceOperationRequest; - break; - } - } - if (adminDownOpRequest != null) { - List adminDownParams = adminDownOpRequest.getOpDetails().getParmeters(); - for (ParameterDTO adminDownParam : adminDownParams) { - adminDownParam.setParamValue("0"); - } - DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(adminDownOpRequest); - if (deviceRPCResponse == null || !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) { - logger.error("Device operation failed, Reason: {}", ((deviceRPCResponse == null) - ? "Null Operation result" : deviceRPCResponse.getFaultString())); - } - } - } - - /** - * @param deviceId - * @param isBoot - * @return - */ - private List prepareNBIDeviceOperationrequest(String deviceId, String swVersion, - String hwVersion, boolean isBoot) { - logger.debug("Preparing the NBI Device Operation Request"); - List deviceRPCRequestList = new ArrayList<>(); - - ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion); - if (configData == null || configData.getParameterMONameValueMap().isEmpty()) { - logger.debug("No configuration exists for the device"); - return deviceRPCRequestList; - } - - List configParams = new ArrayList<>(); - List adminStateParams = new ArrayList<>(); - Map paramNameValueMap = configData.getParameterMONameValueMap(); - Iterator iter = paramNameValueMap.keySet().iterator(); - while (iter.hasNext()) { - String paramName = iter.next(); - String paramValue = paramNameValueMap.get(paramName); - MOMetaData moMetaData = moMetaDataUtil.getMetaDataByTR69Name(paramName, swVersion, hwVersion); - if ((isBoot && !paramName.endsWith(ADMIN_STATE)) || moMetaData == null) - continue; - ParameterDTO parameterDTO = getParameterDTO(paramName, paramValue, moMetaData); - - if (paramName.endsWith(ADMIN_STATE)) { - adminStateParams.add(parameterDTO); - } else { - configParams.add(parameterDTO); - } - logger.debug("Param -> {} Param Value: {}", paramName, paramValue); - } - - if (configParams.isEmpty() && adminStateParams.isEmpty()) { - logger.debug("Empty parameters list from config db, hence not performing pre-provision"); - return deviceRPCRequestList; - } - - if (!configParams.isEmpty()) { - deviceRPCRequestList.add(createNBIOperationRequest(deviceId, configParams)); - } - - if (!adminStateParams.isEmpty()) { - deviceRPCRequestList.add(createNBIOperationRequest(deviceId, adminStateParams)); - } - - return deviceRPCRequestList; - } - - private ParameterDTO getParameterDTO(String paramName, String paramValue, MOMetaData moMetaData) { - String dataType = moMetaData.getDataType(); - if (dataType.equals("boolean")) { - if (paramValue.equalsIgnoreCase("true")) { - paramValue = "1"; - } else if (paramValue.equalsIgnoreCase("false")) { - paramValue = "0"; - } - } - ParameterDTO parameterDTO = new ParameterDTO(paramName, paramValue); - parameterDTO.setDataType(dataType); - - return parameterDTO; - } - - /** - * @param deviceId - * @param params - * @return - */ - private DeviceRPCRequest createNBIOperationRequest(String deviceId, List params) { - TR069OperationDetails opDetails = new TR069OperationDetails(); - opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES); - - return NetconfToTr069MapperUtil.handleParamsOperation(params, opDetails, deviceId); - - } - - /** - * @param deviceId - * @return - */ - private ConfigurationData getDeviceConfigurationData(String deviceId, String swVersion, - String hwVersion) { - String configDBURI = getConfigDBURI(); - logger.debug( - "Device Configuration to be fetched from Config DB URI: {}, macId {}, swVersion {}, hwVersion {}", - configDBURI, deviceId, swVersion, hwVersion); - ConfigurationData configData = null; - try { - - MultiValueMap uriParams = new LinkedMultiValueMap<>(); - uriParams.add("macId", deviceId); - uriParams.add("swVersion", swVersion); - uriParams.add("hwVersion", hwVersion); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - final HttpEntity> entity = new HttpEntity<>(uriParams, headers); - - ResponseEntity res = - restTemplate.postForEntity(configDBURI, entity, ConfigurationData.class); - configData = res.getBody(); - logger.debug("Successfully retrived config data for device id{} data {}", deviceId, - configData); - } catch (Exception e) { - logger.error("An exception occurred to get the initial device configuration, Reason: {}", - e.getMessage()); - } - return configData; - } - - /** - * @return - */ - private boolean isPreConfigureOnPnPEnabled() { - boolean isEnabled = false; - String preConfigureOnPnP = config.getPreConfigureOnPNP(); - if (preConfigureOnPnP != null && ("true".equalsIgnoreCase(preConfigureOnPnP) - || "false".equalsIgnoreCase(preConfigureOnPnP))) { - isEnabled = Boolean.valueOf(preConfigureOnPnP); - } - - return isEnabled; - } - - /** - * @return - */ - private String getConfigDBURI() { - return config.getConfigDBUri(); - - } - - /** - * it will return the eNodBName if the configuration is imported - * - * @return String - */ - public String getEnodeBName(String deviceId, String swVersion, String hwVersion) { - String eNodeBName = null; - if (isPreConfigureOnPnPEnabled()) { - ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion); - if (configData == null || configData.getParameterMONameValueMap().isEmpty()) { - logger.debug("No configuration exists for the device"); - return eNodeBName; - } - - Map paramNameValueMap = configData.getParameterMONameValueMap(); - Iterator iter = paramNameValueMap.keySet().iterator(); - while (iter.hasNext()) { - String paramName = iter.next(); - if (paramName.endsWith(ENODEB_NAME)) { - eNodeBName = paramNameValueMap.get(paramName); - break; - } - } - } - return eNodeBName; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.acs.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.acs.common.inform.BootInform; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.mapper.MOMetaData; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; +import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; +import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +@Component +public class PnPPreProvisioningHandler { + + private static final Logger logger = LoggerFactory.getLogger(PnPPreProvisioningHandler.class); + + private static String clientString = "client"; + private static final String ADMIN_STATE = "AdminState"; + private static final String ENODEB_NAME = "X_0005B9_eNBName"; + + @Autowired + SynchronizedRequestHandler syncHandler; + + @Autowired + MOMetaDataUtil moMetaDataUtil; + + @Autowired + MapperConfigProperties config; + + private RestTemplate restTemplate = new RestTemplate(); + + /** + * @param notification + */ + public void onDeviceNotification(DeviceInform notification) { + String deviceId = null; + try { + if (notification instanceof BootstrapInform || notification instanceof BootInform) { + logger.debug("Checking whether the PnP pre-configuration is enabled"); + if (isPreConfigureOnPnPEnabled()) { + logger.info( + "Pre-configuration during Bootstrap or Boot is enabled, hence the configuration imported in Config DB shall be provisioned to the device"); + } else { + logger.debug("Pre-configuration on PnP is disabled!!!"); + return; + } + } + + if (notification instanceof BootstrapInform) { + BootstrapInform bootstrapNotification = (BootstrapInform) notification; + deviceId = bootstrapNotification.getDeviceDetails().getDeviceId(); + MDC.put(clientString, deviceId); + logger.info("Bootstrap notification received"); + performPreProvisioning(deviceId, + bootstrapNotification.getDeviceDetails().getSoftwareVersion(), + bootstrapNotification.getDeviceDetails().getHardwareVersion(), false); + + } else if (notification instanceof BootInform) { + BootInform bootNotification = (BootInform) notification; + deviceId = bootNotification.getDeviceDetails().getDeviceId(); + MDC.put(clientString, deviceId); + logger.info("Boot notification received"); + + performPreProvisioning(deviceId, bootNotification.getDeviceDetails().getSoftwareVersion(), + bootNotification.getDeviceDetails().getHardwareVersion(), true); + } + + logger.debug("Successfully completed provisioning of PnP mandatory parameters"); + } finally { + MDC.remove(clientString); + } + } + + /** + * @param deviceId + * @param isBoot + */ + private void performPreProvisioning(String deviceId, String swVersion, String hwVersion, + boolean isBoot) { + List deviceRPCRequestList = + prepareNBIDeviceOperationrequest(deviceId, swVersion, hwVersion, isBoot); + if (deviceRPCRequestList.isEmpty()) { + logger.debug("No Operation requests exists to perform pre provision on the device"); + return; + } + + boolean isMandatoryProvFailed = false; + for (DeviceRPCRequest deviceRPCRequest : deviceRPCRequestList) { + logger.info("Performing PROVISION operation"); + DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest); + logger.debug("Received Provisioning Operation result"); + if (deviceRPCResponse != null && !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) { + logger.error("Device operation failed, Reason: {}", deviceRPCResponse.getFaultString()); + isMandatoryProvFailed = true; + break; + } + + logger.debug("Provisioning is successful"); + } + + if (isMandatoryProvFailed) { + logger + .debug("Mandatory provisioning has failed, hence provisioning Admin down on the device"); + provisionAdminDown(deviceRPCRequestList); + logger.debug("AdminDown Provisioning is successful"); + } + } + + private void provisionAdminDown(List deviceRPCRequestList) { + DeviceRPCRequest adminDownOpRequest = null; + for (DeviceRPCRequest nbiDeviceOperationRequest : deviceRPCRequestList) { + ParameterDTO param = nbiDeviceOperationRequest.getOpDetails().getParmeters().get(0); + if (param.getParamName().endsWith(ADMIN_STATE)) { + adminDownOpRequest = nbiDeviceOperationRequest; + break; + } + } + if (adminDownOpRequest != null) { + List adminDownParams = adminDownOpRequest.getOpDetails().getParmeters(); + for (ParameterDTO adminDownParam : adminDownParams) { + adminDownParam.setParamValue("0"); + } + DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(adminDownOpRequest); + if (deviceRPCResponse == null || !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) { + logger.error("Device operation failed, Reason: {}", + ((deviceRPCResponse == null) ? "Null Operation result" + : deviceRPCResponse.getFaultString())); + } + } + } + + /** + * @param deviceId + * @param isBoot + * @return + */ + private List prepareNBIDeviceOperationrequest(String deviceId, String swVersion, + String hwVersion, boolean isBoot) { + logger.debug("Preparing the NBI Device Operation Request"); + List deviceRPCRequestList = new ArrayList<>(); + + ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion); + if (configData == null || configData.getParameterMONameValueMap().isEmpty()) { + logger.debug("No configuration exists for the device"); + return deviceRPCRequestList; + } + + List configParams = new ArrayList<>(); + List adminStateParams = new ArrayList<>(); + Map paramNameValueMap = configData.getParameterMONameValueMap(); + Iterator iter = paramNameValueMap.keySet().iterator(); + while (iter.hasNext()) { + String paramName = iter.next(); + String paramValue = paramNameValueMap.get(paramName); + MOMetaData moMetaData = moMetaDataUtil.getMetaDataByTR69Name(paramName, swVersion, hwVersion); + if ((isBoot && !paramName.endsWith(ADMIN_STATE)) || moMetaData == null) + continue; + ParameterDTO parameterDTO = getParameterDTO(paramName, paramValue, moMetaData); + + if (paramName.endsWith(ADMIN_STATE)) { + adminStateParams.add(parameterDTO); + } else { + configParams.add(parameterDTO); + } + logger.debug("Param -> {} Param Value: {}", paramName, paramValue); + } + + if (configParams.isEmpty() && adminStateParams.isEmpty()) { + logger.debug("Empty parameters list from config db, hence not performing pre-provision"); + return deviceRPCRequestList; + } + + if (!configParams.isEmpty()) { + deviceRPCRequestList.add(createNBIOperationRequest(deviceId, configParams)); + } + + if (!adminStateParams.isEmpty()) { + deviceRPCRequestList.add(createNBIOperationRequest(deviceId, adminStateParams)); + } + + return deviceRPCRequestList; + } + + private ParameterDTO getParameterDTO(String paramName, String paramValue, MOMetaData moMetaData) { + String dataType = moMetaData.getDataType(); + if (dataType.equals("boolean")) { + if (paramValue.equalsIgnoreCase("true")) { + paramValue = "1"; + } else if (paramValue.equalsIgnoreCase("false")) { + paramValue = "0"; + } + } + ParameterDTO parameterDTO = new ParameterDTO(paramName, paramValue); + parameterDTO.setDataType(dataType); + + return parameterDTO; + } + + /** + * @param deviceId + * @param params + * @return + */ + private DeviceRPCRequest createNBIOperationRequest(String deviceId, List params) { + TR069OperationDetails opDetails = new TR069OperationDetails(); + opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES); + + return NetconfToTr069MapperUtil.handleParamsOperation(params, opDetails, deviceId); + + } + + /** + * @param deviceId + * @return + */ + private ConfigurationData getDeviceConfigurationData(String deviceId, String swVersion, + String hwVersion) { + String configDBURI = getConfigDBURI(); + logger.debug( + "Device Configuration to be fetched from Config DB URI: {}, macId {}, swVersion {}, hwVersion {}", + configDBURI, deviceId, swVersion, hwVersion); + ConfigurationData configData = null; + try { + + MultiValueMap uriParams = new LinkedMultiValueMap<>(); + uriParams.add("macId", deviceId); + uriParams.add("swVersion", swVersion); + uriParams.add("hwVersion", hwVersion); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + final HttpEntity> entity = new HttpEntity<>(uriParams, headers); + + ResponseEntity res = + restTemplate.postForEntity(configDBURI, entity, ConfigurationData.class); + configData = res.getBody(); + logger.debug("Successfully retrived config data for device id{} data {}", deviceId, + configData); + } catch (Exception e) { + logger.error("An exception occurred to get the initial device configuration, Reason: {}", + e.getMessage()); + } + return configData; + } + + /** + * @return + */ + private boolean isPreConfigureOnPnPEnabled() { + boolean isEnabled = false; + String preConfigureOnPnP = config.getPreConfigureOnPNP(); + if (preConfigureOnPnP != null && ("true".equalsIgnoreCase(preConfigureOnPnP) + || "false".equalsIgnoreCase(preConfigureOnPnP))) { + isEnabled = Boolean.valueOf(preConfigureOnPnP); + } + + return isEnabled; + } + + /** + * @return + */ + private String getConfigDBURI() { + return config.getConfigDBUri(); + + } + + /** + * it will return the eNodBName if the configuration is imported + * + * @return String + */ + public String getEnodeBName(String deviceId, String swVersion, String hwVersion) { + String eNodeBName = null; + if (isPreConfigureOnPnPEnabled()) { + ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion); + if (configData == null || configData.getParameterMONameValueMap().isEmpty()) { + logger.debug("No configuration exists for the device"); + return eNodeBName; + } + + Map paramNameValueMap = configData.getParameterMONameValueMap(); + Iterator iter = paramNameValueMap.keySet().iterator(); + while (iter.hasNext()) { + String paramName = iter.next(); + if (paramName.endsWith(ENODEB_NAME)) { + eNodeBName = paramNameValueMap.get(paramName); + break; + } + } + } + return eNodeBName; + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/boot/MapperServiceBooter.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/boot/MapperServiceBooter.java index 27cfe12..2127e5e 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/boot/MapperServiceBooter.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/boot/MapperServiceBooter.java @@ -1,46 +1,46 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.web.client.RestTemplate; - -@SpringBootApplication -@ComponentScan({"org.commscope.tr069adapter.mapper", "org.commscope.tr069adapter.mapper.acs", - "org.commscope.tr069adapter.mapper.ves", "org.commscope.tr069adapter.common"}) -@EnableJpaRepositories("org.commscope.tr069adapter.mapper.dao") -@EntityScan("org.commscope.tr069adapter.mapper.entity") -public class MapperServiceBooter { - - public static void main(String[] args) { - SpringApplication.run(MapperServiceBooter.class, args); - } - - @Bean - public RestTemplate restTemplate(RestTemplateBuilder builder) { - return builder.build(); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.client.RestTemplate; + +@SpringBootApplication +@ComponentScan({"org.commscope.tr069adapter.mapper", "org.commscope.tr069adapter.mapper.acs", + "org.commscope.tr069adapter.mapper.ves", "org.commscope.tr069adapter.common"}) +@EnableJpaRepositories("org.commscope.tr069adapter.mapper.dao") +@EntityScan("org.commscope.tr069adapter.mapper.entity") +public class MapperServiceBooter { + + public static void main(String[] args) { + SpringApplication.run(MapperServiceBooter.class, args); + } + + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/entity/DeviceOperationDetails.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/entity/DeviceOperationDetails.java index 82b1aff..baef55f 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/entity/DeviceOperationDetails.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/entity/DeviceOperationDetails.java @@ -16,75 +16,87 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.mapper.entity; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -@Entity -@Table(name = "device_operation_details", - uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"})) -public class DeviceOperationDetails implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(name = "DEVICE_ID", length = 30) - private String deviceId; - - @Column(name = "SW_VERSION", length = 30) - private String swVersion; - - @Column(name = "DOWN_LOAD_STATUS") - private int downLoadStatus; - - @Column(name = "FIRMWARE_FILE", length = 1024) - private String fileName; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public int getDownLoadStatus() { - return downLoadStatus; - } - - public void setDownLoadStatus(int downLoadStatus) { - this.downLoadStatus = downLoadStatus; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } -} +package org.commscope.tr069adapter.mapper.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +@Entity +@Table(name = "device_operation_details", + uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"})) +public class DeviceOperationDetails implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "DEVICE_ID", length = 30) + private String deviceId; + + @Column(name = "SW_VERSION", length = 30) + private String swVersion; + + @Column(name = "DOWN_LOAD_STATUS") + private int downLoadStatus; + + @Column(name = "FIRMWARE_FILE", length = 1024) + private String fileName; + + @Column(name = "ORIGIN", length = 30) + private String origin; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public int getDownLoadStatus() { + return downLoadStatus; + } + + public void setDownLoadStatus(int downLoadStatus) { + this.downLoadStatus = downLoadStatus; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getOrigin() { + return origin; + } + + public void setOrigin(String origin) { + this.origin = origin; + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfNotificationDTO.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfNotificationDTO.java index dfd0c4e..0fb69b0 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfNotificationDTO.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfNotificationDTO.java @@ -19,14 +19,16 @@ package org.commscope.tr069adapter.mapper.model; import java.io.Serializable; + import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class NetConfNotificationDTO implements Serializable { private static final long serialVersionUID = 4928942484595767042L; - private String deviceID; private String notificaiton; + private String deviceID; public NetConfNotificationDTO() { super(); diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfRequest.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfRequest.java index 40a926c..88978dd 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfRequest.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfRequest.java @@ -1,83 +1,83 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.model; - -import java.io.Serializable; - -public class NetConfRequest implements Serializable { - - private static final long serialVersionUID = -7593813981401577995L; - - private String requestXml; - - // operation status - private String deviceId; - private String swVersion; - private String hwVersion; - - public NetConfRequest() { - super(); - } - - public NetConfRequest(String requestXml, String deviceId, String swVersion, String hwVersion) { - super(); - this.requestXml = requestXml; - this.deviceId = deviceId; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - public String getRequestXml() { - return requestXml; - } - - public void setRequestXml(String requestXml) { - this.requestXml = requestXml; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } - - @Override - public String toString() { - return "NetConfRequest [RequestXml=" + requestXml + ", deviceId=" + deviceId + "]"; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.model; + +import java.io.Serializable; + +public class NetConfRequest implements Serializable { + + private static final long serialVersionUID = -7593813981401577995L; + + private String requestXml; + + // operation status + private String deviceId; + private String swVersion; + private String hwVersion; + + public NetConfRequest() { + super(); + } + + public NetConfRequest(String requestXml, String deviceId, String swVersion, String hwVersion) { + super(); + this.requestXml = requestXml; + this.deviceId = deviceId; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + public String getRequestXml() { + return requestXml; + } + + public void setRequestXml(String requestXml) { + this.requestXml = requestXml; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } + + @Override + public String toString() { + return "NetConfRequest [RequestXml=" + requestXml + ", deviceId=" + deviceId + "]"; + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfServerDetails.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfServerDetails.java index d79a679..625dac0 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfServerDetails.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/NetConfServerDetails.java @@ -1,108 +1,108 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.model; - -import java.io.Serializable; - -public class NetConfServerDetails implements Serializable { - - private static final long serialVersionUID = -7594811982301577995L; - - private String deviceId; - private String enodeBName; - private String listenAddress; - private String listenPort; - private String swVersion; - private String hwVersion; - - private NetconfServerManagementError error; - - public NetConfServerDetails() { - super(); - } - - public NetConfServerDetails(String deviceId, String listenAddress, String listenPort) { - super(); - this.deviceId = deviceId; - this.listenAddress = listenAddress; - this.listenPort = listenPort; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String getListenAddress() { - return listenAddress; - } - - public void setListenAddress(String listenAddress) { - this.listenAddress = listenAddress; - } - - public String getListenPort() { - return listenPort; - } - - public void setListenPort(String listenPort) { - this.listenPort = listenPort; - } - - public NetconfServerManagementError getError() { - return error; - } - - public void setError(NetconfServerManagementError error) { - this.error = error; - } - - public String getEnodeBName() { - return enodeBName; - } - - public void setEnodeBName(String enodeBName) { - this.enodeBName = enodeBName; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } - - @Override - public String toString() { - return "NetConfServerDetails [deviceId=" + deviceId + ", enodeBName=" + enodeBName - + ", listenAddress=" + listenAddress + ", listenPort=" + listenPort + ", swversion=" - + swVersion + ", hwversion=" + hwVersion + ", error=" + error + "]"; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.model; + +import java.io.Serializable; + +public class NetConfServerDetails implements Serializable { + + private static final long serialVersionUID = -7594811982301577995L; + + private String deviceId; + private String enodeBName; + private String listenAddress; + private String listenPort; + private String swVersion; + private String hwVersion; + + private NetconfServerManagementError error; + + public NetConfServerDetails() { + super(); + } + + public NetConfServerDetails(String deviceId, String listenAddress, String listenPort) { + super(); + this.deviceId = deviceId; + this.listenAddress = listenAddress; + this.listenPort = listenPort; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getListenAddress() { + return listenAddress; + } + + public void setListenAddress(String listenAddress) { + this.listenAddress = listenAddress; + } + + public String getListenPort() { + return listenPort; + } + + public void setListenPort(String listenPort) { + this.listenPort = listenPort; + } + + public NetconfServerManagementError getError() { + return error; + } + + public void setError(NetconfServerManagementError error) { + this.error = error; + } + + public String getEnodeBName() { + return enodeBName; + } + + public void setEnodeBName(String enodeBName) { + this.enodeBName = enodeBName; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } + + @Override + public String toString() { + return "NetConfServerDetails [deviceId=" + deviceId + ", enodeBName=" + enodeBName + + ", listenAddress=" + listenAddress + ", listenPort=" + listenPort + ", swversion=" + + swVersion + ", hwversion=" + hwVersion + ", error=" + error + "]"; + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/VESNotification.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/VESNotification.java index 4c0f388..4186000 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/VESNotification.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/model/VESNotification.java @@ -18,18 +18,21 @@ package org.commscope.tr069adapter.mapper.model; -import com.fasterxml.jackson.annotation.JsonTypeInfo; - import java.io.Serializable; +import java.util.List; import org.commscope.tr069adapter.acs.common.DeviceInform; import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") +@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public class VESNotification implements Serializable { private DeviceInform devnotification; private OperationDetails operationDetails; private NetConfServerDetails netconfDetails; + private List netconfParameters; private String eNodeBName; public DeviceInform getDevnotification() { @@ -64,4 +67,12 @@ public class VESNotification implements Serializable { this.eNodeBName = eNodeBName; } + public List getNetconfParameters() { + return netconfParameters; + } + + public void setNetconfParameters(List netconfParameters) { + this.netconfParameters = netconfParameters; + } + } diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfNotificationSender.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfNotificationSender.java index aaf70d3..41e8247 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfNotificationSender.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfNotificationSender.java @@ -1,298 +1,389 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.netconf; - -import java.io.StringWriter; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.MOMetaData; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; -import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -@Component -public class NetConfNotificationSender { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfNotificationSender.class); - private static final String BOOLEAN_TRUE_VALUE = "1"; - private static final String BOOLEAN_FALSE_VALUE = "0"; - private static final String BOOLEAN_DATA_TYPE = "boolean"; - public static final String NOTIFICATION_ELEMENT_NAME = "notification"; - public static final String EVENT_TIME = "eventTime"; - private static final String INDEX_STR = "index"; - private static final String INDEX_REGEX = "[0-9]{1,}"; - - - @Autowired - MapperConfigProperties config; - - @Autowired - MOMetaDataUtil metaDataUtil; - - @Autowired - RestTemplate restTemplate; - - public ResponseEntity sendNotification(DeviceInform deviceInform) { - ResponseEntity response = null; - final String uri = getUri(); - LOG.debug("Posting notification to netconf server {}", uri); - - try { - LOG.debug("deviceInform : {} {}", deviceInform.getInformTypeList(), - deviceInform.getParameters()); - List parameters = new ArrayList<>(); - for (ParameterDTO parameterDTO : deviceInform.getParameters()) { - parameters.add(parameterDTO); - } - - convertTR069ToNetConfParams(parameters, deviceInform.getDeviceDetails().getSoftwareVersion(), - deviceInform.getDeviceDetails().getHardwareVersion()); - - String nameSpace = metaDataUtil.getMetaDataByTR69Name(deviceInform.getInformType().toString(), - deviceInform.getDeviceDetails().getSoftwareVersion(), - deviceInform.getDeviceDetails().getHardwareVersion()).getURI(); - - String notificationXml = - getNetconfResponseXML(parameters, deviceInform.getInformType().toString(), nameSpace); - NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO( - deviceInform.getDeviceDetails().getDeviceId(), notificationXml); - - LOG.debug("Posting notification to netconf server"); - response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class); - LOG.debug("Posting notification to netconf server completed "); - } catch (Exception e) { - LOG.error("Exception while sending the notification.", e); - } - return response; - } - - public ResponseEntity sendCustomNotification(String deviceId, List parameters, - String nameSpace) { - ResponseEntity response = null; - final String uri = getUri(); - LOG.debug("Posting custom notification to netconf server " + uri); - try { - String notificationXml = getNetconfResponseXML(parameters, null, nameSpace); - NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO(deviceId, notificationXml); - - response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class); - LOG.debug("Posting custom notification to netconf server sucessfull"); - } catch (Exception e) { - LOG.error("Exception while sending the custom notification.", e.toString()); - } - return response; - } - - private void convertTR069ToNetConfParams(List parameters, String swVersion, - String hwVersion) { - List removeList = new ArrayList<>(); - if (null != parameters) { - for (ParameterDTO param : parameters) { - if (param.getParamValue() == null || param.getParamValue().trim().length() <= 0) { - removeList.add(param); - continue; - } - handleBooleanParameters(param, swVersion, hwVersion); - if (null != param.getParamName()) { - String netConfMOName = metaDataUtil - .getNetconfNameByTR69NameWithIndexes(param.getParamName(), swVersion, hwVersion); - if (null != netConfMOName) - param.setParamName(netConfMOName); - else - removeList.add(param); // unknown parameter found. - } - } - parameters.removeAll(removeList); - } - } - - private void handleBooleanParameters(ParameterDTO param, String swVersion, String hwVersion) { - MOMetaData metaData = - metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); - if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { - if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(Boolean.TRUE.toString()); - } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(Boolean.FALSE.toString()); - } - } - } - - private String getUri() { - return config.getNbiNotificationUri(); - } - - private static String getNetconfResponseXML(List parameters, - String notificationType, String nameSpace) { - if (parameters == null || parameters.isEmpty()) { - LOG.debug("There are no parameters found in the response."); - return null; - } - - String result = null; - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.newDocument(); - - Map parentNodeMap = new HashMap<>(); - Element dataNode = null; // root of all nodes - - for (ParameterDTO paramDto : parameters) { - String paramName = paramDto.getParamName(); - String paramValue = paramDto.getParamValue(); - StringTokenizer tokenizer = new StringTokenizer(paramName, "."); - String parentNodeName = null; - String parentNodeKey = null; - Element parentNode = null; - while (tokenizer.hasMoreElements()) { - String nodeName = (String) tokenizer.nextElement(); - if (null == parentNodeName) { // construct first node or - // Device node - parentNodeName = nodeName; - parentNodeKey = nodeName; - // check if the node already exists in parentNodeMap - parentNode = parentNodeMap.get(parentNodeKey); - if (null == dataNode) { - dataNode = parentNode; - } - continue; - } else if (nodeName.matches(INDEX_REGEX)) { // construct - // tabular and - // index nodes - - // get parent tabular node from parent MAP - parentNodeKey = parentNodeKey + "." + nodeName; - Element node = parentNodeMap.get(parentNodeKey); - - // create a tabular parent node if doesn't exit in MAP - if (null == node) { - node = doc.createElement(parentNodeName); - parentNodeMap.put(parentNodeKey, node); - - // update current tabular parent node. - if (null != parentNode) - parentNode.appendChild(node); - else - parentNode = node; - - // prepare and add index node to tabular parent node - Element indexNode = doc.createElement(INDEX_STR); - indexNode.setTextContent(nodeName); - node.appendChild(indexNode); - } - parentNode = node; // move parent to child - parentNodeName = nodeName; - } else if (parentNodeName.matches(INDEX_REGEX)) { // move to - // next - // node - // if - // tabular - // attribute - // is - // found - parentNodeKey = parentNodeKey + "." + nodeName; - parentNodeName = nodeName; - } else { - // construct intermediate nodes - Element node = parentNodeMap.get(parentNodeKey); - if (null == node) { - if (null == dataNode) { - node = doc.createElementNS(nameSpace, parentNodeName); - dataNode = node; - } else { - node = doc.createElement(parentNodeName); - } - parentNodeMap.put(parentNodeKey, node); - if (null != parentNode) - parentNode.appendChild(node); - } - parentNodeKey = parentNodeKey + "." + nodeName; - parentNodeName = nodeName; - parentNode = node; - } - } - // construct leaf node - Element leafNode = doc.createElement(parentNodeName); - leafNode.setTextContent(paramValue); - parentNode.appendChild(leafNode); - } - - if (null != dataNode) { - final Element element = doc.createElement(NOTIFICATION_ELEMENT_NAME); - final Element eventTime = doc.createElement(EVENT_TIME); - eventTime - .setTextContent(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); - element.appendChild(element.getOwnerDocument().importNode(eventTime, true)); - - if (notificationType != null) { - final Element evtTypeElement = doc.createElementNS(nameSpace, notificationType); - evtTypeElement.appendChild(dataNode); - element.appendChild(element.getOwnerDocument().importNode(evtTypeElement, true)); - } else { - element.appendChild(element.getOwnerDocument().importNode(dataNode, true)); - } - - result = convertDocumentToString(element); - } - } catch (ParserConfigurationException pce) { - LOG.error("Exception while converting the notification: {}", pce.getMessage()); - } - - return result; - } - - public static String convertDocumentToString(Element element) { - String strxml = null; - try { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(element); - StreamResult result = new StreamResult(new StringWriter()); - transformer.transform(source, result); - strxml = result.getWriter().toString(); - } catch (Exception e) { - LOG.error("Error while converting Element to String" + e); - } - LOG.debug("Converted XML is : {}", strxml); - return strxml; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.netconf; + +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform; +import org.commscope.tr069adapter.mapper.MOMetaData; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; +import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +@Component +public class NetConfNotificationSender { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfNotificationSender.class); + private static final String BOOLEAN_TRUE_VALUE = "1"; + private static final String BOOLEAN_FALSE_VALUE = "0"; + private static final String BOOLEAN_DATA_TYPE = "boolean"; + public static final String NOTIFICATION_ELEMENT_NAME = "notification"; + public static final String EVENT_TIME = "eventTime"; + private static final String INDEX_STR = "index"; + private static final String INDEX_REGEX = "[0-9]{1,}"; + + + @Autowired + MapperConfigProperties config; + + @Autowired + MOMetaDataUtil metaDataUtil; + + @Autowired + RestTemplate restTemplate; + + public ResponseEntity sendNotification(DeviceInform deviceInform) { + ResponseEntity response = null; + final String uri = getUri(); + LOG.debug("Posting notification to netconf server {}", uri); + + try { + LOG.debug("deviceInform : {} {}", deviceInform.getInformTypeList(), + deviceInform.getParameters()); + List parameters = new ArrayList<>(); + for (ParameterDTO parameterDTO : deviceInform.getParameters()) { + if (!parameterDTO.getParamName().equalsIgnoreCase("Device.DeviceInfo.SerialNumber")) + parameters.add(parameterDTO); + } + parameters.add(new ParameterDTO("Device.DeviceInfo.SerialNumber", + deviceInform.getDeviceDetails().getDeviceId())); + + convertTR069ToNetConfParams(parameters, deviceInform.getDeviceDetails().getSoftwareVersion(), + deviceInform.getDeviceDetails().getHardwareVersion()); + + String nameSpace = metaDataUtil.getMetaDataByTR69Name(deviceInform.getInformType().toString(), + deviceInform.getDeviceDetails().getSoftwareVersion(), + deviceInform.getDeviceDetails().getHardwareVersion()).getURI(); + + String notificationXml = + getNetconfResponseXML(parameters, deviceInform.getInformType().toString(), nameSpace); + NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO( + deviceInform.getDeviceDetails().getDeviceId(), notificationXml); + + LOG.debug("Posting notification to netconf server"); + response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class); + LOG.debug("Posting notification to netconf server completed "); + } catch (Exception e) { + LOG.error("Exception while sending the notification.", e); + } + return response; + } + + public ResponseEntity sendTransferCompleteNotification(TransferCompleteInform tcInform) { + ResponseEntity response = null; + final String uri = getUri(); + LOG.debug("Posting notification to netconf server {}", uri); + + try { + // LOG.debug("deviceInform : {} {}", tcInform.getInformTypeList(), + // tcInform.getParameters()); + // List parameters = new ArrayList<>(); + // for (ParameterDTO parameterDTO : tcInform.getParameters()) { + // parameters.add(parameterDTO); + // } + + List parameters = new ArrayList<>(); + parameters.add(new ParameterDTO("command-key", tcInform.getCommandKey())); + parameters.add(new ParameterDTO("fault-code", String.valueOf(tcInform.getFaultCode()))); + parameters.add(new ParameterDTO("fault-string", tcInform.getFaultString())); + parameters.add(new ParameterDTO("start-time", tcInform.getStartTime())); + parameters.add(new ParameterDTO("complete-time", tcInform.getCompleteTime())); + + String nameSpace = metaDataUtil.getMetaDataByTR69Name(tcInform.getInformType().toString(), + tcInform.getDeviceDetails().getSoftwareVersion(), + tcInform.getDeviceDetails().getHardwareVersion()).getURI(); + + String notificationXml = + getNetConfReposneXMLForTC(parameters, tcInform.getInformType().toString(), nameSpace); + NetConfNotificationDTO netConfDTO = + new NetConfNotificationDTO(tcInform.getDeviceDetails().getDeviceId(), notificationXml); + + LOG.debug("Posting notification to netconf server"); + response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class); + LOG.debug("Posting notification to netconf server completed "); + } catch (Exception e) { + LOG.error("Exception while sending the notification.", e); + } + return response; + } + + public ResponseEntity sendCustomNotification(String deviceId, List parameters, + String nameSpace) { + ResponseEntity response = null; + final String uri = getUri(); + LOG.debug("Posting custom notification to netconf server {}", uri); + try { + String notificationXml = getNetconfResponseXML(parameters, null, nameSpace); + NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO(deviceId, notificationXml); + + response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class); + LOG.debug("Posting custom notification to netconf server sucessfull"); + } catch (Exception e) { + LOG.error("Exception while sending the custom notification.", e); + } + return response; + } + + private void convertTR069ToNetConfParams(List parameters, String swVersion, + String hwVersion) { + List removeList = new ArrayList<>(); + if (null != parameters) { + for (ParameterDTO param : parameters) { + if (param.getParamValue() == null || param.getParamValue().trim().length() <= 0) { + removeList.add(param); + continue; + } + handleBooleanParameters(param, swVersion, hwVersion); + if (null != param.getParamName()) { + String netConfMOName = metaDataUtil + .getNetconfNameByTR69NameWithIndexes(param.getParamName(), swVersion, hwVersion); + if (null != netConfMOName) + param.setParamName(netConfMOName); + else + removeList.add(param); // unknown parameter found. + } + } + parameters.removeAll(removeList); + } + } + + private void handleBooleanParameters(ParameterDTO param, String swVersion, String hwVersion) { + MOMetaData metaData = + metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); + if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { + if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(Boolean.TRUE.toString()); + } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(Boolean.FALSE.toString()); + } + } + } + + private String getUri() { + return config.getNbiNotificationUri(); + } + + private static String getNetconfResponseXML(List parameters, + String notificationType, String nameSpace) { + if (parameters == null || parameters.isEmpty()) { + LOG.debug("There are no parameters found in the response."); + return null; + } + + String result = null; + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + + Map parentNodeMap = new HashMap<>(); + Element dataNode = null; // root of all nodes + + for (ParameterDTO paramDto : parameters) { + String paramName = paramDto.getParamName(); + String paramValue = paramDto.getParamValue(); + StringTokenizer tokenizer = new StringTokenizer(paramName, "."); + String parentNodeName = null; + String parentNodeKey = null; + Element parentNode = null; + while (tokenizer.hasMoreElements()) { + String nodeName = (String) tokenizer.nextElement(); + if (null == parentNodeName) { // construct first node or + // Device node + parentNodeName = nodeName; + parentNodeKey = nodeName; + // check if the node already exists in parentNodeMap + parentNode = parentNodeMap.get(parentNodeKey); + if (null == dataNode) { + dataNode = parentNode; + } + continue; + } else if (nodeName.matches(INDEX_REGEX)) { // construct + // tabular and + // index nodes + + // get parent tabular node from parent MAP + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + Element node = parentNodeMap.get(parentNodeKey); + + // create a tabular parent node if doesn't exit in MAP + if (null == node) { + node = doc.createElement(parentNodeName); + parentNodeMap.put(parentNodeKey, node); + + // update current tabular parent node. + if (null != parentNode) + parentNode.appendChild(node); + else + parentNode = node; + + // prepare and add index node to tabular parent node + Element indexNode = doc.createElement(INDEX_STR); + indexNode.setTextContent(nodeName); + node.appendChild(indexNode); + } + parentNode = node; // move parent to child + parentNodeName = nodeName; + } else if (parentNodeName.matches(INDEX_REGEX)) { // move to + // next + // node + // if + // tabular + // attribute + // is + // found + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + parentNodeName = nodeName; + } else { + // construct intermediate nodes + Element node = parentNodeMap.get(parentNodeKey); + if (null == node) { + if (null == dataNode) { + node = doc.createElementNS(nameSpace, parentNodeName); + dataNode = node; + } else { + node = doc.createElement(parentNodeName); + } + parentNodeMap.put(parentNodeKey, node); + if (null != parentNode) + parentNode.appendChild(node); + } + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + parentNodeName = nodeName; + parentNode = node; + } + } + // construct leaf node + Element leafNode = doc.createElement(parentNodeName); + leafNode.setTextContent(paramValue); + if (null != parentNode) + parentNode.appendChild(leafNode); + } + + if (null != dataNode) { + final Element element = doc.createElement(NOTIFICATION_ELEMENT_NAME); + final Element eventTime = doc.createElement(EVENT_TIME); + eventTime + .setTextContent(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); + element.appendChild(element.getOwnerDocument().importNode(eventTime, true)); + + if (notificationType != null) { + final Element evtTypeElement = doc.createElementNS(nameSpace, notificationType); + evtTypeElement.appendChild(dataNode); + element.appendChild(element.getOwnerDocument().importNode(evtTypeElement, true)); + } else { + element.appendChild(element.getOwnerDocument().importNode(dataNode, true)); + } + + result = convertDocumentToString(element); + } + } catch (ParserConfigurationException pce) { + LOG.error("Exception while converting the notification: {}", pce.getMessage()); + } + + return result; + } + + private static String getNetConfReposneXMLForTC(List parameters, + String notificationType, String nameSpace) { + String result = null; + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + final Element element = doc.createElement(NOTIFICATION_ELEMENT_NAME); + final Element eventTime = doc.createElement(EVENT_TIME); + eventTime.setTextContent(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); + element.appendChild(element.getOwnerDocument().importNode(eventTime, true)); + + final Element evtTypeElement = doc.createElementNS(nameSpace, notificationType); + + for (ParameterDTO paramDto : parameters) { + final Element paramNode = doc.createElement(paramDto.getParamName()); + paramNode.setTextContent(paramDto.getParamValue()); + evtTypeElement.appendChild(paramNode); + } + element.appendChild(element.getOwnerDocument().importNode(evtTypeElement, true)); + result = convertDocumentToString(element); + } catch (Exception e) { + LOG.error("Exception in getNetConfReposneXMLForTC: {}", e.getMessage()); + } + return result; + } + + public static String convertDocumentToString(Element element) { + String strxml = null; + try { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(element); + StreamResult result = new StreamResult(new StringWriter()); + transformer.transform(source, result); + strxml = result.getWriter().toString(); + } catch (Exception e) { + LOG.error("Error while converting Element to String", e); + } + LOG.debug("Converted XML is : {}", strxml); + return strxml; + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfRequestHandler.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfRequestHandler.java index 575d24e..da99ad8 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfRequestHandler.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfRequestHandler.java @@ -1,39 +1,53 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.netconf; - -import org.commscope.tr069adapter.mapper.model.NetConfRequest; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; - -public interface NetConfRequestHandler { - - public NetConfResponse handleSetConfigRequest(NetConfRequest request); - - public NetConfResponse handleGetRequest(NetConfRequest request); - - public NetConfResponse handleGetConfigRequest(NetConfRequest request); - - public NetConfResponse handleDelConfigRequest(NetConfRequest request); - - public boolean handelRegisterEvent(NetConfServerDetails request); - - public NetConfResponse handleSWDownloadRequest(NetConfRequest request); - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.netconf; + +import org.commscope.tr069adapter.mapper.model.NetConfRequest; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; + +public interface NetConfRequestHandler { + + public NetConfResponse handleSetConfigRequest(NetConfRequest request); + + public NetConfResponse handleGetRequest(NetConfRequest request); + + public NetConfResponse handleGetConfigRequest(NetConfRequest request); + + public NetConfResponse handleDelConfigRequest(NetConfRequest request); + + public boolean handelRegisterEvent(NetConfServerDetails request); + + public NetConfResponse handleSWDownloadRequest(NetConfRequest request); + + public NetConfResponse handleAddObjectRequest(NetConfRequest request); + + public NetConfResponse handleDeleteObjectRequest(NetConfRequest request); + + public NetConfResponse handleRequestWithoutInputParams(NetConfRequest request); + + public NetConfResponse handleSPAObjectRequest(NetConfRequest request); + + public NetConfResponse handleConnectionStatusRequest(NetConfRequest request); + + public NetConfResponse handleGPAObjectRequest(NetConfRequest request); + + public NetConfResponse handleDownloadRequest(NetConfRequest request); + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfServerManager.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfServerManager.java index 9d53497..940e1ab 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfServerManager.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/NetConfServerManager.java @@ -1,79 +1,79 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.netconf; - -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -@Component -public class NetConfServerManager { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManager.class); - - private static String createServerSVC = "createServer"; - - @Autowired - MapperConfigProperties config; - - @Autowired - RestTemplate restTemplate; - - public NetConfServerDetails createNetconfServer(String deviceID, String enodeBName, - String swVersion, String hwVersion) { - - NetConfServerDetails result = null; - // handle exception - final String uri = getNetconfServerManagerRestUri() + "/" + createServerSVC; - LOG.debug("Sending create netconf server request for device id {}", deviceID); - try { - MultiValueMap uriParams = new LinkedMultiValueMap<>(); - uriParams.add("deviceId", deviceID); - uriParams.add("enodeBName", enodeBName); - uriParams.add("swVersion", swVersion); - uriParams.add("hwVersion", hwVersion); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - final HttpEntity> entity = new HttpEntity<>(uriParams, headers); - ResponseEntity res = - restTemplate.postForEntity(uri, entity, NetConfServerDetails.class); - result = res.getBody(); - LOG.debug("Successfully created netconf server for device id. {} , response= {}", deviceID, - result); - } catch (Exception e) { - LOG.error("Exception while creating netconf server request for device id {}", deviceID, e); - } - return result; - } - - private String getNetconfServerManagerRestUri() { - return config.getNbiServerManagerUri(); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.netconf; + +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +@Component +public class NetConfServerManager { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManager.class); + + private static String createServerSVC = "createServer"; + + @Autowired + MapperConfigProperties config; + + @Autowired + RestTemplate restTemplate; + + public NetConfServerDetails createNetconfServer(String deviceID, String enodeBName, + String swVersion, String hwVersion) { + + NetConfServerDetails result = null; + // handle exception + final String uri = getNetconfServerManagerRestUri() + "/" + createServerSVC; + LOG.debug("Sending create netconf server request for device id {}", deviceID); + try { + MultiValueMap uriParams = new LinkedMultiValueMap<>(); + uriParams.add("deviceId", deviceID); + uriParams.add("enodeBName", enodeBName); + uriParams.add("swVersion", swVersion); + uriParams.add("hwVersion", hwVersion); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + final HttpEntity> entity = new HttpEntity<>(uriParams, headers); + ResponseEntity res = + restTemplate.postForEntity(uri, entity, NetConfServerDetails.class); + result = res.getBody(); + LOG.debug("Successfully created netconf server for device id. {} , response= {}", deviceID, + result); + } catch (Exception e) { + LOG.error("Exception while creating netconf server request for device id {}", deviceID, e); + } + return result; + } + + private String getNetconfServerManagerRestUri() { + return config.getNbiServerManagerUri(); + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/controller/NetConfRequestReceiver.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/controller/NetConfRequestReceiver.java index ca5f15a..1f5e520 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/controller/NetConfRequestReceiver.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/controller/NetConfRequestReceiver.java @@ -1,97 +1,161 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.netconf.controller; - -import org.commscope.tr069adapter.mapper.model.NetConfRequest; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/tr069MapperNBI") -public class NetConfRequestReceiver { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestReceiver.class); - - @Autowired - NetConfRequestHandler handler; - - @PostMapping("/setConfig") - public NetConfResponse setConfigRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for SET-CONFIG. Request : {}", request); - NetConfResponse response = handler.handleSetConfigRequest(request); - LOG.info("Processed SET-CONFIG request. Response : {}", response); - return response; - } - - @PostMapping("/get") - public NetConfResponse getRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for GET. Request : {}", request); - NetConfResponse response = handler.handleGetRequest(request); - LOG.info("Processed GET request. Response : {}", response); - return response; - } - - @PostMapping("/getConfig") - public NetConfResponse getConfigRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for GET-CONFIG. Request : {}", request); - NetConfResponse response = handler.handleGetConfigRequest(request); - LOG.info("Processed GET-CONFIG request. Response : {}", response); - return response; - } - - @PostMapping("/delConfig") - public NetConfResponse delConfigRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for DEL-CONFIG. Request : {}", request); - NetConfResponse response = handler.handleDelConfigRequest(request); - LOG.info("Processed DEL-CONFIG request. Response : {}", response); - return response; - } - - @PostMapping("/softwareDowload") - public NetConfResponse swDownloadRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for SW-DOWNLOAD. Request : {}", request); - NetConfResponse response = handler.handleSWDownloadRequest(request); - LOG.info("Processed SW-DOWNLOAD request. Response : "); - return response; - } - - @PostMapping("/softwareActivate") - public NetConfResponse swActivateRequest(@RequestBody NetConfRequest request) { - LOG.info("Received request for SW-ACTIVATE. Request : {}", request); - LOG.info("Processed SW-ACTIVATE request. Response : "); - return null; - } - - @PostMapping("/registerNetconfServer") - public boolean handelRegisterEvent(@RequestBody NetConfServerDetails request) { - LOG.info("Received request for register event. Request : {}", request); - boolean result = handler.handelRegisterEvent(request); - LOG.info("Processed register event request. Response : {}", request); - return result; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.netconf.controller; + +import org.commscope.tr069adapter.mapper.model.NetConfRequest; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/tr069MapperNBI") +public class NetConfRequestReceiver { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestReceiver.class); + + @Autowired + NetConfRequestHandler handler; + + @PostMapping("/setConfig") + public NetConfResponse setConfigRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for SET-CONFIG. Request : {}", request); + NetConfResponse response = handler.handleSetConfigRequest(request); + LOG.info("Processed SET-CONFIG request. Response : {}", response); + return response; + } + + @PostMapping("/get") + public NetConfResponse getRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for GET. Request : {}", request); + NetConfResponse response = handler.handleGetRequest(request); + LOG.info("Processed GET request. Response : {}", response); + return response; + } + + @PostMapping("/getConfig") + public NetConfResponse getConfigRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for GET-CONFIG. Request : {}", request); + NetConfResponse response = handler.handleGetConfigRequest(request); + LOG.info("Processed GET-CONFIG request. Response : {}", response); + return response; + } + + @PostMapping("/delConfig") + public NetConfResponse delConfigRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for DEL-CONFIG. Request : {}", request); + NetConfResponse response = handler.handleDelConfigRequest(request); + LOG.info("Processed DEL-CONFIG request. Response : {}", response); + return response; + } + + @PostMapping("/softwareDowload") + public NetConfResponse swDownloadRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for SW-DOWNLOAD. Request : {}", request); + NetConfResponse response = handler.handleSWDownloadRequest(request); + LOG.info("Processed SW-DOWNLOAD request. Response : "); + return response; + } + + @PostMapping("/softwareActivate") + public NetConfResponse swActivateRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for SW-ACTIVATE. Request : {}", request); + LOG.info("Processed SW-ACTIVATE request. Response : "); + return null; + } + + @PostMapping("/registerNetconfServer") + public boolean handelRegisterEvent(@RequestBody NetConfServerDetails request) { + LOG.info("Received request for register event. Request : {}", request); + boolean result = handler.handelRegisterEvent(request); + LOG.info("Processed register event request. Response : {}", request); + return result; + } + + @PostMapping("/addobject") + public NetConfResponse addObjectRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for addObject. Request : {}", request); + NetConfResponse response = handler.handleAddObjectRequest(request); + LOG.info("Processed addObject request. Response : {}", response); + return response; + } + + @PostMapping("/deleteobject") + public NetConfResponse deleteObjectRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for deleteObject. Request : {}", request); + NetConfResponse response = handler.handleDeleteObjectRequest(request); + LOG.info("Processed deleteObject request. Response : {}", response); + return response; + } + + @PostMapping("/reboot") + public NetConfResponse rebootRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for Reboot. Request : {}", request); + NetConfResponse response = handler.handleRequestWithoutInputParams(request); + LOG.info("Processed Reboot request. Response : {}", response); + return response; + } + + @PostMapping("/reset") + public NetConfResponse resetRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for Reset. Request : {}", request); + NetConfResponse response = handler.handleRequestWithoutInputParams(request); + LOG.info("Processed Reset request. Response : {}", response); + return response; + } + + @PostMapping("/spaobject") + public NetConfResponse spaObjectRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for SPAObject. Request : {}", request); + NetConfResponse response = handler.handleSPAObjectRequest(request); + LOG.info("Processed SPAObject request. Response : {}", response); + return response; + } + + @PostMapping("/gpaobject") + public NetConfResponse gpaObjectRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for GPAObject. Request : {}", request); + NetConfResponse response = handler.handleGPAObjectRequest(request); + LOG.info("Processed GPAObject request. Response : {}", response); + return response; + } + + @PostMapping("/connectionstatus") + public NetConfResponse connectionStatusRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for Connection Status. Request : {}", request); + NetConfResponse response = handler.handleConnectionStatusRequest(request); + LOG.info("Processed Connection Status request. Response : {}", response); + return response; + } + + @PostMapping("/download") + public NetConfResponse downloadRequest(@RequestBody NetConfRequest request) { + LOG.info("Received request for download. Request : {}", request); + NetConfResponse response = handler.handleDownloadRequest(request); + LOG.info("Processed download request. Response : {}", response); + return response; + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/impl/NetConfRequestHandlerImpl.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/impl/NetConfRequestHandlerImpl.java index 9ae1196..53cae0f 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/impl/NetConfRequestHandlerImpl.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/netconf/impl/NetConfRequestHandlerImpl.java @@ -1,684 +1,1099 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.netconf.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationOptions; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; -import org.commscope.tr069adapter.mapper.MOMetaData; -import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO; -import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails; -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfRequest; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler; -import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; -import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil; -import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus; -import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; -import org.commscope.tr069adapter.mapper.util.MapperConstants; -import org.commscope.tr069adapter.mapper.util.MapperValidator; -import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; -import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -@Component -public class NetConfRequestHandlerImpl implements NetConfRequestHandler { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestHandlerImpl.class); - private static final String BOOLEAN_TRUE_VALUE = "1"; - private static final String BOOLEAN_FALSE_VALUE = "0"; - private static final String BOOLEAN_DATA_TYPE = "boolean"; - - @Autowired - SynchronizedRequestHandler syncHandler; - - @Autowired - NetconfToTr069MapperUtil mapperUtil; - - @Autowired - MOMetaDataUtil metaDataUtil; - - @Autowired - ErrorCodeUtil errorCodeUtil; - - @Autowired - VESNotificationSender vesnotiSender; - - @Autowired - DeviceOperationsDAO deviceOperDAO; - - @Override - public NetConfResponse handleSetConfigRequest(NetConfRequest netConfRequest) { - Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); - NetConfResponse response = null; - DeviceRPCRequest deviceRPCRequest = NetconfToTr069MapperUtil.prepareTR069Request( - netConfRequest.getDeviceId(), el, "config", TR069OperationCode.SET_PARAMETER_VALUES); - - if (deviceRPCRequest == null) { - LOG.debug("There are no supported device parameters found for edit-config."); - return getEmptyResponse(); - } - List requestParams = deviceRPCRequest.getOpDetails().getParmeters(); - List filteredParams = new ArrayList<>(); - List vesRequestParams = new ArrayList<>(); - - if (null != requestParams) { - for (ParameterDTO param : requestParams) { - if (null == param.getParamValue() || StringUtils.isEmpty(param.getParamValue())) { - continue; - } - if (isVesNotificationRequest(param)) { - vesRequestParams.add(param); - } - filteredParams.add(param); - } - deviceRPCRequest.getOpDetails().setParmeters(filteredParams); - } - - if (deviceRPCRequest.getOpDetails() == null - || deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no device parameters found for edit-config."); - return getEmptyResponse(); - } else if (deviceRPCRequest.getOpDetails() != null) { - deviceRPCRequest.getOpDetails() - .setParmeters(filteredSetParameters(deviceRPCRequest.getOpDetails().getParmeters(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); - if (deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no supported device parameters found for edit-config."); - return getEmptyResponse(); - } - } - - handleBooleanParametersReverse(deviceRPCRequest.getOpDetails().getParmeters(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); - LOG.debug("Prepared NBI request for edit-config {}", deviceRPCRequest); - - DeviceRPCResponse deviceRPCResponseVes = null; - List allParamList = deviceRPCRequest.getOpDetails().getParmeters(); - - if (!vesRequestParams.isEmpty()) { - if (!MapperValidator.isCountDownTimerValid(vesRequestParams)) { - return getErrorResponse(MapperConstants.INVALID_PARAM_VAL_ERROR_CODE, - MapperConstants.INVALID_COUNT_DOWN_TIMER_MSG); - } - - deviceRPCRequest.getOpDetails().setParmeters(vesRequestParams); - deviceRPCResponseVes = vesnotiSender.sendEditConfigNotification(deviceRPCRequest); - - if (null == deviceRPCResponseVes) { - return getTimeOutResponse(); - } - } - - allParamList.removeAll(vesRequestParams); - - DeviceRPCResponse deviceRPCResponseDevice = null; - if (null != allParamList && !allParamList.isEmpty()) { - deviceRPCRequest.getOpDetails().setParmeters(allParamList); - if (isAdminStateOverriden(allParamList)) { - deviceRPCRequest.getOpDetails().setOpCode(CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS); - TR069OperationDetails tr069OperationDetails = - (TR069OperationDetails) deviceRPCRequest.getOpDetails(); - tr069OperationDetails.setModifyParamList(allParamList); - tr069OperationDetails.setSetParamList(null); - - deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest); - convertResposeToSPVResponse(deviceRPCResponseDevice); - } else { - deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest); - } - - if (null == deviceRPCResponseDevice) { - return getTimeOutResponse(); - } - } - - DeviceRPCResponse deviceRPCResponse = - mergeSetConfigDeviceRPCResponse(deviceRPCResponseVes, deviceRPCResponseDevice); - if (null == deviceRPCResponse) { - return getTimeOutResponse(); - } - response = mapperUtil.getNetconfResponse(deviceRPCResponse, netConfRequest.getSwVersion(), - netConfRequest.getHwVersion(), false); - return response; - } - - @Override - public NetConfResponse handleDelConfigRequest(NetConfRequest netConfRequest) { - Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); - NetConfResponse response = null; - DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( - netConfRequest.getDeviceId(), el, "config", TR069OperationCode.DELETE_OBJECT); - - if (request == null) { - LOG.debug("There are no supported device parameters found for delete-config."); - return getEmptyResponse(); - } - - List requestParams = request.getOpDetails().getParmeters(); - List filteredParams = new ArrayList<>(); - if (null != requestParams) { - for (ParameterDTO param : requestParams) { - filteredParams.add(param); - } - request.getOpDetails().setParmeters(filteredParams); - } - - if (request.getOpDetails() == null || request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no device parameters found for delete-config."); - return getEmptyResponse(); - } else if (request.getOpDetails() != null) { - request.getOpDetails() - .setParmeters(filteredSetParameters(request.getOpDetails().getParmeters(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); - if (request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no supported device parameters found for delete-config."); - return getEmptyResponse(); - } - } - LOG.debug("Prepared NBI request for delete-config {}", request); - - DeviceRPCResponse opResult; - opResult = syncHandler.performDeviceOperation(request); - if (null == opResult) { - return getTimeOutResponse(); - } - response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), - netConfRequest.getHwVersion(), false); - return response; - } - - @Override - public NetConfResponse handleGetRequest(NetConfRequest netConfRequest) { - Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); - NetConfResponse response = null; - DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( - netConfRequest.getDeviceId(), el, "filter", TR069OperationCode.GET_PARAMETER_VALUES); - - if (request == null || request.getOpDetails() == null - || request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no device parameters found for get."); - return getEmptyResponse(); - } else if (request.getOpDetails() != null) { - - request.getOpDetails() - .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); - - if (request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no supported device parameters found for get."); - return getEmptyResponse(); - } - } - LOG.debug("Prepared NBI request for get {}", request); - - DeviceRPCResponse opResult; - opResult = syncHandler.performDeviceOperation(request); - if (null == opResult) { - return getTimeOutResponse(); - } - response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), - netConfRequest.getHwVersion(), false); - return response; - } - - @Override - public NetConfResponse handleGetConfigRequest(NetConfRequest netConfRequest) { - Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); - NetConfResponse response = null; - List vesRequestParams = new ArrayList<>(); - - boolean isSoftwareInventory = false; - if (netConfRequest.getRequestXml().contains("software-inventory")) { - LOG.info("XML Contains software-inventory"); - isSoftwareInventory = true; - } - - DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( - netConfRequest.getDeviceId(), el, "filter", TR069OperationCode.GET_PARAMETER_VALUES); - - if (request == null || request.getOpDetails() == null - || request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no device parameters found for get-config."); - return getEmptyResponse(); - } else if (request.getOpDetails() != null) { - request.getOpDetails() - .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); - - if (request.getOpDetails().getParmeters().isEmpty()) { - LOG.debug("There are no supported device parameters found for get-config."); - return getEmptyResponse(); - } - for (ParameterDTO param : request.getOpDetails().getParmeters()) { - if (isVesNotificationRequest(param)) { - vesRequestParams.add(param); - } - } - } - LOG.debug("Prepared NBI request for get-config {}", request); - - DeviceRPCResponse opResultVes = null; - List allParamList = request.getOpDetails().getParmeters(); - - if (!vesRequestParams.isEmpty()) { - request.getOpDetails().setParmeters(vesRequestParams); - opResultVes = vesnotiSender.sendGetConfigNotification(request); - - if (null == opResultVes) { - return getTimeOutResponse(); - } - } - - - allParamList.removeAll(vesRequestParams); - - DeviceRPCResponse opResultDevice = null; - if (!allParamList.isEmpty()) { - request.getOpDetails().setParmeters(allParamList); - opResultDevice = syncHandler.performDeviceOperation(request); - - if (null == opResultDevice) { - return getTimeOutResponse(); - } - } - - DeviceRPCResponse opResult = mergeGetConfigDeviceRPCResponse(opResultVes, opResultDevice); - - if (null == opResult) { - return getTimeOutResponse(); - } - LOG.debug("Received GPV response : FaultKey = " + opResult.getFaultKey() + ", FaultString = " - + opResult.getFaultString() + ", Parameters :" - + opResult.getOperationResponse().getParameterDTOs()); - if (null != opResult.getOperationResponse().getParameterDTOs()) - handleBooleanParameters(opResult.getOperationResponse().getParameterDTOs(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); - - if (isSoftwareInventory) { - response = mapperUtil.getNetconfResponseForSoftwareInventory(opResult, - netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); - } else { - response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), - netConfRequest.getHwVersion(), false); - } - - if (opResult.getFaultKey() != null && opResult.getFaultKey().equalsIgnoreCase("9005")) { - // check for tabular - LOG.debug("Tabualr Entry not exist in the device; we need to add it now"); - MOMetaData data = metaDataUtil.getMetaDataByTR69Name( - request.getOpDetails().getParmeters().get(0).getParamName(), - netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); - if (data.isTabluarObj()) { - return getEmptyResponse(); - } - } - - return response; - } - - @Override - public NetConfResponse handleSWDownloadRequest(NetConfRequest request) { - LOG.debug("request received fro sw-download"); - Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); - NetConfResponse response = null; - Map map = - NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "software-download"); - if (map == null || map.size() <= 0) { - LOG.debug("There are no device parameters found for get."); - return getEmptyResponse(); - } - - TR069OperationDetails opDetails = new TR069OperationDetails(); - DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); - TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); - tr069DeviceDetails.setDeviceId(request.getDeviceId()); - deviceRPCRequest.setOpDetails(opDetails); - deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); - OperationOptions options = new OperationOptions(); - options.setExecutionTimeout(60l); - deviceRPCRequest.setOptions(options); - String fileName = map.get("rpc.software-download.remote-file-path"); - String password = map.get("rpc.software-download.password.password"); - - if (fileName == null || password == null || getDownloadFileURI(fileName) == null - || getDownloadUserName(fileName) == null) { - LOG.error( - "remote-file-path value is not as per yang model reference. Allowed pattern sftp://@[:]/path"); - return getOperationAbortedResponse( - "remote-file-path value is not as per yang model reference. Allowed pattern sftp://@[:]/path"); - } - - List paramDTOList = new ArrayList<>(); - paramDTOList.add(new ParameterDTO("FileType", "1 Firmware Upgrade Image")); - paramDTOList.add(new ParameterDTO("URL", getDownloadFileURI(fileName))); - paramDTOList.add(new ParameterDTO("Username", getDownloadUserName(fileName))); - paramDTOList.add(new ParameterDTO("Password", password)); - paramDTOList.add(new ParameterDTO("FileSize", "0")); - paramDTOList.add(new ParameterDTO("TargetFileName", "")); - paramDTOList.add(new ParameterDTO("DelaySeconds", "1")); - paramDTOList.add(new ParameterDTO("SuccessURL", "")); - paramDTOList.add(new ParameterDTO("FailureURL", "")); - - deviceRPCRequest.getOpDetails().setParmeters(paramDTOList); - deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.DOWNLOAD); - - LOG.debug("Prepared NBI request for download " + deviceRPCRequest); - - DeviceOperationDetails fwDetails = deviceOperDAO.findByDeviceId(request.getDeviceId()); - if (fwDetails == null) { - String errorMsg = "TR069 device request has been aborted,due to device not identified"; - return getOperationAbortedResponse(errorMsg); - } - - if (fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus() - && fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) { - - LOG.debug("persisting the fw details " + fwDetails.toString()); - - DeviceRPCResponse opResult; - opResult = syncHandler.performDeviceOperation(deviceRPCRequest); - if (null == opResult) { - return getTimeOutResponse(); - } - fwDetails.setFileName(fileName); - fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()); - deviceOperDAO.save(fwDetails); - ArrayList responseParamDTOList = new ArrayList<>(); - - if (opResult.getOperationResponse().getStatus() == 1) { - responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:status", "STARTED")); - } else { - responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:status", "FAILED")); - responseParamDTOList - .add(new ParameterDTO("rpc-reply.ns1:error-message", opResult.getFaultString())); - } - responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:notification-timeout", "1200")); - - opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); - response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), - request.getHwVersion(), true); - - LOG.debug("update the status for fw details " + fwDetails.toString()); - } else { - LOG.debug("FirmWare Upgrade is in progress"); - String errorMsg = "TR069 device request has been aborted as Firmware Upgrade is inProgress"; - return getOperationAbortedResponse(errorMsg); - } - - return response; - } - - protected DeviceRPCResponse mergeGetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes, - DeviceRPCResponse opResultDevice) { - if (null == opResultVes) { - return opResultDevice; - } - - if (null == opResultDevice) { - return opResultVes; - } - - if (null != opResultVes.getFaultKey() - && !opResultVes.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) { - return opResultVes; - } else if (null != opResultDevice.getFaultKey() - && !opResultDevice.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) { - return opResultDevice; - } - - opResultDevice.getOperationResponse().getParameterDTOs() - .addAll(opResultVes.getOperationResponse().getParameterDTOs()); - return opResultDevice; - } - - protected DeviceRPCResponse mergeSetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes, - DeviceRPCResponse opResultDevice) { - if (null == opResultVes) { - return opResultDevice; - } - - if (null == opResultDevice) { - return opResultVes; - } - - return opResultDevice; - } - - protected boolean isVesNotificationRequest(ParameterDTO param) { - if (null == param.getParamName() || param.getParamName().isEmpty()) { - return false; - } - - if (param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT_PERIOD.toLowerCase()) - || param.getParamName().toLowerCase() - .contains(MapperConstants.COUNT_DOWN_TIMER.toLowerCase()) - || param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT.toLowerCase())) { - return true; - } - - return false; - } - - protected void handleBooleanParameters(List parameterDTOs, String swVersion, - String hwVersion) { - - for (ParameterDTO param : parameterDTOs) { - MOMetaData metaData = - metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); - if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { - if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(Boolean.TRUE.toString()); - } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(Boolean.FALSE.toString()); - } - } - } - } - - protected void handleBooleanParametersReverse(List parameterDTOs, String swVersion, - String hwVersion) { - - for (ParameterDTO param : parameterDTOs) { - MOMetaData metaData = - metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); - if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { - if (Boolean.TRUE.toString().equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(BOOLEAN_TRUE_VALUE); - } else if (Boolean.FALSE.toString().equalsIgnoreCase(param.getParamValue().trim())) { - param.setParamValue(BOOLEAN_FALSE_VALUE); - } - } - } - } - - protected NetConfResponse getEmptyResponse() { - NetConfResponse response = new NetConfResponse(); - ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("0"); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - errorCode.setFaultCode("0"); - errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); - errorCode.setErrorType(errorCodeMetaData.getErrorType()); - errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); - errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); - response.setErrorCode(errorCode); - return response; - } - - protected NetConfResponse getTimeOutResponse() { - // prepare timeout error response - NetConfResponse timeOutErrorResponse = new NetConfResponse(); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); - - errorCode.setFaultCode("8006"); - errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); - errorCode.setErrorType(errorCodeMetaData.getErrorType()); - errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); - errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); - timeOutErrorResponse.setErrorCode(errorCode); - timeOutErrorResponse.setErrorMessage("TR069 device request has been timed out."); - return timeOutErrorResponse; - } - - protected NetConfResponse getErrorResponse(String errCode, String errorMsg) { - NetConfResponse errorResponse = new NetConfResponse(); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); - if (errorCodeMetaData != null) { - errorCode.setFaultCode(errCode); - errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); - errorCode.setErrorType(errorCodeMetaData.getErrorType()); - errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); - errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); - } - errorResponse.setErrorCode(errorCode); - errorResponse.setErrorMessage(errorMsg); - return errorResponse; - } - - protected NetConfResponse getOperationAbortedResponse(String errorMessage) { - // prepare timeout error response - NetConfResponse timeOutErrorResponse = new NetConfResponse(); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); - if (errorCodeMetaData != null) { - errorCode.setFaultCode("8002"); - errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); - errorCode.setErrorType(errorCodeMetaData.getErrorType()); - errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); - errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); - } - timeOutErrorResponse.setErrorCode(errorCode); - timeOutErrorResponse.setErrorMessage(errorMessage); - return timeOutErrorResponse; - } - - public List filteredSetParameters(List parameters, String swVersion, - String hwVersion) { - List result = new ArrayList<>(); - for (ParameterDTO param : parameters) { - MOMetaData metaData = - metaDataUtil.getMetaDataByNetConfName(param.getParamName(), swVersion, hwVersion); - if (null != metaData && !metaData.isReadOnly()) { - String tr069MoName = - MOMetaDataUtil.getTR69MOByReplacingIndexes(param.getParamName(), metaData.getMoName()); - param.setDataType(metaData.getDataType()); - param.setParamName(tr069MoName); - result.add(param); - } - } - return result; - } - - protected List filteredGetParameters(List parameters, - String swVersion, String hwVersion) { - return metaDataUtil.getSupportedChildParameters(parameters, swVersion, hwVersion); - } - - @Override - public boolean handelRegisterEvent(NetConfServerDetails request) { - LOG.debug("processing the handelRegisterEvent started"); - try { - VESNotificationResponse vesRsponse = vesnotiSender.sendNotification(null, request); - if (HttpStatus.valueOf(vesRsponse.getStatusCode()).is2xxSuccessful()) { - LOG.debug("processing the handelRegisterEvent completed"); - return true; - } else { - LOG.error("processing the handelRegisterEvent error code recevived: {}", - vesRsponse.getStatusCode()); - return false; - } - } catch (Exception e) { - LOG.error("processing the handelRegisterEvent exception occurred"); - return false; - } - } - - protected static String getDownloadFileURI(String filepath) { - - if (filepath.contains("@") && filepath.contains("//")) { - String[] str = filepath.split("@"); - String[] strForUserName = str[0].split("//"); - if (str.length > 1) { - String Url = strForUserName[0] + "//" + str[1]; - return Url; - } - } - return null; - } - - protected static String getDownloadUserName(String filepath) { - - if (filepath.contains("@") && filepath.contains("//")) { - String[] str = filepath.split("@"); - String[] strForUserName = str[0].split("//"); - if (strForUserName.length > 1) - return strForUserName[1]; - } - return null; - } - - protected boolean isAdminStateOverriden(List paramList) { - for (ParameterDTO paramDTO : paramList) { - if (paramDTO.getParamName().contains(MapperConstants.ADMIN_STATE) - || paramDTO.getParamName().contains(MapperConstants.ADMIN_STATUS)) { - return true; - } - } - return false; - } - - protected void convertResposeToSPVResponse(DeviceRPCResponse deviceRPCResponse) { - if (null == deviceRPCResponse) { - return; - } - - OperationResponse operationResponse = new SetParameterValueResponse(); - operationResponse.setParameterDTOs(new ArrayList()); - - if (null == deviceRPCResponse.getFaultKey()) { - operationResponse.setStatus(MapperConstants.RPC_SUCCESS_CODE); - } else { - operationResponse.setStatus(MapperConstants.RPC_FAILED_CODE); - } - - deviceRPCResponse.setOperationResponse(operationResponse); - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.netconf.impl; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationOptions; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.acs.common.response.AddObjectResponse; +import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse; +import org.commscope.tr069adapter.acs.common.utils.ConnectionStatusPOJO; +import org.commscope.tr069adapter.mapper.MOMetaData; +import org.commscope.tr069adapter.mapper.acs.ACSRequestSender; +import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO; +import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails; +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfRequest; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler; +import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; +import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil; +import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus; +import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; +import org.commscope.tr069adapter.mapper.util.MapperConstants; +import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; +import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +@Component +public class NetConfRequestHandlerImpl implements NetConfRequestHandler { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestHandlerImpl.class); + private static final String BOOLEAN_TRUE_VALUE = "1"; + private static final String BOOLEAN_FALSE_VALUE = "0"; + private static final String BOOLEAN_DATA_TYPE = "boolean"; + private static final String CONFIG = "config"; + private static final String FILTER = "filter"; + private static final String NO_DEVICE_PARAM_FOUND = + "There are no device parameters found for get."; + private static final String RPC_REPLY_STATUS = "rpc-reply.ns1:status"; + private static final String RPC_REPLY_ERROR = "rpc-reply.ns1:error-message"; + private static final String FAILED = "FAILED"; + private static final String PARAMETER = "parameter"; + + @Autowired + SynchronizedRequestHandler syncHandler; + + @Autowired + NetconfToTr069MapperUtil mapperUtil; + + @Autowired + MOMetaDataUtil metaDataUtil; + + @Autowired + ErrorCodeUtil errorCodeUtil; + + @Autowired + VESNotificationSender vesnotiSender; + + @Autowired + DeviceOperationsDAO deviceOperDAO; + + @Autowired + ACSRequestSender tr069ReqSender; + + @Override + public NetConfResponse handleSetConfigRequest(NetConfRequest netConfRequest) { + Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); + NetConfResponse response = null; + DeviceRPCRequest deviceRPCRequest = NetconfToTr069MapperUtil.prepareTR069Request( + netConfRequest.getDeviceId(), el, CONFIG, TR069OperationCode.SET_PARAMETER_VALUES); + + if (deviceRPCRequest == null) { + LOG.debug("There are no supported device parameters found for edit-config."); + return getEmptyResponse(); + } + List requestParams = deviceRPCRequest.getOpDetails().getParmeters(); + List filteredParams = new ArrayList<>(); + List vesRequestParams = new ArrayList<>(); + + if (null != requestParams) { + for (ParameterDTO param : requestParams) { + if (null == param.getParamValue() || StringUtils.isEmpty(param.getParamValue())) { + continue; + } + if (isVesNotificationRequest(param)) { + vesRequestParams.add(param); + } + filteredParams.add(param); + } + deviceRPCRequest.getOpDetails().setParmeters(filteredParams); + } + + if (deviceRPCRequest.getOpDetails() == null + || deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no device parameters found for edit-config."); + return getEmptyResponse(); + } else if (deviceRPCRequest.getOpDetails() != null) { + deviceRPCRequest.getOpDetails() + .setParmeters(filteredSetParameters(deviceRPCRequest.getOpDetails().getParmeters(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); + if (deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for edit-config."); + return getEmptyResponse(); + } + } + + handleBooleanParametersReverse(deviceRPCRequest.getOpDetails().getParmeters(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); + LOG.debug("Prepared NBI request for edit-config {}", deviceRPCRequest); + + DeviceRPCResponse deviceRPCResponseVes = null; + List allParamList = deviceRPCRequest.getOpDetails().getParmeters(); + + if (!vesRequestParams.isEmpty()) { + deviceRPCRequest.getOpDetails().setParmeters(vesRequestParams); + deviceRPCResponseVes = vesnotiSender.sendEditConfigNotification(deviceRPCRequest); + + if (null == deviceRPCResponseVes) { + return getTimeOutResponse(); + } + } + + allParamList.removeAll(vesRequestParams); + + DeviceRPCResponse deviceRPCResponseDevice = null; + if (null != allParamList && !allParamList.isEmpty()) { + deviceRPCRequest.getOpDetails().setParmeters(allParamList); + if (isAdminStateOverriden(allParamList)) { + deviceRPCRequest.getOpDetails().setOpCode(CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS); + TR069OperationDetails tr069OperationDetails = + (TR069OperationDetails) deviceRPCRequest.getOpDetails(); + tr069OperationDetails.setModifyParamList(allParamList); + tr069OperationDetails.setSetParamList(null); + + deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest); + convertResposeToSPVResponse(deviceRPCResponseDevice); + } else { + deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest); + } + + if (null == deviceRPCResponseDevice) { + return getTimeOutResponse(); + } + } + + DeviceRPCResponse deviceRPCResponse = + mergeSetConfigDeviceRPCResponse(deviceRPCResponseVes, deviceRPCResponseDevice); + if (null == deviceRPCResponse) { + return getTimeOutResponse(); + } + response = mapperUtil.getNetconfResponse(deviceRPCResponse, netConfRequest.getSwVersion(), + netConfRequest.getHwVersion(), false); + return response; + } + + @Override + public NetConfResponse handleDelConfigRequest(NetConfRequest netConfRequest) { + Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); + NetConfResponse response = null; + DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( + netConfRequest.getDeviceId(), el, CONFIG, TR069OperationCode.DELETE_OBJECT); + + if (request == null) { + LOG.debug("There are no supported device parameters found for delete-config."); + return getEmptyResponse(); + } + + List requestParams = request.getOpDetails().getParmeters(); + List filteredParams = new ArrayList<>(); + if (null != requestParams) { + for (ParameterDTO param : requestParams) { + filteredParams.add(param); + } + request.getOpDetails().setParmeters(filteredParams); + } + + if (request.getOpDetails() == null || request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no device parameters found for delete-config."); + return getEmptyResponse(); + } else if (request.getOpDetails() != null) { + request.getOpDetails() + .setParmeters(filteredSetParameters(request.getOpDetails().getParmeters(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); + if (request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for delete-config."); + return getEmptyResponse(); + } + } + LOG.debug("Prepared NBI request for delete-config {}", request); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(request); + if (null == opResult) { + return getTimeOutResponse(); + } + response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), + netConfRequest.getHwVersion(), false); + return response; + } + + @Override + public NetConfResponse handleGetRequest(NetConfRequest netConfRequest) { + Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); + NetConfResponse response = null; + DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( + netConfRequest.getDeviceId(), el, FILTER, TR069OperationCode.GET_PARAMETER_VALUES); + + if (request == null || request.getOpDetails() == null + || request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } else if (request.getOpDetails() != null) { + + request.getOpDetails() + .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); + + if (request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for get."); + return getEmptyResponse(); + } + } + LOG.debug("Prepared NBI request for get {}", request); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(request); + if (null == opResult) { + return getTimeOutResponse(); + } + response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), + netConfRequest.getHwVersion(), false); + return response; + } + + @Override + public NetConfResponse handleGetConfigRequest(NetConfRequest netConfRequest) { + Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml()); + NetConfResponse response = null; + List vesRequestParams = new ArrayList<>(); + + boolean isSoftwareInventory = false; + if (netConfRequest.getRequestXml().contains("software-inventory")) { + LOG.info("XML Contains software-inventory"); + isSoftwareInventory = true; + } + + DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request( + netConfRequest.getDeviceId(), el, FILTER, TR069OperationCode.GET_PARAMETER_VALUES); + + if (request == null || request.getOpDetails() == null + || request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no device parameters found for get-config."); + return getEmptyResponse(); + } else if (request.getOpDetails() != null) { + request.getOpDetails() + .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion())); + + if (request.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for get-config."); + return getEmptyResponse(); + } + for (ParameterDTO param : request.getOpDetails().getParmeters()) { + if (isVesNotificationRequest(param)) { + vesRequestParams.add(param); + } + } + } + LOG.debug("Prepared NBI request for get-config {}", request); + + DeviceRPCResponse opResultVes = null; + List allParamList = request.getOpDetails().getParmeters(); + + if (!vesRequestParams.isEmpty()) { + request.getOpDetails().setParmeters(vesRequestParams); + opResultVes = vesnotiSender.sendGetConfigNotification(request); + + if (null == opResultVes) { + return getTimeOutResponse(); + } + } + + allParamList.removeAll(vesRequestParams); + + DeviceRPCResponse opResultDevice = null; + if (!allParamList.isEmpty()) { + request.getOpDetails().setParmeters(allParamList); + opResultDevice = syncHandler.performDeviceOperation(request); + + if (null == opResultDevice) { + return getTimeOutResponse(); + } + } + + DeviceRPCResponse opResult = mergeGetConfigDeviceRPCResponse(opResultVes, opResultDevice); + + if (null == opResult) { + return getTimeOutResponse(); + } + LOG.debug("Received GPV response : FaultKey = {}, FaultString = {}, Parameters : {}", + opResult.getFaultKey(), opResult.getFaultString(), + opResult.getOperationResponse().getParameterDTOs()); + if (null != opResult.getOperationResponse().getParameterDTOs()) + handleBooleanParameters(opResult.getOperationResponse().getParameterDTOs(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); + + if (isSoftwareInventory) { + response = mapperUtil.getNetconfResponseForSoftwareInventory(opResult, + netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); + } else { + response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(), + netConfRequest.getHwVersion(), false); + } + + if (opResult.getFaultKey() != null && opResult.getFaultKey().equalsIgnoreCase("9005")) { + // check for tabular + LOG.debug("Tabualr Entry not exist in the device; we need to add it now"); + MOMetaData data = metaDataUtil.getMetaDataByTR69Name( + request.getOpDetails().getParmeters().get(0).getParamName(), + netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); + if (data.isTabluarObj()) { + return getEmptyResponse(); + } + } + + return response; + } + + @Override + public NetConfResponse handleSWDownloadRequest(NetConfRequest request) { + LOG.debug("request received fro sw-download"); + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "software-download"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + + TR069OperationDetails opDetails = new TR069OperationDetails(); + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(request.getDeviceId()); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + String fileName = map.get("rpc.software-download.remote-file-path"); + String password = map.get("rpc.software-download.password.password"); + + if (fileName == null || password == null || getDownloadFileURI(fileName) == null + || getDownloadUserName(fileName) == null) { + LOG.error( + "remote-file-path value is not as per yang model reference. Allowed pattern sftp://@[:]/path"); + return getOperationAbortedResponse( + "remote-file-path value is not as per yang model reference. Allowed pattern sftp://@[:]/path"); + } + + List paramDTOList = new ArrayList<>(); + paramDTOList.add(new ParameterDTO("FileType", "1 Firmware Upgrade Image")); + paramDTOList.add(new ParameterDTO("URL", getDownloadFileURI(fileName))); + paramDTOList.add(new ParameterDTO("Username", getDownloadUserName(fileName))); + paramDTOList.add(new ParameterDTO("Password", password)); + paramDTOList.add(new ParameterDTO("FileSize", "0")); + paramDTOList.add(new ParameterDTO("TargetFileName", "")); + paramDTOList.add(new ParameterDTO("DelaySeconds", "1")); + paramDTOList.add(new ParameterDTO("SuccessURL", "")); + paramDTOList.add(new ParameterDTO("FailureURL", "")); + + deviceRPCRequest.getOpDetails().setParmeters(paramDTOList); + deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.DOWNLOAD); + + LOG.debug("Prepared NBI request for download {}", deviceRPCRequest); + + DeviceOperationDetails fwDetails = deviceOperDAO.findByDeviceId(request.getDeviceId()); + if (fwDetails == null) { + String errorMsg = "TR069 device request has been aborted,due to device not identified"; + return getOperationAbortedResponse(errorMsg); + } + + if (fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus() + && fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) { + + LOG.debug("persisting the fw details {}", fwDetails); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + fwDetails.setFileName(fileName); + fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()); + fwDetails.setOrigin("sdnr"); + deviceOperDAO.save(fwDetails); + ArrayList responseParamDTOList = new ArrayList<>(); + + if (opResult.getOperationResponse().getStatus() == 1) { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, "STARTED")); + } else { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, FAILED)); + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_ERROR, opResult.getFaultString())); + } + responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:notification-timeout", "1200")); + + opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); + response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), + request.getHwVersion(), true); + + LOG.debug("update the status for fw details {}", fwDetails); + } else { + LOG.debug("FirmWare Upgrade is in progress"); + String errorMsg = "TR069 device request has been aborted as Firmware Upgrade is inProgress"; + return getOperationAbortedResponse(errorMsg); + } + + return response; + } + + @Override + public NetConfResponse handleAddObjectRequest(NetConfRequest request) { + LOG.debug("request received for addObject"); + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "add-object"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + + Element el = NetconfToTr069MapperUtil.convertStringToDocument(request.getRequestXml()); + DeviceRPCRequest deviceRPCRequest = NetconfToTr069MapperUtil + .prepareTR069Request(request.getDeviceId(), el, PARAMETER, TR069OperationCode.ADD_OBJECT); + + if (deviceRPCRequest == null || deviceRPCRequest.getOpDetails() == null + || deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no device parameters found for addobject."); + return getEmptyResponse(); + } else if (deviceRPCRequest.getOpDetails() != null) { + deviceRPCRequest.getOpDetails() + .setParmeters(filteredGetParameters(deviceRPCRequest.getOpDetails().getParmeters(), + request.getSwVersion(), request.getHwVersion())); + if (deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for addobject."); + return getEmptyResponse(); + } + } + + LOG.debug("Prepared NBI request for addobject {}", deviceRPCRequest); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + if (null == opResult.getOperationResponse()) { + return getTimeOutResponse(); + } + AddObjectResponse addOpresult = (AddObjectResponse) opResult.getOperationResponse(); + + ArrayList responseParamDTOList = new ArrayList<>(); + + if (opResult.getFaultKey() == null) { + String status = String.valueOf(opResult.getOperationResponse().getStatus()); + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, status)); + String instanceNumber = String.valueOf(addOpresult.getInstanceNumber()); + LOG.info("AddObject Passed : Instance Number: {}", instanceNumber); + responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:instance-number", instanceNumber)); + } + LOG.info("AddObject Label value: {}", addOpresult.getLabel()); + if (null == addOpresult.getLabel()) { + responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:label", "")); + } else { + responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:label", addOpresult.getLabel())); + } + + opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); + response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), + request.getHwVersion(), true); + + return response; + } + + @Override + public NetConfResponse handleDeleteObjectRequest(NetConfRequest request) { + LOG.debug("request received for deleteObject"); + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "delete-object"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + + Element el = NetconfToTr069MapperUtil.convertStringToDocument(request.getRequestXml()); + DeviceRPCRequest deviceRPCRequest = NetconfToTr069MapperUtil.prepareTR069Request( + request.getDeviceId(), el, PARAMETER, TR069OperationCode.DELETE_OBJECT); + + if (deviceRPCRequest == null || deviceRPCRequest.getOpDetails() == null + || deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no device parameters found for deleteobject."); + return getEmptyResponse(); + } else if (deviceRPCRequest.getOpDetails() != null) { + deviceRPCRequest.getOpDetails() + .setParmeters(filteredGetParameters(deviceRPCRequest.getOpDetails().getParmeters(), + request.getSwVersion(), request.getHwVersion())); + + if (deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) { + LOG.debug("There are no supported device parameters found for deleteobject."); + return getEmptyResponse(); + } + } + + LOG.debug("Prepared NBI request for addobject: {}", deviceRPCRequest); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + if (null == opResult.getOperationResponse()) { + return getTimeOutResponse(); + } + + ArrayList responseParamDTOList = new ArrayList<>(); + + if (opResult.getFaultKey() == null) { + String status = String.valueOf(opResult.getOperationResponse().getStatus()); + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, status)); + } + opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); + response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), + request.getHwVersion(), true); + + return response; + } + + @Override + public NetConfResponse handleRequestWithoutInputParams(NetConfRequest request) { + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + TR069OperationDetails opDetails = new TR069OperationDetails(); + Map map = null; + + if (request.getRequestXml().contains("reboot")) { + LOG.info("Request Contains Reboot"); + map = NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "reboot"); + opDetails.setOpCode(TR069OperationCode.REBOOT); + } else if (request.getRequestXml().contains("reset")) { + LOG.info("Request Contains Reset"); + map = NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "reset"); + opDetails.setOpCode(TR069OperationCode.FACTORY_RESET); + } + + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(request.getDeviceId()); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + LOG.debug("Received response for request without input params : FaultKey = {}", + opResult.getFaultKey()); + + response = mapperUtil.getNetconfResponseForRequestWithoutInputParams(opResult); + + return response; + } + + @Override + public NetConfResponse handleSPAObjectRequest(NetConfRequest request) { + LOG.debug("request received for spaObject"); + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "set-parameter-attributes"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + List params = new ArrayList<>(); + NodeList nl = d1.getElementsByTagName(CONFIG); + int len = nl.getLength(); + for (int i = 0; i < len; i++) { + Element elm = (Element) nl.item(i); + ParameterAttributeDTO param = mapperUtil.getParamNameAndValueForSPA(elm, CONFIG, + request.getSwVersion(), request.getHwVersion()); + + if (param == null) { + LOG.debug("There are no device parameters found for spaconfig."); + return getEmptyResponse(); + } + + params.add(param); + } + + TR069OperationDetails opDetails = new TR069OperationDetails(); + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(request.getDeviceId()); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + + deviceRPCRequest.getOpDetails().setParmeters(params); + deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.SET_PARAMETER_ATTRIBUTES); + + LOG.debug("Prepared NBI request for spaobject {} ", deviceRPCRequest); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + + ArrayList responseParamDTOList = new ArrayList<>(); + + if (opResult.getFaultKey() == null) { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, "SUCCESS")); + } else { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, FAILED)); + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_ERROR, opResult.getFaultString())); + } + + opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); + response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), + request.getHwVersion(), true); + + return response; + } + + @Override + public NetConfResponse handleGPAObjectRequest(NetConfRequest netConfRequest) { + LOG.debug("request received for gpaObject"); + Document d1 = + NetconfToTr069MapperUtil.convertStringToDocumentXml(netConfRequest.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "get-parameter-attributes"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + List params = new ArrayList<>(); + NodeList nl = d1.getElementsByTagName(FILTER); + int len = nl.getLength(); + for (int i = 0; i < len; i++) { + Element elm = (Element) nl.item(i); + ParameterDTO param = mapperUtil.getParamNameAndValueForGPA(elm, PARAMETER, + netConfRequest.getSwVersion(), netConfRequest.getHwVersion()); + + if (param == null) { + LOG.debug("There are no device parameters found for GPA."); + return getEmptyResponse(); + } + + params.add(param); + } + + TR069OperationDetails opDetails = new TR069OperationDetails(); + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(netConfRequest.getDeviceId()); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + + deviceRPCRequest.getOpDetails().setParmeters(params); + deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.GET_PARAMETER_ATTRIBUTES); + + LOG.debug("Prepared NBI request for gpaobject {}", deviceRPCRequest); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + + response = mapperUtil.getNetconfResponseForGPA(opResult, netConfRequest.getSwVersion(), + netConfRequest.getHwVersion()); + + return response; + } + + @Override + public NetConfResponse handleConnectionStatusRequest(NetConfRequest request) { + NetConfResponse netConfResponse = new NetConfResponse(); + ConnectionStatusPOJO connStatusPOJO = + tr069ReqSender.sendConnectionStatusReq(request.getDeviceId()); + + List paramDTOList = new ArrayList<>(); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); + if (connStatusPOJO.isStatus()) { + paramDTOList.add(new ParameterDTO("rpc-reply.ns1:last-access-status", "SUCCESS")); + } else { + paramDTOList.add(new ParameterDTO("rpc-reply.ns1:last-access-status", FAILED)); + paramDTOList.add(new ParameterDTO(RPC_REPLY_ERROR, connStatusPOJO.getErrorMessage())); + } + String lastContactDate = dateFormat.format(connStatusPOJO.getLastContactTime()); + paramDTOList.add(new ParameterDTO("rpc-reply.ns1:last-contact-time", lastContactDate)); + + String lastFailedAttemptDate = dateFormat.format(connStatusPOJO.getLastFailedAttemptTime()); + paramDTOList + .add(new ParameterDTO("rpc-reply.ns1:last-failure-attempt-time", lastFailedAttemptDate)); + + String xml = mapperUtil.getNetconfResponseXML(paramDTOList, request.getSwVersion(), + request.getHwVersion(), true); + LOG.debug("handleConnectionStatusRequest XML String: {}", xml); + netConfResponse.setNetconfResponseXml(xml); + return netConfResponse; + } + + @Override + public NetConfResponse handleDownloadRequest(NetConfRequest request) { + LOG.debug("request received for download"); + Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml()); + NetConfResponse response = null; + Map map = + NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "download"); + if (map == null || map.size() <= 0) { + LOG.debug(NO_DEVICE_PARAM_FOUND); + return getEmptyResponse(); + } + + TR069OperationDetails opDetails = new TR069OperationDetails(); + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(request.getDeviceId()); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + String fileName = map.get("rpc.download.target-file-name"); + String password = map.get("rpc.download.password"); + String url = map.get("rpc.download.url"); + String userName = map.get("rpc.download.username"); + + if (fileName == null || password == null || url == null || userName == null) { + LOG.error("fileName or password or url or userName is not as per yang model"); + return getOperationAbortedResponse( + "fileName or password or url or userName is not as per yang model"); + } + + List paramDTOList = new ArrayList<>(); + paramDTOList.add(new ParameterDTO("FileType", map.get("rpc.download.file-type"))); + paramDTOList.add(new ParameterDTO("URL", url)); + paramDTOList.add(new ParameterDTO("Username", userName)); + paramDTOList.add(new ParameterDTO("Password", password)); + paramDTOList.add(new ParameterDTO("FileSize", map.get("rpc.download.file-size"))); + paramDTOList.add(new ParameterDTO("TargetFileName", fileName)); + paramDTOList.add(new ParameterDTO("DelaySeconds", map.get("rpc.download.delay-in-seconds"))); + paramDTOList.add(new ParameterDTO("SuccessURL", map.get("rpc.download.success-url"))); + paramDTOList.add(new ParameterDTO("FailureURL", map.get("rpc.download.failure-url"))); + paramDTOList.add(new ParameterDTO("CommandKey", map.get("rpc.download.command-key"))); + + deviceRPCRequest.getOpDetails().setParmeters(paramDTOList); + deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.DOWNLOAD); + + LOG.debug("Prepared NBI request for download {} ", deviceRPCRequest); + + DeviceOperationDetails fwDetails = deviceOperDAO.findByDeviceId(request.getDeviceId()); + if (fwDetails == null) { + String errorMsg = "TR069 device request has been aborted,due to device not identified"; + return getOperationAbortedResponse(errorMsg); + } + + if (fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus() + && fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) { + + LOG.debug("persisting the fw details {}", fwDetails); + + DeviceRPCResponse opResult; + opResult = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == opResult) { + return getTimeOutResponse(); + } + fwDetails.setFileName(fileName); + fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()); + fwDetails.setOrigin("csem"); + deviceOperDAO.save(fwDetails); + ArrayList responseParamDTOList = new ArrayList<>(); + + if (opResult.getOperationResponse().getStatus() == 1) { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, "STARTED")); + } else { + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_STATUS, FAILED)); + responseParamDTOList.add(new ParameterDTO(RPC_REPLY_ERROR, opResult.getFaultString())); + } + responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:notification-timeout", "1200")); + + opResult.getOperationResponse().setParameterDTOs(responseParamDTOList); + response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(), + request.getHwVersion(), true); + + LOG.debug("update the status for fw details {} ", fwDetails); + } else { + LOG.debug("FirmWare Upgrade is in progress"); + String errorMsg = "TR069 device request has been aborted as Firmware Upgrade is inProgress"; + return getOperationAbortedResponse(errorMsg); + } + + return response; + } + + protected DeviceRPCResponse mergeGetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes, + DeviceRPCResponse opResultDevice) { + if (null == opResultVes) { + return opResultDevice; + } + + if (null == opResultDevice) { + return opResultVes; + } + + if (null != opResultVes.getFaultKey() + && !opResultVes.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) { + return opResultVes; + } else if (null != opResultDevice.getFaultKey() + && !opResultDevice.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) { + return opResultDevice; + } + + opResultDevice.getOperationResponse().getParameterDTOs() + .addAll(opResultVes.getOperationResponse().getParameterDTOs()); + return opResultDevice; + } + + protected DeviceRPCResponse mergeSetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes, + DeviceRPCResponse opResultDevice) { + if (null == opResultVes) { + return opResultDevice; + } + + if (null == opResultDevice) { + return opResultVes; + } + + return opResultDevice; + } + + protected boolean isVesNotificationRequest(ParameterDTO param) { + if (null == param.getParamName() || param.getParamName().isEmpty()) { + return false; + } + + if (param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT_PERIOD.toLowerCase()) + || param.getParamName().toLowerCase() + .contains(MapperConstants.COUNT_DOWN_TIMER.toLowerCase()) + || param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT.toLowerCase())) { + return true; + } + + return false; + } + + protected void handleBooleanParameters(List parameterDTOs, String swVersion, + String hwVersion) { + + for (ParameterDTO param : parameterDTOs) { + MOMetaData metaData = + metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); + if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { + if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(Boolean.TRUE.toString()); + } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(Boolean.FALSE.toString()); + } + } + } + } + + protected void handleBooleanParametersReverse(List parameterDTOs, String swVersion, + String hwVersion) { + + for (ParameterDTO param : parameterDTOs) { + MOMetaData metaData = + metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion); + if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) { + if (Boolean.TRUE.toString().equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(BOOLEAN_TRUE_VALUE); + } else if (Boolean.FALSE.toString().equalsIgnoreCase(param.getParamValue().trim())) { + param.setParamValue(BOOLEAN_FALSE_VALUE); + } + } + } + } + + protected NetConfResponse getEmptyResponse() { + NetConfResponse response = new NetConfResponse(); + ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("0"); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + errorCode.setFaultCode("0"); + errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); + errorCode.setErrorType(errorCodeMetaData.getErrorType()); + errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); + errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); + response.setErrorCode(errorCode); + return response; + } + + protected NetConfResponse getTimeOutResponse() { + // prepare timeout error response + NetConfResponse timeOutErrorResponse = new NetConfResponse(); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); + + errorCode.setFaultCode("8006"); + errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); + errorCode.setErrorType(errorCodeMetaData.getErrorType()); + errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); + errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); + timeOutErrorResponse.setErrorCode(errorCode); + timeOutErrorResponse.setErrorMessage("TR069 device request has been timed out."); + return timeOutErrorResponse; + } + + protected NetConfResponse getErrorResponse(String errCode, String errorMsg) { + NetConfResponse errorResponse = new NetConfResponse(); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); + if (errorCodeMetaData != null) { + errorCode.setFaultCode(errCode); + errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); + errorCode.setErrorType(errorCodeMetaData.getErrorType()); + errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); + errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); + } + errorResponse.setErrorCode(errorCode); + errorResponse.setErrorMessage(errorMsg); + return errorResponse; + } + + protected NetConfResponse getOperationAbortedResponse(String errorMessage) { + // prepare timeout error response + NetConfResponse timeOutErrorResponse = new NetConfResponse(); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006"); + if (errorCodeMetaData != null) { + errorCode.setFaultCode("8002"); + errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage()); + errorCode.setErrorType(errorCodeMetaData.getErrorType()); + errorCode.setErrorTag(errorCodeMetaData.getErrorTag()); + errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity()); + } + timeOutErrorResponse.setErrorCode(errorCode); + timeOutErrorResponse.setErrorMessage(errorMessage); + return timeOutErrorResponse; + } + + public List filteredSetParameters(List parameters, String swVersion, + String hwVersion) { + List result = new ArrayList<>(); + for (ParameterDTO param : parameters) { + MOMetaData metaData = + metaDataUtil.getMetaDataByNetConfName(param.getParamName(), swVersion, hwVersion); + if (null != metaData && !metaData.isReadOnly()) { + String tr069MoName = + MOMetaDataUtil.getTR69MOByReplacingIndexes(param.getParamName(), metaData.getMoName()); + param.setDataType(metaData.getDataType()); + param.setParamName(tr069MoName); + result.add(param); + } + } + return result; + } + + protected List filteredGetParameters(List parameters, + String swVersion, String hwVersion) { + return metaDataUtil.getSupportedChildParameters(parameters, swVersion, hwVersion); + } + + @Override + public boolean handelRegisterEvent(NetConfServerDetails request) { + LOG.debug("processing the handelRegisterEvent started"); + try { + VESNotificationResponse vesRsponse = vesnotiSender.sendNotification(null, request); + if (HttpStatus.valueOf(vesRsponse.getStatusCode()).is2xxSuccessful()) { + LOG.debug("processing the handelRegisterEvent completed"); + return true; + } else { + LOG.error("processing the handelRegisterEvent error code recevived: {}", + vesRsponse.getStatusCode()); + return false; + } + } catch (Exception e) { + LOG.error("processing the handelRegisterEvent exception occurred"); + return false; + } + } + + protected static String getDownloadFileURI(String filepath) { + + if (filepath.contains("@") && filepath.contains("//")) { + String[] str = filepath.split("@"); + String[] strForUserName = str[0].split("//"); + if (str.length > 1) { + return strForUserName[0] + "//" + str[1]; + } + } + return null; + } + + protected static String getDownloadUserName(String filepath) { + + if (filepath.contains("@") && filepath.contains("//")) { + String[] str = filepath.split("@"); + String[] strForUserName = str[0].split("//"); + if (strForUserName.length > 1) + return strForUserName[1]; + } + return null; + } + + protected boolean isAdminStateOverriden(List paramList) { + for (ParameterDTO paramDTO : paramList) { + if (paramDTO.getParamName().contains(MapperConstants.ADMIN_STATE) + || paramDTO.getParamName().contains(MapperConstants.ADMIN_STATUS)) { + return true; + } + } + return false; + } + + protected void convertResposeToSPVResponse(DeviceRPCResponse deviceRPCResponse) { + if (null == deviceRPCResponse) { + return; + } + + OperationResponse operationResponse = new SetParameterValueResponse(); + operationResponse.setParameterDTOs(new ArrayList<>()); + + if (null == deviceRPCResponse.getFaultKey()) { + operationResponse.setStatus(MapperConstants.RPC_SUCCESS_CODE); + } else { + operationResponse.setStatus(MapperConstants.RPC_FAILED_CODE); + } + + deviceRPCResponse.setOperationResponse(operationResponse); + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/sync/SynchronizedRequestHandler.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/sync/SynchronizedRequestHandler.java index 532443a..dcdf92b 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/sync/SynchronizedRequestHandler.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/sync/SynchronizedRequestHandler.java @@ -1,109 +1,110 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.sync; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.acs.ACSRequestSender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class SynchronizedRequestHandler { - - private static final Logger LOG = LoggerFactory.getLogger(SynchronizedRequestHandler.class); - - private static Map opResultMap = new HashMap<>(); - private static Map semaphoreMap = new HashMap<>(); - - @Autowired - ACSRequestSender tr069RequestSender; - - @Autowired - MapperConfigProperties config; - - public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) { - Long acsOperationId = tr069RequestSender.sendRequest(deviceRPCRequest); - - if (null == acsOperationId) { - LOG.error("Request could not be sent. opId is null"); - return null; - } - - String mapperUniqOperId = - deviceRPCRequest.getDeviceDetails().getDeviceId() + "_" + acsOperationId; - LOG.debug("Received operation mapperUniqOperId = {}", mapperUniqOperId); - - boolean isSuccess = false; - try { - isSuccess = waitForResult(mapperUniqOperId); - } catch (InterruptedException e) { - LOG.debug( - "InterruptedException while waiting for tr069 operation result for operation request {}", - deviceRPCRequest); - LOG.error("Exception : {}", e.getMessage()); - Thread.currentThread().interrupt(); - } - DeviceRPCResponse result = null; - if (!isSuccess) { - LOG.error("Request got timed out for operation {}", mapperUniqOperId); - semaphoreMap.remove(mapperUniqOperId); - } else { - result = getOperationResult(mapperUniqOperId); - LOG.debug("Received operation result for mapperUniqOperId = {} result : {}", mapperUniqOperId, - result); - } - return result; - - } - - public void notifyResult(DeviceRPCResponse opResult) { - Semaphore mutex = semaphoreMap - .remove(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId()); - if (mutex != null) { - opResultMap.put(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId(), - opResult); - mutex.release(); - } - } - - private DeviceRPCResponse getOperationResult(String mapperUniqOperId) { - return opResultMap.remove(mapperUniqOperId); - } - - private boolean waitForResult(String mapperUniqOperId) throws InterruptedException { - LOG.debug("Waiting for operation result for mapperUniqOperId : {}", mapperUniqOperId); - Semaphore semaphore = new Semaphore(0); - semaphoreMap.put(mapperUniqOperId, semaphore); - LOG.debug("Semaphore MAP size = {}", semaphoreMap.size()); - LOG.debug("opResultMap MAP size = {}", opResultMap.size()); - Integer timeout = 0; - if (null != config.getRequesTimeout()) { - timeout = Integer.valueOf(config.getRequesTimeout()); - } - return semaphore.tryAcquire(timeout, TimeUnit.SECONDS); - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.sync; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.acs.ACSRequestSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SynchronizedRequestHandler { + + private static final Logger LOG = LoggerFactory.getLogger(SynchronizedRequestHandler.class); + + private static Map opResultMap = new HashMap<>(); + private static Map semaphoreMap = new HashMap<>(); + + @Autowired + ACSRequestSender tr069RequestSender; + + @Autowired + MapperConfigProperties config; + + public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) { + Long acsOperationId = tr069RequestSender.sendRequest(deviceRPCRequest); + + if (null == acsOperationId) { + LOG.error("Request could not be sent. opId is null"); + return null; + } + + String mapperUniqOperId = + deviceRPCRequest.getDeviceDetails().getDeviceId() + "_" + acsOperationId; + LOG.debug("Received operation mapperUniqOperId = {}", mapperUniqOperId); + + boolean isSuccess = false; + try { + isSuccess = waitForResult(mapperUniqOperId); + } catch (InterruptedException e) { + LOG.debug( + "InterruptedException while waiting for tr069 operation result for operation request {}", + deviceRPCRequest); + LOG.error("Exception : {}", e.getMessage()); + Thread.currentThread().interrupt(); + } + DeviceRPCResponse result = null; + if (!isSuccess) { + LOG.error("Request got timed out for operation {}", mapperUniqOperId); + semaphoreMap.remove(mapperUniqOperId); + } else { + result = getOperationResult(mapperUniqOperId); + LOG.debug("Received operation result for mapperUniqOperId = {} result : {}", mapperUniqOperId, + result); + } + return result; + + } + + public void notifyResult(DeviceRPCResponse opResult) { + Semaphore mutex = semaphoreMap + .remove(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId()); + if (mutex != null) { + opResultMap.put(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId(), + opResult); + mutex.release(); + } + } + + private DeviceRPCResponse getOperationResult(String mapperUniqOperId) { + return opResultMap.remove(mapperUniqOperId); + } + + private boolean waitForResult(String mapperUniqOperId) throws InterruptedException { + LOG.debug("Waiting for operation result for mapperUniqOperId : {}", mapperUniqOperId); + Semaphore semaphore = new Semaphore(0); + semaphoreMap.put(mapperUniqOperId, semaphore); + LOG.debug("Semaphore MAP size = {}", semaphoreMap.size()); + LOG.debug("opResultMap MAP size = {}", opResultMap.size()); + Integer timeout = 0; + if (null != config.getRequesTimeout()) { + timeout = Integer.valueOf(config.getRequesTimeout()); + } + return semaphore.tryAcquire(timeout, TimeUnit.SECONDS); + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/FirwareUpgradeErrorCode.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/FirwareUpgradeErrorCode.java index 01c926e..3d924aa 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/FirwareUpgradeErrorCode.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/FirwareUpgradeErrorCode.java @@ -16,28 +16,32 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.mapper.util; - -import java.util.HashMap; -import java.util.Map; - -public class FirwareUpgradeErrorCode { - private static Map ErrorCodes = new HashMap();; - - static { - ErrorCodes.put(9019, "AUTHENTICATION_ERROR"); - ErrorCodes.put(9001, "AUTHENTICATION_ERROR"); - ErrorCodes.put(9016, "AUTHENTICATION_ERROR"); - ErrorCodes.put(9012, "AUTHENTICATION_ERROR"); - ErrorCodes.put(9015, "PROTOCOL_ERROR"); - ErrorCodes.put(9002, "APPLICATION_ERROR"); - ErrorCodes.put(9003, "APPLICATION_ERROR"); - ErrorCodes.put(9020, "TIMEOUT"); - ErrorCodes.put(0, "COMPLETED"); - } - - public static String getErrorCodeMapping(int errorCode) { - return ErrorCodes.get(errorCode) != null ? ErrorCodes.get(errorCode) : "APPLICATION_ERROR"; - } - -} +package org.commscope.tr069adapter.mapper.util; + +import java.util.HashMap; +import java.util.Map; + +public class FirwareUpgradeErrorCode { + private FirwareUpgradeErrorCode() {} + + private static Map errorCodes = new HashMap<>(); + private static final String AUTHENTICATION_ERROR = "AUTHENTICATION_ERROR"; + private static final String APPLICATION_ERROR = "APPLICATION_ERROR"; + + static { + errorCodes.put(9019, AUTHENTICATION_ERROR); + errorCodes.put(9001, AUTHENTICATION_ERROR); + errorCodes.put(9016, AUTHENTICATION_ERROR); + errorCodes.put(9012, AUTHENTICATION_ERROR); + errorCodes.put(9015, "PROTOCOL_ERROR"); + errorCodes.put(9002, APPLICATION_ERROR); + errorCodes.put(9003, APPLICATION_ERROR); + errorCodes.put(9020, "TIMEOUT"); + errorCodes.put(0, "COMPLETED"); + } + + public static String getErrorCodeMapping(int errorCode) { + return errorCodes.get(errorCode) != null ? errorCodes.get(errorCode) : APPLICATION_ERROR; + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/MOMetaDataUtil.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/MOMetaDataUtil.java index dcebc63..394c73c 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/MOMetaDataUtil.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/MOMetaDataUtil.java @@ -1,234 +1,273 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.util; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.PostConstruct; -import org.apache.commons.io.FileUtils; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; -import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition; -import org.commscope.tr069adapter.mapper.MOMetaData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class MOMetaDataUtil { - - private static final String STRING_I = ".{i}."; - private static final Logger LOG = LoggerFactory.getLogger(MOMetaDataUtil.class); - private static final String GENERIC_INDEX_REGEX = "\\.\\{[i-l]\\}\\."; - private static final String INDEX_REGEX = "\\.[0-9]{1,}\\."; - private static final String MO_META_DATA_FILE_LOCATION = "mapper-schema"; - private Map> metaDataMap; - private Map> metaDataReverseMap; - public static final String ORAN_SW_MGMT_URI = "urn:o-ran:software-management:1.0"; - - @Autowired - DeviceVersionManager versionManager; - - @PostConstruct - public void loadMetaData() { - - try { - LOG.info("Loading mapper schema"); - if (metaDataMap != null) - metaDataMap.clear(); - if (metaDataReverseMap != null) - metaDataReverseMap.clear(); - getMetaDataAsMap(MO_META_DATA_FILE_LOCATION); - LOG.info("Loading mapper schema successfully completed"); - } catch (IOException e) { - LOG.error("Exception : {}", e.getMessage()); - } - } - - private void getMetaDataAsMap(String fileLocation) throws IOException { - metaDataMap = new HashMap<>(); - metaDataReverseMap = new HashMap<>(); - - List profiles = versionManager.getSupportedProfileDefinitions(); - for (ProfileDefinition profileDefinition : profiles) { - Map profileMetaDataMap = new HashMap<>(); - Map profileMetaDataReverseMap = new HashMap<>(); - - Collection files = FileUtils.listFiles( - new File(fileLocation + "/" + profileDefinition.getCsdmMappingPath()), null, false); - for (File file : files) { - LOG.info("Loading mapper schema from {}", file.getName()); - List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); - for (String line : lines) { - if (line != null && line.startsWith("#")) { - continue; - } - if (line != null && line.split(",").length >= 3) { - parseMetaDataLine(line, profileMetaDataMap, profileMetaDataReverseMap); - } - } - } - metaDataMap.put(profileDefinition.getProfileId(), profileMetaDataMap); - metaDataReverseMap.put(profileDefinition.getProfileId(), profileMetaDataReverseMap); - } - } - - private static void parseMetaDataLine(String line, Map profileMetaDataMap, - Map profileMetaDataReverseMap) { - String[] split = line.split(","); - boolean isReadOnly = false; - boolean isTabluar = false; - boolean isTabObject = false; - if (split[2].contains("-")) { - String[] dataAttr = split[2].split("-"); - if ("Tabular".equalsIgnoreCase(dataAttr[0])) - isTabluar = true; - if ("ReadOnly".equalsIgnoreCase(dataAttr[1])) - isReadOnly = true; - } else if ("TabularObject".equalsIgnoreCase(split[2])) { - isTabObject = true; - } - prepareMOMetaData(isReadOnly, isTabluar, split, isTabObject, profileMetaDataMap, - profileMetaDataReverseMap); - } - - private static void prepareMOMetaData(boolean isReadOnly, boolean isTabluar, String[] split, - boolean isTabObject, Map profileMetaDataMap, - Map profileMetaDataReverseMap) { - String dataType = ""; - if (split.length > 3) { - dataType = split[3]; - } - if (isTabObject) { - String logMessage = split[1].substring(0, split[1].length() - 5); - LOG.info("Adding Parent Objects {}", logMessage); - String substring = split[0].substring(0, split[0].length() - 4); - MOMetaData metaTabData = - new MOMetaData(substring, dataType, isReadOnly, isTabluar, isTabObject); - if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) { - metaTabData.setURI(split[4]); - } - profileMetaDataMap.put(logMessage, metaTabData); - } - MOMetaData metaData = new MOMetaData(split[0], dataType, isReadOnly, isTabluar, isTabObject); - if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) { - metaData.setURI(split[4]); - } - profileMetaDataMap.put(split[1], metaData); - profileMetaDataReverseMap.put(split[0], split[1]); - } - - public MOMetaData getMetaDataByNetConfName(String moName, String swVersion, String hwVersion) { - String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); - - String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); - Map metaData = metaDataMap.get(profileId); - - return metaData.get(moNameInGnrForm); - } - - public MOMetaData getMetaDataByTR69Name(String moName, String swVersion, String hwVersion) { - String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); - - String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); - Map profileReverseMetaData = metaDataReverseMap.get(profileId); - Map profileMetaData = metaDataMap.get(profileId); - - String netconfMoName = profileReverseMetaData.get(moNameInGnrForm); - return profileMetaData.get(netconfMoName); - } - - public String getNetconfNameByTR69NameWithIndexes(String moName, String swVersion, - String hwVersion) { - String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); - String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); - Map reverseMetaData = metaDataReverseMap.get(profileId); - String netConfNMoName = reverseMetaData.get(moNameInGnrForm); - return netConfNMoName != null ? getNetConfMOByReplacingIndexes(netConfNMoName, moName) - : netConfNMoName; - } - - public List getSupportedChildParameters(List parameters, - String swVersion, String hwVersion) { - List result = new ArrayList<>(); - Set allMatchedChilds = new HashSet<>(); - String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); - Map profileMetaData = metaDataMap.get(profileId); - for (ParameterDTO param : parameters) { - String parentMONameInGnrc = param.getParamName().replaceAll(INDEX_REGEX, STRING_I); - MOMetaData moData = profileMetaData.get(parentMONameInGnrc); - if (moData != null) { - allMatchedChilds.add(new MOMetaData( - getTR69MOByReplacingIndexes(param.getParamName(), moData.getMoName()), - moData.getDataType(), moData.isReadOnly(), moData.isTabluar(), moData.isTabluarObj())); - } - } - for (MOMetaData metaData : allMatchedChilds) { - ParameterDTO param = new ParameterDTO(); - String paramName = metaData.getMoName(); - - param.setParamName(paramName); - param.setDataType(metaData.getDataType()); - result.add(param); - } - return result; - } - - public List getDeviceSupportedChildParameters() { - List result = new ArrayList<>(); - - ParameterDTO param1 = new ParameterDTO(); - param1.setParamName("Device.DeviceInfo.Description"); - param1.setParamValue("Internal"); - param1.setDataType("string"); - result.add(param1); - return result; - } - - public static String getTR69MOByReplacingIndexes(String netconfMo, String tr69Mo) { - - String[] split = netconfMo.split("\\."); - for (int i = 0; i < split.length; i++) { - if (split[i].matches("[0-9]{1,}")) { - tr69Mo = tr69Mo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + "."); - } - } - return tr69Mo; - } - - public static String getNetConfMOByReplacingIndexes(String netconfMo, String tr69Mo) { - - String[] split = tr69Mo.split("\\."); - for (int i = 0; i < split.length; i++) { - if (split[i].matches("[0-9]{1,}")) { - netconfMo = netconfMo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + "."); - } - } - return netconfMo; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.util; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; + +import org.apache.commons.io.FileUtils; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; +import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition; +import org.commscope.tr069adapter.mapper.MOMetaData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class MOMetaDataUtil { + + private static final String STRING_I = ".{i}."; + private static final Logger LOG = LoggerFactory.getLogger(MOMetaDataUtil.class); + private static final String GENERIC_INDEX_REGEX = "\\.\\{[i-l]\\}\\."; + private static final String INDEX_REGEX = "\\.[0-9]{1,}\\."; + private static final String MO_META_DATA_FILE_LOCATION = "mapper-schema"; + private Map> metaDataMap; + private Map> metaDataReverseMap; + public static final String ORAN_SW_MGMT_URI = "urn:o-ran:software-management:1.0"; + + @Autowired + DeviceVersionManager versionManager; + + @PostConstruct + public void loadMetaData() { + + try { + LOG.info("Loading mapper schema"); + if (metaDataMap != null) + metaDataMap.clear(); + if (metaDataReverseMap != null) + metaDataReverseMap.clear(); + getMetaDataAsMap(MO_META_DATA_FILE_LOCATION); + LOG.info("Loading mapper schema successfully completed"); + } catch (IOException e) { + LOG.error("Exception : {}", e.getMessage()); + } + } + + private void getMetaDataAsMap(String fileLocation) throws IOException { + metaDataMap = new HashMap<>(); + metaDataReverseMap = new HashMap<>(); + + List profiles = versionManager.getSupportedProfileDefinitions(); + for (ProfileDefinition profileDefinition : profiles) { + Map profileMetaDataMap = new HashMap<>(); + Map profileMetaDataReverseMap = new HashMap<>(); + + Collection files = FileUtils.listFiles( + new File(fileLocation + "/" + profileDefinition.getCsdmMappingPath()), null, false); + for (File file : files) { + LOG.info("Loading mapper schema from {}", file.getName()); + List lines = FileUtils.readLines(file, StandardCharsets.UTF_8); + for (String line : lines) { + if (line != null && line.startsWith("#")) { + continue; + } + if (line != null && line.split(",").length >= 3) { + parseMetaDataLine(line, profileMetaDataMap, profileMetaDataReverseMap); + } + } + } + metaDataMap.put(profileDefinition.getProfileId(), profileMetaDataMap); + metaDataReverseMap.put(profileDefinition.getProfileId(), profileMetaDataReverseMap); + } + } + + private static void parseMetaDataLine(String line, Map profileMetaDataMap, + Map profileMetaDataReverseMap) { + String[] split = line.split(","); + boolean isReadOnly = false; + boolean isTabluar = false; + boolean isTabObject = false; + if (split[2].contains("-")) { + String[] dataAttr = split[2].split("-"); + if ("Tabular".equalsIgnoreCase(dataAttr[0])) + isTabluar = true; + if ("ReadOnly".equalsIgnoreCase(dataAttr[1])) + isReadOnly = true; + } else if ("TabularObject".equalsIgnoreCase(split[2])) { + isTabObject = true; + } + prepareMOMetaData(isReadOnly, isTabluar, split, isTabObject, profileMetaDataMap, + profileMetaDataReverseMap); + } + + private static void prepareMOMetaData(boolean isReadOnly, boolean isTabluar, String[] split, + boolean isTabObject, Map profileMetaDataMap, + Map profileMetaDataReverseMap) { + String dataType = ""; + if (split.length > 3) { + dataType = split[3]; + } + if (isTabObject) { + String logMessage = split[1].substring(0, split[1].length() - 5); + LOG.info("Adding Parent Objects {}", logMessage); + String substring = split[0].substring(0, split[0].length() - 4); + MOMetaData metaTabData = + new MOMetaData(substring, dataType, isReadOnly, isTabluar, isTabObject); + if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) { + metaTabData.setURI(split[4]); + } + profileMetaDataMap.put(logMessage, metaTabData); + } + MOMetaData metaData = new MOMetaData(split[0], dataType, isReadOnly, isTabluar, isTabObject); + if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) { + metaData.setURI(split[4]); + } + profileMetaDataMap.put(split[1], metaData); + profileMetaDataReverseMap.put(split[0], split[1]); + } + + public MOMetaData getMetaDataByNetConfName(String moName, String swVersion, String hwVersion) { + String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); + String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); + Map metaData = metaDataMap.get(profileId); + return metaData.get(moNameInGnrForm); + } + + public MOMetaData getMetaDataByTR69Name(String moName, String swVersion, String hwVersion) { + String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); + + String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); + Map profileReverseMetaData = metaDataReverseMap.get(profileId); + Map profileMetaData = metaDataMap.get(profileId); + + String netconfMoName = profileReverseMetaData.get(moNameInGnrForm); + return profileMetaData.get(netconfMoName); + } + + public String getNetconfNameByTR69NameWithIndexes(String moName, String swVersion, + String hwVersion) { + String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I); + String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); + Map reverseMetaData = metaDataReverseMap.get(profileId); + String netConfNMoName = reverseMetaData.get(moNameInGnrForm); + return netConfNMoName != null ? getNetConfMOByReplacingIndexes(netConfNMoName, moName) + : netConfNMoName; + } + + public String getTR069NameByNetconfNameWithIndexes(String netconfName, String swVersion, + String hwVersion) { + String moNameInGnrForm = netconfName.replaceAll(INDEX_REGEX, STRING_I); + String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); + Map profileMetaData = metaDataMap.get(profileId); + String tr069MoName = profileMetaData.get(moNameInGnrForm).getMoName(); + return tr069MoName != null ? getTR69MOByReplacingIndexes(netconfName, tr069MoName) + : tr069MoName; + } + + public List getSupportedChildParameters(List parameters, + String swVersion, String hwVersion) { + List result = new ArrayList<>(); + Set allMatchedChilds = new HashSet<>(); + String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion); + Map profileMetaData = metaDataMap.get(profileId); + for (ParameterDTO param : parameters) { + String parentMONameInGnrc = param.getParamName().replaceAll(INDEX_REGEX, STRING_I); + MOMetaData moData = profileMetaData.get(parentMONameInGnrc); + if (moData != null) { + allMatchedChilds.add(new MOMetaData( + getTR69MOByReplacingIndexes(param.getParamName(), moData.getMoName()), + moData.getDataType(), moData.isReadOnly(), moData.isTabluar(), moData.isTabluarObj())); + } + } + for (MOMetaData metaData : allMatchedChilds) { + ParameterDTO param = new ParameterDTO(); + String paramName = metaData.getMoName(); + + param.setParamName(paramName); + param.setDataType(metaData.getDataType()); + result.add(param); + } + return result; + } + + public List getDeviceSupportedChildParameters() { + List result = new ArrayList<>(); + + ParameterDTO param1 = new ParameterDTO(); + param1.setParamName("Device.DeviceInfo.Description"); + param1.setParamValue("Internal"); + param1.setDataType("string"); + result.add(param1); + return result; + } + + public static String getTR69MOByReplacingIndexes(String netconfMo, String tr69Mo) { + + String[] split = netconfMo.split("\\."); + for (int i = 0; i < split.length; i++) { + if (split[i].matches("[0-9]{1,}")) { + tr69Mo = tr69Mo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + "."); + } + } + return tr69Mo; + } + + public static String getNetConfMOByReplacingIndexes(String netconfMo, String tr69Mo) { + + String[] split = tr69Mo.split("\\."); + for (int i = 0; i < split.length; i++) { + if (split[i].matches("[0-9]{1,}")) { + netconfMo = netconfMo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + "."); + } + } + return netconfMo; + } + + public String getNetconfXPathNameByTR69NameWithIndexes(String paramName, String swVersion, + String hwVersion) { + String netconfName = getNetconfNameByTR69NameWithIndexes(paramName, swVersion, hwVersion); + if (netconfName == null) + return null; + String[] splitArray = netconfName.split("\\."); + StringBuilder sb = new StringBuilder(); + StringBuilder nodeName = new StringBuilder(); + String tokenizer = "."; + for (String token : splitArray) { + if (nodeName.length() == 0) + nodeName.append(token); + else { + nodeName.append(tokenizer); + nodeName.append(token); + } + MOMetaData metaData = getMetaDataByNetConfName(nodeName.toString(), swVersion, hwVersion); + if (null != metaData && null != metaData.getURI()) { + sb.append("/" + token + "[" + "@xmlns=" + metaData.getURI() + "]"); + } else if (token.matches("[0-9]*")) { + sb.append("[" + token + "]"); + } else { + sb.append("/" + token); + } + } + return sb.toString(); + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/NetconfToTr069MapperUtil.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/NetconfToTr069MapperUtil.java index 81245d0..1eb3bdc 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/NetconfToTr069MapperUtil.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/util/NetconfToTr069MapperUtil.java @@ -1,584 +1,825 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.util; - -import java.io.Serializable; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationOptions; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -@Component -public class NetconfToTr069MapperUtil { - - @Autowired - MOMetaDataUtil metaDataUtil; - - @Autowired - MapperConfigProperties config; - - private static final Logger logger = LoggerFactory.getLogger(NetconfToTr069MapperUtil.class); - private static final String INDEX_STR = "index"; - private static final String INDEX_REGEX = "[0-9]{1,}"; - - @Autowired - private ErrorCodeUtil errorCodeUtil; - - public static Element convertStringToDocument(String xmlStr) { - try { - Document doc = convertStringToDocumentXml(xmlStr); - if (null != doc) - return doc.getDocumentElement(); - } catch (Exception e) { - logger.error("Error while converting String to element {}", e.getMessage()); - } - return null; - } - - public static Document convertStringToDocumentXml(String xmlStr) { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - DocumentBuilder builder; - builder = factory.newDocumentBuilder(); - return builder.parse(new InputSource(new StringReader(xmlStr))); - } catch (Exception e) { - logger.error("Error while converting String to element {}", e.getMessage()); - } - return null; - } - - public static Map extractRequestParamters(Document operationElement, - String netconfTag, String filterElement) { - Node requestDataNode = getParameterDataNode(operationElement, netconfTag, filterElement); - Map map = getParameterMapForNode(requestDataNode, -1); - return map; - } - - public static DeviceRPCRequest prepareTR069Request(String deviceId, Element operationElement, - String netconfTag, TR069OperationCode opCode) { - Node requestDataNode = getDeviceDataNode(operationElement, netconfTag); - if (requestDataNode == null) { - logger.debug("No matching device parameters found in the netconf request XML."); - return null; - } - Map map = getParameterMapForNode(requestDataNode, -1); - List params = new ArrayList<>(); - - for (java.util.Map.Entry entry : map.entrySet()) { - if (!entry.getKey().equalsIgnoreCase("filter")) { - String moName = entry.getKey(); - String value = entry.getValue(); - if (moName.endsWith("." + INDEX_STR) - && (TR069OperationCode.GET_PARAMETER_VALUES.equals(opCode) - || TR069OperationCode.DELETE_OBJECT.equals(opCode))) { - logger.debug("Index node found : {}", moName); - moName = moName.replaceFirst("." + INDEX_STR, "."); - value = null; - - } - - ParameterDTO param = new ParameterDTO(moName, value); - params.add(param); - } - } - - TR069OperationDetails opDetails = new TR069OperationDetails(); - opDetails.setOpCode(opCode); - return handleParamsOperation(params, opDetails, deviceId); - } - - public static DeviceRPCRequest handleParamsOperation(List params, - TR069OperationDetails opDetails, String deviceId) { - opDetails.setParmeters(params); - - DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); - TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); - tr069DeviceDetails.setDeviceId(deviceId); - deviceRPCRequest.setOpDetails(opDetails); - deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); - OperationOptions options = new OperationOptions(); - options.setExecutionTimeout(60l); - deviceRPCRequest.setOptions(options); - return deviceRPCRequest; - } - - public NetConfResponse getNetconfResponse(DeviceRPCResponse opResult, String swVersion, - String hwVersion, boolean isCustomparameter) { - NetConfResponse netConfResponse = new NetConfResponse(); - ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - if (errorCodeDetails != null) { - errorCode.setFaultCode(opResult.getFaultKey()); - errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); - errorCode.setErrorType(errorCodeDetails.getErrorType()); - errorCode.setErrorTag(errorCodeDetails.getErrorTag()); - errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage(opResult.getFaultString()); - } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { - errorCode.setFaultCode(opResult.getFaultKey()); - errorCode.setErrorMessage(opResult.getFaultString()); - errorCode.setErrorType("application"); - errorCode.setErrorTag("operation-failed"); - errorCode.setErrorSeverity("ERROR"); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage(opResult.getFaultString()); - } - netConfResponse.setNetconfResponseXml( - getNetconfResponseXML(opResult.getOperationResponse().getParameterDTOs(), swVersion, - hwVersion, isCustomparameter)); - return netConfResponse; - } - - public NetConfResponse getNetconfResponseForSoftwareInventory(DeviceRPCResponse opResult, - String swVersion, String hwVersion) { - - NetConfResponse netConfResponse = new NetConfResponse(); - ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); - ErrorCodeDetails errorCode = new ErrorCodeDetails(); - if (errorCodeDetails != null) { - errorCode.setFaultCode(opResult.getFaultKey()); - errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); - errorCode.setErrorType(errorCodeDetails.getErrorType()); - errorCode.setErrorTag(errorCodeDetails.getErrorTag()); - errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage(opResult.getFaultString()); - return netConfResponse; - } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { - errorCode.setFaultCode(opResult.getFaultKey()); - errorCode.setErrorMessage(opResult.getFaultString()); - errorCode.setErrorType("application"); - errorCode.setErrorTag("operation-failed"); - errorCode.setErrorSeverity("ERROR"); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage(opResult.getFaultString()); - return netConfResponse; - } - List paramDTOList = new ArrayList<>(); - - String build = null; - String productClass = null; - for (ParameterDTO paramDto : opResult.getOperationResponse().getParameterDTOs()) { - if (paramDto.getParamName().equals("Device.DeviceInfo.SoftwareVersion")) - build = paramDto.getParamValue(); - else if (paramDto.getParamName().equals("Device.DeviceInfo.ProductClass")) - productClass = paramDto.getParamValue(); - } - - String[] arrOfBuild = build.split("\\."); - String buildId = arrOfBuild[arrOfBuild.length - 1]; - StringBuilder buildVersion = new StringBuilder(); - for (int i = 0; i < arrOfBuild.length - 1; i++) { - if (i == arrOfBuild.length - 2) { - buildVersion.append(arrOfBuild[i]); - } else { - buildVersion.append(arrOfBuild[i]); - buildVersion.append("."); - } - } - - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.name", "Active Partition")); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.status", "VALID")); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.active", "true")); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.running", "true")); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.access", "READ_ONLY")); - paramDTOList - .add(new ParameterDTO("software-inventory.software-slot.product-code", productClass)); - paramDTOList.add( - new ParameterDTO("software-inventory.software-slot.vendor-code", config.getVendorName())); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-id", buildId)); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-version", - buildVersion.toString())); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.name", "BC_ONE")); - paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.integrity", "OK")); - - String XmlStr = getNetconfResponseXML(paramDTOList, swVersion, hwVersion, true); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - Document doc = null; - try { - builder = factory.newDocumentBuilder(); - doc = builder.parse(new InputSource(new StringReader(XmlStr))); - } catch (Exception e) { - logger.error("Error while converting String to element" + e); - errorCode.setFaultCode("8002"); - errorCode.setErrorMessage("Operation Aborted"); - errorCode.setErrorType("application"); - errorCode.setErrorTag("operation-failed"); - errorCode.setErrorSeverity("ERROR"); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage("Operation Aborted"); - return netConfResponse; - } - - Element originalDocumentElement = doc.getDocumentElement(); - Element newDocumentElement = doc.createElementNS("urn:o-ran:software-management:1.0", - originalDocumentElement.getNodeName()); - NodeList list = originalDocumentElement.getChildNodes(); - while (list.getLength() != 0) { - newDocumentElement.appendChild(list.item(0)); - } - // Replace the original element - doc.replaceChild(newDocumentElement, originalDocumentElement); - - String strxml = null; - try { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(new StringWriter()); - transformer.transform(source, result); - strxml = result.getWriter().toString(); - } catch (Exception e) { - logger.error("Error while converting Element to String" + e); - errorCode.setFaultCode("8002"); - errorCode.setErrorMessage("Operation Aborted"); - errorCode.setErrorType("application"); - errorCode.setErrorTag("operation-failed"); - errorCode.setErrorSeverity("ERROR"); - netConfResponse.setErrorCode(errorCode); - netConfResponse.setErrorMessage("Operation Aborted"); - return netConfResponse; - } - - netConfResponse.setNetconfResponseXml(strxml); - logger.debug("NetConf Response XML String for software inventory: " + strxml); - return netConfResponse; - } - - private String getNetconfResponseXML(List parameters, String swVersion, - String hwVersion, boolean isCustomparameter) { - if (null == parameters || parameters.isEmpty()) { - // LOG.debug("There are no parameters found in the response."); - return null; - } - Collections.sort(parameters, new SortByParamterName()); - - String result = null; - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.newDocument(); - - Map parentNodeMap = new HashMap<>(); - Element dataNode = null; // root of all nodes - - for (ParameterDTO paramDto : parameters) { - String paramName = metaDataUtil.getNetconfNameByTR69NameWithIndexes(paramDto.getParamName(), - swVersion, hwVersion); - if (paramName == null && isCustomparameter) { - paramName = paramDto.getParamName(); - } - String paramValue = paramDto.getParamValue(); - if (paramValue == null || paramValue.trim().isEmpty()) { - continue; - } - StringTokenizer tokenizer = new StringTokenizer(paramName, "."); - String parentNodeName = null; - String parentNodeKey = null; - Element parentNode = null; - while (tokenizer.hasMoreElements()) { - String nodeName = (String) tokenizer.nextElement(); - if (null == parentNodeName) { // construct first node or - // Device node - parentNodeName = nodeName; - parentNodeKey = nodeName; - // check if the node already exists in parentNodeMap - parentNode = parentNodeMap.get(parentNodeKey); - if (null == dataNode) { - dataNode = parentNode; - } - continue; - } else if (nodeName.matches(INDEX_REGEX)) { // construct - // tabular and - // index nodes - - // get parent tabular node from parent MAP - parentNodeKey = parentNodeKey + "." + nodeName; - Element node = parentNodeMap.get(parentNodeKey); - - // create a tabular parent node if doesn't exit in MAP - if (null == node) { - if (metaDataUtil.getMetaDataByNetConfName(parentNodeKey + ".", swVersion, - hwVersion) != null - && metaDataUtil - .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion) - .getURI() != null) { - node = doc.createElementNS(metaDataUtil - .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion).getURI(), - parentNodeName); - } else { - node = doc.createElement(parentNodeName); - } - parentNodeMap.put(parentNodeKey, node); - - // update current tabular parent node. - if (null != parentNode) - parentNode.appendChild(node); - - // prepare and add index node to tabular parent node - Element indexNode = doc.createElement(INDEX_STR); - indexNode.setTextContent(nodeName); - node.appendChild(indexNode); - } - parentNode = node; // move parent to child - parentNodeName = nodeName; - } else if (parentNodeName.matches(INDEX_REGEX)) { // move to - // next - // node - // if - // tabular - // attribute - // is - // found - parentNodeKey = parentNodeKey + "." + nodeName; - parentNodeName = nodeName; - } else { - // construct intermediate nodes - Element node = parentNodeMap.get(parentNodeKey); - if (null == node) { - if (metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion) != null - && metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion) - .getURI() != null) { - node = doc.createElementNS(metaDataUtil - .getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion).getURI(), - parentNodeName); - if (dataNode == null) - dataNode = node; - } else { - node = doc.createElement(parentNodeName); - } - parentNodeMap.put(parentNodeKey, node); - if (null != parentNode) - parentNode.appendChild(node); - - } - parentNodeKey = parentNodeKey + "." + nodeName; - parentNodeName = nodeName; - parentNode = node; - } - } - // construct leaf node - Element leafNode = doc.createElement(parentNodeName); - leafNode.setTextContent(paramValue); - if (parentNode != null) - parentNode.appendChild(leafNode); - } - - if (null != dataNode) { - result = convertDocumentToString(dataNode); - } - } catch (ParserConfigurationException pce) { - logger.error("Response xml formatting is failed : {} ", pce.toString()); - } - - return result; - } - - public static String convertDocumentToString(Element element) { - String strxml = null; - try { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(element); - StreamResult result = new StreamResult(new StringWriter()); - transformer.transform(source, result); - strxml = result.getWriter().toString(); - } catch (Exception e) { - logger.error("Error while converting Element to String {}", e.toString()); - } - logger.debug("Converted XML is : {} ", strxml); - return strxml; - } - - // TODO: Need to optimize the Node element logic for better performance - private static Map getParameterMapForNode(Node moRNode, int numberOfChilds) { - Map result = new HashMap<>(); - if (moRNode.getNodeType() == Node.ELEMENT_NODE) { - NodeList childs = moRNode.getChildNodes(); - boolean hasChildElements = false; - hasChildElements = checkMoreElements(result, childs, hasChildElements); - if (!hasChildElements) { - String moName = getMOName(moRNode); - if (moName.equals("software-inventory")) { - result.put("device.device-info.software-version", moRNode.getTextContent()); - result.put("device.device-info.product-class", moRNode.getTextContent()); - } else if (!moName.endsWith("." + INDEX_STR)) { - result.put(moName, moRNode.getTextContent()); - } else if (numberOfChilds == 1) { - result.put(moName, moRNode.getTextContent()); - } - } - } - - return result; - } - - private static boolean checkMoreElements(Map result, NodeList childs, - boolean hasChildElements) { - if (childs.getLength() > 0) { - int counter = 0; - for (int i = 0; i < childs.getLength(); i++) { - Node cNode = childs.item(i); - if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) { - counter++; - } - } - - for (int i = 0; i < childs.getLength(); i++) { - Node cNode = childs.item(i); - if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) { - hasChildElements = true; - Map subResult = getParameterMapForNode(cNode, counter); - result.putAll(subResult); - } - } - } - return hasChildElements; - } - - private static String getMOName(Node moRNode) { - String result = removeNS(moRNode.getNodeName()); - Node pNode = moRNode; - while (true) { - pNode = pNode.getParentNode(); - if (pNode == null || pNode.getNodeType() != Node.ELEMENT_NODE - || pNode.getNodeName().equals("edit-config") || pNode.getNodeName().equals("config") - || pNode.getNodeName().equals("get-config") || pNode.getNodeName().equals("filter") - || pNode.getNodeName().equals("get")) { - return result; - } else { - String indexStr = getMOIndex(pNode); - StringBuilder bld = new StringBuilder(removeNS(pNode.getNodeName())); - bld.append("."); - if (indexStr == null) { - bld.append(result); - result = bld.toString(); - } else { - bld.append(indexStr); - bld.append("."); - bld.append(result); - result = bld.toString(); - } - } - } - } - - private static Node getParameterDataNode(Document el, String docStart, String filterElement) { - NodeList nodeList = el.getElementsByTagName(docStart); - if (nodeList.getLength() > 0) { - nodeList = nodeList.item(0).getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - String nodeName = removeNS(node.getNodeName()); - if (nodeName.equals(filterElement)) { - return node; - } - } - } - return null; - } - - private static Node getDeviceDataNode(Element el, String filter) { - try { - NodeList nodeList = el.getElementsByTagName(filter); - if (nodeList.getLength() > 0) { - nodeList = nodeList.item(0).getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - return node; - } - } - } - } catch (Exception e) { - logger.error("exception occured while parsing the request xml {}", e.getMessage()); - } - return null; - } - - private static String removeNS(String nodeName) { - // remove name space - int li = nodeName.lastIndexOf(':'); - nodeName = nodeName.substring(li + 1); - return nodeName; - } - - private static String getMOIndex(Node pNode) { - if (null != pNode) { - NodeList nodeList = pNode.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node childNode = nodeList.item(i); - String nodeName = removeNS(childNode.getNodeName()); - if (nodeName.equalsIgnoreCase(INDEX_STR)) { - return childNode.getTextContent(); - } - } - } - return null; - } - -} - - -class SortByParamterName implements Comparator, Serializable { - private static final long serialVersionUID = 3010693349267067945L; - - public int compare(ParameterDTO a, ParameterDTO b) { - return a.getParamName().compareTo(b.getParamName()); - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.util; + +import java.io.Serializable; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationOptions; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +@Component +public class NetconfToTr069MapperUtil { + + @Autowired + MOMetaDataUtil metaDataUtil; + + @Autowired + MapperConfigProperties config; + + private static final Logger logger = LoggerFactory.getLogger(NetconfToTr069MapperUtil.class); + private static final String INDEX_STR = "index"; + private static final String INDEX_REGEX = "[0-9]{1,}"; + private static final String APPLICATION = "application"; + private static final String OPERATION_FAILED = "operation-failed"; + private static final String ERROR = "ERROR"; + private static final String OPERATION_ABORTED = "Operation Aborted"; + private static final String INDEX_NODE_FOUND = "Index node found : {}"; + + @Autowired + private ErrorCodeUtil errorCodeUtil; + + public static Element convertStringToDocument(String xmlStr) { + try { + Document doc = convertStringToDocumentXml(xmlStr); + if (null != doc) + return doc.getDocumentElement(); + } catch (Exception e) { + logger.error("Error while converting String to element {}", e.getMessage()); + } + return null; + } + + public static Document convertStringToDocumentXml(String xmlStr) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + builder = factory.newDocumentBuilder(); + return builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element {}", e.getMessage()); + } + return null; + } + + public static Map extractRequestParamters(Document operationElement, + String netconfTag, String filterElement) { + Node requestDataNode = getParameterDataNode(operationElement, netconfTag, filterElement); + Map result = new HashMap<>(); + try { + result = getParameterMapForNode(requestDataNode, -1); + } catch (Exception e) { + logger.error("Error while getting parameter Map {}", e.getMessage()); + } + return result; + } + + public static DeviceRPCRequest prepareTR069Request(String deviceId, Element operationElement, + String netconfTag, TR069OperationCode opCode) { + Node requestDataNode = getDeviceDataNode(operationElement, netconfTag); + if (requestDataNode == null) { + logger.debug("No matching device parameters found in the netconf request XML."); + return null; + } + Map map = getParameterMapForNode(requestDataNode, -1); + List params = new ArrayList<>(); + + for (java.util.Map.Entry entry : map.entrySet()) { + if (!entry.getKey().equalsIgnoreCase("filter")) { + String moName = entry.getKey(); + String value = entry.getValue(); + if (moName.endsWith("." + INDEX_STR) + && (TR069OperationCode.GET_PARAMETER_VALUES.equals(opCode) + || TR069OperationCode.DELETE_OBJECT.equals(opCode))) { + logger.debug(INDEX_NODE_FOUND, moName); + moName = moName.replaceFirst("." + INDEX_STR, "."); + value = null; + + } + + ParameterDTO param = new ParameterDTO(moName, value); + params.add(param); + } + } + + TR069OperationDetails opDetails = new TR069OperationDetails(); + opDetails.setOpCode(opCode); + return handleParamsOperation(params, opDetails, deviceId); + } + + public static DeviceRPCRequest handleParamsOperation(List params, + TR069OperationDetails opDetails, String deviceId) { + opDetails.setParmeters(params); + + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails(); + tr069DeviceDetails.setDeviceId(deviceId); + deviceRPCRequest.setOpDetails(opDetails); + deviceRPCRequest.setDeviceDetails(tr069DeviceDetails); + OperationOptions options = new OperationOptions(); + options.setExecutionTimeout(60l); + deviceRPCRequest.setOptions(options); + return deviceRPCRequest; + } + + public NetConfResponse getNetconfResponse(DeviceRPCResponse opResult, String swVersion, + String hwVersion, boolean isCustomparameter) { + NetConfResponse netConfResponse = new NetConfResponse(); + ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + if (errorCodeDetails != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); + errorCode.setErrorType(errorCodeDetails.getErrorType()); + errorCode.setErrorTag(errorCodeDetails.getErrorTag()); + errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(opResult.getFaultString()); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } + netConfResponse.setNetconfResponseXml( + getNetconfResponseXML(opResult.getOperationResponse().getParameterDTOs(), swVersion, + hwVersion, isCustomparameter)); + return netConfResponse; + } + + public NetConfResponse getNetconfResponseForSoftwareInventory(DeviceRPCResponse opResult, + String swVersion, String hwVersion) { + + NetConfResponse netConfResponse = new NetConfResponse(); + ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + if (errorCodeDetails != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); + errorCode.setErrorType(errorCodeDetails.getErrorType()); + errorCode.setErrorTag(errorCodeDetails.getErrorTag()); + errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + return netConfResponse; + } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(opResult.getFaultString()); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + return netConfResponse; + } + List paramDTOList = new ArrayList<>(); + + String build = null; + String productClass = null; + for (ParameterDTO paramDto : opResult.getOperationResponse().getParameterDTOs()) { + if (paramDto.getParamName().equals("Device.DeviceInfo.SoftwareVersion")) + build = paramDto.getParamValue(); + else if (paramDto.getParamName().equals("Device.DeviceInfo.ProductClass")) + productClass = paramDto.getParamValue(); + } + + String[] arrOfBuild = build.split("\\."); + String buildId = arrOfBuild[arrOfBuild.length - 1]; + StringBuilder buildVersion = new StringBuilder(); + for (int i = 0; i < arrOfBuild.length - 1; i++) { + if (i == arrOfBuild.length - 2) { + buildVersion.append(arrOfBuild[i]); + } else { + buildVersion.append(arrOfBuild[i]); + buildVersion.append("."); + } + } + + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.name", "Active Partition")); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.status", "VALID")); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.active", "true")); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.running", "true")); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.access", "READ_ONLY")); + paramDTOList + .add(new ParameterDTO("software-inventory.software-slot.product-code", productClass)); + paramDTOList.add( + new ParameterDTO("software-inventory.software-slot.vendor-code", config.getVendorName())); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-id", buildId)); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-version", + buildVersion.toString())); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.name", "BC_ONE")); + paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.integrity", "OK")); + + String xmlStr = getNetconfResponseXML(paramDTOList, swVersion, hwVersion, true); + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + Document doc = null; + try { + builder = factory.newDocumentBuilder(); + doc = builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element", e); + errorCode.setFaultCode("8002"); + errorCode.setErrorMessage(OPERATION_ABORTED); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(OPERATION_ABORTED); + return netConfResponse; + } + + Element originalDocumentElement = doc.getDocumentElement(); + Element newDocumentElement = doc.createElementNS("urn:o-ran:software-management:1.0", + originalDocumentElement.getNodeName()); + NodeList list = originalDocumentElement.getChildNodes(); + while (list.getLength() != 0) { + newDocumentElement.appendChild(list.item(0)); + } + // Replace the original element + doc.replaceChild(newDocumentElement, originalDocumentElement); + + String strxml = null; + try { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(doc); + StreamResult result = new StreamResult(new StringWriter()); + transformer.transform(source, result); + strxml = result.getWriter().toString(); + } catch (Exception e) { + logger.error("Error while converting Element to String", e); + errorCode.setFaultCode("8002"); + errorCode.setErrorMessage(OPERATION_ABORTED); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(OPERATION_ABORTED); + return netConfResponse; + } + + netConfResponse.setNetconfResponseXml(strxml); + logger.debug("NetConf Response XML String for software inventory:{} ", strxml); + return netConfResponse; + } + + public NetConfResponse getNetconfResponseForRequestWithoutInputParams( + DeviceRPCResponse opResult) { + NetConfResponse netConfResponse = new NetConfResponse(); + ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + if (errorCodeDetails != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); + errorCode.setErrorType(errorCodeDetails.getErrorType()); + errorCode.setErrorTag(errorCodeDetails.getErrorTag()); + errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(opResult.getFaultString()); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } + String xml = "true"; + netConfResponse.setNetconfResponseXml(xml); + return netConfResponse; + } + + public NetConfResponse getNetconfResponseForGPA(DeviceRPCResponse opResult, String swVersion, + String hwVersion) { + NetConfResponse netConfResponse = new NetConfResponse(); + ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey()); + ErrorCodeDetails errorCode = new ErrorCodeDetails(); + if (errorCodeDetails != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(errorCodeDetails.getErrorMessage()); + errorCode.setErrorType(errorCodeDetails.getErrorType()); + errorCode.setErrorTag(errorCodeDetails.getErrorTag()); + errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity()); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) { + errorCode.setFaultCode(opResult.getFaultKey()); + errorCode.setErrorMessage(opResult.getFaultString()); + errorCode.setErrorType(APPLICATION); + errorCode.setErrorTag(OPERATION_FAILED); + errorCode.setErrorSeverity(ERROR); + netConfResponse.setErrorCode(errorCode); + netConfResponse.setErrorMessage(opResult.getFaultString()); + } + netConfResponse.setNetconfResponseXml(getGPANetconfResponseXML( + opResult.getOperationResponse().getParameterDTOs(), swVersion, hwVersion)); + return netConfResponse; + } + + private String getGPANetconfResponseXML(List parameters, String swVersion, + String hwVersion) { + + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + DOMImplementation impl = docBuilder.getDOMImplementation(); + Document doc = impl.createDocument(null, "rpc-reply", (DocumentType) null); + Element parent = doc.getDocumentElement(); + Element child = null; + String result = null; + int i = 1; + for (ParameterDTO param : parameters) { + child = doc.createElement("ns1:data"); + Element keyNode = doc.createElement("ns1:keyindex"); + keyNode.setTextContent(String.valueOf(i)); + child.appendChild(keyNode); + i++; + List paramList = new ArrayList<>(); + paramList.add(param); + String paramName = metaDataUtil + .getNetconfXPathNameByTR69NameWithIndexes(param.getParamName(), swVersion, hwVersion); + Element parameterTag = doc.createElement("ns1:parameter"); + parameterTag.setTextContent(paramName); + child.appendChild(parameterTag); + String[] accesslist = ((ParameterAttributeDTO) param).getAccessList(); + int notification = ((ParameterAttributeDTO) param).getNotification(); + Element notfChild = doc.createElement("ns1:notification"); + notfChild.setTextContent(String.valueOf(notification)); + child.appendChild(notfChild); + for (String access : accesslist) { + Element accChild = doc.createElement("ns1:access-list"); + accChild.setTextContent(access); + child.appendChild(accChild); + } + + parent.appendChild(child); + } + result = convertDocumentToString(parent); + return result; + } catch (Exception e) { + logger.error("Exception in getGPANetconfResponseXML: {}", e.getMessage()); + } + return null; + } + + public String getNetconfResponseXML(List parameters, String swVersion, + String hwVersion, boolean isCustomparameter) { + if (null == parameters || parameters.isEmpty()) { + logger.debug("There are no parameters found in the response."); + return null; + } + Collections.sort(parameters, new SortByParamterName()); + + String result = null; + try { + Document doc = null; + Element dataNode = getNetconfResponseXMLElement(parameters, isCustomparameter, doc, false, + swVersion, hwVersion); + if (null != dataNode) { + result = convertDocumentToString(dataNode); + } + } catch (Exception pce) { + logger.error("Exception: {}", pce.getMessage()); + } + + return result; + } + + private Element getNetconfResponseXMLElement(List parameters, + boolean isCustomparameter, Document doc, boolean isGPA, String swVersion, String hwVersion) { + if (null == parameters || parameters.isEmpty()) { + return null; + } + Collections.sort(parameters, new SortByParamterName()); + try { + if (doc == null) { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + docFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + doc = docBuilder.newDocument(); + } + + Map parentNodeMap = new HashMap<>(); + Element dataNode = null; // root of all nodes + + for (ParameterDTO paramDto : parameters) { + String paramName = metaDataUtil.getNetconfNameByTR69NameWithIndexes(paramDto.getParamName(), + swVersion, hwVersion); + if (paramName == null && isCustomparameter) { + paramName = paramDto.getParamName(); + } + String paramValue = paramDto.getParamValue(); + + if ((!isGPA) && (paramValue == null || paramValue.trim().isEmpty())) { + logger.debug("Values is empty so skipping this parameter."); + continue; + } + StringTokenizer tokenizer = new StringTokenizer(paramName, "."); + String parentNodeName = null; + String parentNodeKey = null; + Element parentNode = null; + while (tokenizer.hasMoreElements()) { + String nodeName = (String) tokenizer.nextElement(); + if (null == parentNodeName) { // construct first node or + // Device node + parentNodeName = nodeName; + parentNodeKey = nodeName; + // check if the node already exists in parentNodeMap + parentNode = parentNodeMap.get(parentNodeKey); + if (null == dataNode) { + dataNode = parentNode; + } + continue; + } else if (nodeName.matches(INDEX_REGEX)) { // construct + // tabular and + // index nodes + + // get parent tabular node from parent MAP + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + Element node = parentNodeMap.get(parentNodeKey); + + // create a tabular parent node if doesn't exit in MAP + if (null == node) { + if ((!isGPA) + && metaDataUtil.getMetaDataByNetConfName(parentNodeKey + ".", swVersion, + hwVersion) != null + && metaDataUtil + .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion) + .getURI() != null) { + node = doc.createElementNS(metaDataUtil + .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion).getURI(), + parentNodeName); + } else { + node = doc.createElement(parentNodeName); + } + parentNodeMap.put(parentNodeKey, node); + + // update current tabular parent node. + if (null != parentNode) + parentNode.appendChild(node); + + // prepare and add index node to tabular parent node + Element indexNode = doc.createElement(INDEX_STR); + indexNode.setTextContent(nodeName); + node.appendChild(indexNode); + } + parentNode = node; // move parent to child + parentNodeName = nodeName; + } else if (parentNodeName.matches(INDEX_REGEX)) { // move to + // next + // node + // if + // tabular + // attribute + // is + // found + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + parentNodeName = nodeName; + } else { + // construct intermediate nodes + Element node = parentNodeMap.get(parentNodeKey); + if (null == node) { + if ((!isGPA) + && metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, + hwVersion) != null + && metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion) + .getURI() != null) { + node = doc.createElementNS(metaDataUtil + .getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion).getURI(), + parentNodeName); + + } else { + node = doc.createElement(parentNodeName); + } + if (dataNode == null) + dataNode = node; + parentNodeMap.put(parentNodeKey, node); + if (null != parentNode) + parentNode.appendChild(node); + + } + StringBuilder bld = new StringBuilder(); + bld.append(parentNodeKey); + bld.append("."); + bld.append(nodeName); + parentNodeKey = bld.toString(); + parentNodeName = nodeName; + parentNode = node; + } + } + // construct leaf node + Element leafNode = doc.createElement(parentNodeName); + leafNode.setTextContent(paramValue); + if (parentNode != null) + parentNode.appendChild(leafNode); + } + + if (null != dataNode) { + return dataNode; + } + } catch (ParserConfigurationException pce) { + logger.error("Response xml formatting is failed : {} ", pce.toString()); + } + + return null; + } + + public ParameterDTO getParamNameAndValueForGPA(Element operationElement, String netconfTag, + String swVersion, String hwVersion) { + Node deviceNode = getDeviceDataNode(operationElement, netconfTag); + Map map = null; + try { + map = getParameterMapForNode(deviceNode, -1); + } catch (Exception e) { + logger.error("Exception in getParamNameAndValueForGPA: {}", e.getMessage()); + return null; + } + ParameterDTO param = new ParameterDTO(); + for (String moName : map.keySet()) { + if (moName.endsWith("." + INDEX_STR)) { + logger.debug(INDEX_NODE_FOUND, moName); + moName = moName.replaceFirst("." + INDEX_STR, "."); + } + String tr069Moname = + metaDataUtil.getTR069NameByNetconfNameWithIndexes(moName, swVersion, hwVersion); + param.setParamName(tr069Moname); + param.setParamValue(""); + } + return param; + } + + public ParameterAttributeDTO getParamNameAndValueForSPA(Element operationElement, + String netconfTag, String swVersion, String hwVersion) { + Node requestDataNode = getDeviceDataNode(operationElement, netconfTag); + if (requestDataNode == null) { + logger.debug("No matching device parameters found in the netconf request XML."); + } + Node deviceNode = getDeviceDataNode(operationElement, "parameter"); + Map map = new HashMap<>(); + try { + map = getParameterMapForNode(deviceNode, -1); + } catch (Exception e) { + logger.error("Error while getting parameter Map {}", e.getMessage()); + } + + NodeList nodeList = operationElement.getChildNodes(); + int length = nodeList.getLength(); + String notificationVal = null; + List accessList = new ArrayList<>(); + String accesslistChange = null; + String notificationChange = null; + for (int i = 0; i < length; i++) { + if (nodeList.item(i).getNodeName().equals("notification")) { + notificationVal = nodeList.item(i).getTextContent(); + } else if (nodeList.item(i).getNodeName().equals("access-list")) { + if (nodeList.item(i).getTextContent() != null + && !(nodeList.item(i).getTextContent().isEmpty())) { + accessList.add(nodeList.item(i).getTextContent()); + } + } else if (nodeList.item(i).getNodeName().equals("access-list-change")) { + accesslistChange = nodeList.item(i).getTextContent(); + } else if (nodeList.item(i).getNodeName().equals("notification-change")) { + notificationChange = nodeList.item(i).getTextContent(); + } + } + String[] accList = accessList.toArray(new String[accessList.size()]); + ParameterAttributeDTO param = new ParameterAttributeDTO(); + param.setAccessList(accList); + param.setNotification(Integer.valueOf(notificationVal)); + param.setAccesslistChange(Boolean.parseBoolean(accesslistChange)); + param.setNotificationChange(Boolean.parseBoolean(notificationChange)); + + for (String moName : map.keySet()) { + if (moName.endsWith("." + INDEX_STR)) { + logger.debug(INDEX_NODE_FOUND, moName); + moName = moName.replaceFirst("." + INDEX_STR, "."); + } + String tr069Moname = + metaDataUtil.getTR069NameByNetconfNameWithIndexes(moName, swVersion, hwVersion); + param.setParamName(tr069Moname); + param.setParamValue(""); + } + + return param; + } + + public static String convertDocumentToString(Element element) { + String strxml = null; + try { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(element); + StreamResult result = new StreamResult(new StringWriter()); + transformer.transform(source, result); + strxml = result.getWriter().toString(); + } catch (Exception e) { + logger.error("Error while converting Element to String {}", e.toString()); + } + logger.debug("Converted XML is : {} ", strxml); + return strxml; + } + + // TODO: Need to optimize the Node element logic for better performance + private static Map getParameterMapForNode(Node moRNode, int numberOfChilds) { + Map result = new HashMap<>(); + if (moRNode.getNodeType() == Node.ELEMENT_NODE) { + NodeList childs = moRNode.getChildNodes(); + boolean hasChildElements = false; + hasChildElements = checkMoreElements(result, childs, hasChildElements); + if (!hasChildElements) { + String moName = getMOName(moRNode); + if (moName.contains("software-inventory")) { + result.put("device.device-info.software-version", moRNode.getTextContent()); + result.put("device.device-info.product-class", moRNode.getTextContent()); + } else if (!moName.endsWith("." + INDEX_STR)) { + result.put(moName, moRNode.getTextContent()); + } else if (numberOfChilds == 1) { + result.put(moName, moRNode.getTextContent()); + } + } + } + + return result; + } + + private static boolean checkMoreElements(Map result, NodeList childs, + boolean hasChildElements) { + if (childs.getLength() > 0) { + int counter = 0; + for (int i = 0; i < childs.getLength(); i++) { + Node cNode = childs.item(i); + if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) { + counter++; + } + } + + for (int i = 0; i < childs.getLength(); i++) { + Node cNode = childs.item(i); + if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) { + hasChildElements = true; + Map subResult = getParameterMapForNode(cNode, counter); + result.putAll(subResult); + } + } + } + return hasChildElements; + } + + private static String getMOName(Node moRNode) { + String result = removeNS(moRNode.getNodeName()); + Node pNode = moRNode; + while (true) { + pNode = pNode.getParentNode(); + if (pNode == null || pNode.getNodeType() != Node.ELEMENT_NODE + || pNode.getNodeName().equals("edit-config") || pNode.getNodeName().equals("config") + || pNode.getNodeName().equals("get-config") || pNode.getNodeName().equals("filter") + || pNode.getNodeName().equals("get") || pNode.getNodeName().equals("parameter")) { + return result; + } else { + String indexStr = getMOIndex(pNode); + StringBuilder bld = new StringBuilder(removeNS(pNode.getNodeName())); + bld.append("."); + if (indexStr == null) { + bld.append(result); + result = bld.toString(); + } else { + bld.append(indexStr); + bld.append("."); + bld.append(result); + result = bld.toString(); + } + } + } + } + + private static Node getParameterDataNode(Document el, String docStart, String filterElement) { + NodeList nodeList = el.getElementsByTagName(docStart); + if (nodeList.getLength() > 0) { + nodeList = nodeList.item(0).getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String nodeName = removeNS(node.getNodeName()); + if (nodeName.equals(filterElement)) { + return node; + } + } + } + return null; + } + + private static Node getDeviceDataNode(Element el, String filter) { + try { + NodeList nodeList = el.getElementsByTagName(filter); + if (nodeList.getLength() > 0) { + nodeList = nodeList.item(0).getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + return node; + } + } + } + } catch (Exception e) { + logger.error("exception occured while parsing the request xml {}", e.getMessage()); + } + return null; + } + + private static String removeNS(String nodeName) { + // remove name space + int li = nodeName.lastIndexOf(':'); + nodeName = nodeName.substring(li + 1); + return nodeName; + } + + private static String getMOIndex(Node pNode) { + if (null != pNode) { + NodeList nodeList = pNode.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node childNode = nodeList.item(i); + String nodeName = removeNS(childNode.getNodeName()); + if (nodeName.equalsIgnoreCase(INDEX_STR)) { + return childNode.getTextContent(); + } + } + } + return null; + } +} + + +class SortByParamterName implements Comparator, Serializable { + private static final long serialVersionUID = 3010693349267067945L; + + public int compare(ParameterDTO a, ParameterDTO b) { + return a.getParamName().compareTo(b.getParamName()); + } +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/VESNotificationSender.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/VESNotificationSender.java index 7e28744..b1ec97b 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/VESNotificationSender.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/VESNotificationSender.java @@ -1,89 +1,115 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper.ves; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -@Component -public class VESNotificationSender { - - private static final Logger LOG = LoggerFactory.getLogger(VESNotificationSender.class); - - @Autowired - MapperConfigProperties config; - - @Autowired - PnPPreProvisioningHandler pnpPreProvisioningHandler; - - @Autowired - VESNotificationSender vesnotiSender; - - @Autowired - RestTemplate restTemplate; - - public VESNotificationResponse sendNotification(DeviceInform deviceInform, - NetConfServerDetails serverInfo) { - final String uri = getUri(); - LOG.debug("Posting ves event to ves notifier {}", uri); - - VESNotification vesNotifi = new VESNotification(); - if (deviceInform != null) { - vesNotifi.seteNodeBName( - pnpPreProvisioningHandler.getEnodeBName(deviceInform.getDeviceDetails().getDeviceId(), - deviceInform.getDeviceDetails().getSoftwareVersion(), - deviceInform.getDeviceDetails().getHardwareVersion())); - } else { - vesNotifi.seteNodeBName(serverInfo.getEnodeBName()); - } - vesNotifi.setNetconfDetails(serverInfo); - vesNotifi.setDevnotification(deviceInform); - - return restTemplate.postForObject(uri, vesNotifi, VESNotificationResponse.class); - } - - public DeviceRPCResponse sendEditConfigNotification(DeviceRPCRequest deviceRPCRequest) { - final String uri = config.getVerConfigUri() + "/editConfig"; - LOG.debug("Posting edit config request to ves agent {}", uri); - return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class); - } - - public DeviceRPCResponse sendGetConfigNotification(DeviceRPCRequest deviceRPCRequest) { - final String uri = config.getVerConfigUri() + "/getConfig"; - LOG.debug("Posting get config request to ves agent {}", uri); - return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class); - } - - - private String getUri() { - return config.getVesUri(); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper.ves; + +import java.util.ArrayList; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +public class VESNotificationSender { + + private static final Logger LOG = LoggerFactory.getLogger(VESNotificationSender.class); + + @Autowired + MapperConfigProperties config; + + @Autowired + PnPPreProvisioningHandler pnpPreProvisioningHandler; + + @Autowired + VESNotificationSender vesnotiSender; + + @Autowired + RestTemplate restTemplate; + + @Autowired + MOMetaDataUtil metaDataUtil; + + public VESNotificationResponse sendNotification(DeviceInform deviceInform, + NetConfServerDetails serverInfo) { + final String uri = getUri(); + LOG.debug("Posting ves event to ves notifier {}", uri); + + VESNotification vesNotifi = new VESNotification(); + if (deviceInform != null) { + // Replace TR-069 parameter names with NETCONF parameter names + List parameters = deviceInform.getParameters(); + if (parameters != null && !parameters.isEmpty()) { + List netconfParameters = new ArrayList<>(); + for (ParameterDTO param : parameters) { + String paramXPath = metaDataUtil.getNetconfXPathNameByTR69NameWithIndexes( + param.getParamName(), deviceInform.getDeviceDetails().getSoftwareVersion(), + deviceInform.getDeviceDetails().getHardwareVersion()); + if (paramXPath != null) + netconfParameters + .add(new ParameterDTO(paramXPath, param.getParamValue(), param.getDataType())); + else { + LOG.warn("Skipping param {}, as it is not present in mapping configuration", + param.getParamName()); + } + } + vesNotifi.setNetconfParameters(netconfParameters); + } + vesNotifi.seteNodeBName( + pnpPreProvisioningHandler.getEnodeBName(deviceInform.getDeviceDetails().getDeviceId(), + deviceInform.getDeviceDetails().getSoftwareVersion(), + deviceInform.getDeviceDetails().getHardwareVersion())); + } else { + vesNotifi.seteNodeBName(serverInfo.getEnodeBName()); + } + vesNotifi.setNetconfDetails(serverInfo); + vesNotifi.setDevnotification(deviceInform); + + return restTemplate.postForObject(uri, vesNotifi, VESNotificationResponse.class); + } + + public DeviceRPCResponse sendEditConfigNotification(DeviceRPCRequest deviceRPCRequest) { + final String uri = config.getVerConfigUri() + "/editConfig"; + LOG.debug("Posting edit config request to ves agent {}", uri); + return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class); + } + + public DeviceRPCResponse sendGetConfigNotification(DeviceRPCRequest deviceRPCRequest) { + final String uri = config.getVerConfigUri() + "/getConfig"; + LOG.debug("Posting get config request to ves agent {}", uri); + return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class); + } + + + private String getUri() { + return config.getVesUri(); + } + +} diff --git a/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/impl/VesRequestHandlerImpl.java b/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/impl/VesRequestHandlerImpl.java index b320667..044f2df 100644 --- a/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/impl/VesRequestHandlerImpl.java +++ b/mapper/src/main/java/org/commscope/tr069adapter/mapper/ves/impl/VesRequestHandlerImpl.java @@ -16,70 +16,67 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.mapper.ves.impl; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.mapper.MapperConfigProperties; -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; -import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil; -import org.commscope.tr069adapter.mapper.util.MapperConstants; -import org.commscope.tr069adapter.mapper.ves.VesRequestHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class VesRequestHandlerImpl implements VesRequestHandler { - - private static final Logger LOG = LoggerFactory.getLogger(VesRequestHandlerImpl.class); - - @Autowired - SynchronizedRequestHandler syncHandler; - - @Autowired - MapperConfigProperties config; - - @Autowired - private ErrorCodeUtil errorCodeUtil; - - - @Override - public DeviceRPCResponse handleDeviceConnectivityRequest(DeviceRPCRequest deviceRPCRequest) { - DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest); - if (null == deviceRPCResponse) { - return getTimeOutResponse(deviceRPCRequest); - } - - return deviceRPCResponse; - } - - private DeviceRPCResponse getTimeOutResponse(DeviceRPCRequest deviceRPCRequest) { - DeviceRPCResponse timeOutErrorResponse = new DeviceRPCResponse(); - - timeOutErrorResponse.setDeviceDetails(deviceRPCRequest.getDeviceDetails()); - - OperationResponse operationResponse = new OperationResponse(); - operationResponse.setStatus(MapperConstants.DEVICE_REACHABILITY_OP_FAILURE_CODE);// device - // reachable...change - // value 1 to - // some - // constant or - // enum - operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode()); - - timeOutErrorResponse.setOperationResponse(operationResponse); - timeOutErrorResponse.setFaultKey(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE); - ErrorCodeDetails errorCodeDetails = - errorCodeUtil.getErrorCodeMetaData(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE); - if (null != errorCodeDetails) { - timeOutErrorResponse.setFaultString(errorCodeDetails.getErrorMessage()); - } else { - timeOutErrorResponse.setFaultString(MapperConstants.DEFAULT_OP_TIMEOUT_MSG); - } - return timeOutErrorResponse; - } -} +package org.commscope.tr069adapter.mapper.ves.impl; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.mapper.MapperConfigProperties; +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; +import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil; +import org.commscope.tr069adapter.mapper.util.MapperConstants; +import org.commscope.tr069adapter.mapper.ves.VesRequestHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class VesRequestHandlerImpl implements VesRequestHandler { + + + @Autowired + SynchronizedRequestHandler syncHandler; + + @Autowired + MapperConfigProperties config; + + @Autowired + private ErrorCodeUtil errorCodeUtil; + + + @Override + public DeviceRPCResponse handleDeviceConnectivityRequest(DeviceRPCRequest deviceRPCRequest) { + DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest); + if (null == deviceRPCResponse) { + return getTimeOutResponse(deviceRPCRequest); + } + + return deviceRPCResponse; + } + + private DeviceRPCResponse getTimeOutResponse(DeviceRPCRequest deviceRPCRequest) { + DeviceRPCResponse timeOutErrorResponse = new DeviceRPCResponse(); + + timeOutErrorResponse.setDeviceDetails(deviceRPCRequest.getDeviceDetails()); + + OperationResponse operationResponse = new OperationResponse(); + operationResponse.setStatus(MapperConstants.DEVICE_REACHABILITY_OP_FAILURE_CODE);// device + // reachable...change + // value 1 to + // some + // constant or + // enum + operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode()); + + timeOutErrorResponse.setOperationResponse(operationResponse); + timeOutErrorResponse.setFaultKey(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE); + ErrorCodeDetails errorCodeDetails = + errorCodeUtil.getErrorCodeMetaData(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE); + if (null != errorCodeDetails) { + timeOutErrorResponse.setFaultString(errorCodeDetails.getErrorMessage()); + } else { + timeOutErrorResponse.setFaultString(MapperConstants.DEFAULT_OP_TIMEOUT_MSG); + } + return timeOutErrorResponse; + } +} diff --git a/mapper/src/main/resources/application.properties b/mapper/src/main/resources/application.properties index db5085e..797ac85 100644 --- a/mapper/src/main/resources/application.properties +++ b/mapper/src/main/resources/application.properties @@ -23,6 +23,7 @@ config.requesTimeout=${REQUEST_TIMEOUT} config.alarmMORegex=${ALARM_MO_REGEX} config.preConfigureOnPNP=${preConfigureOnPNP} config.sbiUri=http://${SBI_REST_HOST}:${SBI_REST_PORT}/MapperService/initiateDeviceOperation +config.connStatusUri=http://${SBI_REST_HOST}:${SBI_REST_PORT}/MapperService/connectionStatusOperation config.configDBUri=http://${CONFIG_DB_REST_HOST}:${CONFIG_DB_REST_PORT}/getConfig config.nbiNotificationUri=http://${NBI_REST_HOST}:${NBI_REST_PORT}/netConfNotificationService/notification config.nbiServerManagerUri=http://${NBI_REST_HOST}:${NBI_REST_PORT}/netConfServerManagerService diff --git a/mapper/src/main/resources/schema-mariadb.sql b/mapper/src/main/resources/schema-mariadb.sql index b680a21..a8500aa 100644 --- a/mapper/src/main/resources/schema-mariadb.sql +++ b/mapper/src/main/resources/schema-mariadb.sql @@ -1 +1 @@ -CREATE TABLE IF NOT EXISTS device_operation_details (ID int null,DEVICE_ID varchar(30) not null, SW_VERSION varchar(30) not null, DOWN_LOAD_STATUS int default 0, FIRMWARE_FILE varchar(1024) ); \ No newline at end of file +CREATE TABLE IF NOT EXISTS device_operation_details (ID int null,DEVICE_ID varchar(30) not null, SW_VERSION varchar(30) not null, DOWN_LOAD_STATUS int default 0, FIRMWARE_FILE varchar(1024), ORIGIN varchar(30) ); \ No newline at end of file diff --git a/mapper/src/test/java/org/commscope/tr069adapter/mapper/ACSNotificationHandlerImplTest.java b/mapper/src/test/java/org/commscope/tr069adapter/mapper/ACSNotificationHandlerImplTest.java index 492f40e..6b1c283 100644 --- a/mapper/src/test/java/org/commscope/tr069adapter/mapper/ACSNotificationHandlerImplTest.java +++ b/mapper/src/test/java/org/commscope/tr069adapter/mapper/ACSNotificationHandlerImplTest.java @@ -1,178 +1,178 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.List; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069InformType; -import org.commscope.tr069adapter.acs.common.inform.BootInform; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform; -import org.commscope.tr069adapter.mapper.acs.impl.ACSNotificationHandlerImpl; -import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; -import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@SpringBootTest(classes = {MapperServiceBooter.class}) -@RunWith(SpringRunner.class) -public class ACSNotificationHandlerImplTest { - - @Autowired - ACSNotificationHandlerImpl aCSNotificationHandlerImpl; - - @Mock - NetConfServerManager netConfServerManager; - - @Test - public void testHandleBootStrapNotification() { - - BootstrapInform notification = new BootstrapInform(); - List params = new ArrayList(); - ParameterDTO param = new ParameterDTO(); - param.setParamName("ExpeditedEvent"); - params.add(param); - notification.setDeviceDetails(getDeviceDetails()); - notification.setParameters(params); - NetConfServerDetails serverInfo = new NetConfServerDetails(); - serverInfo.setError(NetconfServerManagementError.SUCCESS); - Mockito.when(netConfServerManager.createNetconfServer(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(serverInfo); - /* - * String URI = "http://tr069adapter-netconf-server:8181/netConfServerManagerService"; - * Mockito.when(netConfServerManager.getNetconfServerManagerRestUri()). thenReturn(value) - */ - aCSNotificationHandlerImpl.handleNotification(notification); - assertNull(notification.getValueChangeNotification()); - } - - @Test - public void testHandleBootStrapNotificationNegativeScenario() { - - BootstrapInform notification = new BootstrapInform(); - List params = new ArrayList(); - ParameterDTO param = new ParameterDTO(); - param.setParamName("Test"); - params.add(param); - notification.setDeviceDetails(getDeviceDetails()); - notification.setParameters(params); - // Mockito.doReturn(null).when(netConfServerManager.createNetconfServer(Mockito.anyString(), - // Mockito.anyString())); - aCSNotificationHandlerImpl.handleNotification(notification); - assertNull(notification.getValueChangeNotification()); - } - - @Test - public void testHandleBootNotification() { - - BootInform notification = new BootInform(); - List params = new ArrayList(); - ParameterDTO param = new ParameterDTO(); - param.setParamName("Test"); - params.add(param); - notification.setDeviceDetails(getDeviceDetails()); - notification.setParameters(params); - aCSNotificationHandlerImpl.handleNotification(notification); - assertNull(notification.getValueChangeNotification()); - } - - @Test - public void testGetDeviceBootNotification() { - DeviceInform deviceInform = new DeviceInform(); - deviceInform.setDeviceDetails(getDeviceDetails()); - deviceInform.setParameters(getGeneralParams()); - - BootInform bInform = - ACSNotificationHandlerImpl.getDeviceBootNotification(deviceInform, TR069InformType.BOOT); - assertEquals("00005B9A1", bInform.getDeviceDetails().getDeviceId()); - assertNotNull(bInform.getInformTypeList()); - assertEquals(TR069InformType.BOOT, bInform.getInformTypeList().get(0)); - } - - @Test - public void testGetDeviceBooStraptNotification() { - DeviceInform deviceInform = new DeviceInform(); - deviceInform.setDeviceDetails(getDeviceDetails()); - deviceInform.setParameters(getGeneralParams()); - - BootstrapInform bsInform = ACSNotificationHandlerImpl - .getDeviceBootStrapNotification(deviceInform, TR069InformType.BOOTSTRAP); - assertEquals("00005B9A1", bsInform.getDeviceDetails().getDeviceId()); - assertNotNull(bsInform.getInformTypeList()); - assertEquals(TR069InformType.BOOTSTRAP, bsInform.getInformTypeList().get(0)); - } - - @Test - public void testGetDeviceValueChangeNotification() { - DeviceInform deviceInform = new DeviceInform(); - deviceInform.setDeviceDetails(getDeviceDetails()); - deviceInform.setParameters(getGeneralParams()); - - ValueChangeInform vInform = ACSNotificationHandlerImpl - .getDeviceValueChangeNotification(deviceInform, TR069InformType.VALUECHANGE); - assertEquals("00005B9A1", vInform.getDeviceDetails().getDeviceId()); - assertNotNull(vInform.getInformTypeList()); - assertEquals(TR069InformType.VALUECHANGE, vInform.getInformTypeList().get(0)); - } - - private DeviceDetails getDeviceDetails() { - DeviceDetails nf = new DeviceDetails(); - nf.setDeviceId("00005B9A1"); - nf.setDeviceTypeId(50); - nf.setOui("0005B9"); - nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); - return nf; - } - - private DeviceDetails getDeviceDetailsNegativeCase() { - DeviceDetails nf = new DeviceDetails(); - // nf.setDeviceId("00005B9A1"); - nf.setDeviceTypeId(50); - nf.setOui("0005B9"); - nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); - return nf; - } - - private ArrayList getGeneralParams() { - ArrayList params = new ArrayList<>(); - params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); - params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); - params.add(new ParameterDTO("Device.DeviceInfo.HardwareVersion", "750742.00.04")); - params.add(new ParameterDTO("Device.DeviceInfo.SoftwareVersion", "4.3.00.231")); - params.add(new ParameterDTO("Device.DeviceInfo.Manufacturer", "ORAN")); - params.add(new ParameterDTO("Device.DeviceInfo.SerialNumber", "00005B9A1")); - params.add(new ParameterDTO("Device.IP.Interface.1.IPv4Address.1.IPAddress", "10.211.5.55")); - return params; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069InformType; +import org.commscope.tr069adapter.acs.common.inform.BootInform; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform; +import org.commscope.tr069adapter.mapper.acs.impl.ACSNotificationHandlerImpl; +import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; +import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@SpringBootTest(classes = {MapperServiceBooter.class}) +@RunWith(SpringRunner.class) +public class ACSNotificationHandlerImplTest { + + @Autowired + ACSNotificationHandlerImpl aCSNotificationHandlerImpl; + + @Mock + NetConfServerManager netConfServerManager; + + @Test + public void testHandleBootStrapNotification() { + + BootstrapInform notification = new BootstrapInform(); + List params = new ArrayList(); + ParameterDTO param = new ParameterDTO(); + param.setParamName("ExpeditedEvent"); + params.add(param); + notification.setDeviceDetails(getDeviceDetails()); + notification.setParameters(params); + NetConfServerDetails serverInfo = new NetConfServerDetails(); + serverInfo.setError(NetconfServerManagementError.SUCCESS); + Mockito.when(netConfServerManager.createNetconfServer(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString())).thenReturn(serverInfo); + /* + * String URI = "http://tr069adapter-netconf-server:8181/netConfServerManagerService"; + * Mockito.when(netConfServerManager.getNetconfServerManagerRestUri()). thenReturn(value) + */ + aCSNotificationHandlerImpl.handleNotification(notification); + assertNull(notification.getValueChangeNotification()); + } + + @Test + public void testHandleBootStrapNotificationNegativeScenario() { + + BootstrapInform notification = new BootstrapInform(); + List params = new ArrayList(); + ParameterDTO param = new ParameterDTO(); + param.setParamName("Test"); + params.add(param); + notification.setDeviceDetails(getDeviceDetails()); + notification.setParameters(params); + // Mockito.doReturn(null).when(netConfServerManager.createNetconfServer(Mockito.anyString(), + // Mockito.anyString())); + aCSNotificationHandlerImpl.handleNotification(notification); + assertNull(notification.getValueChangeNotification()); + } + + @Test + public void testHandleBootNotification() { + + BootInform notification = new BootInform(); + List params = new ArrayList(); + ParameterDTO param = new ParameterDTO(); + param.setParamName("Test"); + params.add(param); + notification.setDeviceDetails(getDeviceDetails()); + notification.setParameters(params); + aCSNotificationHandlerImpl.handleNotification(notification); + assertNull(notification.getValueChangeNotification()); + } + + @Test + public void testGetDeviceBootNotification() { + DeviceInform deviceInform = new DeviceInform(); + deviceInform.setDeviceDetails(getDeviceDetails()); + deviceInform.setParameters(getGeneralParams()); + + BootInform bInform = + ACSNotificationHandlerImpl.getDeviceBootNotification(deviceInform, TR069InformType.BOOT); + assertEquals("00005B9A1", bInform.getDeviceDetails().getDeviceId()); + assertNotNull(bInform.getInformTypeList()); + assertEquals(TR069InformType.BOOT, bInform.getInformTypeList().get(0)); + } + + @Test + public void testGetDeviceBooStraptNotification() { + DeviceInform deviceInform = new DeviceInform(); + deviceInform.setDeviceDetails(getDeviceDetails()); + deviceInform.setParameters(getGeneralParams()); + + BootstrapInform bsInform = ACSNotificationHandlerImpl + .getDeviceBootStrapNotification(deviceInform, TR069InformType.BOOTSTRAP); + assertEquals("00005B9A1", bsInform.getDeviceDetails().getDeviceId()); + assertNotNull(bsInform.getInformTypeList()); + assertEquals(TR069InformType.BOOTSTRAP, bsInform.getInformTypeList().get(0)); + } + + @Test + public void testGetDeviceValueChangeNotification() { + DeviceInform deviceInform = new DeviceInform(); + deviceInform.setDeviceDetails(getDeviceDetails()); + deviceInform.setParameters(getGeneralParams()); + + ValueChangeInform vInform = ACSNotificationHandlerImpl + .getDeviceValueChangeNotification(deviceInform, TR069InformType.VALUECHANGE); + assertEquals("00005B9A1", vInform.getDeviceDetails().getDeviceId()); + assertNotNull(vInform.getInformTypeList()); + assertEquals(TR069InformType.VALUECHANGE, vInform.getInformTypeList().get(0)); + } + + private DeviceDetails getDeviceDetails() { + DeviceDetails nf = new DeviceDetails(); + nf.setDeviceId("00005B9A1"); + nf.setDeviceTypeId(50); + nf.setOui("0005B9"); + nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); + return nf; + } + + private DeviceDetails getDeviceDetailsNegativeCase() { + DeviceDetails nf = new DeviceDetails(); + // nf.setDeviceId("00005B9A1"); + nf.setDeviceTypeId(50); + nf.setOui("0005B9"); + nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); + return nf; + } + + private ArrayList getGeneralParams() { + ArrayList params = new ArrayList<>(); + params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); + params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); + params.add(new ParameterDTO("Device.DeviceInfo.HardwareVersion", "750742.00.04")); + params.add(new ParameterDTO("Device.DeviceInfo.SoftwareVersion", "4.3.00.231")); + params.add(new ParameterDTO("Device.DeviceInfo.Manufacturer", "ORAN")); + params.add(new ParameterDTO("Device.DeviceInfo.SerialNumber", "00005B9A1")); + params.add(new ParameterDTO("Device.IP.Interface.1.IPv4Address.1.IPAddress", "10.211.5.55")); + return params; + } +} diff --git a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfRequestReceiverTest.java b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfRequestReceiverTest.java index ba213f6..0ee89d2 100644 --- a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfRequestReceiverTest.java +++ b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfRequestReceiverTest.java @@ -1,280 +1,280 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import static org.junit.Assert.assertFalse; - -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.Semaphore; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.acs.ACSRequestSender; -import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; -import org.commscope.tr069adapter.mapper.model.NetConfRequest; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.netconf.controller.NetConfRequestReceiver; -import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; - -@SpringBootTest(classes = {MapperServiceBooter.class}) -@RunWith(SpringRunner.class) -public class NetConfRequestReceiverTest { - - @Autowired - NetConfRequestReceiver receiver; - - @MockBean - ACSRequestSender tr069RequestSender; - - @MockBean - Semaphore semaphore; - - @MockBean - SynchronizedRequestHandler sync; - - @MockBean - Map opResultMap; - - @Test - public void getConfigRequestTest() { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) - .thenReturn(prepareDeviceResponseSucess()); - - NetConfRequest req = prepareNetConfRequest( - "1"); - NetConfResponse nfres = receiver.getConfigRequest(req); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertNotNull(nfres.getNetconfResponseXml()); - } - - @Test - public void getConfigRequestTestTimeOut() throws InterruptedException { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(semaphore.tryAcquire(Mockito.anyInt(), Mockito.anyObject())).thenReturn(true); - Mockito.when(opResultMap.remove(Mockito.anyLong())).thenReturn(prepareDeviceResponseSucess()); - - NetConfRequest req = prepareNetConfRequest( - "1"); - NetConfResponse nfres = receiver.getConfigRequest(req); - Assert.assertEquals("8006", nfres.getErrorCode().getFaultCode()); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("Operation Timed out", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void getConfigRequestWithNoParamTest() { - NetConfRequest req = prepareNetConfRequest( - ""); - NetConfResponse nfres = receiver.getConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - - } - - @Test - public void getConfigRequestWithUnknownParamTest() { - NetConfRequest req = prepareNetConfRequest( - "1"); - NetConfResponse nfres = receiver.getRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void getRequestTest() { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) - .thenReturn(prepareDeviceResponseSucess()); - NetConfRequest req = prepareNetConfRequest( - "1"); - NetConfResponse nfres = receiver.getRequest(req); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertNotNull(nfres.getNetconfResponseXml()); - } - - @Test - public void getRequestWithNoParamTest() { - NetConfRequest req = prepareNetConfRequest( - ""); - NetConfResponse nfres = receiver.getRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void getRequestWithUnknownParamTest() { - NetConfRequest req = prepareNetConfRequest( - "1"); - NetConfResponse nfres = receiver.getRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void setConfigRequestTest() { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) - .thenReturn(prepareSPVDeviceResponseSucess()); - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.setConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void setConfigRequestWithErrorResTest() { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) - .thenReturn(prepareDeviceResponseError()); - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.setConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("9001", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Request denied", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void setConfigRequestWithNoParamTest() { - NetConfRequest req = prepareNetConfRequest( - ""); - NetConfResponse nfres = receiver.setConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void setConfigRequestWithUnknowParatmerTest() { - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.setConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void setConfigRequestInvalidRequestXMLTest() { - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.setConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - } - - @Test - public void delConfigRequestTest() { - Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); - Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) - .thenReturn(prepareSPVDeviceResponseSucess()); - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.delConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void delConfigwithUnknownParamterRequestTest() { - NetConfRequest req = prepareNetConfRequest( - "11310767falsetruecpe-131true"); - NetConfResponse nfres = receiver.delConfigRequest(req); - Assert.assertNull(nfres.getNetconfResponseXml()); - Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); - } - - @Test - public void handelRegisterEventTest() { - try { - assertFalse(receiver - .handelRegisterEvent(new NetConfServerDetails("00005BA1", "10.211.55.14", "17830"))); - } catch (Exception e) { - } - - } - - private NetConfRequest prepareNetConfRequest(String requestXml) { - NetConfRequest req = new NetConfRequest(); - req.setDeviceId("0005B9A1"); - req.setRequestXml(requestXml); - req.setSwVersion("4.3.0.0"); - req.setHwVersion("*"); - return req; - } - - private DeviceRPCResponse prepareDeviceResponseError() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("9001"); - opResult.setFaultString("Request denied"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - // opr.setParameterDTOs(getGeneralParams()); - opResult.setOperationResponse(opr); - return opResult; - } - - private DeviceRPCResponse prepareDeviceResponseSucess() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("0"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - opr.setParameterDTOs(getGeneralParams()); - opResult.setOperationResponse(opr); - return opResult; - } - - private DeviceRPCResponse prepareSPVDeviceResponseSucess() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("0"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - opResult.setOperationResponse(opr); - return opResult; - } - - private ArrayList getGeneralParams() { - ArrayList params = new ArrayList<>(); - params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); - params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); - params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", - "30324")); - return params; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import static org.junit.Assert.assertFalse; + +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.Semaphore; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.acs.ACSRequestSender; +import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; +import org.commscope.tr069adapter.mapper.model.NetConfRequest; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.netconf.controller.NetConfRequestReceiver; +import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +@SpringBootTest(classes = {MapperServiceBooter.class}) +@RunWith(SpringRunner.class) +public class NetConfRequestReceiverTest { + + @Autowired + NetConfRequestReceiver receiver; + + @MockBean + ACSRequestSender tr069RequestSender; + + @MockBean + Semaphore semaphore; + + @MockBean + SynchronizedRequestHandler sync; + + @MockBean + Map opResultMap; + + @Test + public void getConfigRequestTest() { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) + .thenReturn(prepareDeviceResponseSucess()); + + NetConfRequest req = prepareNetConfRequest( + "1"); + NetConfResponse nfres = receiver.getConfigRequest(req); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertNotNull(nfres.getNetconfResponseXml()); + } + + @Test + public void getConfigRequestTestTimeOut() throws InterruptedException { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(semaphore.tryAcquire(Mockito.anyInt(), Mockito.anyObject())).thenReturn(true); + Mockito.when(opResultMap.remove(Mockito.anyLong())).thenReturn(prepareDeviceResponseSucess()); + + NetConfRequest req = prepareNetConfRequest( + "1"); + NetConfResponse nfres = receiver.getConfigRequest(req); + Assert.assertEquals("8006", nfres.getErrorCode().getFaultCode()); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("Operation Timed out", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void getConfigRequestWithNoParamTest() { + NetConfRequest req = prepareNetConfRequest( + ""); + NetConfResponse nfres = receiver.getConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + + } + + @Test + public void getConfigRequestWithUnknownParamTest() { + NetConfRequest req = prepareNetConfRequest( + "1"); + NetConfResponse nfres = receiver.getRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void getRequestTest() { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) + .thenReturn(prepareDeviceResponseSucess()); + NetConfRequest req = prepareNetConfRequest( + "1"); + NetConfResponse nfres = receiver.getRequest(req); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertNotNull(nfres.getNetconfResponseXml()); + } + + @Test + public void getRequestWithNoParamTest() { + NetConfRequest req = prepareNetConfRequest( + ""); + NetConfResponse nfres = receiver.getRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void getRequestWithUnknownParamTest() { + NetConfRequest req = prepareNetConfRequest( + "1"); + NetConfResponse nfres = receiver.getRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void setConfigRequestTest() { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) + .thenReturn(prepareSPVDeviceResponseSucess()); + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.setConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void setConfigRequestWithErrorResTest() { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) + .thenReturn(prepareDeviceResponseError()); + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.setConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("9001", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Request denied", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void setConfigRequestWithNoParamTest() { + NetConfRequest req = prepareNetConfRequest( + ""); + NetConfResponse nfres = receiver.setConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void setConfigRequestWithUnknowParatmerTest() { + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.setConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void setConfigRequestInvalidRequestXMLTest() { + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.setConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + } + + @Test + public void delConfigRequestTest() { + Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L); + Mockito.when(sync.performDeviceOperation(Mockito.anyObject())) + .thenReturn(prepareSPVDeviceResponseSucess()); + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.delConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void delConfigwithUnknownParamterRequestTest() { + NetConfRequest req = prepareNetConfRequest( + "11310767falsetruecpe-131true"); + NetConfResponse nfres = receiver.delConfigRequest(req); + Assert.assertNull(nfres.getNetconfResponseXml()); + Assert.assertEquals("0", nfres.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage()); + } + + @Test + public void handelRegisterEventTest() { + try { + assertFalse(receiver + .handelRegisterEvent(new NetConfServerDetails("00005BA1", "10.211.55.14", "17830"))); + } catch (Exception e) { + } + + } + + private NetConfRequest prepareNetConfRequest(String requestXml) { + NetConfRequest req = new NetConfRequest(); + req.setDeviceId("0005B9A1"); + req.setRequestXml(requestXml); + req.setSwVersion("4.3.0.0"); + req.setHwVersion("*"); + return req; + } + + private DeviceRPCResponse prepareDeviceResponseError() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("9001"); + opResult.setFaultString("Request denied"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + // opr.setParameterDTOs(getGeneralParams()); + opResult.setOperationResponse(opr); + return opResult; + } + + private DeviceRPCResponse prepareDeviceResponseSucess() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("0"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + opr.setParameterDTOs(getGeneralParams()); + opResult.setOperationResponse(opr); + return opResult; + } + + private DeviceRPCResponse prepareSPVDeviceResponseSucess() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("0"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + opResult.setOperationResponse(opr); + return opResult; + } + + private ArrayList getGeneralParams() { + ArrayList params = new ArrayList<>(); + params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); + params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); + params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", + "30324")); + return params; + } +} diff --git a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfServerManagerTest.java b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfServerManagerTest.java index 76bd4ba..45315b1 100644 --- a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfServerManagerTest.java +++ b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetConfServerManagerTest.java @@ -1,149 +1,151 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import java.util.ArrayList; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.InformType; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069InformType; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender; -import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; -import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -@SpringBootTest(classes = {MapperServiceBooter.class}) -@RunWith(SpringRunner.class) -public class NetConfServerManagerTest { - - @Autowired - NetConfServerManager server; - - @Autowired - NetConfNotificationSender nfSender; - - @Autowired - VESNotificationSender vesSender; - - @MockBean - RestTemplate restTemplate; - - @Test - public void createServerTest() { - ResponseEntity res = new ResponseEntity( - new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830"), HttpStatus.ACCEPTED); - Mockito.when( - restTemplate.postForEntity(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(res); - NetConfServerDetails nfDetails = server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*"); - - Assert.assertNotNull(nfDetails); - Assert.assertEquals("17830", nfDetails.getListenPort()); - } - - @Test - public void createServerFailureWithRestCallTest() { - NetConfServerDetails nfDetails = server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*"); - Assert.assertNull(nfDetails); - } - - @Test - public void sendNotificaionTest() { - ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED); - Mockito.when( - restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(res); - DeviceInform inform = new BootstrapInform(); - inform.setDeviceDetails(getDeviceDetails()); - ArrayList list = new ArrayList<>(); - list.add(TR069InformType.BOOTSTRAP); - inform.setInformTypeList(list); - inform.setParameters(getGeneralParams()); - ResponseEntity response = nfSender.sendNotification(inform); - Assert.assertNotNull(response); - Assert.assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); - } - - @Test - public void sendNotificaionInformNullTest() { - ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED); - Mockito.when( - restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(res); - ResponseEntity response = nfSender.sendNotification(null); - Assert.assertNull(response); - } - - @Test - public void sendVesEventTest() { - - Mockito.when( - restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) - .thenReturn(new VESNotificationResponse(202, "sucess")); - - DeviceInform inform = new BootstrapInform(); - inform.setDeviceDetails(getDeviceDetails()); - ArrayList list = new ArrayList(); - list.add(TR069InformType.BOOTSTRAP); - inform.setInformTypeList(list); - inform.setParameters(getGeneralParams()); - VESNotificationResponse response = vesSender.sendNotification(inform, - new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830")); - Assert.assertNotNull(response); - Assert.assertEquals(202, response.getStatusCode()); - } - - private ArrayList getGeneralParams() { - ArrayList params = new ArrayList<>(); - params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); - params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); - params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", - "30324")); - params.add(new ParameterDTO( - "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1")); - params.add( - new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0")); - return params; - } - - private DeviceDetails getDeviceDetails() { - DeviceDetails nf = new DeviceDetails(); - nf.setDeviceId("00005B9A1"); - nf.setDeviceTypeId(50); - nf.setOui("0005B9"); - nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); - return nf; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import java.util.ArrayList; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.InformType; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069InformType; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender; +import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager; +import org.commscope.tr069adapter.mapper.ves.VESNotificationSender; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +@SpringBootTest(classes = {MapperServiceBooter.class}) +@RunWith(SpringRunner.class) +public class NetConfServerManagerTest { + + @Autowired + NetConfServerManager server; + + @Autowired + NetConfNotificationSender nfSender; + + @Autowired + VESNotificationSender vesSender; + + @MockBean + RestTemplate restTemplate; + + @Test + public void createServerTest() { + ResponseEntity res = new ResponseEntity( + new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830"), HttpStatus.ACCEPTED); + Mockito.when( + restTemplate.postForEntity(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) + .thenReturn(res); + NetConfServerDetails nfDetails = + server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*"); + + Assert.assertNotNull(nfDetails); + Assert.assertEquals("17830", nfDetails.getListenPort()); + } + + @Test + public void createServerFailureWithRestCallTest() { + NetConfServerDetails nfDetails = + server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*"); + Assert.assertNull(nfDetails); + } + + @Test + public void sendNotificaionTest() { + ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED); + Mockito.when( + restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) + .thenReturn(res); + DeviceInform inform = new BootstrapInform(); + inform.setDeviceDetails(getDeviceDetails()); + ArrayList list = new ArrayList<>(); + list.add(TR069InformType.BOOTSTRAP); + inform.setInformTypeList(list); + inform.setParameters(getGeneralParams()); + ResponseEntity response = nfSender.sendNotification(inform); + Assert.assertNotNull(response); + Assert.assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); + } + + @Test + public void sendNotificaionInformNullTest() { + ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED); + Mockito.when( + restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) + .thenReturn(res); + ResponseEntity response = nfSender.sendNotification(null); + Assert.assertNull(response); + } + + @Test + public void sendVesEventTest() { + + Mockito.when( + restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject())) + .thenReturn(new VESNotificationResponse(202, "sucess")); + + DeviceInform inform = new BootstrapInform(); + inform.setDeviceDetails(getDeviceDetails()); + ArrayList list = new ArrayList(); + list.add(TR069InformType.BOOTSTRAP); + inform.setInformTypeList(list); + inform.setParameters(getGeneralParams()); + VESNotificationResponse response = vesSender.sendNotification(inform, + new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830")); + Assert.assertNotNull(response); + Assert.assertEquals(202, response.getStatusCode()); + } + + private ArrayList getGeneralParams() { + ArrayList params = new ArrayList<>(); + params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); + params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); + params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", + "30324")); + params.add(new ParameterDTO( + "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1")); + params.add( + new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0")); + return params; + } + + private DeviceDetails getDeviceDetails() { + DeviceDetails nf = new DeviceDetails(); + nf.setDeviceId("00005B9A1"); + nf.setDeviceTypeId(50); + nf.setOui("0005B9"); + nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); + return nf; + } +} diff --git a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetconfToTr069MapperUtilTest.java b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetconfToTr069MapperUtilTest.java index 943ad9f..e6c6f5d 100644 --- a/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetconfToTr069MapperUtilTest.java +++ b/mapper/src/test/java/org/commscope/tr069adapter/mapper/NetconfToTr069MapperUtilTest.java @@ -1,100 +1,100 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import java.util.ArrayList; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationResponse; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; -import org.junit.Assert; -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.test.context.junit4.SpringRunner; - -@SpringBootTest(classes = {MapperServiceBooter.class}) -@RunWith(SpringRunner.class) -public class NetconfToTr069MapperUtilTest { - - @Autowired - NetconfToTr069MapperUtil mapUtil; - - @Test - public void getNetconfResponseTest() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("0"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - opr.setParameterDTOs(getGeneralParams()); - opResult.setOperationResponse(opr); - NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); - Assert.assertNotNull(netConfRes); - Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage()); - } - - @Test - public void getNetconfResponseErrorTest() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("9001"); - opResult.setFaultString("Request denied"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - opr.setParameterDTOs(getGeneralParams()); - opResult.setOperationResponse(opr); - NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); - Assert.assertNotNull(netConfRes); - Assert.assertEquals("9001", netConfRes.getErrorCode().getFaultCode()); - Assert.assertEquals("Request denied", netConfRes.getErrorCode().getErrorMessage()); - } - - @Test - public void getNetconfResponseWithoutParamtersTest() { - DeviceRPCResponse opResult = new DeviceRPCResponse(); - opResult.setFaultKey("0"); - opResult.setDeviceDetails(new DeviceDetails()); - OperationResponse opr = new OperationResponse(); - opResult.setOperationResponse(opr); - NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); - Assert.assertNotNull(netConfRes); - Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode()); - Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage()); - Assert.assertNull(netConfRes.getNetconfResponseXml()); - } - - private ArrayList getGeneralParams() { - ArrayList params = new ArrayList<>(); - params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); - params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); - params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", - "30324")); - params.add(new ParameterDTO( - "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1")); - params.add( - new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0")); - - return params; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import java.util.ArrayList; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationResponse; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil; +import org.junit.Assert; +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.test.context.junit4.SpringRunner; + +@SpringBootTest(classes = {MapperServiceBooter.class}) +@RunWith(SpringRunner.class) +public class NetconfToTr069MapperUtilTest { + + @Autowired + NetconfToTr069MapperUtil mapUtil; + + @Test + public void getNetconfResponseTest() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("0"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + opr.setParameterDTOs(getGeneralParams()); + opResult.setOperationResponse(opr); + NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); + Assert.assertNotNull(netConfRes); + Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage()); + } + + @Test + public void getNetconfResponseErrorTest() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("9001"); + opResult.setFaultString("Request denied"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + opr.setParameterDTOs(getGeneralParams()); + opResult.setOperationResponse(opr); + NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); + Assert.assertNotNull(netConfRes); + Assert.assertEquals("9001", netConfRes.getErrorCode().getFaultCode()); + Assert.assertEquals("Request denied", netConfRes.getErrorCode().getErrorMessage()); + } + + @Test + public void getNetconfResponseWithoutParamtersTest() { + DeviceRPCResponse opResult = new DeviceRPCResponse(); + opResult.setFaultKey("0"); + opResult.setDeviceDetails(new DeviceDetails()); + OperationResponse opr = new OperationResponse(); + opResult.setOperationResponse(opr); + NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false); + Assert.assertNotNull(netConfRes); + Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode()); + Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage()); + Assert.assertNull(netConfRes.getNetconfResponseXml()); + } + + private ArrayList getGeneralParams() { + ArrayList params = new ArrayList<>(); + params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9")); + params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl")); + params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID", + "30324")); + params.add(new ParameterDTO( + "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1")); + params.add( + new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0")); + + return params; + } +} diff --git a/mapper/src/test/java/org/commscope/tr069adapter/mapper/PnPPreProvisioningHandlerTest.java b/mapper/src/test/java/org/commscope/tr069adapter/mapper/PnPPreProvisioningHandlerTest.java index b84b5c6..c813ce6 100644 --- a/mapper/src/test/java/org/commscope/tr069adapter/mapper/PnPPreProvisioningHandlerTest.java +++ b/mapper/src/test/java/org/commscope/tr069adapter/mapper/PnPPreProvisioningHandlerTest.java @@ -1,101 +1,101 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.mapper; - -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; -import org.commscope.tr069adapter.acs.common.inform.BootInform; -import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; -import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler; -import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -@SpringBootTest(classes = {MapperServiceBooter.class}) -@RunWith(SpringRunner.class) -public class PnPPreProvisioningHandlerTest { - - @Autowired - PnPPreProvisioningHandler pnPPreProvisioningHandler; - - @Mock - RestTemplate restTemplate; - - @Test - public void testGetEnodeBName() { - ConfigurationData configData = new ConfigurationData(); - Map paramMap = new HashMap(); - paramMap.put("X_0005B9_eNBName", "Enodb1"); - configData.setParameterMONameValueMap(paramMap); - Mockito.when(restTemplate.getForObject(Mockito.anyString(), Mockito.any())) - .thenReturn(configData); - String eNodeBName = pnPPreProvisioningHandler.getEnodeBName("00005B9A1", "4.3.0.0", "*"); - assertNull(eNodeBName); - } - - @Test - public void testOnDeviceBootStrapNotification() { - BootstrapInform notification = new BootstrapInform(); - List params = new ArrayList(); - ParameterDTO param = new ParameterDTO(); - param.setParamName("ExpeditedEvent"); - params.add(param); - notification.setDeviceDetails(getDeviceDetails()); - notification.setParameters(params); - pnPPreProvisioningHandler.onDeviceNotification(notification); - assertNull(notification.getValueChangeNotification()); - } - - @Test - public void testOnDeviceBootNotification() { - BootInform notification = new BootInform(); - List params = new ArrayList(); - ParameterDTO param = new ParameterDTO(); - param.setParamName("ExpeditedEvent"); - params.add(param); - notification.setDeviceDetails(getDeviceDetails()); - notification.setParameters(params); - pnPPreProvisioningHandler.onDeviceNotification(notification); - assertNull(notification.getValueChangeNotification()); - } - - private DeviceDetails getDeviceDetails() { - DeviceDetails nf = new DeviceDetails(); - nf.setDeviceId("00005B9A1"); - nf.setDeviceTypeId(50); - nf.setOui("0005B9"); - nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); - return nf; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.mapper; + +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.ConfigurationData; +import org.commscope.tr069adapter.acs.common.inform.BootInform; +import org.commscope.tr069adapter.acs.common.inform.BootstrapInform; +import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler; +import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +@SpringBootTest(classes = {MapperServiceBooter.class}) +@RunWith(SpringRunner.class) +public class PnPPreProvisioningHandlerTest { + + @Autowired + PnPPreProvisioningHandler pnPPreProvisioningHandler; + + @Mock + RestTemplate restTemplate; + + @Test + public void testGetEnodeBName() { + ConfigurationData configData = new ConfigurationData(); + Map paramMap = new HashMap(); + paramMap.put("X_0005B9_eNBName", "Enodb1"); + configData.setParameterMONameValueMap(paramMap); + Mockito.when(restTemplate.getForObject(Mockito.anyString(), Mockito.any())) + .thenReturn(configData); + String eNodeBName = pnPPreProvisioningHandler.getEnodeBName("00005B9A1", "4.3.0.0", "*"); + assertNull(eNodeBName); + } + + @Test + public void testOnDeviceBootStrapNotification() { + BootstrapInform notification = new BootstrapInform(); + List params = new ArrayList(); + ParameterDTO param = new ParameterDTO(); + param.setParamName("ExpeditedEvent"); + params.add(param); + notification.setDeviceDetails(getDeviceDetails()); + notification.setParameters(params); + pnPPreProvisioningHandler.onDeviceNotification(notification); + assertNull(notification.getValueChangeNotification()); + } + + @Test + public void testOnDeviceBootNotification() { + BootInform notification = new BootInform(); + List params = new ArrayList(); + ParameterDTO param = new ParameterDTO(); + param.setParamName("ExpeditedEvent"); + params.add(param); + notification.setDeviceDetails(getDeviceDetails()); + notification.setParameters(params); + pnPPreProvisioningHandler.onDeviceNotification(notification); + assertNull(notification.getValueChangeNotification()); + } + + private DeviceDetails getDeviceDetails() { + DeviceDetails nf = new DeviceDetails(); + nf.setDeviceId("00005B9A1"); + nf.setDeviceTypeId(50); + nf.setOui("0005B9"); + nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl"); + return nf; + } + +} diff --git a/netconf-server/pom.xml b/netconf-server/pom.xml index f801ba7..7da657a 100644 --- a/netconf-server/pom.xml +++ b/netconf-server/pom.xml @@ -203,6 +203,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin diff --git a/netconf-server/schemas/common/tr069-operations.yang b/netconf-server/schemas/common/tr069-operations.yang new file mode 100644 index 0000000..7d5da90 --- /dev/null +++ b/netconf-server/schemas/common/tr069-operations.yang @@ -0,0 +1,328 @@ +module tr069-operations { + yang-version 1; + namespace "urn:tr069rpc:1.0"; + prefix cr; + + organization + "CommScope"; + contact + "Radio access OneCell <5g@commscope.com> + + CommScope Inc + 1100 10th Ave Ct SE, + Hickory, + NC 28602, + USA"; + description + "This module contains a YANG definition for the TR069 device operations."; + + revision 2020-08-07 { + description + "PLEASE READ BELOW NOTES BEFORE USING THE RPCs: + 1) All the RPCs supported by TR-069 protocol are translated to NETCONF + RPCs except following RPCs. + i. GetRPCMethods + ii. GetParameterNames + iii. InitiateCR + iv. Download + v. ScheduleDownload + vi. Upload + "; + reference + "Subset of TR-069 protocol RPCs mapped to NETCONF RPCs"; + } + + grouping add-object-output { + description + "Grouping for add-object rpc output"; + leaf status { + type enumeration { + enum 0 { + description + "The Object has been created."; + } + enum 1 { + description + "The Object creation has been validated and committed, but not yet applied (for example, if a reboot is required before the new Object can be applied)."; + } + } + mandatory true; + description + "Status of the addObject"; + } + + leaf instance-number { + type int32; + description + "Instance Number when the status is passed."; + } + leaf label { + type string; + description + "label attribute for add-object output."; + } + } + + grouping delete-object-output { + description + "Grouping for add-object rpc output"; + leaf status { + type enumeration { + enum 0 { + description + "The Object has been deleted."; + } + enum 1 { + description + "The Object deletion has been validated and committed, but not yet applied (for example, if a reboot is required before the Object can be deleted)."; + } + } + mandatory true; + description + "Status of the addObject"; + } + } + + grouping set-parameter-attributes-input { + description + "Grouping for set-parameter-attributes rpc input"; + list config { + key "keyindex"; + description + "config container object for set parameter attributes RPC."; + leaf keyindex { + type uint16; + description + "keyindex for each set parameter attribute"; + } + anyxml parameter { + description + "parameter attribute"; + } + leaf notification { + type int32; + mandatory true; + description + "notification attribute for a set parameter attribute"; + } + leaf notification-change { + type boolean; + description + "notification change attribute for a set parameter attribute"; + } + leaf-list access-list { + type string; + description + "access list attributes for a set parameter attribute"; + } + leaf access-list-change { + type boolean; + description + "access list change attribute for a set parameter attribute"; + } + } + } + + grouping get-parameter-attributes-output { + description + "Grouping for get-parameter-attributes rpc output"; + list data { + key "keyindex"; + description + "get parameter attribute configuration Object"; + leaf keyindex { + type uint16; + description + "keyindex attribute"; + } + leaf parameter { + type string; + description + "parameter attribute"; + } + leaf notification { + type int32; + mandatory true; + description + "notification parameter"; + } + leaf-list access-list { + type string; + description + "access list of a attribute"; + } + } + } + + grouping download-input { + description + "Grouping for download rpc input"; + leaf command-key { + type string; + description + "command key"; + } + leaf file-type { + type string; + description + "file type"; + } + leaf url { + type string; + description + "url string"; + } + leaf username { + type string; + description + "Username"; + } + leaf password { + type string; + description + "password"; + } + leaf file-size { + type int32; + description + "file size"; + } + leaf target-file-name { + type string; + description + "target file name"; + } + leaf delay-in-seconds { + type int32; + description + "delay in seconds"; + } + leaf success-url { + type string; + description + "success url"; + } + leaf failure-url { + type string; + description + "failure url"; + } + } + + rpc add-object { + description + "adds object for parameter on the device."; + input { + anyxml parameter { + description + "parameter attribute for add-object"; + } + } + output { + uses add-object-output; + } + } + + rpc delete-object { + description + "adds object for parameter on the device."; + input { + anyxml parameter { + description + "access container Object"; + } + } + output { + uses delete-object-output; + } + } + + rpc set-parameter-attributes { + description + "SPA for parameter on the device."; + input { + uses set-parameter-attributes-input; + } + } + + rpc get-parameter-attributes { + description + "GPA for parameter on the device."; + input { + list filter { + key "keyindex"; + description + "get-parameter-attributes Object as rpc input"; + leaf keyindex { + type uint16; + description + "keyindex attribute for a get parameter attribute"; + } + anyxml parameter { + description + "parameter GPA RPC input"; + } + } + } + output { + uses get-parameter-attributes-output; + } + } + + rpc reboot { + description + "Reboots the device."; + } + + rpc reset { + description + "resets the device."; + } + + rpc connection-status { + description + "device connection status."; + output { + leaf last-contact-time { + type string; + mandatory true; + description + "when device has last contacted the ONAP."; + } + leaf last-failure-attempt-time { + type string; + mandatory true; + description + "when the last access attempt has failed from ONAP."; + } + leaf last-access-status { + type enumeration { + enum SUCCESS { + description + "Last connection was successful."; + } + enum FAILED { + description + "Last device access was failed."; + } + } + mandatory true; + description + "Status of last device access."; + } + leaf error-message { + when "../current-status = 'FAILED'"; + type string; + description + "Detailed error Message when the status is failed."; + } + } + } + rpc download { + description + "download."; + input { + uses download-input; + } + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/boot/NetConfServiceBooter.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/boot/NetConfServiceBooter.java index 9614865..f051dd6 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/boot/NetConfServiceBooter.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/boot/NetConfServiceBooter.java @@ -1,135 +1,135 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.boot; - -import java.util.Arrays; -import javax.jms.ConnectionFactory; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; -import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jms.annotation.EnableJms; -import org.springframework.jms.config.DefaultJmsListenerContainerFactory; -import org.springframework.jms.config.JmsListenerContainerFactory; -import org.springframework.jms.listener.MessageListenerContainer; -import org.springframework.jms.support.converter.MappingJackson2MessageConverter; -import org.springframework.jms.support.converter.MessageConverter; -import org.springframework.jms.support.converter.MessageType; -import org.springframework.retry.annotation.EnableRetry; - -@EnableJms -@SpringBootApplication -@ComponentScan({"org.commscope.tr069adapter.netconf", "org.opendaylight.netconf.test", - "org.commscope.tr069adapter.common"}) -@EnableJpaRepositories("org.commscope.tr069adapter.netconf.dao") -@EntityScan("org.commscope.tr069adapter.netconf.entity") -@EnableRetry -public class NetConfServiceBooter { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfServiceBooter.class); - - private static ApplicationContext appContext; - - public static void main(String[] args) { - if (args != null) - appContext = SpringApplication.run(NetConfServiceBooter.class, args); - NetConfServerManagerImpl serverManager = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerManagerImpl.class); - boolean isSchemaLoaded = serverManager.loadSchemas(); - if (!isSchemaLoaded) { - LOG.error("Loading the schema failed while starting the container"); - System.exit(1); - } - serverManager.restartServers(); - } - - public static ApplicationContext getApplicationContext() { - return appContext; - } - - /* - * JMS Configuration Defining the connection factories used in the application Setting the - * Re-delivery configuration goes here - */ - @Bean - public BrokerService broker() throws Exception { - final BrokerService broker = new BrokerService(); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://localhost"); - broker.setPersistent(false); - return broker; - } - - @Bean - public ConnectionFactory jmsConnectionFactory() { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - connectionFactory - .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter")); - connectionFactory.setMaxThreadPoolSize(7); - - ActiveMQQueue notificationQueue = new ActiveMQQueue(NetConfServerConstants.NETCONF_NOTIFICATION_Q); - RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy(); - notificationQueuePolicy.setInitialRedeliveryDelay(2* 60 * 1000L); - notificationQueuePolicy.setUseCollisionAvoidance(true); - notificationQueuePolicy.setRedeliveryDelay(2* 60 * 1000L); - notificationQueuePolicy.setUseExponentialBackOff(false); - notificationQueuePolicy.setMaximumRedeliveries(3); - notificationQueuePolicy.setDestination(notificationQueue); - - RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap(); - rdMap.put(notificationQueue, notificationQueuePolicy); - return connectionFactory; - } - - @Bean - public JmsListenerContainerFactory netConfNotificationCF( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - return handleJMSCommonConfiguration(connectionFactory, configurer); - } - - public JmsListenerContainerFactory handleJMSCommonConfiguration( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); - configurer.configure(factory, connectionFactory); - return factory; - } - - @Bean - public MessageConverter jacksonJmsMessageConverter() { - MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); - converter.setTargetType(MessageType.TEXT); - converter.setTypeIdPropertyName("_type"); - return converter; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.boot; + +import java.util.Arrays; +import javax.jms.ConnectionFactory; +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.RedeliveryPolicy; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; +import org.apache.activemq.command.ActiveMQQueue; +import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; +import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jms.annotation.EnableJms; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.config.JmsListenerContainerFactory; +import org.springframework.jms.listener.MessageListenerContainer; +import org.springframework.jms.support.converter.MappingJackson2MessageConverter; +import org.springframework.jms.support.converter.MessageConverter; +import org.springframework.jms.support.converter.MessageType; +import org.springframework.retry.annotation.EnableRetry; + +@EnableJms +@SpringBootApplication +@ComponentScan({"org.commscope.tr069adapter.netconf", "org.opendaylight.netconf.test", + "org.commscope.tr069adapter.common"}) +@EnableJpaRepositories("org.commscope.tr069adapter.netconf.dao") +@EntityScan("org.commscope.tr069adapter.netconf.entity") +@EnableRetry +public class NetConfServiceBooter { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfServiceBooter.class); + + private static ApplicationContext appContext; + + public static void main(String[] args) { + if (args != null) + appContext = SpringApplication.run(NetConfServiceBooter.class, args); + NetConfServerManagerImpl serverManager = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerManagerImpl.class); + boolean isSchemaLoaded = serverManager.loadSchemas(); + if (!isSchemaLoaded) { + LOG.error("Loading the schema failed while starting the container"); + System.exit(1); + } + serverManager.restartServers(); + } + + public static ApplicationContext getApplicationContext() { + return appContext; + } + + /* + * JMS Configuration Defining the connection factories used in the application Setting the + * Re-delivery configuration goes here + */ + @Bean + public BrokerService broker() throws Exception { + final BrokerService broker = new BrokerService(); + broker.addConnector("tcp://localhost:61616"); + broker.addConnector("vm://localhost"); + broker.setPersistent(false); + return broker; + } + + @Bean + public ConnectionFactory jmsConnectionFactory() { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory + .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter")); + connectionFactory.setMaxThreadPoolSize(7); + + ActiveMQQueue notificationQueue = new ActiveMQQueue(NetConfServerConstants.NETCONF_NOTIFICATION_Q); + RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy(); + notificationQueuePolicy.setInitialRedeliveryDelay(2* 60 * 1000L); + notificationQueuePolicy.setUseCollisionAvoidance(true); + notificationQueuePolicy.setRedeliveryDelay(2* 60 * 1000L); + notificationQueuePolicy.setUseExponentialBackOff(false); + notificationQueuePolicy.setMaximumRedeliveries(3); + notificationQueuePolicy.setDestination(notificationQueue); + + RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap(); + rdMap.put(notificationQueue, notificationQueuePolicy); + return connectionFactory; + } + + @Bean + public JmsListenerContainerFactory netConfNotificationCF( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + return handleJMSCommonConfiguration(connectionFactory, configurer); + } + + public JmsListenerContainerFactory handleJMSCommonConfiguration( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + return factory; + } + + @Bean + public MessageConverter jacksonJmsMessageConverter() { + MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); + converter.setTargetType(MessageType.TEXT); + converter.setTypeIdPropertyName("_type"); + return converter; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/entity/NetConfServerDetailsEntity.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/entity/NetConfServerDetailsEntity.java index e37fd99..b6ce916 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/entity/NetConfServerDetailsEntity.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/entity/NetConfServerDetailsEntity.java @@ -1,102 +1,102 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.entity; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "netconf_server_details") -public class NetConfServerDetailsEntity implements Serializable { - - private static final long serialVersionUID = 3572178771247249366L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(name = "DEVICE_ID", length = 30) - private String deviceId; - - @Column(name = "ENODEB_NAME", length = 255) - private String enodeBName; - - @Column(name = "PORT", length = 10) - private String listenPort; - - @Column(name = "SW_VERSION", length = 64) - private String swVersion; - - @Column(name = "HW_VERSION", length = 64) - private String hwVersion; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String getListenPort() { - return listenPort; - } - - public void setListenPort(String listenPort) { - this.listenPort = listenPort; - } - - public String getEnodeBName() { - return enodeBName; - } - - public void setEnodeBName(String enodeBName) { - this.enodeBName = enodeBName; - } - - public String getSwVersion() { - return swVersion; - } - - public void setSwVersion(String swVersion) { - this.swVersion = swVersion; - } - - public String getHwVersion() { - return hwVersion; - } - - public void setHwVersion(String hwVersion) { - this.hwVersion = hwVersion; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "netconf_server_details") +public class NetConfServerDetailsEntity implements Serializable { + + private static final long serialVersionUID = 3572178771247249366L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "DEVICE_ID", length = 30) + private String deviceId; + + @Column(name = "ENODEB_NAME", length = 255) + private String enodeBName; + + @Column(name = "PORT", length = 10) + private String listenPort; + + @Column(name = "SW_VERSION", length = 64) + private String swVersion; + + @Column(name = "HW_VERSION", length = 64) + private String hwVersion; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getListenPort() { + return listenPort; + } + + public void setListenPort(String listenPort) { + this.listenPort = listenPort; + } + + public String getEnodeBName() { + return enodeBName; + } + + public void setEnodeBName(String enodeBName) { + this.enodeBName = enodeBName; + } + + public String getSwVersion() { + return swVersion; + } + + public void setSwVersion(String swVersion) { + this.swVersion = swVersion; + } + + public String getHwVersion() { + return hwVersion; + } + + public void setHwVersion(String hwVersion) { + this.hwVersion = hwVersion; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NetConfSessionUtil.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NetConfSessionUtil.java index 55c40b2..25ded43 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NetConfSessionUtil.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NetConfSessionUtil.java @@ -1,50 +1,50 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.notification; - -import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; -import org.commscope.tr069adapter.netconf.error.NetconfNotificationException; -import org.commscope.tr069adapter.netconf.rpc.CreateSubscription; -import org.opendaylight.netconf.api.NetconfMessage; -import org.opendaylight.netconf.api.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class NetConfSessionUtil { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfSessionUtil.class); - - public void sendNetConfNotification(NetConfNotificationDTO netConNotifDTO) - throws NetconfNotificationException { - NetconfMessage netconfMessage = convertToNetConfMessage(netConNotifDTO); - CreateSubscription.sendNotification(netconfMessage, netConNotifDTO.getDeviceID()); - } - - private NetconfMessage convertToNetConfMessage(NetConfNotificationDTO netConNotifDTO) - throws NetconfNotificationException { - try { - return new NetconfMessage(XmlUtil.readXmlToDocument(netConNotifDTO.getNotificaiton())); - } catch (Exception e) { - LOG.error("Error while converting to netcon notification "); - throw new NetconfNotificationException("Cannot parse notifications", e); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.notification; + +import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; +import org.commscope.tr069adapter.netconf.error.NetconfNotificationException; +import org.commscope.tr069adapter.netconf.rpc.CreateSubscription; +import org.opendaylight.netconf.api.NetconfMessage; +import org.opendaylight.netconf.api.xml.XmlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class NetConfSessionUtil { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfSessionUtil.class); + + public void sendNetConfNotification(NetConfNotificationDTO netConNotifDTO) + throws NetconfNotificationException { + NetconfMessage netconfMessage = convertToNetConfMessage(netConNotifDTO); + CreateSubscription.sendNotification(netconfMessage, netConNotifDTO.getDeviceID()); + } + + private NetconfMessage convertToNetConfMessage(NetConfNotificationDTO netConNotifDTO) + throws NetconfNotificationException { + try { + return new NetconfMessage(XmlUtil.readXmlToDocument(netConNotifDTO.getNotificaiton())); + } catch (Exception e) { + LOG.error("Error while converting to netcon notification "); + throw new NetconfNotificationException("Cannot parse notifications", e); + } + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NotificationHandler.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NotificationHandler.java index fe80c4a..ff2171a 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NotificationHandler.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/notification/NotificationHandler.java @@ -1,56 +1,56 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.notification; - -import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; -import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.stereotype.Component; - -@Component -public class NotificationHandler { - - private static final Logger logger = LoggerFactory.getLogger(NotificationHandler.class); - private static final String CLIENT_STR = "client"; - - @Autowired - NetConfSessionUtil netConfSessionUtil; - - @Autowired - private JmsTemplate jmsTemplate; - - public void handleNetConfNotification(NetConfNotificationDTO netConNotifDTO) { - logger.debug("processing netconf notification {}", netConNotifDTO); - try { - MDC.put(CLIENT_STR, netConNotifDTO.getDeviceID()); - - logger.debug("NetConf notificaiton reviced for {}", netConNotifDTO.getDeviceID()); - jmsTemplate.convertAndSend(NetConfServerConstants.NETCONF_NOTIFICATION_Q, netConNotifDTO); - logger.debug("Successfully posted the notiticaiton to JMS to forward to SDNR"); - } catch (Exception e) { - logger.error("Posting notification failed; Reason: {}", e.getMessage()); - } finally { - MDC.remove(CLIENT_STR); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.notification; + +import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; +import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.stereotype.Component; + +@Component +public class NotificationHandler { + + private static final Logger logger = LoggerFactory.getLogger(NotificationHandler.class); + private static final String CLIENT_STR = "client"; + + @Autowired + NetConfSessionUtil netConfSessionUtil; + + @Autowired + private JmsTemplate jmsTemplate; + + public void handleNetConfNotification(NetConfNotificationDTO netConNotifDTO) { + logger.debug("processing netconf notification {}", netConNotifDTO); + try { + MDC.put(CLIENT_STR, netConNotifDTO.getDeviceID()); + + logger.debug("NetConf notificaiton reviced for {}", netConNotifDTO.getDeviceID()); + jmsTemplate.convertAndSend(NetConfServerConstants.NETCONF_NOTIFICATION_Q, netConNotifDTO); + logger.debug("Successfully posted the notiticaiton to JMS to forward to SDNR"); + } catch (Exception e) { + logger.error("Posting notification failed; Reason: {}", e.getMessage()); + } finally { + MDC.remove(CLIENT_STR); + } + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreator.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreator.java index 5ad9dfd..8d9f549 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreator.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreator.java @@ -1,117 +1,136 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.operations; - -import com.google.common.collect.Sets; - -import java.util.Optional; -import java.util.Set; - -import org.commscope.tr069adapter.netconf.rpc.CreateSubscription; -import org.commscope.tr069adapter.netconf.rpc.DeleteConfigOperation; -import org.commscope.tr069adapter.netconf.rpc.GetConfigOperation; -import org.commscope.tr069adapter.netconf.rpc.GetOperation; -import org.commscope.tr069adapter.netconf.rpc.OperationCommit; -import org.commscope.tr069adapter.netconf.rpc.OperationLock; -import org.commscope.tr069adapter.netconf.rpc.OperationUnLock; -import org.commscope.tr069adapter.netconf.rpc.SetConfigOperation; -import org.commscope.tr069adapter.netconf.rpc.SoftwareActivateOperation; -import org.commscope.tr069adapter.netconf.rpc.SoftwareDownloadOperation; -import org.opendaylight.netconf.api.capability.Capability; -import org.opendaylight.netconf.impl.SessionIdProvider; -import org.opendaylight.netconf.mapping.api.NetconfOperation; -import org.opendaylight.netconf.mapping.api.NetconfOperationService; -import org.opendaylight.netconf.test.tool.operations.OperationsCreator; -import org.opendaylight.netconf.test.tool.rpc.DataList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class CustomOperationsCreator implements OperationsCreator { - private static final Logger logger = LoggerFactory.getLogger(CustomOperationsCreator.class); - - private String macID = null; - - private String swVersion; - - private String hwVersion; - - private OperationService operationService; - - public CustomOperationsCreator(String macID, String swVersion, String hwVersion) { - this.macID = macID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - public NetconfOperationService getNetconfOperationService(final Set caps, - final SessionIdProvider idProvider, final String netconfSessionIdForReporting) { - if (null == operationService) { - operationService = - new OperationService(idProvider.getCurrentSessionId(), macID, swVersion, hwVersion); - } - return operationService; - } - - static class OperationService implements NetconfOperationService { - - private final long currentSessionId; - private String macID; - private String swVersion; - private String hwVersion; - - OperationService(final long currentSessionId, String macID, String swVersion, - String hwVersion) { - this.currentSessionId = currentSessionId; - this.macID = macID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - public Set getNetconfOperations() { - final DataList storage = new DataList(); - final GetOperation oGet = - new GetOperation(String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion); - final GetConfigOperation oGetConfig = new GetConfigOperation(String.valueOf(currentSessionId), - Optional.empty(), macID, swVersion, hwVersion); - final SetConfigOperation oSetConfig = - new SetConfigOperation(String.valueOf(currentSessionId), macID, swVersion, hwVersion); - final DeleteConfigOperation oDelConfig = new DeleteConfigOperation( - String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion); - final OperationCommit oCommit = new OperationCommit(String.valueOf(currentSessionId)); - final OperationLock oLock = new OperationLock(String.valueOf(currentSessionId)); - final OperationUnLock oUnlock = new OperationUnLock(String.valueOf(currentSessionId)); - final CreateSubscription sCreateSubs = new CreateSubscription( - String.valueOf(currentSessionId), Optional.empty(), macID, swVersion, hwVersion); - SoftwareDownloadOperation swDownloadOperation = - new SoftwareDownloadOperation(macID, swVersion, hwVersion); - SoftwareActivateOperation swActivateOperation = - new SoftwareActivateOperation(macID, swVersion, hwVersion); - return Sets.newHashSet(oGet, oGetConfig, oSetConfig, oDelConfig, oCommit, oLock, oUnlock, - sCreateSubs, swDownloadOperation, swActivateOperation); - } - - @Override - public void close() { - logger.debug("close called on CustomOperationsCreator"); - } - - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.operations; + +import com.google.common.collect.Sets; + +import java.util.Optional; +import java.util.Set; + +import org.commscope.tr069adapter.netconf.rpc.AddObjectOperation; +import org.commscope.tr069adapter.netconf.rpc.ConnectionStatus; +import org.commscope.tr069adapter.netconf.rpc.CreateSubscription; +import org.commscope.tr069adapter.netconf.rpc.DeleteConfigOperation; +import org.commscope.tr069adapter.netconf.rpc.DeleteObjectOperation; +import org.commscope.tr069adapter.netconf.rpc.DownloadOperation; +import org.commscope.tr069adapter.netconf.rpc.GPAObjectOperation; +import org.commscope.tr069adapter.netconf.rpc.GetConfigOperation; +import org.commscope.tr069adapter.netconf.rpc.GetOperation; +import org.commscope.tr069adapter.netconf.rpc.OperationCommit; +import org.commscope.tr069adapter.netconf.rpc.OperationLock; +import org.commscope.tr069adapter.netconf.rpc.OperationUnLock; +import org.commscope.tr069adapter.netconf.rpc.RebootOperation; +import org.commscope.tr069adapter.netconf.rpc.ResetOperation; +import org.commscope.tr069adapter.netconf.rpc.SPAObjectOperation; +import org.commscope.tr069adapter.netconf.rpc.SetConfigOperation; +import org.commscope.tr069adapter.netconf.rpc.SoftwareActivateOperation; +import org.commscope.tr069adapter.netconf.rpc.SoftwareDownloadOperation; +import org.opendaylight.netconf.api.capability.Capability; +import org.opendaylight.netconf.impl.SessionIdProvider; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationService; +import org.opendaylight.netconf.test.tool.operations.OperationsCreator; +import org.opendaylight.netconf.test.tool.rpc.DataList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class CustomOperationsCreator implements OperationsCreator { + private static final Logger logger = LoggerFactory.getLogger(CustomOperationsCreator.class); + + private String macID = null; + + private String swVersion; + + private String hwVersion; + + private OperationService operationService; + + public CustomOperationsCreator(String macID, String swVersion, String hwVersion) { + this.macID = macID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public NetconfOperationService getNetconfOperationService(final Set caps, + final SessionIdProvider idProvider, final String netconfSessionIdForReporting) { + if (null == operationService) { + operationService = + new OperationService(idProvider.getCurrentSessionId(), macID, swVersion, hwVersion); + } + return operationService; + } + + static class OperationService implements NetconfOperationService { + + private final long currentSessionId; + private String macID; + private String swVersion; + private String hwVersion; + + OperationService(final long currentSessionId, String macID, String swVersion, + String hwVersion) { + this.currentSessionId = currentSessionId; + this.macID = macID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public Set getNetconfOperations() { + final DataList storage = new DataList(); + final GetOperation oGet = + new GetOperation(String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion); + final GetConfigOperation oGetConfig = new GetConfigOperation(String.valueOf(currentSessionId), + Optional.empty(), macID, swVersion, hwVersion); + final SetConfigOperation oSetConfig = + new SetConfigOperation(String.valueOf(currentSessionId), macID, swVersion, hwVersion); + final DeleteConfigOperation oDelConfig = new DeleteConfigOperation( + String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion); + final OperationCommit oCommit = new OperationCommit(String.valueOf(currentSessionId)); + final OperationLock oLock = new OperationLock(String.valueOf(currentSessionId)); + final OperationUnLock oUnlock = new OperationUnLock(String.valueOf(currentSessionId)); + final CreateSubscription sCreateSubs = new CreateSubscription( + String.valueOf(currentSessionId), Optional.empty(), macID, swVersion, hwVersion); + SoftwareDownloadOperation swDownloadOperation = + new SoftwareDownloadOperation(macID, swVersion, hwVersion); + SoftwareActivateOperation swActivateOperation = + new SoftwareActivateOperation(macID, swVersion, hwVersion); + AddObjectOperation addObjectOperation = new AddObjectOperation(macID, swVersion, hwVersion); + DeleteObjectOperation deleteObjectOperation = + new DeleteObjectOperation(macID, swVersion, hwVersion); + GPAObjectOperation gpaObjectOperation = new GPAObjectOperation(macID, swVersion, hwVersion); + SPAObjectOperation spaObjectOperation = new SPAObjectOperation(macID, swVersion, hwVersion); + ConnectionStatus connStatus = new ConnectionStatus(macID, swVersion, hwVersion); + RebootOperation rebootOperation = new RebootOperation(macID, swVersion, hwVersion); + ResetOperation resetOperation = new ResetOperation(macID, swVersion, hwVersion); + DownloadOperation downloadOp = new DownloadOperation(macID, swVersion, hwVersion); + return Sets.newHashSet(oGet, oGetConfig, oSetConfig, oDelConfig, oCommit, oLock, oUnlock, + sCreateSubs, swDownloadOperation, swActivateOperation, addObjectOperation, + deleteObjectOperation, gpaObjectOperation, spaObjectOperation, connStatus, + rebootOperation, resetOperation, downloadOp); + } + + @Override + public void close() { + logger.debug("close called on CustomOperationsCreator"); + } + + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApi.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApi.java index 6057c67..5418a8c 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApi.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApi.java @@ -1,86 +1,93 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.restapi; - -import java.util.List; - -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/netConfServerManagerService") -public class NetConfServerManagerRestApi { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerRestApi.class); - - @Autowired - NetConfServerManagerImpl manager; - - @PostMapping("/createServer") - public NetConfServerDetails createNetConfServerInstance(@RequestParam String deviceId, - @RequestParam String enodeBName, @RequestParam String swVersion, - @RequestParam String hwVersion) { - LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}, swversion: {}", deviceId, - enodeBName, swVersion); - NetConfServerDetails serverDetails = - manager.createServer(deviceId, enodeBName, swVersion, hwVersion); - LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails); - return serverDetails; - } - - @PostMapping("/restartOnVersionChange") - public NetConfServerDetails restartOnVersionChange(@RequestParam String deviceId, - @RequestParam String enodeBName, @RequestParam String swVersion, - @RequestParam String hwVersion) { - LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}", deviceId, - enodeBName); - NetConfServerDetails serverDetails = - manager.restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion); - LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails); - return serverDetails; - } - - @GetMapping("/listServers") - public List listNetConfServersInfo() { - LOG.info("Received request to list all NetConf Servers information"); - List serverDetails = manager.getServersInfo(); - LOG.info("Successfully processed request to list all NetConf Servers information"); - return serverDetails; - } - - @PostMapping("/unregisterServer") - public String unregisterNetConfServerInstance(@RequestParam String deviceId, - @RequestParam String enodeBName) { - LOG.info("Received request for Unregister NetConf Server for deviceID: {}, enodeBName: {} ", - deviceId, enodeBName); - String result = manager.unregister(deviceId, enodeBName); - LOG.info("Unregister request is processed. NetConf Server for deviceID: {} , unregisted= {}", - deviceId, result); - return result; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.restapi; + +import java.util.List; + +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/netConfServerManagerService") +public class NetConfServerManagerRestApi { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerRestApi.class); + public static final String PATTERN = "[\n|\r|\t]"; + + @Autowired + NetConfServerManagerImpl manager; + + @PostMapping("/createServer") + public NetConfServerDetails createNetConfServerInstance(@RequestParam String deviceId, + @RequestParam String enodeBName, @RequestParam String swVersion, + @RequestParam String hwVersion) { + deviceId = deviceId.replaceAll(PATTERN, "_"); + enodeBName = enodeBName.replaceAll(PATTERN, "_"); + LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}, swversion: {}", deviceId, + enodeBName, swVersion); + NetConfServerDetails serverDetails = + manager.createServer(deviceId, enodeBName, swVersion, hwVersion); + LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails); + return serverDetails; + } + + @PostMapping("/restartOnVersionChange") + public NetConfServerDetails restartOnVersionChange(@RequestParam String deviceId, + @RequestParam String enodeBName, @RequestParam String swVersion, + @RequestParam String hwVersion) { + deviceId = deviceId.replaceAll(PATTERN, "_"); + enodeBName = enodeBName.replaceAll(PATTERN, "_"); + LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}", deviceId, + enodeBName); + NetConfServerDetails serverDetails = + manager.restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion); + LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails); + return serverDetails; + } + + @GetMapping("/listServers") + public List listNetConfServersInfo() { + LOG.info("Received request to list all NetConf Servers information"); + List serverDetails = manager.getServersInfo(); + LOG.info("Successfully processed request to list all NetConf Servers information"); + return serverDetails; + } + + @PostMapping("/unregisterServer") + public String unregisterNetConfServerInstance(@RequestParam String deviceId, + @RequestParam String enodeBName) { + deviceId = deviceId.replaceAll(PATTERN, "_"); + enodeBName = enodeBName.replaceAll(PATTERN, "_"); + LOG.info("Received request for Unregister NetConf Server for deviceID: {}, enodeBName: {} ", + deviceId, enodeBName); + String result = manager.unregister(deviceId, enodeBName); + LOG.info("Unregister request is processed. NetConf Server for deviceID: {} , unregisted= {}", + deviceId, result); + return result; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NotificationReceiverService.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NotificationReceiverService.java index 7186363..ec58967 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NotificationReceiverService.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/restapi/NotificationReceiverService.java @@ -16,33 +16,31 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.netconf.restapi; - -import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; -import org.commscope.tr069adapter.netconf.notification.NotificationHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/netConfNotificationService") -public class NotificationReceiverService { - - private static final Logger LOG = LoggerFactory.getLogger(NotificationReceiverService.class); - - @Autowired - NotificationHandler handler; - - @PostMapping("/notification") - public void processNotification(@RequestBody NetConfNotificationDTO netConNotifDTO) { - System.out.println("Received NetConf Notification :" + netConNotifDTO); - LOG.debug("Received NetConf Notification :" + netConNotifDTO); - handler.handleNetConfNotification(netConNotifDTO); - LOG.debug("Processed NetConf Notification for :" + netConNotifDTO); - System.out.println("Processed NetConf Notification for :" + netConNotifDTO); - } -} +package org.commscope.tr069adapter.netconf.restapi; + +import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO; +import org.commscope.tr069adapter.netconf.notification.NotificationHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/netConfNotificationService") +public class NotificationReceiverService { + + private static final Logger LOG = LoggerFactory.getLogger(NotificationReceiverService.class); + + @Autowired + NotificationHandler handler; + + @PostMapping("/notification") + public void processNotification(@RequestBody NetConfNotificationDTO netConNotifDTO) { + LOG.debug("Received NetConf Notification : {}", netConNotifDTO); + handler.handleNetConfNotification(netConNotifDTO); + LOG.debug("Processed NetConf Notification for : {}", netConNotifDTO); + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/AddObjectOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/AddObjectOperation.java new file mode 100644 index 0000000..03c1776 --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/AddObjectOperation.java @@ -0,0 +1,171 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class AddObjectOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(AddObjectOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "add-object"; + private String deviceID; + private String swVersion; + private String hwVersion; + + public AddObjectOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("AddObject rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("AddObject rpc requestXml={}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/addobject"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("addobject rpc response received from mapper {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + document = + builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); + document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); + document.getDocumentElement().setAttribute("xmlns", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); + } catch (Exception e) { + logger.error("while contruscting the response {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ConnectionStatus.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ConnectionStatus.java new file mode 100644 index 0000000..3af3d34 --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ConnectionStatus.java @@ -0,0 +1,172 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class ConnectionStatus implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(ConnectionStatus.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "connection-status"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public ConnectionStatus(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("ConnectionStatus rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("ConnectionStatus rpc requestXml= {}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/connectionstatus"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("ConnectionStatus rpc response received from mapper {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + document = + builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); + document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); + document.getDocumentElement().setAttribute("xmlns", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/CreateSubscription.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/CreateSubscription.java index a5ac333..70350f8 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/CreateSubscription.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/CreateSubscription.java @@ -1,238 +1,240 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlRootElement; -import org.commscope.tr069adapter.netconf.error.NetconfNotificationException; -import org.opendaylight.netconf.api.NetconfMessage; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.api.xml.XmlUtil; -import org.opendaylight.netconf.impl.NetconfServerSession; -import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation; -import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; -import com.google.common.base.Preconditions; -import com.google.common.collect.Maps; - -public class CreateSubscription extends AbstractLastNetconfOperation - implements DefaultNetconfOperation { - - private static final Logger logger = LoggerFactory.getLogger(CreateSubscription.class); - private final Map notifications; - private NetconfServerSession session; - private ScheduledExecutorService scheduledExecutorService; - private static Map netconfServerSessionMap = new HashMap<>(); - private String deviceID; - private String swVersion; - private String hwVersion; - - public CreateSubscription(final String id, final Optional notificationsFile, - String deviceID, String swVersion, String hwVersion) { - - super(id); - - logger.debug("CreateSubscription RPC is created with macID {}", deviceID); - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - - final Optional notifs; - - if (notificationsFile.isPresent()) { - notifs = Optional.of(loadNotifications(notificationsFile.get())); - scheduledExecutorService = Executors.newScheduledThreadPool(1); - } else { - notifs = Optional.empty(); - } - - if (notifs.isPresent()) { - final Collection toCopy = notifs.get().getNotificationList(); - final Map preparedMessages = - Maps.newHashMapWithExpectedSize(toCopy.size()); - for (final Notification notification : toCopy) { - final NetconfMessage parsedNotification = - parseNetconfNotification(notification.getContent()); - preparedMessages.put(notification, parsedNotification); - } - this.notifications = preparedMessages; - } else { - this.notifications = Collections.emptyMap(); - } - } - - private static Notifications loadNotifications(final File file) { - try { - final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class); - final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - return (Notifications) jaxbUnmarshaller.unmarshal(file); - } catch (final JAXBException e) { - throw new IllegalArgumentException("can not parse file " + file + " as a notifications file", - e); - } - } - - @Override - protected String getOperationName() { - return "create-subscription"; - } - - @Override - protected String getOperationNamespace() { - return "urn:ietf:params:xml:ns:netconf:notification:1.0"; - } - - @Override - protected Element handleWithNoSubsequentOperations(final Document document, - final XmlElement operationElement) { - long delayAggregator = 0; - for (final Map.Entry notification : notifications.entrySet()) { - for (int i = 0; i <= notification.getKey().getTimes(); i++) { - - delayAggregator += notification.getKey().getDelayInSeconds(); - - scheduledExecutorService.schedule(() -> { - Preconditions.checkState(session != null, - "Session is not set, cannot process notifications"); - session.sendMessage(notification.getValue()); - }, delayAggregator, TimeUnit.SECONDS); - } - } - return document.createElement(XmlNetconfConstants.OK); - } - - private static NetconfMessage parseNetconfNotification(String content) { - final int startEventTime = content.indexOf("") + "".length(); - final int endEventTime = content.indexOf(""); - final String eventTime = content.substring(startEventTime, endEventTime); - if (eventTime.equals("XXXX")) { - content = content.replace(eventTime, - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); - } - - try { - return new NetconfMessage(XmlUtil.readXmlToDocument(content)); - } catch (SAXException | IOException e) { - throw new IllegalArgumentException("Cannot parse notifications", e); - } - } - - @Override - public void setNetconfSession(final NetconfServerSession newSession) { - logger.debug("Adding netconf session to notification server sessions map : {}", newSession); - logger.debug("This CreateSubscription is setup to support macID= {}", deviceID); - this.session = newSession; - netconfServerSessionMap.put(deviceID, newSession); - } - - public static void sendNotification(NetconfMessage netconfMessage, String deviceID) - throws NetconfNotificationException { - logger.debug("Request to send notification. NetConfMessage : {}", netconfMessage); - NetconfServerSession session = netconfServerSessionMap.get(deviceID); - if (session != null && session.isUp()) { - try { - session.sendMessage(netconfMessage); - logger.debug("Successfully send notification for deviceID: {}", deviceID); - } catch (Exception e) { - logger.error("Failed to send notification. while posting got error. {}", e.toString()); - throw new NetconfNotificationException("Exception while posting the netconf message", e); - } - - } else { - logger.debug( - "Failed to send notification. None of valid netconf session is available for {}.", - deviceID); - logger.debug("Available netconf sessions : {}", netconfServerSessionMap); - throw new NetconfNotificationException("NetConf active session deosn't not exist"); - } - } - - @XmlRootElement(name = "notifications") - public static final class Notifications { - - @javax.xml.bind.annotation.XmlElement(nillable = false, name = "notification", required = true) - private List notificationList; - - public List getNotificationList() { - return notificationList; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Notifications{"); - sb.append("notificationList=").append(notificationList); - sb.append('}'); - return sb.toString(); - } - } - - public static final class Notification { - - @javax.xml.bind.annotation.XmlElement(nillable = false, name = "delay") - private long delayInSeconds; - - @javax.xml.bind.annotation.XmlElement(nillable = false, name = "times") - private long times; - - @javax.xml.bind.annotation.XmlElement(nillable = false, name = "content", required = true) - private String content; - - public long getDelayInSeconds() { - return delayInSeconds; - } - - public long getTimes() { - return times; - } - - public String getContent() { - return content; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Notification{"); - sb.append("delayInSeconds=").append(delayInSeconds); - sb.append(", times=").append(times); - sb.append(", content='").append(content).append('\''); - sb.append('}'); - return sb.toString(); - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlRootElement; +import org.commscope.tr069adapter.netconf.error.NetconfNotificationException; +import org.opendaylight.netconf.api.NetconfMessage; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.api.xml.XmlUtil; +import org.opendaylight.netconf.impl.NetconfServerSession; +import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation; +import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +public class CreateSubscription extends AbstractLastNetconfOperation + implements DefaultNetconfOperation { + + private static final Logger logger = LoggerFactory.getLogger(CreateSubscription.class); + private final Map notifications; + private NetconfServerSession session; + private ScheduledExecutorService scheduledExecutorService; + private static Map netconfServerSessionMap = new HashMap<>(); + private String deviceID; + private String swVersion; + private String hwVersion; + + public CreateSubscription(final String id, final Optional notificationsFile, + String deviceID, String swVersion, String hwVersion) { + + super(id); + + logger.debug("CreateSubscription RPC is created with macID {}", deviceID); + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + + final Optional notifs; + + if (notificationsFile.isPresent()) { + notifs = Optional.of(loadNotifications(notificationsFile.get())); + scheduledExecutorService = Executors.newScheduledThreadPool(1); + } else { + notifs = Optional.empty(); + } + + if (notifs.isPresent()) { + final Collection toCopy = notifs.get().getNotificationList(); + final Map preparedMessages = + Maps.newHashMapWithExpectedSize(toCopy.size()); + for (final Notification notification : toCopy) { + final NetconfMessage parsedNotification = + parseNetconfNotification(notification.getContent()); + preparedMessages.put(notification, parsedNotification); + } + this.notifications = preparedMessages; + } else { + this.notifications = Collections.emptyMap(); + } + } + + private static Notifications loadNotifications(final File file) { + try { + final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class); + final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + return (Notifications) jaxbUnmarshaller.unmarshal(file); + } catch (final JAXBException e) { + throw new IllegalArgumentException("can not parse file " + file + " as a notifications file", + e); + } + } + + @Override + protected String getOperationName() { + return "create-subscription"; + } + + @Override + protected String getOperationNamespace() { + return "urn:ietf:params:xml:ns:netconf:notification:1.0"; + } + + @Override + protected Element handleWithNoSubsequentOperations(final Document document, + final XmlElement operationElement) { + long delayAggregator = 0; + for (final Map.Entry notification : notifications.entrySet()) { + for (int i = 0; i <= notification.getKey().getTimes(); i++) { + + delayAggregator += notification.getKey().getDelayInSeconds(); + + scheduledExecutorService.schedule(() -> { + Preconditions.checkState(session != null, + "Session is not set, cannot process notifications"); + session.sendMessage(notification.getValue()); + }, delayAggregator, TimeUnit.SECONDS); + } + } + return document.createElement(XmlNetconfConstants.OK); + } + + private static NetconfMessage parseNetconfNotification(String content) { + final int startEventTime = content.indexOf("") + "".length(); + final int endEventTime = content.indexOf(""); + final String eventTime = content.substring(startEventTime, endEventTime); + if (eventTime.equals("XXXX")) { + content = content.replace(eventTime, + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); + } + + try { + return new NetconfMessage(XmlUtil.readXmlToDocument(content)); + } catch (SAXException | IOException e) { + throw new IllegalArgumentException("Cannot parse notifications", e); + } + } + + @Override + public void setNetconfSession(final NetconfServerSession newSession) { + logger.debug("Adding netconf session to notification server sessions map : {}", newSession); + logger.debug("This CreateSubscription is setup to support macID= {}", deviceID); + this.session = newSession; + netconfServerSessionMap.put(deviceID, newSession); + } + + public static void sendNotification(NetconfMessage netconfMessage, String deviceID) + throws NetconfNotificationException { + logger.debug("Request to send notification. NetConfMessage : {}", netconfMessage); + NetconfServerSession session = netconfServerSessionMap.get(deviceID); + if (session != null && session.isUp()) { + try { + session.sendMessage(netconfMessage); + logger.debug("Successfully send notification for deviceID: {}", deviceID); + } catch (Exception e) { + logger.error("Failed to send notification. while posting got error. {}", e.toString()); + throw new NetconfNotificationException("Exception while posting the netconf message", e); + } + + } else { + logger.debug( + "Failed to send notification. None of valid netconf session is available for {}.", + deviceID); + logger.debug("Available netconf sessions : {}", netconfServerSessionMap); + throw new NetconfNotificationException("NetConf active session deosn't not exist"); + } + } + + @XmlRootElement(name = "notifications") + public static final class Notifications { + + @javax.xml.bind.annotation.XmlElement(nillable = false, name = "notification", required = true) + private List notificationList; + + public List getNotificationList() { + return notificationList; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Notifications{"); + sb.append("notificationList=").append(notificationList); + sb.append('}'); + return sb.toString(); + } + } + + public static final class Notification { + + @javax.xml.bind.annotation.XmlElement(nillable = false, name = "delay") + private long delayInSeconds; + + @javax.xml.bind.annotation.XmlElement(nillable = false, name = "times") + private long times; + + @javax.xml.bind.annotation.XmlElement(nillable = false, name = "content", required = true) + private String content; + + public long getDelayInSeconds() { + return delayInSeconds; + } + + public long getTimes() { + return times; + } + + public String getContent() { + return content; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Notification{"); + sb.append("delayInSeconds=").append(delayInSeconds); + sb.append(", times=").append(times); + sb.append(", content='").append(content).append('\''); + sb.append('}'); + return sb.toString(); + } + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteConfigOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteConfigOperation.java index 1230144..ff64e96 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteConfigOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteConfigOperation.java @@ -1,119 +1,119 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; -import org.opendaylight.netconf.api.DocumentedException.ErrorTag; -import org.opendaylight.netconf.api.DocumentedException.ErrorType; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.test.tool.rpc.DataList; -import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class DeleteConfigOperation extends AbstractLastNetconfOperation { - - private static final Logger logger = LoggerFactory.getLogger(DeleteConfigOperation.class); - - private static final String DELETE_EDIT_CONFIG = "delete"; - private static final String OPERATION = "operation"; - private static final String REMOVE_EDIT_CONFIG = "remove"; - private final DataList storage; - private String deviceID; - private String swVersion; - private String hwVersion; - - public DeleteConfigOperation(final String netconfSessionIdForReporting, final DataList storage, - String deviceID, String swVersion, String hwVersion) { - super(netconfSessionIdForReporting); - this.storage = storage; - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - protected Element handleWithNoSubsequentOperations(final Document document, - final XmlElement operationElement) throws DocumentedException { - final XmlElement configElementData = - operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY); - containsDelete(configElementData); - if (containsDelete(configElementData)) { - storage.resetConfigList(); - } else { - storage.setConfigList(configElementData.getChildElements()); - } - - String requestXml = XmlUtility.convertDocumentToString(operationElement); - logger.debug("netconf request recevied : {}", requestXml); - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/delConfig"; - NetConfResponse restResponse = - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - - if (restResponse != null) { - ErrorCodeDetails errorCode = restResponse.getErrorCode(); - - if (errorCode != null && errorCode.getFaultCode() != null - && !errorCode.getFaultCode().equalsIgnoreCase("0")) { - throw new DocumentedException(errorCode.getErrorMessage(), - ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), - ErrorSeverity.from(errorCode.getErrorSeverity())); - } else { - return document.createElement(XmlNetconfConstants.OK); - } - } else { - logger.error("received the null response from mapper "); - throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), - ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); - } - - } - - @Override - protected String getOperationName() { - return "delete-config"; - } - - private boolean containsDelete(final XmlElement element) { - for (final Attr o : element.getAttributes().values()) { - if (o.getLocalName().equals(OPERATION) - && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) { - return true; - } - } - for (final XmlElement xmlElement : element.getChildElements()) { - if (containsDelete(xmlElement)) { - return true; - } - } - return false; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.test.tool.rpc.DataList; +import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class DeleteConfigOperation extends AbstractLastNetconfOperation { + + private static final Logger logger = LoggerFactory.getLogger(DeleteConfigOperation.class); + + private static final String DELETE_EDIT_CONFIG = "delete"; + private static final String OPERATION = "operation"; + private static final String REMOVE_EDIT_CONFIG = "remove"; + private final DataList storage; + private String deviceID; + private String swVersion; + private String hwVersion; + + public DeleteConfigOperation(final String netconfSessionIdForReporting, final DataList storage, + String deviceID, String swVersion, String hwVersion) { + super(netconfSessionIdForReporting); + this.storage = storage; + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + protected Element handleWithNoSubsequentOperations(final Document document, + final XmlElement operationElement) throws DocumentedException { + final XmlElement configElementData = + operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY); + containsDelete(configElementData); + if (containsDelete(configElementData)) { + storage.resetConfigList(); + } else { + storage.setConfigList(configElementData.getChildElements()); + } + + String requestXml = XmlUtility.convertDocumentToString(operationElement); + logger.debug("netconf request recevied : {}", requestXml); + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/delConfig"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + + if (restResponse != null) { + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else { + return document.createElement(XmlNetconfConstants.OK); + } + } else { + logger.error("received the null response from mapper "); + throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + + } + + @Override + protected String getOperationName() { + return "delete-config"; + } + + private boolean containsDelete(final XmlElement element) { + for (final Attr o : element.getAttributes().values()) { + if (o.getLocalName().equals(OPERATION) + && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) { + return true; + } + } + for (final XmlElement xmlElement : element.getChildElements()) { + if (containsDelete(xmlElement)) { + return true; + } + } + return false; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteObjectOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteObjectOperation.java new file mode 100644 index 0000000..475dbc6 --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DeleteObjectOperation.java @@ -0,0 +1,172 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class DeleteObjectOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(DeleteObjectOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "delete-object"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public DeleteObjectOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("DeleteObject rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("DeleteObject rpc requestXml={}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/deleteobject"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("deleteobject rpc response received from mapper {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + document = + builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); + document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); + document.getDocumentElement().setAttribute("xmlns", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); + } catch (Exception e) { + logger.error("while contruscting the response {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DownloadOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DownloadOperation.java new file mode 100644 index 0000000..434fe7f --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/DownloadOperation.java @@ -0,0 +1,182 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +public class DownloadOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(DownloadOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "download"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public DownloadOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("download rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + final Element element = + requestMessage.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, + XmlNetconfConstants.RPC_REPLY_KEY); + element.setAttribute("xmlns:ns1", getOperationNamespace()); + element.setAttribute("message-id", msgId); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("download rpc requestXml= {}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/download"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("download rpc response received from mapper: {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + Node child = requestMessage.createElement(XmlNetconfConstants.OK); + element.appendChild(child); + String xmlStr = XmlUtility.convertDocumentToString(element); + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GPAObjectOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GPAObjectOperation.java new file mode 100644 index 0000000..3c0040c --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GPAObjectOperation.java @@ -0,0 +1,169 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class GPAObjectOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(GPAObjectOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "get-parameter-attributes"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public GPAObjectOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("gpaObject rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("gpaObject rpc requestXml= {}", requestXml); + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/gpaobject"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("gpaobject rpc response received from mapper {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + document = + builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); + document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); + document.getDocumentElement().setAttribute("xmlns", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetConfigOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetConfigOperation.java index 4fd08e0..d7c4e98 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetConfigOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetConfigOperation.java @@ -1,109 +1,109 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import java.io.File; -import java.io.IOException; -import java.util.Optional; - -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; -import org.opendaylight.netconf.api.DocumentedException.ErrorTag; -import org.opendaylight.netconf.api.DocumentedException.ErrorType; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.api.xml.XmlUtil; -import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -public class GetConfigOperation extends AbstractLastNetconfOperation { - private static final Logger logger = LoggerFactory.getLogger(GetConfigOperation.class); - - private String deviceID; - private String swVersion; - private String hwVersion; - - public GetConfigOperation(final String netconfSessionIdForReporting, - final Optional initialConfigXMLFile, String deviceID, String swVersion, - String hwVersion) { - super(netconfSessionIdForReporting); - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - if (initialConfigXMLFile.isPresent()) { - logger.info("File is present: {}", initialConfigXMLFile.get().getName()); - } - } - - @Override - protected Element handleWithNoSubsequentOperations(final Document document, - final XmlElement operationElement) throws DocumentedException { - final Element element = document.createElement(XmlNetconfConstants.DATA_KEY); - - String requestXml = XmlUtility.convertDocumentToString(operationElement); - logger.debug("netconf request recevied : {}", requestXml); - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/getConfig"; - NetConfResponse restResponse = - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - - if (restResponse != null) { - ErrorCodeDetails errorCode = restResponse.getErrorCode(); - if (errorCode != null && errorCode.getFaultCode() != null - && !errorCode.getFaultCode().equalsIgnoreCase("0")) { - logger.error("Error received : {} ", errorCode); - throw new DocumentedException(errorCode.getErrorMessage(), - ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), - ErrorSeverity.from(errorCode.getErrorSeverity())); - } else if (restResponse.getNetconfResponseXml() != null) { - Element element1 = null; - try { - logger.debug("Response received from mapper :{}", restResponse.getNetconfResponseXml()); - element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml()); - XmlElement xmlElement = XmlElement.fromDomElement(element1); - Element domElement = xmlElement.getDomElement(); - element.appendChild(element.getOwnerDocument().importNode(domElement, true)); - } catch (SAXException | IOException e1) { - logger.error("Error while constructing the reponse {}", e1.toString()); - } - } - } else { - logger.error("received the null response from mapper "); - throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), - ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); - } - - return element; - } - - @Override - protected String getOperationName() { - return XmlNetconfConstants.GET_CONFIG; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.File; +import java.io.IOException; +import java.util.Optional; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.api.xml.XmlUtil; +import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +public class GetConfigOperation extends AbstractLastNetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(GetConfigOperation.class); + + private String deviceID; + private String swVersion; + private String hwVersion; + + public GetConfigOperation(final String netconfSessionIdForReporting, + final Optional initialConfigXMLFile, String deviceID, String swVersion, + String hwVersion) { + super(netconfSessionIdForReporting); + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + if (initialConfigXMLFile.isPresent()) { + logger.info("File is present: {}", initialConfigXMLFile.get().getName()); + } + } + + @Override + protected Element handleWithNoSubsequentOperations(final Document document, + final XmlElement operationElement) throws DocumentedException { + final Element element = document.createElement(XmlNetconfConstants.DATA_KEY); + + String requestXml = XmlUtility.convertDocumentToString(operationElement); + logger.debug("netconf request recevied : {}", requestXml); + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/getConfig"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + + if (restResponse != null) { + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error received : {} ", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + Element element1 = null; + try { + logger.debug("Response received from mapper :{}", restResponse.getNetconfResponseXml()); + element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml()); + XmlElement xmlElement = XmlElement.fromDomElement(element1); + Element domElement = xmlElement.getDomElement(); + element.appendChild(element.getOwnerDocument().importNode(domElement, true)); + } catch (SAXException | IOException e1) { + logger.error("Error while constructing the reponse {}", e1.toString()); + } + } + } else { + logger.error("received the null response from mapper "); + throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + + return element; + } + + @Override + protected String getOperationName() { + return XmlNetconfConstants.GET_CONFIG; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetOperation.java index 47cc0ea..f522062 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/GetOperation.java @@ -1,108 +1,108 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import java.io.IOException; - -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; -import org.opendaylight.netconf.api.DocumentedException.ErrorTag; -import org.opendaylight.netconf.api.DocumentedException.ErrorType; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.api.xml.XmlUtil; -import org.opendaylight.netconf.test.tool.rpc.DataList; -import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -public class GetOperation extends AbstractLastNetconfOperation { - private static final Logger logger = LoggerFactory.getLogger(GetOperation.class); - - private final DataList storage; - private String deviceID; - private String swVersion; - private String hwVersion; - - public GetOperation(final String netconfSessionIdForReporting, final DataList storage, - String deviceID, String swVersion, String hwVersion) { - super(netconfSessionIdForReporting); - this.deviceID = deviceID; - this.storage = storage; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - protected Element handleWithNoSubsequentOperations(final Document document, - final XmlElement operationElement) throws DocumentedException { - final Element element = document.createElement(XmlNetconfConstants.DATA_KEY); - - for (final XmlElement e : storage.getConfigList()) { - final Element domElement = e.getDomElement(); - element.appendChild(element.getOwnerDocument().importNode(domElement, true)); - } - - String requestXml = XmlUtility.convertDocumentToString(operationElement); - logger.debug("netconf request recevied : {}", requestXml); - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/get"; - NetConfResponse restResponse = - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - - if (restResponse != null) { - ErrorCodeDetails errorCode = restResponse.getErrorCode(); - if (errorCode != null && errorCode.getFaultCode() != null - && !errorCode.getFaultCode().equalsIgnoreCase("0")) { - throw new DocumentedException(errorCode.getErrorMessage(), - ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), - ErrorSeverity.from(errorCode.getErrorSeverity())); - } else if (restResponse.getNetconfResponseXml() != null) { - Element element1 = null; - try { - element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml()); - XmlElement xmlElement = XmlElement.fromDomElement(element1); - Element domElement = xmlElement.getDomElement(); - element.appendChild(element.getOwnerDocument().importNode(domElement, true)); - } catch (SAXException | IOException e1) { - logger.error("Error while constructing the reponse {}", e1.toString()); - } - } - } else { - logger.error("received the null response from mapper "); - throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), - ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); - } - return element; - } - - @Override - protected String getOperationName() { - return XmlNetconfConstants.GET; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.IOException; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.api.xml.XmlUtil; +import org.opendaylight.netconf.test.tool.rpc.DataList; +import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +public class GetOperation extends AbstractLastNetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(GetOperation.class); + + private final DataList storage; + private String deviceID; + private String swVersion; + private String hwVersion; + + public GetOperation(final String netconfSessionIdForReporting, final DataList storage, + String deviceID, String swVersion, String hwVersion) { + super(netconfSessionIdForReporting); + this.deviceID = deviceID; + this.storage = storage; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + protected Element handleWithNoSubsequentOperations(final Document document, + final XmlElement operationElement) throws DocumentedException { + final Element element = document.createElement(XmlNetconfConstants.DATA_KEY); + + for (final XmlElement e : storage.getConfigList()) { + final Element domElement = e.getDomElement(); + element.appendChild(element.getOwnerDocument().importNode(domElement, true)); + } + + String requestXml = XmlUtility.convertDocumentToString(operationElement); + logger.debug("netconf request recevied : {}", requestXml); + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/get"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + + if (restResponse != null) { + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + Element element1 = null; + try { + element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml()); + XmlElement xmlElement = XmlElement.fromDomElement(element1); + Element domElement = xmlElement.getDomElement(); + element.appendChild(element.getOwnerDocument().importNode(domElement, true)); + } catch (SAXException | IOException e1) { + logger.error("Error while constructing the reponse {}", e1.toString()); + } + } + } else { + logger.error("received the null response from mapper "); + throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + return element; + } + + @Override + protected String getOperationName() { + return XmlNetconfConstants.GET; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/RebootOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/RebootOperation.java new file mode 100644 index 0000000..d5e8066 --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/RebootOperation.java @@ -0,0 +1,180 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +public class RebootOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(RebootOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "reboot"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public RebootOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("Reboot rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + final Element element = + requestMessage.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, + XmlNetconfConstants.RPC_REPLY_KEY); + element.setAttribute("xmlns:ns1", getOperationNamespace()); + element.setAttribute("message-id", msgId); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("reboot rpc requestXml= {}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/reboot"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document respDoc = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + Node child = requestMessage.createElement(XmlNetconfConstants.OK); + element.appendChild(child); + String xmlStr = XmlUtility.convertDocumentToString(element); + try { + builder = factory.newDocumentBuilder(); + respDoc = builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return respDoc; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ResetOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ResetOperation.java new file mode 100644 index 0000000..05e30c5 --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/ResetOperation.java @@ -0,0 +1,179 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +public class ResetOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(ResetOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "reset"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public ResetOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("Reset rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + final Element element = + requestMessage.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, + XmlNetconfConstants.RPC_REPLY_KEY); + element.setAttribute("xmlns:ns1", getOperationNamespace()); + element.setAttribute("message-id", msgId); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("reset rpc requestXml= {}", requestXml); + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/reset"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document respDoc = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + Node child = requestMessage.createElement(XmlNetconfConstants.OK); + element.appendChild(child); + String xmlStr = XmlUtility.convertDocumentToString(element); + try { + builder = factory.newDocumentBuilder(); + respDoc = builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return respDoc; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SPAObjectOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SPAObjectOperation.java new file mode 100644 index 0000000..c614d7f --- /dev/null +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SPAObjectOperation.java @@ -0,0 +1,182 @@ +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +public class SPAObjectOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(SPAObjectOperation.class); + public static final String OP_NAMESPACE = "urn:tr069rpc:1.0"; + public static final String OP_NAME = "set-parameter-attributes"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public SPAObjectOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + logger.debug("spaObject rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + final Element element = + requestMessage.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, + XmlNetconfConstants.RPC_REPLY_KEY); + element.setAttribute("xmlns:ns1", getOperationNamespace()); + element.setAttribute("message-id", msgId); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("spaObject rpc requestXml= {}", requestXml); + + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/spaobject"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("spaobject rpc response received from mapper: {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + Node child = requestMessage.createElement(XmlNetconfConstants.OK); + element.appendChild(child); + String xmlStr = XmlUtility.convertDocumentToString(element); + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(xmlStr))); + } catch (Exception e) { + logger.error("Error while converting String to element: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } catch (Exception e) { + logger.error("Error while contruscting the response: {}", e.getMessage()); + throw new DocumentedException("Operation Aborted", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(getOperationName()) + && operationNamespace.equals(getOperationNamespace()) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return OP_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SetConfigOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SetConfigOperation.java index b011420..dfc7a66 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SetConfigOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SetConfigOperation.java @@ -1,120 +1,120 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; -import org.opendaylight.netconf.api.DocumentedException.ErrorTag; -import org.opendaylight.netconf.api.DocumentedException.ErrorType; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class SetConfigOperation extends AbstractLastNetconfOperation { - private static final Logger logger = LoggerFactory.getLogger(SetConfigOperation.class); - - private static final String DELETE_EDIT_CONFIG = "delete"; - private static final String OPERATION = "operation"; - private static final String REMOVE_EDIT_CONFIG = "remove"; - private String deviceID; - private String swVersion; - private String hwVersion; - - public SetConfigOperation(final String netconfSessionIdForReporting, String deviceID, - String swVersion, String hwVersion) { - super(netconfSessionIdForReporting); - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - protected Element handleWithNoSubsequentOperations(final Document document, - final XmlElement operationElement) throws DocumentedException { - final XmlElement configElementData = - operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY); - String delOrEditUrl = "setConfig"; - if (containsDelete(configElementData)) { - delOrEditUrl = "delConfig"; - } - - String requestXml = XmlUtility.convertDocumentToString(operationElement); - logger.debug("netconf request recevied : {}", requestXml); - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/" + delOrEditUrl; - NetConfResponse restResponse = - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - - if (restResponse != null) { - ErrorCodeDetails errorCode = restResponse.getErrorCode(); - if (errorCode != null) { - if (errorCode.getFaultCode() != null && errorCode.getFaultCode().equalsIgnoreCase("0")) { - return document.createElement(XmlNetconfConstants.OK); - } else { - logger.error("Error received : {}", errorCode); - throw new DocumentedException(errorCode.getErrorMessage(), - ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), - ErrorSeverity.from(errorCode.getErrorSeverity())); - } - } else { - return document.createElement(XmlNetconfConstants.OK); - } - } else { - logger.error("received the null response from mapper "); - throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), - ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); - } - - } - - @Override - protected String getOperationName() { - return "edit-config"; - } - - private boolean containsDelete(final XmlElement element) { - for (final Attr o : element.getAttributes().values()) { - if (o.getLocalName().equals(OPERATION) - && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) { - return true; - } - - } - - for (final XmlElement xmlElement : element.getChildElements()) { - if (containsDelete(xmlElement)) { - return true; - } - - } - - return false; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class SetConfigOperation extends AbstractLastNetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(SetConfigOperation.class); + + private static final String DELETE_EDIT_CONFIG = "delete"; + private static final String OPERATION = "operation"; + private static final String REMOVE_EDIT_CONFIG = "remove"; + private String deviceID; + private String swVersion; + private String hwVersion; + + public SetConfigOperation(final String netconfSessionIdForReporting, String deviceID, + String swVersion, String hwVersion) { + super(netconfSessionIdForReporting); + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + protected Element handleWithNoSubsequentOperations(final Document document, + final XmlElement operationElement) throws DocumentedException { + final XmlElement configElementData = + operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY); + String delOrEditUrl = "setConfig"; + if (containsDelete(configElementData)) { + delOrEditUrl = "delConfig"; + } + + String requestXml = XmlUtility.convertDocumentToString(operationElement); + logger.debug("netconf request recevied : {}", requestXml); + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/" + delOrEditUrl; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + + if (restResponse != null) { + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null) { + if (errorCode.getFaultCode() != null && errorCode.getFaultCode().equalsIgnoreCase("0")) { + return document.createElement(XmlNetconfConstants.OK); + } else { + logger.error("Error received : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } + } else { + return document.createElement(XmlNetconfConstants.OK); + } + } else { + logger.error("received the null response from mapper "); + throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"), + ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR")); + } + + } + + @Override + protected String getOperationName() { + return "edit-config"; + } + + private boolean containsDelete(final XmlElement element) { + for (final Attr o : element.getAttributes().values()) { + if (o.getLocalName().equals(OPERATION) + && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) { + return true; + } + + } + + for (final XmlElement xmlElement : element.getChildElements()) { + if (containsDelete(xmlElement)) { + return true; + } + + } + + return false; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareActivateOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareActivateOperation.java index 6439498..a78e5fa 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareActivateOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareActivateOperation.java @@ -1,112 +1,112 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.mapping.api.HandlingPriority; -import org.opendaylight.netconf.mapping.api.NetconfOperation; -import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -public class SoftwareActivateOperation implements NetconfOperation { - private static final Logger logger = LoggerFactory.getLogger(SoftwareActivateOperation.class); - public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0"; - - private String deviceID; - private String swVersion; - private String hwVersion; - - public SoftwareActivateOperation(String deviceID, String swVersion, String hwVersion) { - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - public HandlingPriority canHandle(final Document message) throws DocumentedException { - OperationNameAndNamespace operationNameAndNamespace = null; - operationNameAndNamespace = new OperationNameAndNamespace(message); - return canHandle(operationNameAndNamespace.getOperationName(), - operationNameAndNamespace.getNamespace()); - } - - @Override - public Document handle(Document requestMessage, - NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { - - logger.debug("sw-activate rpc recevied in netconf server"); - final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); - - String requestXml = XmlUtility.convertDocumentToString(requestElement); - logger.debug("sw-activate rpc recevied requestXml = {}", requestXml); - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/softwareActivate"; - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - return null; - } - - protected HandlingPriority canHandle(final String operationName, - final String operationNamespace) { - return operationName.equals("software-activate") - && operationNamespace.equals(SOFT_MGMT_NAMESPACE) - ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) - : HandlingPriority.CANNOT_HANDLE; - } - - public static final class OperationNameAndNamespace { - private final String operationName; - private final String namespace; - - private final XmlElement operationElement; - - public OperationNameAndNamespace(final Document message) throws DocumentedException { - XmlElement requestElement = null; - requestElement = getRequestElementWithCheck(message); - operationElement = requestElement.getOnlyChildElement(); - operationName = operationElement.getName(); - namespace = operationElement.getNamespace(); - } - - public String getOperationName() { - return operationName; - } - - public String getNamespace() { - return namespace; - } - - public XmlElement getOperationElement() { - return operationElement; - } - } - - protected static XmlElement getRequestElementWithCheck(final Document message) - throws DocumentedException { - return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), - XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +public class SoftwareActivateOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(SoftwareActivateOperation.class); + public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public SoftwareActivateOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + + logger.debug("sw-activate rpc recevied in netconf server"); + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("sw-activate rpc recevied requestXml = {}", requestXml); + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/softwareActivate"; + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + return null; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals("software-activate") + && operationNamespace.equals(SOFT_MGMT_NAMESPACE) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareDownloadOperation.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareDownloadOperation.java index f5b1454..a480ea4 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareDownloadOperation.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/SoftwareDownloadOperation.java @@ -1,164 +1,167 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.opendaylight.netconf.api.DocumentedException; -import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; -import org.opendaylight.netconf.api.DocumentedException.ErrorTag; -import org.opendaylight.netconf.api.DocumentedException.ErrorType; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.opendaylight.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.netconf.mapping.api.HandlingPriority; -import org.opendaylight.netconf.mapping.api.NetconfOperation; -import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; - -public class SoftwareDownloadOperation implements NetconfOperation { - private static final Logger logger = LoggerFactory.getLogger(SoftwareDownloadOperation.class); - public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0"; - - private String deviceID; - private String swVersion; - private String hwVersion; - - public SoftwareDownloadOperation(String deviceID, String swVersion, String hwVersion) { - this.deviceID = deviceID; - this.swVersion = swVersion; - this.hwVersion = hwVersion; - } - - @Override - public HandlingPriority canHandle(final Document message) throws DocumentedException { - OperationNameAndNamespace operationNameAndNamespace = null; - operationNameAndNamespace = new OperationNameAndNamespace(message); - return canHandle(operationNameAndNamespace.getOperationName(), - operationNameAndNamespace.getNamespace()); - } - - @Override - public Document handle(Document requestMessage, - NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { - - logger.debug("soft-ware download rpc is received in netconfserver"); - - final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); - final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); - - String requestXml = XmlUtility.convertDocumentToString(requestElement); - logger.debug("soft-ware download rpc requestXml=" + requestXml); - - NetConfServerProperties config = - NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); - - final String baseUrl = config.getMapperPath() + "/softwareDowload"; - NetConfResponse restResponse = - XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); - - Document document = null; - - ErrorCodeDetails errorCode = restResponse.getErrorCode(); - if (errorCode != null && errorCode.getFaultCode() != null - && !errorCode.getFaultCode().equalsIgnoreCase("0")) { - logger.error("Error recevied : " + errorCode); - throw new DocumentedException(errorCode.getErrorMessage(), - ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), - ErrorSeverity.from(errorCode.getErrorSeverity())); - } else if (restResponse != null && restResponse.getNetconfResponseXml() != null) { - logger.debug("soft-ware download rpc response received from mapper " - + restResponse.getNetconfResponseXml()); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - try { - builder = factory.newDocumentBuilder(); - document = - builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); - document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); - document.getDocumentElement().setAttribute("xmlns", - XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); - document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); - } catch (Exception e) { - logger.error("while contruscting the response; ", e.toString()); - } - } - - return document; - } - - protected HandlingPriority canHandle(final String operationName, - final String operationNamespace) { - return operationName.equals("software-download") - && operationNamespace.equals(SOFT_MGMT_NAMESPACE) - ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) - : HandlingPriority.CANNOT_HANDLE; - } - - public static final class OperationNameAndNamespace { - private final String operationName; - private final String namespace; - - private final XmlElement operationElement; - - public OperationNameAndNamespace(final Document message) throws DocumentedException { - XmlElement requestElement = null; - requestElement = getRequestElementWithCheck(message); - operationElement = requestElement.getOnlyChildElement(); - operationName = operationElement.getName(); - namespace = operationElement.getNamespace(); - } - - public String getOperationName() { - return operationName; - } - - public String getNamespace() { - return namespace; - } - - public XmlElement getOperationElement() { - return operationElement; - } - - } - - protected static XmlElement getRequestElementWithCheck(final Document message) - throws DocumentedException { - return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), - XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); - } - - protected String getOperationNamespace() { - return "urn:o-ran:software-management:1.0"; - } - - protected String getOperationName() { - return "software-download"; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.opendaylight.netconf.api.DocumentedException; +import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity; +import org.opendaylight.netconf.api.DocumentedException.ErrorTag; +import org.opendaylight.netconf.api.DocumentedException.ErrorType; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.opendaylight.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.netconf.mapping.api.HandlingPriority; +import org.opendaylight.netconf.mapping.api.NetconfOperation; +import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class SoftwareDownloadOperation implements NetconfOperation { + private static final Logger logger = LoggerFactory.getLogger(SoftwareDownloadOperation.class); + public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0"; + public static final String OP_NAME = "software-download"; + + private String deviceID; + private String swVersion; + private String hwVersion; + + public SoftwareDownloadOperation(String deviceID, String swVersion, String hwVersion) { + this.deviceID = deviceID; + this.swVersion = swVersion; + this.hwVersion = hwVersion; + } + + @Override + public HandlingPriority canHandle(final Document message) throws DocumentedException { + OperationNameAndNamespace operationNameAndNamespace = null; + operationNameAndNamespace = new OperationNameAndNamespace(message); + return canHandle(operationNameAndNamespace.getOperationName(), + operationNameAndNamespace.getNamespace()); + } + + @Override + public Document handle(Document requestMessage, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { + + logger.debug("soft-ware download rpc is received in netconfserver"); + + final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage); + final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID); + + String requestXml = XmlUtility.convertDocumentToString(requestElement); + logger.debug("soft-ware download rpc requestXml= {}", requestXml); + + NetConfServerProperties config = + NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class); + + final String baseUrl = config.getMapperPath() + "/softwareDowload"; + NetConfResponse restResponse = + XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion); + + Document document = null; + + ErrorCodeDetails errorCode = restResponse.getErrorCode(); + if (errorCode != null && errorCode.getFaultCode() != null + && !errorCode.getFaultCode().equalsIgnoreCase("0")) { + logger.error("Error recevied : {}", errorCode); + throw new DocumentedException(errorCode.getErrorMessage(), + ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()), + ErrorSeverity.from(errorCode.getErrorSeverity())); + } else if (restResponse.getNetconfResponseXml() != null) { + logger.debug("soft-ware download rpc response received from mapper {}", + restResponse.getNetconfResponseXml()); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + document = + builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml()))); + document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace()); + document.getDocumentElement().setAttribute("xmlns", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId); + } catch (Exception e) { + logger.error("while contruscting the response; {} ", e.toString()); + } + } + + return document; + } + + protected HandlingPriority canHandle(final String operationName, + final String operationNamespace) { + return operationName.equals(OP_NAME) && operationNamespace.equals(SOFT_MGMT_NAMESPACE) + ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100) + : HandlingPriority.CANNOT_HANDLE; + } + + public static final class OperationNameAndNamespace { + private final String operationName; + private final String namespace; + + private final XmlElement operationElement; + + public OperationNameAndNamespace(final Document message) throws DocumentedException { + XmlElement requestElement = null; + requestElement = getRequestElementWithCheck(message); + operationElement = requestElement.getOnlyChildElement(); + operationName = operationElement.getName(); + namespace = operationElement.getNamespace(); + } + + public String getOperationName() { + return operationName; + } + + public String getNamespace() { + return namespace; + } + + public XmlElement getOperationElement() { + return operationElement; + } + + } + + protected static XmlElement getRequestElementWithCheck(final Document message) + throws DocumentedException { + return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), + XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + } + + protected String getOperationNamespace() { + return SOFT_MGMT_NAMESPACE; + } + + protected String getOperationName() { + return OP_NAME; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/XmlUtility.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/XmlUtility.java index 4ca1ce6..e6c65e2 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/XmlUtility.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/rpc/XmlUtility.java @@ -1,112 +1,112 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import java.io.StringReader; -import java.io.StringWriter; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.commscope.tr069adapter.mapper.model.NetConfRequest; -import org.commscope.tr069adapter.mapper.model.NetConfResponse; -import org.opendaylight.netconf.api.xml.XmlElement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.web.client.RestTemplate; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.InputSource; - -public class XmlUtility { - private static final Logger logger = LoggerFactory.getLogger(XmlUtility.class); - - private XmlUtility() {} - - private static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class); - - public static String convertDocumentToString(XmlElement element) { - return convertDocumentToString(element.getDomElement()); - } - - public static String convertDocumentToString(Element element) { - String strxml = null; - try { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); - Transformer transformer = transformerFactory.newTransformer(); - DOMSource source = new DOMSource(element); - StreamResult result = new StreamResult(new StringWriter()); - transformer.transform(source, result); - strxml = result.getWriter().toString(); - } catch (Exception e) { - LOG.error("Error while converting Element to String {}", e.toString()); - } - - return strxml; - - } - - public static Element convertStringToDocument(String xmlStr) { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - DocumentBuilder builder; - try { - builder = factory.newDocumentBuilder(); - Document doc = builder.parse(new InputSource(new StringReader(xmlStr))); - return doc.getDocumentElement(); - } catch (Exception e) { - LOG.error("Error while converting String to element {}", e.toString()); - } - return null; - } - - public static NetConfResponse invokeMapperCall(String requestUrl, String requestXml, - String deviceID, String swVersion, String hwVersion) { - URI uri = null; - try { - uri = new URI(requestUrl); - } catch (URISyntaxException e) { - logger.error("invalid URI {}", e.toString()); - } - - RestTemplate restTemplate = new RestTemplate(); - HttpHeaders headers = new HttpHeaders(); - NetConfRequest req = new NetConfRequest(requestXml, deviceID, swVersion, hwVersion); - - HttpEntity entity = new HttpEntity<>(req, headers); - NetConfResponse restResponse = null; - if (uri != null) { - restResponse = restTemplate.postForObject(uri, entity, NetConfResponse.class); - } - - return restResponse; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.commscope.tr069adapter.mapper.model.NetConfRequest; +import org.commscope.tr069adapter.mapper.model.NetConfResponse; +import org.opendaylight.netconf.api.xml.XmlElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.web.client.RestTemplate; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +public class XmlUtility { + private static final Logger logger = LoggerFactory.getLogger(XmlUtility.class); + + private XmlUtility() {} + + private static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class); + + public static String convertDocumentToString(XmlElement element) { + return convertDocumentToString(element.getDomElement()); + } + + public static String convertDocumentToString(Element element) { + String strxml = null; + try { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(element); + StreamResult result = new StreamResult(new StringWriter()); + transformer.transform(source, result); + strxml = result.getWriter().toString(); + } catch (Exception e) { + LOG.error("Error while converting Element to String {}", e.toString()); + } + + return strxml; + + } + + public static Element convertStringToDocument(String xmlStr) { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + Document doc = builder.parse(new InputSource(new StringReader(xmlStr))); + return doc.getDocumentElement(); + } catch (Exception e) { + LOG.error("Error while converting String to element {}", e.toString()); + } + return null; + } + + public static NetConfResponse invokeMapperCall(String requestUrl, String requestXml, + String deviceID, String swVersion, String hwVersion) { + URI uri = null; + try { + uri = new URI(requestUrl); + } catch (URISyntaxException e) { + logger.error("invalid URI {}", e.toString()); + } + + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + NetConfRequest req = new NetConfRequest(requestXml, deviceID, swVersion, hwVersion); + + HttpEntity entity = new HttpEntity<>(req, headers); + NetConfResponse restResponse = null; + if (uri != null) { + restResponse = restTemplate.postForObject(uri, entity, NetConfResponse.class); + } + + return restResponse; + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetConfServerManagerImpl.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetConfServerManagerImpl.java index 852d205..b1c7460 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetConfServerManagerImpl.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetConfServerManagerImpl.java @@ -1,445 +1,445 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.server; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import org.apache.commons.io.FileUtils; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; -import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; -import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository; -import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity; -import org.commscope.tr069adapter.netconf.error.RetryFailedException; -import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException; -import org.commscope.tr069adapter.netconf.server.helper.ServerPortAllocationHelper; -import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; -import org.commscope.tr069adapter.netconf.server.ves.VESNotificationSender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -@Component -public class NetConfServerManagerImpl { - - private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerImpl.class); - - @Autowired - ServerPortAllocationHelper serverPortAllocator; - - @Autowired - NetConfServerDetailsRepository netconfDAO; - - @Autowired - NetConfServerProperties config; - - @Autowired - NetconfServerStarter ncServerStarter; - - @Autowired - RestartNetconfServerHandler restartServersHandler; - - @Autowired - VESNotificationSender vesNotificationSender; - - @Autowired - DeviceVersionManager versionManager; - - ExecutorService executorService = Executors.newFixedThreadPool(10); - - public boolean loadSchemas() { - LOG.debug("Loading yang schema started"); - List profiles = versionManager.getSupportedProfileDefinitions(); - try { - String commonSchemaPath = config.getSchemaDirPath() + "/common"; - - for (ProfileDefinition profile : profiles) { - String verSpecificSchemaPath = - config.getSchemaDirPath() + File.separator + profile.getNetConfSchemaPath(); - File schemaDir = new File(commonSchemaPath); - File schemaVerDir = new File(verSpecificSchemaPath); - - if (!schemaVerDir.isDirectory()) { - LOG.error("No folder path found for given version path {}", - schemaVerDir.getAbsolutePath()); - return false; - } - - try { - FileUtils.copyDirectory(schemaDir, schemaVerDir); - } catch (IOException e) { - LOG.error("Failed to copy directory " + e.getMessage()); - } - boolean isSchemaLoaded = ncServerStarter.loadSchemas(schemaVerDir); - if (!isSchemaLoaded) { - LOG.debug("Failed to load schema for profile {}", profile.getProfileId()); - return false; - } - } - } catch (Exception e) { - LOG.error("Load schema's failed in netconf server {}", e.getMessage()); - return false; - } - LOG.debug("Loading yang schema completed"); - return true; - } - - public void restartServers() { - LOG.debug("Restarting all netconf servers during startup..."); - Iterable entities = netconfDAO.findAll(); - - for (NetConfServerDetailsEntity entity : entities) { - boolean isReserved = serverPortAllocator.checkAndReserveServerPort(entity.getListenPort()); - if (isReserved) { - ServerStartTask task = new ServerStartTask(entity, this); - executorService.execute(task); - } else { - try { - restartServersHandler.restart(entity); - } catch (RetryFailedException e) { - LOG.error("submit task for restarting is failed {}", e.toString()); - } - } - } - LOG.debug("Restarting netconf servers during startup is completed."); - } - - public NetConfServerDetails createServer(String deviceId, String enodeBName, String swVersion, - String hwVersion) { - NetConfServerDetails result = new NetConfServerDetails(); - NetConfServerDetailsEntity entity = null; - if (deviceId != null) { - entity = netconfDAO.findByDeviceId(deviceId); - } else if (enodeBName != null) { - entity = netconfDAO.findByEnodeBName(enodeBName); - } else { - // none is specified - LOG.error( - "Both deviceID and enodeBName are null. Hence failed to create the netconf server."); - return null; - } - - if (null != entity && ncServerStarter.isNetConfServerRunning(deviceId)) { - if (isVersionChanged(entity, swVersion, hwVersion)) { - return restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion); - } - - // found the entity. server is already running. double check and run - // if - // required. else return the details. - - // update the ENB Name if Changed - entity.setEnodeBName(enodeBName); - netconfDAO.save(entity); - result = getNetConfServerDetails(deviceId, entity); - return result; - } - - try { - - String port = serverPortAllocator.reserveServerPort(); - if (port == null) { - result.setError(NetconfServerManagementError.PORT_NOT_AVAILBLE); - LOG.error( - "All ports are exhausted. Hence cannot allocate a port to start new netconf server"); - return result; - } else { - LOG.debug("Successfully reserved a port for deviceID={} ,port={}", deviceId, port); - - // start the server - boolean isServerStarted = ncServerStarter.startServer(port, deviceId, swVersion, hwVersion); - boolean isPortInUse = serverPortAllocator.isServerPortInUse(port); - - if (!isServerStarted || !isPortInUse) { - LOG.error( - "Failed to start netconf server for deviceID: {}, at port:{} , isServerStarted={} ,isPortInUse={}", - deviceId, port, isServerStarted, isPortInUse); - result.setError(NetconfServerManagementError.PORT_IN_USE); - return result; - } - } - - // save the record in db - entity = new NetConfServerDetailsEntity(); - entity.setDeviceId(deviceId); - entity.setListenPort(port); - entity.setEnodeBName(enodeBName); - entity.setSwVersion(swVersion); - entity.setHwVersion(hwVersion); - netconfDAO.save(entity); - - result = getNetConfServerDetails(deviceId, entity); - LOG.debug("Successfully started netconf server for deviceID= {}, port={}", deviceId, port); - - } catch (ServerPortAllocationException e) { - LOG.error("Failed to allocate a port {}", e.toString()); - } - - if (entity != null) { - result.setDeviceId(deviceId); - result.setListenPort(entity.getListenPort()); - String netconfListenAddress = getServiceHost(); - if (netconfListenAddress == null) { - netconfListenAddress = config.getNetconfServerIP(); - } - result.setListenAddress(netconfListenAddress); - result.setError(NetconfServerManagementError.SUCCESS); - } - return result; - } - - public NetConfServerDetails restartOnVersionChange(String deviceId, String enodeBName, - String swVersion, String hwVersion) { - - NetConfServerDetailsEntity entity = null; - if (deviceId != null) { - entity = netconfDAO.findByDeviceId(deviceId); - } - if (entity == null) { - return null; - } - - boolean isVersionChanged = isVersionChanged(entity, swVersion, hwVersion); - if (isVersionChanged) { - LOG.debug("software version changed, stopping the the existing netconf instance"); - boolean result = this.ncServerStarter.stopServer(deviceId); - if (result) { - LOG.debug( - "successfully stopped the netconf instance; trying to start with new version yang models"); - entity.setSwVersion(swVersion); - entity.setHwVersion(hwVersion); - netconfDAO.save(entity); - - boolean isSuccess = startNetConfServerInstance(entity); - - if (!isSuccess) { - try { - restartServersHandler.restart(entity); - } catch (RetryFailedException e) { - LOG.debug(""); - } - } - } - } - return getNetConfServerDetails(deviceId, entity); - } - - - public boolean startNetConfServerInstance(NetConfServerDetailsEntity entity) { - boolean isSuccess = false; - - boolean isServerStarted = ncServerStarter.startServer(entity.getListenPort(), - entity.getDeviceId(), entity.getSwVersion(), entity.getHwVersion()); - if (isServerStarted) { - LOG.info("Successfully restarted NETCONF server {} on port {} .", - entity.getDeviceId(), entity.getListenPort()); - // we need to push the pnfEntry for IP updated - NetConfServerDetails details = getNetConfServerDetails(entity.getDeviceId(), entity); - - final String baseUrl = config.getMapperPath() + "/registerNetconfServer"; - URI uri = null; - try { - uri = new URI(baseUrl); - } catch (URISyntaxException e) { - LOG.error("error while contructing the URI {}", e.toString()); - } - RestTemplate restTemplate = new RestTemplate(); - HttpHeaders headers = new HttpHeaders(); - HttpEntity httpentity = new HttpEntity<>(details, headers); - if (uri != null) { - isSuccess = restTemplate.postForObject(uri, httpentity, Boolean.class); - } - - if (!isSuccess) { - LOG.error("Netconf Register request is failed update the updated host details.."); - } else { - LOG.debug("successfully started the server"); - } - } else { - LOG.error("Failed to restart NETCONF server {} on port {} upon application startup.", - entity.getDeviceId(), entity.getListenPort()); - } - return isSuccess; - } - - private NetConfServerDetails getNetConfServerDetails(String deviceId, - NetConfServerDetailsEntity entity) { - NetConfServerDetails result = new NetConfServerDetails(); - result.setDeviceId(deviceId); - result.setListenPort(entity.getListenPort()); - result.setEnodeBName(entity.getEnodeBName()); - result.setSwVersion(entity.getSwVersion()); - result.setHwVersion(entity.getHwVersion()); - String netconfListenAddress = getServiceHost(); - if (netconfListenAddress == null) { - netconfListenAddress = config.getNetconfServerIP(); - } - result.setListenAddress(netconfListenAddress); - result.setError(NetconfServerManagementError.SUCCESS); - return result; - } - - public String unregister(String deviceId, String enodeBName) { - String resultMsg = null; - NetConfServerDetailsEntity entity = null; - if (deviceId != null) { - entity = this.netconfDAO.findByDeviceId(deviceId); - } else if (enodeBName != null) { - entity = this.netconfDAO.findByEnodeBName(enodeBName); - } else { - LOG.error( - "Both deviceID and enodeBName are null. Hence failed to unregister the netconf server."); - resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName - + ". Invalid deviceId/enodeBName specified."; - } - if (entity == null) { - resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName - + ". Invalid deviceId/enodeBName specified."; - LOG.info(resultMsg); - return resultMsg; - } - boolean result = this.ncServerStarter.stopServer(deviceId); - if (result) { - resultMsg = - "Successfully unregistered the device " + deviceId + " and enodeBName=" + enodeBName; - this.serverPortAllocator.unReserveServerPort(entity.getListenPort()); - this.netconfDAO.delete(entity); - LOG.info(resultMsg); - delteHeartBeatTimer(deviceId); - } else { - resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName; - LOG.error(resultMsg); - } - - return resultMsg; - } - - private void delteHeartBeatTimer(String deviceId) { - VESNotification vesNotification = new VESNotification(); - - vesNotification.seteNodeBName(deviceId); - - ParameterDTO paramDTO = new ParameterDTO(); - paramDTO.setParamName(NetConfServerConstants.HEART_BEAT); - - List paramDTOList = new ArrayList<>(); - paramDTOList.add(paramDTO); - - OperationDetails opDetails = new OperationDetails(); - opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT); - opDetails.setParmeters(paramDTOList); - - vesNotification.setOperationDetails(opDetails); - - VESNotificationResponse response = - vesNotificationSender.sendDeleteConfigNotification(vesNotification); - - if (response.getStatusCode() == NetConfServerConstants.SUCCESS) { - LOG.info("Heart beat timer is deleted successfully for device {}", deviceId); - } else { - LOG.error("Failed to delete heart beat timer for device {}. ErrorMsg : {}", deviceId, - response.getResponseMsg()); - } - - } - - public List getServersInfo() { - Iterable serverEntities = netconfDAO.findAll(); - String netconfListenAddress = getServiceHost(); - if (netconfListenAddress == null) { - netconfListenAddress = config.getNetconfServerIP(); - } - List result = new ArrayList<>(); - - for (NetConfServerDetailsEntity entity : serverEntities) { - NetConfServerDetails server = new NetConfServerDetails(); - server.setDeviceId(entity.getDeviceId()); - server.setEnodeBName(entity.getEnodeBName()); - server.setError(NetconfServerManagementError.SUCCESS); - server.setListenAddress(netconfListenAddress); - server.setListenPort(entity.getListenPort()); - server.setSwVersion(entity.getSwVersion()); - server.setHwVersion(entity.getHwVersion()); - result.add(server); - } - return result; - } - - private String getServiceHost() { - Map envs = System.getenv(); - for (Entry entry : envs.entrySet()) { - if (entry.getKey() != null && entry.getKey().endsWith("_NETCONF_SERVICE_SERVICE_HOST")) { - return entry.getValue(); - } - } - return null; - } - - private boolean isVersionChanged(NetConfServerDetailsEntity entity, String swVersion, - String hwVersion) { - String existingProfileId = - versionManager.getAssociatedProfileId(entity.getSwVersion(), entity.getHwVersion()); - String newProfiled = versionManager.getAssociatedProfileId(swVersion, hwVersion); - return !existingProfileId.equalsIgnoreCase(newProfiled) ? true : false; - } - - class ServerStartTask implements Runnable { - - NetConfServerDetailsEntity entity; - NetConfServerManagerImpl netconfServerManager; - - public ServerStartTask(NetConfServerDetailsEntity entity, - NetConfServerManagerImpl netconfServerManager) { - this.entity = entity; - this.netconfServerManager = netconfServerManager; - } - - @Override - public void run() { - boolean isSuccess = netconfServerManager.startNetConfServerInstance(entity); - if (!isSuccess) { - try { - netconfServerManager.restartServersHandler.restart(entity); - } catch (RetryFailedException e) { - LOG.debug(""); - } - } - } - - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.server; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.apache.commons.io.FileUtils; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode; +import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; +import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository; +import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity; +import org.commscope.tr069adapter.netconf.error.RetryFailedException; +import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException; +import org.commscope.tr069adapter.netconf.server.helper.ServerPortAllocationHelper; +import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants; +import org.commscope.tr069adapter.netconf.server.ves.VESNotificationSender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +public class NetConfServerManagerImpl { + + private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerImpl.class); + + @Autowired + ServerPortAllocationHelper serverPortAllocator; + + @Autowired + NetConfServerDetailsRepository netconfDAO; + + @Autowired + NetConfServerProperties config; + + @Autowired + NetconfServerStarter ncServerStarter; + + @Autowired + RestartNetconfServerHandler restartServersHandler; + + @Autowired + VESNotificationSender vesNotificationSender; + + @Autowired + DeviceVersionManager versionManager; + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + public boolean loadSchemas() { + LOG.debug("Loading yang schema started"); + List profiles = versionManager.getSupportedProfileDefinitions(); + try { + String commonSchemaPath = config.getSchemaDirPath() + "/common"; + + for (ProfileDefinition profile : profiles) { + String verSpecificSchemaPath = + config.getSchemaDirPath() + File.separator + profile.getNetConfSchemaPath(); + File schemaDir = new File(commonSchemaPath); + File schemaVerDir = new File(verSpecificSchemaPath); + + if (!schemaVerDir.isDirectory()) { + LOG.error("No folder path found for given version path {}", + schemaVerDir.getAbsolutePath()); + return false; + } + + try { + FileUtils.copyDirectory(schemaDir, schemaVerDir); + } catch (IOException e) { + LOG.error("Failed to copy directory {} ", e.getMessage()); + } + boolean isSchemaLoaded = ncServerStarter.loadSchemas(schemaVerDir); + if (!isSchemaLoaded) { + LOG.debug("Failed to load schema for profile {}", profile.getProfileId()); + return false; + } + } + } catch (Exception e) { + LOG.error("Load schemas failed in netconf server {}", e.getMessage()); + return false; + } + LOG.debug("Loading yang schema completed"); + return true; + } + + public void restartServers() { + LOG.debug("Restarting all netconf servers during startup..."); + Iterable entities = netconfDAO.findAll(); + + for (NetConfServerDetailsEntity entity : entities) { + boolean isReserved = serverPortAllocator.checkAndReserveServerPort(entity.getListenPort()); + if (isReserved) { + ServerStartTask task = new ServerStartTask(entity, this); + executorService.execute(task); + } else { + try { + restartServersHandler.restart(entity); + } catch (RetryFailedException e) { + LOG.error("Error while restarting netconf servers {}",e.getMessage()); + } + } + } + LOG.debug("Restarting netconf servers during startup is completed."); + } + + public NetConfServerDetails createServer(String deviceId, String enodeBName, String swVersion, + String hwVersion) { + NetConfServerDetails result = new NetConfServerDetails(); + NetConfServerDetailsEntity entity = null; + if (deviceId != null) { + entity = netconfDAO.findByDeviceId(deviceId); + } else if (enodeBName != null) { + entity = netconfDAO.findByEnodeBName(enodeBName); + } else { + // none is specified + LOG.error( + "Both deviceID and enodeBName are null. Hence failed to create the netconf server."); + return null; + } + + if (null != entity && ncServerStarter.isNetConfServerRunning(deviceId)) { + if (isVersionChanged(entity, swVersion, hwVersion)) { + return restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion); + } + + // found the entity. server is already running. double check and run + // if + // required. else return the details. + + // update the ENB Name if Changed + entity.setEnodeBName(enodeBName); + netconfDAO.save(entity); + result = getNetConfServerDetails(deviceId, entity); + return result; + } + + try { + + String port = serverPortAllocator.reserveServerPort(); + if (port == null) { + result.setError(NetconfServerManagementError.PORT_NOT_AVAILBLE); + LOG.error( + "All ports are exhausted. Hence cannot allocate a port to start new netconf server"); + return result; + } else { + LOG.debug("Successfully reserved a port for deviceID={} ,port={}", deviceId, port); + + // start the server + boolean isServerStarted = ncServerStarter.startServer(port, deviceId, swVersion, hwVersion); + boolean isPortInUse = serverPortAllocator.isServerPortInUse(port); + + if (!isServerStarted || !isPortInUse) { + LOG.error( + "Failed to start netconf server for deviceID: {}, at port:{} , isServerStarted={} ,isPortInUse={}", + deviceId, port, isServerStarted, isPortInUse); + result.setError(NetconfServerManagementError.PORT_IN_USE); + return result; + } + } + + // save the record in db + entity = new NetConfServerDetailsEntity(); + entity.setDeviceId(deviceId); + entity.setListenPort(port); + entity.setEnodeBName(enodeBName); + entity.setSwVersion(swVersion); + entity.setHwVersion(hwVersion); + netconfDAO.save(entity); + + result = getNetConfServerDetails(deviceId, entity); + LOG.debug("Successfully started netconf server for deviceID= {}, port={}", deviceId, port); + + } catch (ServerPortAllocationException e) { + LOG.error("Failed to allocate a port {}", e.toString()); + } + + if (entity != null) { + result.setDeviceId(deviceId); + result.setListenPort(entity.getListenPort()); + String netconfListenAddress = getServiceHost(); + if (netconfListenAddress == null) { + netconfListenAddress = config.getNetconfServerIP(); + } + result.setListenAddress(netconfListenAddress); + result.setError(NetconfServerManagementError.SUCCESS); + } + return result; + } + + public NetConfServerDetails restartOnVersionChange(String deviceId, String enodeBName, + String swVersion, String hwVersion) { + + NetConfServerDetailsEntity entity = null; + if (deviceId != null) { + entity = netconfDAO.findByDeviceId(deviceId); + } + if (entity == null) { + return null; + } + + boolean isVersionChanged = isVersionChanged(entity, swVersion, hwVersion); + if (isVersionChanged) { + LOG.debug("software version changed, stopping the the existing netconf instance"); + boolean result = this.ncServerStarter.stopServer(deviceId); + if (result) { + LOG.debug( + "successfully stopped the netconf instance; trying to start with new version yang models"); + entity.setSwVersion(swVersion); + entity.setHwVersion(hwVersion); + netconfDAO.save(entity); + + boolean isSuccess = startNetConfServerInstance(entity); + + if (!isSuccess) { + try { + restartServersHandler.restart(entity); + } catch (RetryFailedException e) { + LOG.debug(""); + } + } + } + } + return getNetConfServerDetails(deviceId, entity); + } + + + public boolean startNetConfServerInstance(NetConfServerDetailsEntity entity) { + boolean isSuccess = false; + + boolean isServerStarted = ncServerStarter.startServer(entity.getListenPort(), + entity.getDeviceId(), entity.getSwVersion(), entity.getHwVersion()); + if (isServerStarted) { + LOG.info("Successfully restarted NETCONF server {} on port {} .", + entity.getDeviceId(), entity.getListenPort()); + // we need to push the pnfEntry for IP updated + NetConfServerDetails details = getNetConfServerDetails(entity.getDeviceId(), entity); + + final String baseUrl = config.getMapperPath() + "/registerNetconfServer"; + URI uri = null; + try { + uri = new URI(baseUrl); + } catch (URISyntaxException e) { + LOG.error("error while contructing the URI {}", e.toString()); + } + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + HttpEntity httpentity = new HttpEntity<>(details, headers); + if (uri != null) { + isSuccess = restTemplate.postForObject(uri, httpentity, Boolean.class); + } + + if (!isSuccess) { + LOG.error("Netconf Register request is failed update the updated host details.."); + } else { + LOG.debug("successfully started the server"); + } + } else { + LOG.error("Failed to restart NETCONF server {} on port {} upon application startup.", + entity.getDeviceId(), entity.getListenPort()); + } + return isSuccess; + } + + private NetConfServerDetails getNetConfServerDetails(String deviceId, + NetConfServerDetailsEntity entity) { + NetConfServerDetails result = new NetConfServerDetails(); + result.setDeviceId(deviceId); + result.setListenPort(entity.getListenPort()); + result.setEnodeBName(entity.getEnodeBName()); + result.setSwVersion(entity.getSwVersion()); + result.setHwVersion(entity.getHwVersion()); + String netconfListenAddress = getServiceHost(); + if (netconfListenAddress == null) { + netconfListenAddress = config.getNetconfServerIP(); + } + result.setListenAddress(netconfListenAddress); + result.setError(NetconfServerManagementError.SUCCESS); + return result; + } + + public String unregister(String deviceId, String enodeBName) { + String resultMsg = null; + NetConfServerDetailsEntity entity = null; + if (deviceId != null) { + entity = this.netconfDAO.findByDeviceId(deviceId); + } else if (enodeBName != null) { + entity = this.netconfDAO.findByEnodeBName(enodeBName); + } else { + LOG.error( + "Both deviceID and enodeBName are null. Hence failed to unregister the netconf server."); + resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName + + ". Invalid deviceId/enodeBName specified."; + } + if (entity == null) { + resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName + + ". Invalid deviceId/enodeBName specified."; + LOG.info(resultMsg); + return resultMsg; + } + boolean result = this.ncServerStarter.stopServer(deviceId); + if (result) { + resultMsg = + "Successfully unregistered the device " + deviceId + " and enodeBName=" + enodeBName; + this.serverPortAllocator.unReserveServerPort(entity.getListenPort()); + this.netconfDAO.delete(entity); + LOG.info(resultMsg); + delteHeartBeatTimer(deviceId); + } else { + resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName; + LOG.error(resultMsg); + } + + return resultMsg; + } + + private void delteHeartBeatTimer(String deviceId) { + VESNotification vesNotification = new VESNotification(); + + vesNotification.seteNodeBName(deviceId); + + ParameterDTO paramDTO = new ParameterDTO(); + paramDTO.setParamName(NetConfServerConstants.HEART_BEAT); + + List paramDTOList = new ArrayList<>(); + paramDTOList.add(paramDTO); + + OperationDetails opDetails = new OperationDetails(); + opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT); + opDetails.setParmeters(paramDTOList); + + vesNotification.setOperationDetails(opDetails); + + VESNotificationResponse response = + vesNotificationSender.sendDeleteConfigNotification(vesNotification); + + if (response.getStatusCode() == NetConfServerConstants.SUCCESS) { + LOG.info("Heart beat timer is deleted successfully for device {}", deviceId); + } else { + LOG.error("Failed to delete heart beat timer for device {}. ErrorMsg : {}", deviceId, + response.getResponseMsg()); + } + + } + + public List getServersInfo() { + Iterable serverEntities = netconfDAO.findAll(); + String netconfListenAddress = getServiceHost(); + if (netconfListenAddress == null) { + netconfListenAddress = config.getNetconfServerIP(); + } + List result = new ArrayList<>(); + + for (NetConfServerDetailsEntity entity : serverEntities) { + NetConfServerDetails server = new NetConfServerDetails(); + server.setDeviceId(entity.getDeviceId()); + server.setEnodeBName(entity.getEnodeBName()); + server.setError(NetconfServerManagementError.SUCCESS); + server.setListenAddress(netconfListenAddress); + server.setListenPort(entity.getListenPort()); + server.setSwVersion(entity.getSwVersion()); + server.setHwVersion(entity.getHwVersion()); + result.add(server); + } + return result; + } + + private String getServiceHost() { + Map envs = System.getenv(); + for (Entry entry : envs.entrySet()) { + if (entry.getKey() != null && entry.getKey().endsWith("_NETCONF_SERVICE_SERVICE_HOST")) { + return entry.getValue(); + } + } + return null; + } + + private boolean isVersionChanged(NetConfServerDetailsEntity entity, String swVersion, + String hwVersion) { + String existingProfileId = + versionManager.getAssociatedProfileId(entity.getSwVersion(), entity.getHwVersion()); + String newProfiled = versionManager.getAssociatedProfileId(swVersion, hwVersion); + return !existingProfileId.equalsIgnoreCase(newProfiled) ? true : false; + } + + class ServerStartTask implements Runnable { + + NetConfServerDetailsEntity entity; + NetConfServerManagerImpl netconfServerManager; + + public ServerStartTask(NetConfServerDetailsEntity entity, + NetConfServerManagerImpl netconfServerManager) { + this.entity = entity; + this.netconfServerManager = netconfServerManager; + } + + @Override + public void run() { + boolean isSuccess = netconfServerManager.startNetConfServerInstance(entity); + if (!isSuccess) { + try { + netconfServerManager.restartServersHandler.restart(entity); + } catch (RetryFailedException e) { + LOG.debug(""); + } + } + } + + } +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetconfServerStarter.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetconfServerStarter.java index 392b693..8b97a1d 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetconfServerStarter.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/NetconfServerStarter.java @@ -1,226 +1,230 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.server; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.commscope.tr069adapter.netconf.operations.CustomOperationsCreator; -import org.opendaylight.netconf.test.tool.NetconfDeviceSimulator; -import org.opendaylight.netconf.test.tool.config.Configuration; -import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder; -import org.opendaylight.netconf.test.tool.operations.OperationsCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; -import com.google.common.base.Preconditions; - - -@Component -@Scope("singleton") -public class NetconfServerStarter { - - private static final Logger LOG = LoggerFactory.getLogger(NetconfServerStarter.class); - - private static Map serversMap = new HashMap<>(); - - @Autowired - NetConfServerProperties config; - - @Autowired - DeviceVersionManager versionManager; - - public boolean startServer(String netConfPort, String macID, String swVersion, String hwVersion) { - - if (netConfPort == null) { - LOG.error("Invalid NETCONF port for deviceID: {}, port is null.", macID); - return false; - } - - LOG.debug( - "Starting Netconf server for MACID :{}, on port :{}, softwareVersion {}, hardwareVersion {}", - macID, netConfPort, swVersion, hwVersion); - boolean result = - startServer(netConfPort, config.getSchemaDirPath(), macID, swVersion, hwVersion); - LOG.debug("Completed starting Netconf server for MACID :{} , on port :{}, server status={}", - macID, netConfPort, result); - - return result; - } - - @SuppressWarnings({"resource", "deprecation"}) - private boolean startServer(String portStr, String schemaDirPath, String macID, String swVersion, - String hwVersion) { - - // creating configuration for the netconf instance - final Configuration configuration = new ConfigurationBuilder().build(); - OperationsCreator operationsCreator = new CustomOperationsCreator(macID, swVersion, hwVersion); - configuration.setOperationsCreator(operationsCreator); - configuration.setGenerateConfigsTimeout((int) TimeUnit.MINUTES.toMillis(30)); - if (portStr != null) { - try { - int port = Integer.parseInt(portStr); - configuration.setStartingPort(port); - } catch (Exception e) { - LOG.error("Failed to get netconf service instance port for parameters {}", e.toString()); - return false; - } - } - configuration.setDeviceCount(1); - configuration.setSsh(Boolean.TRUE); - configuration.setCapabilities(Configuration.DEFAULT_BASE_CAPABILITIES_EXI); - configuration.setIp("0.0.0.0"); - - String versionPath = versionManager.getNetconfYangSchemaPath(swVersion, hwVersion); - if (versionPath == null && swVersion != null) { - LOG.error("Failed to get version path for software version {}, calling base version", - swVersion); - versionPath = versionManager.getBaseNetconfYangSchemaPath(); - } else if (swVersion == null) { - LOG.error("Software version is null {}", swVersion); - return false; - } - String schemaVerPath = schemaDirPath + File.separator + versionPath; - File schemaVerDir = new File(schemaVerPath); - configuration.setSchemasDir(schemaVerDir); - - try (final NetconfDevice netconfDevice = new NetconfDevice(configuration)) { - final List openDevices = netconfDevice.start(); - if (openDevices.isEmpty()) { - LOG.debug("Failed to start netconf server instance {}", macID); - return false; - } - netconfDevice.setAutoClose(false); - serversMap.put(macID, netconfDevice); - } catch (RuntimeException e) { - LOG.error("Unhandled exception. Failed to start the server", e); - return false; - } - - return true; - } - - public boolean stopServer(String macID) { - try { - LOG.debug("Stopping Netconf server for MACID {}", macID); - NetconfDevice netconf = serversMap.get(macID); - netconf.setAutoClose(true); - netconf.close(); - serversMap.remove(macID); - LOG.debug("Completed stopping Netconf server for MACID {}", macID); - return true; - } catch (Exception e) { - LOG.debug("Error while stopping Netconf server for MACID {}; error message {}", macID, - e.getMessage()); - } - - return false; - } - - protected boolean loadSchemas(File schemasDir) { - if (schemasDir != null) { - if (!schemasDir.exists() || !schemasDir.isDirectory() || !schemasDir.canRead()) { - LOG.error("Failed to load schema. schema location is not valid."); - return false; - } - - Pattern yangregex = Pattern.compile("(?.*)@(?\\d{4}-\\d{2}-\\d{2})\\.yang"); - Pattern revisionregex = Pattern.compile("revision\\s+\"?(\\d{4}-\\d{2}-\\d{2})\"?"); - - final File[] filesArray = schemasDir.listFiles(); - final List files = - filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList(); - for (final File file : files) { - final Matcher yangMatcher = yangregex.matcher(file.getName()); - if (!yangMatcher.matches()) { - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line = reader.readLine(); - while (line != null && !revisionregex.matcher(line).find()) { - line = reader.readLine(); - } - loadSchemaPattren(line, file, revisionregex); - } catch (final IOException e) { - LOG.error("Unhandled exception. Failed to load the schema.{}", e.toString()); - return false; - } - } - } - } - return true; - } - - public boolean isNetConfServerRunning(String deviceId) { - NetconfDevice nc = serversMap.get(deviceId); - if (null != nc) - return true; - else - return false; - } - - private void loadSchemaPattren(String line, File file, Pattern revisionregex) { - if (line != null) { - final Matcher m = revisionregex.matcher(line); - Preconditions.checkState(m.find()); - String moduleName = file.getAbsolutePath(); - if (file.getName().endsWith(".yang")) { - moduleName = moduleName.substring(0, moduleName.length() - 5); - } - final String revision = m.group(1); - final String correctName = moduleName + "@" + revision + ".yang"; - final File correctNameFile = new File(correctName); - if (!file.renameTo(correctNameFile)) { - throw new IllegalStateException("Failed to rename '%s'." + file); - } - } - } - -} - - -class NetconfDevice extends NetconfDeviceSimulator { - boolean autoClose = true; - - public NetconfDevice(Configuration configuration) { - super(configuration); - } - - @Override - public void close() { - if (autoClose) - super.close(); - } - - public void setAutoClose(boolean autoClose) { - this.autoClose = autoClose; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.server; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager; +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.commscope.tr069adapter.netconf.operations.CustomOperationsCreator; +import org.opendaylight.netconf.test.tool.NetconfDeviceSimulator; +import org.opendaylight.netconf.test.tool.config.Configuration; +import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder; +import org.opendaylight.netconf.test.tool.operations.OperationsCreator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import com.google.common.base.Preconditions; + + +@Component +@Scope("singleton") +public class NetconfServerStarter { + + private static final Logger LOG = LoggerFactory.getLogger(NetconfServerStarter.class); + public static final String PATTERN = "[\n|\r|\t]"; + + private static Map serversMap = new HashMap<>(); + + @Autowired + NetConfServerProperties config; + + @Autowired + DeviceVersionManager versionManager; + + public boolean startServer(String netConfPort, String macID, String swVersion, String hwVersion) { + macID = macID.replaceAll(PATTERN, "_"); + if (netConfPort == null) { + LOG.error("Invalid NETCONF port for deviceID: {}, port is null.", macID); + return false; + } + + LOG.debug( + "Starting Netconf server for MACID :{}, on port :{}, softwareVersion {}, hardwareVersion {}", + macID, netConfPort, swVersion, hwVersion); + boolean result = + startServer(netConfPort, config.getSchemaDirPath(), macID, swVersion, hwVersion); + LOG.debug("Completed starting Netconf server for MACID :{} , on port :{}, server status={}", + macID, netConfPort, result); + + return result; + } + + @SuppressWarnings({"resource", "deprecation"}) + private boolean startServer(String portStr, String schemaDirPath, String macID, String swVersion, + String hwVersion) { + + // creating configuration for the netconf instance + final Configuration configuration = new ConfigurationBuilder().build(); + OperationsCreator operationsCreator = new CustomOperationsCreator(macID, swVersion, hwVersion); + configuration.setOperationsCreator(operationsCreator); + configuration.setGenerateConfigsTimeout((int) TimeUnit.MINUTES.toMillis(30)); + if (portStr != null) { + try { + int port = Integer.parseInt(portStr); + configuration.setStartingPort(port); + } catch (Exception e) { + LOG.error("Failed to get netconf service instance port for parameters {}", e.toString()); + return false; + } + } + configuration.setDeviceCount(1); + configuration.setSsh(Boolean.TRUE); + configuration.setCapabilities(Configuration.DEFAULT_BASE_CAPABILITIES_EXI); + configuration.setIp("0.0.0.0"); + + String versionPath = versionManager.getNetconfYangSchemaPath(swVersion, hwVersion); + if (versionPath == null && swVersion != null) { + swVersion = swVersion.replaceAll(PATTERN, "_"); + LOG.error("Failed to get version path for software version {}, calling base version", + swVersion); + versionPath = versionManager.getBaseNetconfYangSchemaPath(); + } else if (swVersion == null) { + LOG.error("Software version is null "); + return false; + } + String schemaVerPath = schemaDirPath + File.separator + versionPath; + File schemaVerDir = new File(schemaVerPath); + configuration.setSchemasDir(schemaVerDir); + + try (final NetconfDevice netconfDevice = new NetconfDevice(configuration)) { + final List openDevices = netconfDevice.start(); + if (openDevices.isEmpty()) { + LOG.debug("Failed to start netconf server instance {}", macID); + return false; + } + netconfDevice.setAutoClose(false); + serversMap.put(macID, netconfDevice); + } catch (RuntimeException e) { + LOG.error("Unhandled exception. Failed to start the server", e); + return false; + } + + return true; + } + + public boolean stopServer(String macID) { + try { + LOG.debug("Stopping Netconf server for MACID {}", macID); + NetconfDevice netconf = serversMap.get(macID); + netconf.setAutoClose(true); + netconf.close(); + serversMap.remove(macID); + LOG.debug("Completed stopping Netconf server for MACID {}", macID); + return true; + } catch (Exception e) { + LOG.debug("Error while stopping Netconf server for MACID {}; error message {}", macID, + e.getMessage()); + } + + return false; + } + + protected boolean loadSchemas(File schemasDir) { + if (schemasDir != null) { + if (!schemasDir.exists() || !schemasDir.isDirectory() || !schemasDir.canRead()) { + LOG.error("Failed to load schema. schema location is not valid."); + return false; + } + + Pattern yangregex = Pattern.compile("(?.*)@(?\\d{4}-\\d{2}-\\d{2})\\.yang"); + Pattern revisionregex = Pattern.compile("revision\\s+\"?(\\d{4}-\\d{2}-\\d{2})\"?"); + + final File[] filesArray = schemasDir.listFiles(); + final List files = + filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList(); + for (final File file : files) { + final Matcher yangMatcher = yangregex.matcher(file.getName()); + if (!yangMatcher.matches()) { + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + String line = reader.readLine(); + while (line != null && !revisionregex.matcher(line).find()) { + line = reader.readLine(); + } + loadSchemaPattren(line, file, revisionregex); + } catch (final IOException e) { + LOG.error("Unhandled exception. Failed to load the schema.{}", e.toString()); + return false; + } + } + } + } + return true; + } + + public boolean isNetConfServerRunning(String deviceId) { + NetconfDevice nc = serversMap.get(deviceId); + if (null != nc) + return true; + else + return false; + } + + private void loadSchemaPattren(String line, File file, Pattern revisionregex) { + if (line != null) { + final Matcher m = revisionregex.matcher(line); + Preconditions.checkState(m.find()); + String moduleName = file.getAbsolutePath(); + if (file.getName().endsWith(".yang")) { + moduleName = moduleName.substring(0, moduleName.length() - 5); + } + final String revision = m.group(1); + final String correctName = moduleName + "@" + revision + ".yang"; + final File correctNameFile = new File(correctName); + if (!file.renameTo(correctNameFile)) { + throw new IllegalStateException("Failed to rename '%s'." + file); + } + } + } + +} + + +class NetconfDevice extends NetconfDeviceSimulator { + boolean autoClose = true; + + public NetconfDevice(Configuration configuration) { + super(configuration); + } + + @Override + public void close() { + if (autoClose) + super.close(); + } + + public void setAutoClose(boolean autoClose) { + this.autoClose = autoClose; + } + +} diff --git a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/helper/ServerPortAllocationHelper.java b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/helper/ServerPortAllocationHelper.java index 9e5479d..b292201 100644 --- a/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/helper/ServerPortAllocationHelper.java +++ b/netconf-server/src/main/java/org/commscope/tr069adapter/netconf/server/helper/ServerPortAllocationHelper.java @@ -1,161 +1,161 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.server.helper; - -import java.io.IOException; -import java.net.Socket; -import java.util.HashMap; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.concurrent.Semaphore; - -import javax.annotation.PostConstruct; - -import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; -import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ServerPortAllocationHelper { - - private static final Logger LOG = LoggerFactory.getLogger(ServerPortAllocationHelper.class); - - private static Map semaphoreMap = new HashMap<>(); - - private PriorityQueue availablePorts = new PriorityQueue<>(); - - @Autowired - NetConfServerProperties config; - - @PostConstruct - public void init() { - // read the port range and it the available ports. - - Integer startPort = config.getDefaultNetconfStartPort(); - Integer maxServers = config.getDefaultMaxServers(); - - try { - startPort = Integer.parseInt(config.getNetconfServersStartPort()); - } catch (Exception e) { - LOG.warn( - "Failed to initialize the starting port from the environment {}. Hence using the default port range.", - config.getNetconfServersStartPort()); - } - - try { - maxServers = Integer.parseInt(config.getMaxNumOfNetconfServers()); - } catch (Exception e) { - LOG.warn( - "Failed to initialize the max netconf server from the environment {} Hence using the default max servers.", - config.getMaxNumOfNetconfServers()); - } - - for (int i = startPort + maxServers - 1; i >= startPort; i--) { - semaphoreMap.put(String.valueOf(i), new Semaphore(1)); - availablePorts.add(String.valueOf(i)); - } - LOG.debug("Successfully populated available ports list."); - } - - public synchronized String reserveServerPort() throws ServerPortAllocationException { - - if (availablePorts.isEmpty()) { - LOG.debug( - "All ports are exhausted. Hence cannot allocate a port to start new netconf server."); - return null; - } - - String port = availablePorts.peek(); - - LOG.debug("Trying to reserve port : {}", port); - if (isServerPortInUse(port)) { - LOG.debug("Port {} is already in use.", port); - availablePorts.poll(); - return reserveServerPort(); // retry if current port is not available - } - - Semaphore semaphore = semaphoreMap.get(port); - boolean isAcquired = semaphore.tryAcquire(); - if (isAcquired) { - LOG.debug("Failed to acquire a lock for port :{}. Hence retrying...", port); - return reserveServerPort(); - } - - availablePorts.poll(); - semaphore.release(); - LOG.debug("Rserved port is {}", port); - return port; - } - - public boolean unReserveServerPort(String port) { - - try { - Semaphore semaphore = semaphoreMap.get(port); - semaphore.acquire(); - availablePorts.add(port); - semaphore.release(); - LOG.error("Successfully un-reserved the port " + port + " to start netconf server."); - } catch (InterruptedException e) { - LOG.warn("Failed to un-reserve the port " + port, e); - Thread.currentThread().interrupt(); - return false; - } - - return true; - } - - public boolean checkAndReserveServerPort(String port) { - - try { - Semaphore semaphore = semaphoreMap.get(port); - semaphore.acquire(); - if (isServerPortInUse(port)) { - LOG.error("Port {} already in use.", port); - semaphore.release(); - return false; - } - availablePorts.remove(port); - semaphore.release(); - LOG.error("Successfully reserved the port {} to start netconf server", port); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOG.error("Failed to lock the port {} : Exception :{}", port, e.toString()); - return checkAndReserveServerPort(port); // retry acquiring the lock. - } - - return true; - } - - public boolean isServerPortInUse(String port) { - return checkIfPortAvailable(port); - } - - private static boolean checkIfPortAvailable(String portStr) { - Integer port = Integer.parseInt(portStr); - try (Socket ignored = new Socket("localhost", port)) { - return true; - } catch (IOException e) { - LOG.error("while checkIfPortAvailable {}", e.toString()); - return false; - } - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.server.helper; + +import java.io.IOException; +import java.net.Socket; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Semaphore; + +import javax.annotation.PostConstruct; + +import org.commscope.tr069adapter.netconf.config.NetConfServerProperties; +import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ServerPortAllocationHelper { + + private static final Logger LOG = LoggerFactory.getLogger(ServerPortAllocationHelper.class); + + private static Map semaphoreMap = new HashMap<>(); + + private PriorityQueue availablePorts = new PriorityQueue<>(); + + @Autowired + NetConfServerProperties config; + + @PostConstruct + public void init() { + // read the port range and it the available ports. + + Integer startPort = config.getDefaultNetconfStartPort(); + Integer maxServers = config.getDefaultMaxServers(); + + try { + startPort = Integer.parseInt(config.getNetconfServersStartPort()); + } catch (Exception e) { + LOG.warn( + "Failed to initialize the starting port from the environment {}. Hence using the default port range.", + config.getNetconfServersStartPort()); + } + + try { + maxServers = Integer.parseInt(config.getMaxNumOfNetconfServers()); + } catch (Exception e) { + LOG.warn( + "Failed to initialize the max netconf server from the environment {} Hence using the default max servers.", + config.getMaxNumOfNetconfServers()); + } + + for (int i = startPort + maxServers - 1; i >= startPort; i--) { + semaphoreMap.put(String.valueOf(i), new Semaphore(1)); + availablePorts.add(String.valueOf(i)); + } + LOG.debug("Successfully populated available ports list."); + } + + public synchronized String reserveServerPort() throws ServerPortAllocationException { + + if (availablePorts.isEmpty()) { + LOG.debug( + "All ports are exhausted. Hence cannot allocate a port to start new netconf server."); + return null; + } + + String port = availablePorts.peek(); + + LOG.debug("Trying to reserve port : {}", port); + if (isServerPortInUse(port)) { + LOG.debug("Port {} is already in use.", port); + availablePorts.poll(); + return reserveServerPort(); // retry if current port is not available + } + + Semaphore semaphore = semaphoreMap.get(port); + boolean isAcquired = semaphore.tryAcquire(); + if (isAcquired) { + LOG.debug("Failed to acquire a lock for port :{}. Hence retrying...", port); + return reserveServerPort(); + } + + availablePorts.poll(); + semaphore.release(); + LOG.debug("Rserved port is {}", port); + return port; + } + + public boolean unReserveServerPort(String port) { + + try { + Semaphore semaphore = semaphoreMap.get(port); + semaphore.acquire(); + availablePorts.add(port); + semaphore.release(); + LOG.error("Successfully un-reserved the port {} to start netconf server.", port); + } catch (InterruptedException e) { + LOG.warn("Failed to un-reserve the port {} {}", port, e.getMessage()); + Thread.currentThread().interrupt(); + return false; + } + + return true; + } + + public boolean checkAndReserveServerPort(String port) { + port = port.replaceAll("[\n|\r|\t]", "_"); + try { + Semaphore semaphore = semaphoreMap.get(port); + semaphore.acquire(); + if (isServerPortInUse(port)) { + LOG.error("Port {} already in use.", port); + semaphore.release(); + return false; + } + availablePorts.remove(port); + semaphore.release(); + LOG.error("Successfully reserved the port {} to start netconf server", port); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.error("Failed to lock the port {} : Exception :{}", port, e.toString()); + return checkAndReserveServerPort(port); // retry acquiring the lock. + } + + return true; + } + + public boolean isServerPortInUse(String port) { + return checkIfPortAvailable(port); + } + + private static boolean checkIfPortAvailable(String portStr) { + Integer port = Integer.parseInt(portStr); + try (Socket ignored = new Socket("localhost", port)) { + return true; + } catch (IOException e) { + LOG.error("while checkIfPortAvailable {}", e.toString()); + return false; + } + } +} diff --git a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/error/ServerPortAllocationExceptionTest.java b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/error/ServerPortAllocationExceptionTest.java index ede1054..2fdd76b 100644 --- a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/error/ServerPortAllocationExceptionTest.java +++ b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/error/ServerPortAllocationExceptionTest.java @@ -1,60 +1,60 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.error; - -import static org.junit.jupiter.api.Assertions.*; - -import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; -import org.junit.jupiter.api.Test; - -class ServerPortAllocationExceptionTest { - - @Test - void testServerPortAllocationException() { - try { - throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE); - - } catch (ServerPortAllocationException e) { - assertTrue(true); - } - } - - @Test - void testGetError() { - try { - throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE); - - } catch (ServerPortAllocationException e) { - assertTrue(e.getError().equals(NetconfServerManagementError.PORT_IN_USE)); - } - } - - @Test - void testSetError() { - try { - ServerPortAllocationException se = - new ServerPortAllocationException(NetconfServerManagementError.INTERNAL_ERROR); - throw se; - - } catch (ServerPortAllocationException e) { - assertTrue(e.getError().equals(NetconfServerManagementError.INTERNAL_ERROR)); - } - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.error; + +import static org.junit.jupiter.api.Assertions.*; + +import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError; +import org.junit.jupiter.api.Test; + +class ServerPortAllocationExceptionTest { + + @Test + void testServerPortAllocationException() { + try { + throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE); + + } catch (ServerPortAllocationException e) { + assertTrue(true); + } + } + + @Test + void testGetError() { + try { + throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE); + + } catch (ServerPortAllocationException e) { + assertEquals(NetconfServerManagementError.PORT_IN_USE, e.getError()); + } + } + + @Test + void testSetError() { + try { + ServerPortAllocationException se = + new ServerPortAllocationException(NetconfServerManagementError.INTERNAL_ERROR); + throw se; + + } catch (ServerPortAllocationException e) { + assertEquals(NetconfServerManagementError.INTERNAL_ERROR, e.getError()); + } + } + +} diff --git a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreatorTest.java b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreatorTest.java index ef47e48..dadbab4 100644 --- a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreatorTest.java +++ b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/operations/CustomOperationsCreatorTest.java @@ -1,49 +1,50 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.operations; - -import static org.junit.Assert.assertTrue; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.jupiter.api.Test; -import org.opendaylight.netconf.api.capability.Capability; -import org.opendaylight.netconf.impl.SessionIdProvider; -import org.opendaylight.netconf.mapping.api.NetconfOperation; - -class CustomOperationsCreatorTest { - - @Test - void testCustomOperationsCreator() { - CustomOperationsCreator coc = getCustomOperationsCreator(); - Set capabilities = new HashSet(); - Set opers = - coc.getNetconfOperationService(capabilities, new SessionIdProvider(), "1") - .getNetconfOperations(); - assertTrue(opers != null); - assertTrue(!opers.isEmpty()); - } - - CustomOperationsCreator getCustomOperationsCreator() { - CustomOperationsCreator coc = new CustomOperationsCreator("0005B9AB1", "4.3.0", "*"); - return coc; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.operations; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.opendaylight.netconf.api.capability.Capability; +import org.opendaylight.netconf.impl.SessionIdProvider; +import org.opendaylight.netconf.mapping.api.NetconfOperation; + +class CustomOperationsCreatorTest { + + @Test + void testCustomOperationsCreator() { + CustomOperationsCreator coc = getCustomOperationsCreator(); + Set capabilities = new HashSet(); + Set opers = + coc.getNetconfOperationService(capabilities, new SessionIdProvider(), "1") + .getNetconfOperations(); + assertNotNull(opers); + assertTrue(!opers.isEmpty()); + } + + CustomOperationsCreator getCustomOperationsCreator() { + CustomOperationsCreator coc = new CustomOperationsCreator("0005B9AB1", "4.3.0", "*"); + return coc; + } + +} diff --git a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApiTest.java b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApiTest.java index 2060974..652f945 100644 --- a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApiTest.java +++ b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/restapi/NetConfServerManagerRestApiTest.java @@ -1,105 +1,105 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.restapi; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; -import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository; -import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity; -import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; -import org.junit.FixMethodOrder; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runners.MethodSorters; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@ExtendWith(SpringExtension.class) -@SpringBootTest(classes = {NetConfServiceBooter.class}, - args = "--schemas-dir test-schemas --debug true --starting-port 17830") -@AutoConfigureMockMvc -public class NetConfServerManagerRestApiTest { - - @Autowired - private MockMvc mockMvc; - - @MockBean - NetConfServerDetailsRepository netconfDAO; - - @Autowired - NetConfServerManagerImpl manager; - - @Test - public void createNetconfServer() throws Exception { - - NetConfServerDetailsEntity entity = new NetConfServerDetailsEntity(); - entity.setDeviceId("0005B9AB1"); - entity.setEnodeBName("0005B9AB1"); - entity.setId(1l); - entity.setListenPort("17830"); - - MockHttpServletRequestBuilder requestBuilder = - MockMvcRequestBuilders.post("/netConfServerManagerService/createServer") - .param("deviceId", "0005B9AB1").param("enodeBName", "0005B9AB1") - .param("swVersion", "4.4.3").param("hwVersion", "*").accept(MediaType.APPLICATION_JSON); - MvcResult result = mockMvc.perform(requestBuilder).andReturn(); - - MockHttpServletResponse response = result.getResponse(); - - assertEquals(HttpStatus.OK.value(), response.getStatus()); - - } - - @Test - public void listNetconfServers() throws Exception { - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/netConfServerManagerService/listServers").accept(MediaType.APPLICATION_JSON); - MvcResult result = mockMvc.perform(requestBuilder).andReturn(); - MockHttpServletResponse response = result.getResponse(); - - assertEquals(HttpStatus.OK.value(), response.getStatus()); - - } - - @Test - public void restartServersOnStartup() { - boolean result = false; - try { - manager.restartServers(); - result = true; - } catch (Exception e) { - assertEquals(false, result); // if no exception - } - assertEquals(true, result); // if no exception - - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.restapi; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter; +import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository; +import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity; +import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl; +import org.junit.FixMethodOrder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = {NetConfServiceBooter.class}, + args = "--schemas-dir test-schemas --debug true --starting-port 17830") +@AutoConfigureMockMvc +public class NetConfServerManagerRestApiTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + NetConfServerDetailsRepository netconfDAO; + + @Autowired + NetConfServerManagerImpl manager; + + @Test + public void createNetconfServer() throws Exception { + + NetConfServerDetailsEntity entity = new NetConfServerDetailsEntity(); + entity.setDeviceId("0005B9AB1"); + entity.setEnodeBName("0005B9AB1"); + entity.setId(1l); + entity.setListenPort("17830"); + + MockHttpServletRequestBuilder requestBuilder = + MockMvcRequestBuilders.post("/netConfServerManagerService/createServer") + .param("deviceId", "0005B9AB1").param("enodeBName", "0005B9AB1") + .param("swVersion", "4.4.3").param("hwVersion", "*").accept(MediaType.APPLICATION_JSON); + MvcResult result = mockMvc.perform(requestBuilder).andReturn(); + + MockHttpServletResponse response = result.getResponse(); + + assertEquals(HttpStatus.OK.value(), response.getStatus()); + + } + + @Test + public void listNetconfServers() throws Exception { + + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders + .get("/netConfServerManagerService/listServers").accept(MediaType.APPLICATION_JSON); + MvcResult result = mockMvc.perform(requestBuilder).andReturn(); + MockHttpServletResponse response = result.getResponse(); + + assertEquals(HttpStatus.OK.value(), response.getStatus()); + + } + + @Test + public void restartServersOnStartup() { + boolean result = false; + try { + manager.restartServers(); + result = true; + } catch (Exception e) { + assertEquals(false, result); // if no exception + } + assertEquals(true, result); // if no exception + + } +} diff --git a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/rpc/XmlUtilityTest.java b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/rpc/XmlUtilityTest.java index 91d420b..dae2f81 100644 --- a/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/rpc/XmlUtilityTest.java +++ b/netconf-server/src/test/java/org/commscope/tr069adapter/netconf/rpc/XmlUtilityTest.java @@ -1,55 +1,56 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.netconf.rpc; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.jupiter.api.Test; -import org.w3c.dom.Element; - -class XmlUtilityTest { - - @Test - void testConvertDocumentToStringXmlElement() { - - String xmlStr = - "1"; - try { - Element el = XmlUtility.convertStringToDocument(xmlStr); - String result = XmlUtility.convertDocumentToString(el); - assertTrue(result != null); - } catch (Exception e) { - fail("Failed to convert string into document."); - } - } - - @Test - void testConvertStringToDocument() { - String xmlStr = - ""; - try { - XmlUtility.convertStringToDocument(xmlStr); - } catch (Exception e) { - fail("Failed to convert string into document."); - } - assertTrue(true); - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.netconf.rpc; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.jupiter.api.Test; +import org.w3c.dom.Element; + +class XmlUtilityTest { + + @Test + void testConvertDocumentToStringXmlElement() { + + String xmlStr = + "1"; + try { + Element el = XmlUtility.convertStringToDocument(xmlStr); + String result = XmlUtility.convertDocumentToString(el); + assertNotNull(result); + } catch (Exception e) { + fail("Failed to convert string into document."); + } + } + + @Test + void testConvertStringToDocument() { + String xmlStr = + ""; + try { + XmlUtility.convertStringToDocument(xmlStr); + } catch (Exception e) { + fail("Failed to convert string into document."); + } + assertTrue(true); + } + +} diff --git a/ves-agent/pom.xml b/ves-agent/pom.xml index 817fcbd..5e69928 100644 --- a/ves-agent/pom.xml +++ b/ves-agent/pom.xml @@ -175,6 +175,25 @@ false + + org.jacoco + jacoco-maven-plugin + + + + prepare-agent + + + + + report + test + + report + + + + maven-failsafe-plugin diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncRequestHandler.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncRequestHandler.java index aeb8c03..beb3019 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncRequestHandler.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncRequestHandler.java @@ -16,147 +16,138 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.async; - -import java.util.concurrent.Future; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationCode; -import org.commscope.tr069adapter.acs.common.OperationOptions; -import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; -import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; -import org.commscope.tr069adapter.vesagent.VesConfiguration; -import org.commscope.tr069adapter.vesagent.controller.HeartBeatMessageHandler; -import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; -import org.commscope.tr069adapter.vesagent.mapper.MapperRequestSender; -import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; -import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; - -/** - * - * @version 1.0 - * @since June 12, 2020 - * @author Prashant Kumar - */ -@Component -public class AsyncRequestHandler { - - private static final Logger LOG = LoggerFactory.getLogger(AsyncRequestHandler.class); - - @Autowired - MapperRequestSender mapperRequestSender; - - @Autowired - WaitForNotifications waitForNotifications; - - @Autowired - HeartBeatMessageHandler heartBeatMessageHandler; - - @Autowired - VesConfiguration config; - - public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) { - LOG.info("Initiating device connectivity request to ACS for device {}", - deviceRPCRequest.getDeviceDetails().getDeviceId()); - - Future futureResponse = mapperRequestSender.sendRequest(deviceRPCRequest); - if (null == futureResponse) { - LOG.error("Request could not be sent. response is null"); - return null; - } - - boolean isSuccess = false; - DeviceRPCResponse response = null; - - OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode(); - String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); - long timeOut = getOperationTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout()); - - try { - waitForNotifications.waitForResult(deviceId, opCode, futureResponse, timeOut); - response = waitForNotifications.getOperationResult(deviceId, opCode); - - if (null == response) { - LOG.error("Request got timed out."); - } else { - LOG.debug("Received operation result for device : {}, operation = {} as {}", deviceId, - opCode, response); - } - waitForNotifications.stopOperation(deviceId, opCode); - - // if(isSuccess) { - // response = waitForNotifications.getOperationResult(deviceId, opCode); - // LOG.debug("Received operation result for device : {}, operation = {} as {}",deviceId, - // opCode,response); - // - // waitForNotifications.stopOperation(deviceId, opCode); - // }else { - // LOG.error("Request got timed out."); - // } - } catch (InterruptedException e) { - LOG.debug( - "InterruptedException while waiting for mapper operation result for device : {}, operation : {} request.", - deviceId, opCode); - } - - return response; - } - - private long getOperationTimeOut(long timeOut) { - if (timeOut > 0) { - return timeOut; - } - - if (null != config.getRequestTimeout()) { - timeOut = Long.valueOf(config.getRequestTimeout()); - } - - return timeOut; - } - - @Async("threadPoolTaskExecutor1") +package org.commscope.tr069adapter.vesagent.async; + +import java.util.concurrent.Future; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationCode; +import org.commscope.tr069adapter.acs.common.OperationOptions; +import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode; +import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails; +import org.commscope.tr069adapter.vesagent.VesConfiguration; +import org.commscope.tr069adapter.vesagent.controller.HeartBeatMessageHandler; +import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; +import org.commscope.tr069adapter.vesagent.mapper.MapperRequestSender; +import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; +import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * + * @version 1.0 + * @since June 12, 2020 + * @author Prashant Kumar + */ +@Component +public class AsyncRequestHandler { + + private static final Logger LOG = LoggerFactory.getLogger(AsyncRequestHandler.class); + + @Autowired + MapperRequestSender mapperRequestSender; + + @Autowired + WaitForNotifications waitForNotifications; + + @Autowired + HeartBeatMessageHandler heartBeatMessageHandler; + + @Autowired + VesConfiguration config; + + public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) { + LOG.info("Initiating device connectivity request to ACS for device {}", + deviceRPCRequest.getDeviceDetails().getDeviceId()); + + Future futureResponse = mapperRequestSender.sendRequest(deviceRPCRequest); + if (null == futureResponse) { + LOG.error("Request could not be sent. response is null"); + return null; + } + + DeviceRPCResponse response = null; + + OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode(); + String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); + long timeOut = getOperationTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout()); + + try { + waitForNotifications.waitForResult(deviceId, opCode, futureResponse, timeOut); + response = waitForNotifications.getOperationResult(deviceId, opCode); + + if (null == response) { + LOG.error("Request got timed out."); + } else { + LOG.debug("Received operation result for device : {}, operation = {} as {}", deviceId, + opCode, response); + } + waitForNotifications.stopOperation(deviceId, opCode); + + } catch (InterruptedException e) { + LOG.debug( + "InterruptedException while waiting for mapper operation result for device : {}, operation : {} request.", + deviceId, opCode); + Thread.currentThread().interrupt(); + } + + return response; + } + + private long getOperationTimeOut(long timeOut) { + if (timeOut > 0) { + return timeOut; + } + + if (null != config.getRequestTimeout()) { + timeOut = Long.valueOf(config.getRequestTimeout()); + } + + return timeOut; + } + + @Async("threadPoolTaskExecutor1") public void initiateDeviceReachabilityCheck(DeviceDataEntity deviceDataEntity) { - deviceDataEntity.setStartEpochMicrosec(VesAgentUtils.getStartEpochTime()*1000); - DeviceDetails deviceDetails = new DeviceDetails(); - deviceDetails.setDeviceId(deviceDataEntity.getDeviceId()); - deviceDetails.setOui(deviceDataEntity.getOui()); - deviceDetails.setProductClass(deviceDataEntity.getProductClass()); - - TR069OperationDetails operationDetails = new TR069OperationDetails(); - operationDetails.setOpCode(CustomOperationCode.CONNECT); - - DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); - - deviceRPCRequest.setDeviceDetails(deviceDetails); - deviceRPCRequest.setOpDetails(operationDetails); - - OperationOptions options = new OperationOptions(); - if (null != config.getRequestTimeout()) { - options.setExecutionTimeout(Integer.valueOf(config.getRequestTimeout())); - } - - deviceRPCRequest.setOptions(options); - - DeviceRPCResponse deviceRPCResponse = performDeviceOperation(deviceRPCRequest); - - if (VesAgentUtils.isDeviceReachable(deviceRPCResponse)) { - LOG.debug("Device {} is reachable.", deviceDataEntity.getDeviceId()); - try { - LOG.debug("Sending heatbeat event for device {}.", deviceDataEntity.getDeviceId()); - heartBeatMessageHandler.sendHeartBeatEvent(deviceDataEntity, Integer.parseInt( - deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD))); - } catch (NumberFormatException e) { - LOG.error("heartBeatPeriod doesn't have numeric value. ErrorMsg: {}", e.getMessage()); - } catch (Exception e) { - LOG.error("Error while sending heart beat ves event. ErrorMsg: {}", e.getMessage()); - } - } - } -} + deviceDataEntity.setStartEpochMicrosec(VesAgentUtils.getStartEpochTime() * 1000); + DeviceDetails deviceDetails = new DeviceDetails(); + deviceDetails.setDeviceId(deviceDataEntity.getDeviceId()); + deviceDetails.setOui(deviceDataEntity.getOui()); + deviceDetails.setProductClass(deviceDataEntity.getProductClass()); + + TR069OperationDetails operationDetails = new TR069OperationDetails(); + operationDetails.setOpCode(CustomOperationCode.CONNECT); + + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + + deviceRPCRequest.setDeviceDetails(deviceDetails); + deviceRPCRequest.setOpDetails(operationDetails); + + OperationOptions options = new OperationOptions(); + if (null != config.getRequestTimeout()) { + options.setExecutionTimeout(Integer.valueOf(config.getRequestTimeout())); + } + + deviceRPCRequest.setOptions(options); + + DeviceRPCResponse deviceRPCResponse = performDeviceOperation(deviceRPCRequest); + + if (VesAgentUtils.isDeviceReachable(deviceRPCResponse)) { + LOG.debug("Device {} is reachable.", deviceDataEntity.getDeviceId()); + try { + LOG.debug("Sending heatbeat event for device {}.", deviceDataEntity.getDeviceId()); + heartBeatMessageHandler.sendHeartBeatEvent(deviceDataEntity, Integer.parseInt( + deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD))); + } catch (NumberFormatException e) { + LOG.error("heartBeatPeriod doesn't have numeric value. ErrorMsg: {}", e.getMessage()); + } catch (Exception e) { + LOG.error("Error while sending heart beat ves event. ErrorMsg: {}", e.getMessage()); + } + } + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncThreadPoolConfig.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncThreadPoolConfig.java index bb87a7c..f441e53 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncThreadPoolConfig.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/async/AsyncThreadPoolConfig.java @@ -20,6 +20,7 @@ package org.commscope.tr069adapter.vesagent.async; import java.util.concurrent.Executor; import java.util.concurrent.Executors; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/AlarmMappingHandler.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/AlarmMappingHandler.java index 2f6ec36..6217349 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/AlarmMappingHandler.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/AlarmMappingHandler.java @@ -1,205 +1,205 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.controller; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.vesagent.VesConfiguration; -import org.commscope.tr069adapter.vesagent.exception.InvalidFaultOperationException; -import org.commscope.tr069adapter.vesagent.fault.AlarmFrameWorkSeverityEnum; -import org.commscope.tr069adapter.vesagent.fault.ExpeditedEvent; -import org.commscope.tr069adapter.vesagent.fault.Parser; -import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; -import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; -import org.commscope.tr069adapter.vesagent.model.Event; -import org.commscope.tr069adapter.vesagent.model.EventMessage; -import org.commscope.tr069adapter.vesagent.model.FaultFields; -import org.commscope.tr069adapter.vesagent.util.EventUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - -@Component -public class AlarmMappingHandler { - - private static final Logger logger = LoggerFactory.getLogger(AlarmMappingHandler.class); - - @Autowired - VesConfiguration config; - - @Autowired - HttpRequestSender sender; - - public VESNotificationResponse handleAlarmNotification(VESNotification notification) - throws InvalidFaultOperationException, JsonProcessingException { - List events = convertNotificationToVESEvent(notification.getDevnotification(), - notification.geteNodeBName()); - - for (Iterator iterator = events.iterator(); iterator.hasNext();) { - Event event = iterator.next(); - EventMessage evMsg = new EventMessage(); - evMsg.setEvent(event); - - ObjectMapper mapper = new ObjectMapper(); - - String requestBody = mapper.writeValueAsString(evMsg); - if (requestBody.isEmpty()) { - logger.debug("Alarm Event body is empty"); - } - - String url = config.getFaultVesUrl(); - VESNotificationResponse response = sender.postRequest(url, requestBody); - if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) { - logger.debug( - "Error received while posting alarms; skiiping this alarm in the fault event and continue for remaining"); - } - } - - return new VESNotificationResponse(HttpStatus.ACCEPTED.value(), "No Alarms in the request"); - } - - List convertNotificationToVESEvent(DeviceInform notification, String eNodeBName) - throws InvalidFaultOperationException { - logger.debug("Converting Notification to VES fault event started"); - ArrayList mlist = new ArrayList<>(); - - List parameter = notification.getParameters(); - Map hmAlarmParameters = null; - Parser parser = new Parser(); - hmAlarmParameters = parser.parseFaultParams(parameter); - - for (Iterator iterator = hmAlarmParameters.keySet().iterator(); iterator.hasNext();) { - ExpeditedEvent event = hmAlarmParameters.get(iterator.next()); - - if (event.getAdditionalInformation() != null - && event.getAdditionalInformation().contains("-")) { - String eNBName = event.getAdditionalInformation().split("-")[0].trim(); - eNodeBName = eNBName; - } - - Event faultEvent = new Event(); - CommonEventHeader eventHeader = new CommonEventHeader(); - eventHeader.setDomain("fault"); - eventHeader.setEventId(event.getAlarmIdentifier()); - eventHeader.setEventName("Fault_" + notification.getDeviceDetails().getProductClass() + "-" - + config.getVendorName() + "_" + event.getProbableCause().replace(" ", "")); - eventHeader.setEventType(config.getFaultEventType()); - eventHeader.setLastEpochMicrosec(System.currentTimeMillis()); - eventHeader.setTimeZoneOffset(extractTimeZoneOffSet(event.getAdditionalInformation())); - eventHeader.setPriority(extractPriority(event.getPerceivedSeverity())); - - EventUtil.populateEnodeBName(eventHeader, notification, eNodeBName); - - eventHeader.setSequence(1); - eventHeader.setStartEpochMicrosec(System.currentTimeMillis()*1000); - eventHeader.setVersion(config.getEventVersion()); - if (eNodeBName != null && eNodeBName.length() > 3) - eventHeader.setNfNamingCode(eNodeBName.substring(0, 3)); - else - eventHeader.setNfNamingCode(""); - eventHeader.setNfcNamingCode(""); - eventHeader.setNfVendorName(config.getVendorName()); - eventHeader.setVesEventListenerVersion(config.getVesVersion()); - faultEvent.setCommonEventHeader(eventHeader); - - FaultFields faultfields = new FaultFields(); - faultfields.setAlarmCondition(event.getProbableCause().replace(" ", "")); - - faultfields.setEventSeverity(event.getPerceivedSeverity().toString()); - if (event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEAR - || event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEARED) { - faultfields.setEventSeverity("NORMAL"); - } - - faultfields.setEventSourceType(config.getFaultEventSourcePrefix() + "_" - + notification.getDeviceDetails().getProductClass()); - faultfields.setFaultFieldsVersion(config.getFaultFeildVersion()); - faultfields.setSpecificProblem(event.getSpecificProblem()); - faultfields.setVfStatus("Active"); - faultfields.setEventCategory(event.getEventType()); - faultfields.setAlarmInterfaceA(event.getManagedObjectInstance()); - Map addition = new HashMap<>(); - addition.put("eventTime", - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.s'Z'").format(new Date())); - addition.put("AdditionalText", event.getAdditionalText()); - addition.put("AdditionalInformation", event.getAdditionalInformation()); - faultfields.setAlarmAdditionalInformation(addition); - - faultEvent.setFaultFields(faultfields); - mlist.add(faultEvent); - - } - logger.debug("Converting Notification to VES fault event completed :{}", mlist); - return mlist; - } - - private String extractTimeZoneOffSet(String additionalInformation) { - String[] additionalInfoArray = null; - String[] timeZoneOffset = null; - String timeOffset = "UTC+00.00"; - - if (additionalInformation != null && additionalInformation.contains("|")) { - additionalInfoArray = additionalInformation.split("\\|"); - - int index = -1; - for (int i = 0; i < additionalInfoArray.length; i++) { - if (additionalInfoArray[i].contains("TZD=")) { - index = i; - } - } - if (index >= 0) { - timeZoneOffset = additionalInfoArray[index].split("="); - timeOffset = timeZoneOffset[timeZoneOffset.length - 1]; - } - } else if (additionalInformation != null && additionalInformation.contains("TZD=")) { - timeZoneOffset = additionalInformation.split("="); - timeOffset = timeZoneOffset[timeZoneOffset.length - 1]; - } - - return timeOffset; - } - - private String extractPriority(AlarmFrameWorkSeverityEnum severity) { - String priority; - if (severity == AlarmFrameWorkSeverityEnum.CRITICAL - || severity == AlarmFrameWorkSeverityEnum.MAJOR) { - priority = "High"; - } else if (severity == AlarmFrameWorkSeverityEnum.MINOR) { - priority = "Medium"; - } else { - priority = "Low"; - } - - return priority; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.vesagent.VesConfiguration; +import org.commscope.tr069adapter.vesagent.exception.InvalidFaultOperationException; +import org.commscope.tr069adapter.vesagent.fault.AlarmFrameWorkSeverityEnum; +import org.commscope.tr069adapter.vesagent.fault.ExpeditedEvent; +import org.commscope.tr069adapter.vesagent.fault.Parser; +import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; +import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; +import org.commscope.tr069adapter.vesagent.model.Event; +import org.commscope.tr069adapter.vesagent.model.EventMessage; +import org.commscope.tr069adapter.vesagent.model.FaultFields; +import org.commscope.tr069adapter.vesagent.util.EventUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +@Component +public class AlarmMappingHandler { + + private static final Logger logger = LoggerFactory.getLogger(AlarmMappingHandler.class); + + @Autowired + VesConfiguration config; + + @Autowired + HttpRequestSender sender; + + public VESNotificationResponse handleAlarmNotification(VESNotification notification) + throws InvalidFaultOperationException, JsonProcessingException { + List events = convertNotificationToVESEvent(notification.getDevnotification(), + notification.geteNodeBName()); + + for (Iterator iterator = events.iterator(); iterator.hasNext();) { + Event event = iterator.next(); + EventMessage evMsg = new EventMessage(); + evMsg.setEvent(event); + + ObjectMapper mapper = new ObjectMapper(); + + String requestBody = mapper.writeValueAsString(evMsg); + if (requestBody.isEmpty()) { + logger.debug("Alarm Event body is empty"); + } + + String url = config.getFaultVesUrl(); + VESNotificationResponse response = sender.postRequest(url, requestBody); + if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) { + logger.debug( + "Error received while posting alarms; skiiping this alarm in the fault event and continue for remaining"); + } + } + + return new VESNotificationResponse(HttpStatus.ACCEPTED.value(), "No Alarms in the request"); + } + + List convertNotificationToVESEvent(DeviceInform notification, String eNodeBName) + throws InvalidFaultOperationException { + logger.debug("Converting Notification to VES fault event started"); + ArrayList mlist = new ArrayList<>(); + + List parameter = notification.getParameters(); + Map hmAlarmParameters = null; + Parser parser = new Parser(); + hmAlarmParameters = parser.parseFaultParams(parameter); + + for (Iterator iterator = hmAlarmParameters.keySet().iterator(); iterator.hasNext();) { + ExpeditedEvent event = hmAlarmParameters.get(iterator.next()); + + if (event.getAdditionalInformation() != null + && event.getAdditionalInformation().contains("-")) { + String eNBName = event.getAdditionalInformation().split("-")[0].trim(); + eNodeBName = eNBName; + } + + Event faultEvent = new Event(); + CommonEventHeader eventHeader = new CommonEventHeader(); + eventHeader.setDomain("fault"); + eventHeader.setEventId(event.getAlarmIdentifier()); + eventHeader.setEventName("Fault_" + notification.getDeviceDetails().getProductClass() + "-" + + config.getVendorName() + "_" + event.getProbableCause().replace(" ", "")); + eventHeader.setEventType(config.getFaultEventType()); + eventHeader.setLastEpochMicrosec(System.currentTimeMillis()); + eventHeader.setTimeZoneOffset(extractTimeZoneOffSet(event.getAdditionalInformation())); + eventHeader.setPriority(extractPriority(event.getPerceivedSeverity())); + + EventUtil.populateEnodeBName(eventHeader, notification, eNodeBName); + + eventHeader.setSequence(1); + eventHeader.setStartEpochMicrosec(System.currentTimeMillis() * 1000); + eventHeader.setVersion(config.getEventVersion()); + if (eNodeBName != null && eNodeBName.length() > 3) + eventHeader.setNfNamingCode(eNodeBName.substring(0, 3)); + else + eventHeader.setNfNamingCode(""); + eventHeader.setNfcNamingCode(""); + eventHeader.setNfVendorName(config.getVendorName()); + eventHeader.setVesEventListenerVersion(config.getVesVersion()); + faultEvent.setCommonEventHeader(eventHeader); + + FaultFields faultfields = new FaultFields(); + faultfields.setAlarmCondition(event.getProbableCause().replace(" ", "")); + + faultfields.setEventSeverity(event.getPerceivedSeverity().toString()); + if (event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEAR + || event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEARED) { + faultfields.setEventSeverity("NORMAL"); + } + + faultfields.setEventSourceType(config.getFaultEventSourcePrefix() + "_" + + notification.getDeviceDetails().getProductClass()); + faultfields.setFaultFieldsVersion(config.getFaultFeildVersion()); + faultfields.setSpecificProblem(event.getSpecificProblem()); + faultfields.setVfStatus("Active"); + faultfields.setEventCategory(event.getEventType()); + faultfields.setAlarmInterfaceA(event.getManagedObjectInstance()); + Map addition = new HashMap<>(); + addition.put("eventTime", + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.s'Z'").format(new Date())); + addition.put("AdditionalText", event.getAdditionalText()); + addition.put("AdditionalInformation", event.getAdditionalInformation()); + faultfields.setAlarmAdditionalInformation(addition); + + faultEvent.setFaultFields(faultfields); + mlist.add(faultEvent); + + } + logger.debug("Converting Notification to VES fault event completed :{}", mlist); + return mlist; + } + + private String extractTimeZoneOffSet(String additionalInformation) { + String[] additionalInfoArray = null; + String[] timeZoneOffset = null; + String timeOffset = "UTC+00.00"; + + if (additionalInformation != null && additionalInformation.contains("|")) { + additionalInfoArray = additionalInformation.split("\\|"); + + int index = -1; + for (int i = 0; i < additionalInfoArray.length; i++) { + if (additionalInfoArray[i].contains("TZD=")) { + index = i; + } + } + if (index >= 0) { + timeZoneOffset = additionalInfoArray[index].split("="); + timeOffset = timeZoneOffset[timeZoneOffset.length - 1]; + } + } else if (additionalInformation != null && additionalInformation.contains("TZD=")) { + timeZoneOffset = additionalInformation.split("="); + timeOffset = timeZoneOffset[timeZoneOffset.length - 1]; + } + + return timeOffset; + } + + private String extractPriority(AlarmFrameWorkSeverityEnum severity) { + String priority; + if (severity == AlarmFrameWorkSeverityEnum.CRITICAL + || severity == AlarmFrameWorkSeverityEnum.MAJOR) { + priority = "High"; + } else if (severity == AlarmFrameWorkSeverityEnum.MINOR) { + priority = "Medium"; + } else { + priority = "Low"; + } + + return priority; + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/HeartBeatMessageHandler.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/HeartBeatMessageHandler.java index 80da0f6..f72a731 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/HeartBeatMessageHandler.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/HeartBeatMessageHandler.java @@ -1,239 +1,239 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.controller; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.ArrayList; -import java.util.List; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.acs.common.OperationDetails; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.vesagent.VesConfiguration; -import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; -import org.commscope.tr069adapter.vesagent.exception.VesAgentException; -import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; -import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; -import org.commscope.tr069adapter.vesagent.model.Event; -import org.commscope.tr069adapter.vesagent.model.EventMessage; -import org.commscope.tr069adapter.vesagent.model.HeartbeatFields; -import org.commscope.tr069adapter.vesagent.service.VesAgentServiceHelper; -import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; -import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class HeartBeatMessageHandler { - - private static final Logger logger = LoggerFactory.getLogger(HeartBeatMessageHandler.class); - - @Autowired - VesAgentServiceHelper vesAgentServiceHelper; - - @Autowired - VesConfiguration config; - - @Autowired - HttpRequestSender sender; - - public VESNotificationResponse sendHeartBeatEvent(DeviceDataEntity deviceDataEntity, - int heartBeatPeriod) throws Exception { - Event event = convertNotificationToVESEvent(deviceDataEntity, heartBeatPeriod); - - EventMessage evMsg = new EventMessage(); - evMsg.setEvent(event); - - ObjectMapper mapper = new ObjectMapper(); - - String requestBody = mapper.writeValueAsString(evMsg); - if (requestBody.isEmpty()) { - logger.debug("VES Event body is empty"); - } - - String url = config.getPnfRegVesUrl(); - return sender.postRequest(url, requestBody); - } - - public void handleRegisterRequest(VESNotification vesNotification) { - try { - VesAgentUtils.validateVESNotification(vesNotification); - } catch (VesAgentException e) { - logger.error( - "Failed to create heartbeat timers for device on recieving bootstrap. ErrorMsg: {}", - e.getMessage()); - return; - } - - List deviceDataEntityList = vesAgentServiceHelper.findByDeviceIdAndGroup( - vesNotification.getDevnotification().getDeviceDetails().getDeviceId(), - VesAgentConstants.HEART_BEAT); - - if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) { - DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0); - String heartbeatPeriod = - deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD); - - if (!VesAgentUtils.isNullOrEmpty(heartbeatPeriod) - && !heartbeatPeriod.equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { - return; - } - } - - logger.info("Creating heartbeat records and timer using default heartbeatPeriod {} minutes.", - VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL); - - DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); - deviceRPCRequest.setDeviceDetails(vesNotification.getDevnotification().getDeviceDetails()); - - OperationDetails opDetails = new OperationDetails(); - - ParameterDTO heartBeatPeriodParam = new ParameterDTO(); - heartBeatPeriodParam.setParamName(VesAgentConstants.HEART_BEAT_PERIOD); - heartBeatPeriodParam.setParamValue(VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL); - - List paramList = new ArrayList<>(); - paramList.add(heartBeatPeriodParam); - - opDetails.setParmeters(paramList); - deviceRPCRequest.setOpDetails(opDetails); - - deviceRPCRequest.addContextParam(VesAgentConstants.ENODEB_NAME, - vesNotification.geteNodeBName()); - - handleSetConfigRequest(deviceRPCRequest); - - } - - public DeviceRPCResponse handleSetConfigRequest(DeviceRPCRequest deviceRPCRequest) { - try { - VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest); - } catch (VesAgentException e) { - return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); - } - - OperationDetails operationDetails = deviceRPCRequest.getOpDetails(); - - String heartBeatPeriod = null; - String countDownTimer = null; - - ParameterDTO countDownTimerDTO = null; - - List paramDTOList = operationDetails.getParmeters(); - for (ParameterDTO paramDTO : paramDTOList) { - if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.HEART_BEAT_PERIOD)) { - heartBeatPeriod = paramDTO.getParamValue(); - } - - if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) { - countDownTimer = paramDTO.getParamValue(); - countDownTimerDTO = paramDTO; - } - } - - try { - vesAgentServiceHelper.processHeartBeatSetRequest(deviceRPCRequest, heartBeatPeriod, - countDownTimer); - } catch (VesAgentException e) { - return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); - } - - copyHeartBeatPeriodToTimerForResponse(countDownTimerDTO, heartBeatPeriod); - return VesAgentUtils.getSuccessResponse(deviceRPCRequest); - } - - private void copyHeartBeatPeriodToTimerForResponse(ParameterDTO countDownParam, - String heartBeatPeriod) { - if (null != countDownParam && !VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) { - countDownParam.setParamValue(heartBeatPeriod); - } - } - - public DeviceRPCResponse handleGetConfigRequest(DeviceRPCRequest deviceRPCRequest) { - try { - VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest); - } catch (VesAgentException e) { - return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); - } - - vesAgentServiceHelper.processHeartBeatGetRequest(deviceRPCRequest); - return VesAgentUtils.getSuccessResponse(deviceRPCRequest); - } - - public VESNotificationResponse handleDeleteConfigRequest(VESNotification vesNotification) { - try { - VesAgentUtils.validateDelVESNotification(vesNotification); - vesAgentServiceHelper.processHeartBeatDeleteRequest(vesNotification); - } catch (VesAgentException e) { - return new VESNotificationResponse(Integer.parseInt(e.getErrorCode()), e.getMessage()); - } catch (Exception e) { - return new VESNotificationResponse(VesAgentConstants.RPC_FAILED, e.getMessage()); - } - - return new VESNotificationResponse(VesAgentConstants.RPC_SUCCESS, "success"); - } - - Event convertNotificationToVESEvent(DeviceDataEntity deviceDataEntity, int heartBeatPeriod) { - Event hbEvent = new Event(); - CommonEventHeader eventHeader = new CommonEventHeader(); - - eventHeader.setDomain("heartbeat"); - eventHeader - .setEventId("heartbeat_" + deviceDataEntity.getDeviceId() + System.currentTimeMillis()); - eventHeader.setEventName( - "heartbeat_" + deviceDataEntity.getProductClass() + "-" + config.getVendorName()); - eventHeader.setEventType("CommScope_RAN_heartbeat"); - eventHeader.setLastEpochMicrosec(System.currentTimeMillis() * 1000); - - eventHeader.setPriority("High"); - eventHeader.setSequence(0); - - if (deviceDataEntity.geteNodeBName() == null) { - eventHeader.setReportingEntityName(deviceDataEntity.getDeviceId()); - eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId()); - eventHeader.setSourceId(deviceDataEntity.getDeviceId()); - eventHeader.setSourceName(deviceDataEntity.getDeviceId()); - } else { - eventHeader.setReportingEntityName(deviceDataEntity.geteNodeBName()); - eventHeader.setSourceName(deviceDataEntity.geteNodeBName()); - eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId()); - eventHeader.setSourceId(deviceDataEntity.getDeviceId()); - } - - eventHeader.setStartEpochMicrosec(deviceDataEntity.getStartEpochMicrosec()); - eventHeader.setVersion(config.getEventVersion()); - eventHeader.setNfNamingCode(""); - eventHeader.setNfcNamingCode(""); - eventHeader.setNfVendorName(config.getVendorName()); - eventHeader.setVesEventListenerVersion(config.getVesVersion()); - hbEvent.setCommonEventHeader(eventHeader); - - HeartbeatFields heartbeatFields = new HeartbeatFields(); - heartbeatFields.setHeartbeatFieldsVersion("3.0"); - heartbeatFields.setHeartbeatInterval(heartBeatPeriod * 60); - hbEvent.setHeartbeatFields(heartbeatFields); - - return hbEvent; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.acs.common.OperationDetails; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.vesagent.VesConfiguration; +import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; +import org.commscope.tr069adapter.vesagent.exception.VesAgentException; +import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; +import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; +import org.commscope.tr069adapter.vesagent.model.Event; +import org.commscope.tr069adapter.vesagent.model.EventMessage; +import org.commscope.tr069adapter.vesagent.model.HeartbeatFields; +import org.commscope.tr069adapter.vesagent.service.VesAgentServiceHelper; +import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; +import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class HeartBeatMessageHandler { + + private static final Logger logger = LoggerFactory.getLogger(HeartBeatMessageHandler.class); + + @Autowired + VesAgentServiceHelper vesAgentServiceHelper; + + @Autowired + VesConfiguration config; + + @Autowired + HttpRequestSender sender; + + public VESNotificationResponse sendHeartBeatEvent(DeviceDataEntity deviceDataEntity, + int heartBeatPeriod) throws Exception { + Event event = convertNotificationToVESEvent(deviceDataEntity, heartBeatPeriod); + + EventMessage evMsg = new EventMessage(); + evMsg.setEvent(event); + + ObjectMapper mapper = new ObjectMapper(); + + String requestBody = mapper.writeValueAsString(evMsg); + if (requestBody.isEmpty()) { + logger.debug("VES Event body is empty"); + } + + String url = config.getPnfRegVesUrl(); + return sender.postRequest(url, requestBody); + } + + public void handleRegisterRequest(VESNotification vesNotification) { + try { + VesAgentUtils.validateVESNotification(vesNotification); + } catch (VesAgentException e) { + logger.error( + "Failed to create heartbeat timers for device on recieving bootstrap. ErrorMsg: {}", + e.getMessage()); + return; + } + + List deviceDataEntityList = vesAgentServiceHelper.findByDeviceIdAndGroup( + vesNotification.getDevnotification().getDeviceDetails().getDeviceId(), + VesAgentConstants.HEART_BEAT); + + if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) { + DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0); + String heartbeatPeriod = + deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD); + + if (!VesAgentUtils.isNullOrEmpty(heartbeatPeriod) + && !heartbeatPeriod.equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { + return; + } + } + + logger.info("Creating heartbeat records and timer using default heartbeatPeriod {} minutes.", + VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL); + + DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest(); + deviceRPCRequest.setDeviceDetails(vesNotification.getDevnotification().getDeviceDetails()); + + OperationDetails opDetails = new OperationDetails(); + + ParameterDTO heartBeatPeriodParam = new ParameterDTO(); + heartBeatPeriodParam.setParamName(VesAgentConstants.HEART_BEAT_PERIOD); + heartBeatPeriodParam.setParamValue(VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL); + + List paramList = new ArrayList<>(); + paramList.add(heartBeatPeriodParam); + + opDetails.setParmeters(paramList); + deviceRPCRequest.setOpDetails(opDetails); + + deviceRPCRequest.addContextParam(VesAgentConstants.ENODEB_NAME, + vesNotification.geteNodeBName()); + + handleSetConfigRequest(deviceRPCRequest); + + } + + public DeviceRPCResponse handleSetConfigRequest(DeviceRPCRequest deviceRPCRequest) { + try { + VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest); + } catch (VesAgentException e) { + return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); + } + + OperationDetails operationDetails = deviceRPCRequest.getOpDetails(); + + String heartBeatPeriod = null; + String countDownTimer = null; + + ParameterDTO countDownTimerDTO = null; + + List paramDTOList = operationDetails.getParmeters(); + for (ParameterDTO paramDTO : paramDTOList) { + if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.HEART_BEAT_PERIOD)) { + heartBeatPeriod = paramDTO.getParamValue(); + } + + if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) { + countDownTimer = paramDTO.getParamValue(); + countDownTimerDTO = paramDTO; + } + } + + try { + vesAgentServiceHelper.processHeartBeatSetRequest(deviceRPCRequest, heartBeatPeriod, + countDownTimer); + } catch (VesAgentException e) { + return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); + } + + copyHeartBeatPeriodToTimerForResponse(countDownTimerDTO, heartBeatPeriod); + return VesAgentUtils.getSuccessResponse(deviceRPCRequest); + } + + private void copyHeartBeatPeriodToTimerForResponse(ParameterDTO countDownParam, + String heartBeatPeriod) { + if (null != countDownParam && !VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) { + countDownParam.setParamValue(heartBeatPeriod); + } + } + + public DeviceRPCResponse handleGetConfigRequest(DeviceRPCRequest deviceRPCRequest) { + try { + VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest); + } catch (VesAgentException e) { + return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage()); + } + + vesAgentServiceHelper.processHeartBeatGetRequest(deviceRPCRequest); + return VesAgentUtils.getSuccessResponse(deviceRPCRequest); + } + + public VESNotificationResponse handleDeleteConfigRequest(VESNotification vesNotification) { + try { + VesAgentUtils.validateDelVESNotification(vesNotification); + vesAgentServiceHelper.processHeartBeatDeleteRequest(vesNotification); + } catch (VesAgentException e) { + return new VESNotificationResponse(Integer.parseInt(e.getErrorCode()), e.getMessage()); + } catch (Exception e) { + return new VESNotificationResponse(VesAgentConstants.RPC_FAILED, e.getMessage()); + } + + return new VESNotificationResponse(VesAgentConstants.RPC_SUCCESS, "success"); + } + + Event convertNotificationToVESEvent(DeviceDataEntity deviceDataEntity, int heartBeatPeriod) { + Event hbEvent = new Event(); + CommonEventHeader eventHeader = new CommonEventHeader(); + + eventHeader.setDomain("heartbeat"); + eventHeader + .setEventId("heartbeat" + deviceDataEntity.getDeviceId() + System.currentTimeMillis()); + eventHeader.setEventName( + "heartbeat_" + deviceDataEntity.getProductClass() + "-" + config.getVendorName()); + eventHeader.setEventType("CommScope_RAN_heartbeat"); + eventHeader.setLastEpochMicrosec(System.currentTimeMillis() * 1000); + + eventHeader.setPriority("High"); + eventHeader.setSequence(0); + + if (deviceDataEntity.geteNodeBName() == null) { + eventHeader.setReportingEntityName(deviceDataEntity.getDeviceId()); + eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId()); + eventHeader.setSourceId(deviceDataEntity.getDeviceId()); + eventHeader.setSourceName(deviceDataEntity.getDeviceId()); + } else { + eventHeader.setReportingEntityName(deviceDataEntity.geteNodeBName()); + eventHeader.setSourceName(deviceDataEntity.geteNodeBName()); + eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId()); + eventHeader.setSourceId(deviceDataEntity.getDeviceId()); + } + + eventHeader.setStartEpochMicrosec(deviceDataEntity.getStartEpochMicrosec()); + eventHeader.setVersion(config.getEventVersion()); + eventHeader.setNfNamingCode(""); + eventHeader.setNfcNamingCode(""); + eventHeader.setNfVendorName(config.getVendorName()); + eventHeader.setVesEventListenerVersion(config.getVesVersion()); + hbEvent.setCommonEventHeader(eventHeader); + + HeartbeatFields heartbeatFields = new HeartbeatFields(); + heartbeatFields.setHeartbeatFieldsVersion("3.0"); + heartbeatFields.setHeartbeatInterval(heartBeatPeriod * 60); + hbEvent.setHeartbeatFields(heartbeatFields); + + return hbEvent; + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/PnfRegMappingHandler.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/PnfRegMappingHandler.java index 211e897..a3500b7 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/PnfRegMappingHandler.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/controller/PnfRegMappingHandler.java @@ -1,211 +1,236 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.controller; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.commscope.tr069adapter.acs.common.DeviceInform; -import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; -import org.commscope.tr069adapter.vesagent.VesConfiguration; -import org.commscope.tr069adapter.vesagent.fault.Parser; -import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; -import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; -import org.commscope.tr069adapter.vesagent.model.Event; -import org.commscope.tr069adapter.vesagent.model.EventMessage; -import org.commscope.tr069adapter.vesagent.model.PnfRegEventAdditionalFeilds; -import org.commscope.tr069adapter.vesagent.model.PnfRegEventFields; -import org.commscope.tr069adapter.vesagent.util.EventUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class PnfRegMappingHandler { - private static final Logger logger = LoggerFactory.getLogger(PnfRegMappingHandler.class); - public static final String SSH_USERNAME = "netconf"; - public static final String SSH_PSSWORD = "netconf"; - - @Autowired - VesConfiguration config; - - @Autowired - HttpRequestSender sender; - - public VESNotificationResponse handlePnfRegNotification(VESNotification vesNoti) - throws JsonProcessingException { - Event event = convertNotificationToVESEvent(vesNoti.getDevnotification(), - vesNoti.getNetconfDetails(), vesNoti.geteNodeBName()); - if (null != event) { - EventMessage evMsg = new EventMessage(); - evMsg.setEvent(event); - - ObjectMapper mapper = new ObjectMapper(); - - String requestBody = mapper.writeValueAsString(evMsg); - if (requestBody.isEmpty()) { - logger.debug("VES Event body is empty"); - } - - String url = config.getPnfRegVesUrl(); - return sender.postRequest(url, requestBody); - } else { - return new VESNotificationResponse(-1, - "unable to prepare ves event due to insufficient data"); - } - } - - public VESNotificationResponse handlePnfRegNotificationOnRestart(VESNotification vesNoti) - throws JsonProcessingException { - Event event = convertNotificationToVESEventOnRestart(vesNoti.getNetconfDetails()); - - EventMessage evMsg = new EventMessage(); - evMsg.setEvent(event); - - ObjectMapper mapper = new ObjectMapper(); - - String requestBody = mapper.writeValueAsString(evMsg); - if (requestBody.isEmpty()) { - logger.debug("VES Event body is empty"); - } - - String url = config.getPnfRegVesUrl(); - return sender.postRequest(url, requestBody); - } - - Event convertNotificationToVESEvent(DeviceInform notification, - NetConfServerDetails netconfServerDetails, String eNodeBName) { - logger.debug("Converting Notification to VES pnfevent started"); - Parser parser = new Parser(); - - - Event regEvent = new Event(); - CommonEventHeader eventHeader = new CommonEventHeader(); - - eventHeader.setDomain("pnfRegistration"); - eventHeader.setEventId( - "PnfReg" + notification.getDeviceDetails().getDeviceId() + System.currentTimeMillis()); - eventHeader.setEventName("pnfReg_" + notification.getDeviceDetails().getProductClass() + "-" - + config.getVendorName()); - eventHeader.setEventType(config.getPnfRegEventType()); - eventHeader.setPriority("High"); - EventUtil.populateEventHeaderFields(eventHeader, notification, eNodeBName, config); - regEvent.setCommonEventHeader(eventHeader); - - PnfRegEventFields pnfRegistrationFields = - parser.parseNotificationParams(notification.getParameters()); - populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields); - pnfRegistrationFields.setModelNumber(notification.getDeviceDetails().getProductClass()); - - regEvent.setPnfRegistrationFields(pnfRegistrationFields); - logger.debug("Converting Notification to VES pnfevent completed"); - return regEvent; - } - - Event convertNotificationToVESEventOnRestart(NetConfServerDetails netconfServerDetails) { - logger.debug("Converting Notification to VES pnfevent started"); - - Event regEvent = new Event(); - CommonEventHeader eventHeader = new CommonEventHeader(); - - if (null == netconfServerDetails) { - logger.error("netconf server details as received as null {}", netconfServerDetails); - return null; - } - eventHeader.setDomain("pnfRegistration"); - eventHeader - .setEventId("PnfReg" + netconfServerDetails.getDeviceId() + System.currentTimeMillis()); - eventHeader.setEventName( - "pnfReg_" + netconfServerDetails.getDeviceId() + "-" + config.getVendorName()); - eventHeader.setEventType(config.getPnfRegEventType()); - eventHeader.setLastEpochMicrosec(System.currentTimeMillis()); - - eventHeader.setPriority("High"); - eventHeader.setSequence(0); - - if (netconfServerDetails.getEnodeBName() == null) { - eventHeader.setReportingEntityName(netconfServerDetails.getDeviceId()); - eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId()); - eventHeader.setSourceId(netconfServerDetails.getDeviceId()); - eventHeader.setSourceName(netconfServerDetails.getDeviceId()); - } else { - eventHeader.setReportingEntityName(netconfServerDetails.getEnodeBName()); - eventHeader.setSourceName(netconfServerDetails.getEnodeBName()); - - eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId()); - eventHeader.setSourceId(netconfServerDetails.getDeviceId()); - } - - eventHeader.setStartEpochMicrosec(System.currentTimeMillis()*1000); - eventHeader.setVersion(config.getEventVersion()); - eventHeader.setNfNamingCode(""); - eventHeader.setNfcNamingCode(""); - eventHeader.setNfVendorName(config.getVendorName()); - eventHeader.setVesEventListenerVersion(config.getVesVersion()); - regEvent.setCommonEventHeader(eventHeader); - PnfRegEventFields pnfRegistrationFields = new PnfRegEventFields(); - regEvent.setPnfRegistrationFields( - populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields)); - logger.debug("Converting Notification to VES pnfevent completed"); - return regEvent; - } - - private PnfRegEventFields populatePnfRegFeilds(NetConfServerDetails netconfServerDetails, - PnfRegEventFields pnfRegistrationFields) { - - pnfRegistrationFields.setSerialNumber(netconfServerDetails.getDeviceId()); - pnfRegistrationFields.setPnfRegistrationFieldsVersion(config.getPnfFeildVersion()); - pnfRegistrationFields.setMacAddress(netconfServerDetails.getDeviceId()); - pnfRegistrationFields.setVendorName(config.getVendorName()); - pnfRegistrationFields.setSoftwareVersion(netconfServerDetails.getSwVersion()); - PnfRegEventAdditionalFeilds additionalFields = new PnfRegEventAdditionalFeilds(); - - pnfRegistrationFields.setOamV4IpAddress(netconfServerDetails.getListenAddress()); - // TODO: since not supporting 1pv6 we are configuring empty value - pnfRegistrationFields.setOamV6IpAddress(""); - - pnfRegistrationFields.setManufactureDate(""); - pnfRegistrationFields.setUnitType(config.getUnitType()); - pnfRegistrationFields.setUnitFamily(config.getUnitFamily()); - pnfRegistrationFields.setLastServiceDate(new SimpleDateFormat("ddMMyyyy").format(new Date())); - additionalFields.setOamPort(netconfServerDetails.getListenPort()); - additionalFields.setProtocol("SSH"); - additionalFields.setUsername(SSH_USERNAME); - additionalFields.setPassword(SSH_PSSWORD); - additionalFields.setReconnectOnChangedSchema(Boolean.FALSE.toString()); - additionalFields.setSleepfactor("1.5"); - additionalFields.setTcpOnly(Boolean.FALSE.toString()); - additionalFields.setConnectionTimeout("20000"); - additionalFields.setMaxConnectionAttempts("100"); - additionalFields.setBetweenAttemptsTimeout("2000"); - additionalFields.setKeepaliveDelay("120"); - - pnfRegistrationFields.setAdditionalFields(additionalFields); - - return pnfRegistrationFields; - - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import org.commscope.tr069adapter.acs.common.DeviceInform; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.model.NetConfServerDetails; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.mapper.model.VESNotificationResponse; +import org.commscope.tr069adapter.vesagent.VesConfiguration; +import org.commscope.tr069adapter.vesagent.fault.Parser; +import org.commscope.tr069adapter.vesagent.http.HttpRequestSender; +import org.commscope.tr069adapter.vesagent.model.CommonEventHeader; +import org.commscope.tr069adapter.vesagent.model.Event; +import org.commscope.tr069adapter.vesagent.model.EventMessage; +import org.commscope.tr069adapter.vesagent.model.PnfRegEventAdditionalFeilds; +import org.commscope.tr069adapter.vesagent.model.PnfRegEventFields; +import org.commscope.tr069adapter.vesagent.util.EventUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PnfRegMappingHandler { + private static final Logger logger = LoggerFactory.getLogger(PnfRegMappingHandler.class); + public static final String SSH_USERNAME = "netconf"; + public static final String SSH_PSSWORD = "netconf"; + + @Autowired + VesConfiguration config; + + @Autowired + HttpRequestSender sender; + + public VESNotificationResponse handlePnfRegNotification(VESNotification vesNoti) + throws JsonProcessingException { + Event event = convertNotificationToVESEvent(vesNoti.getDevnotification(), + vesNoti.getNetconfDetails(), vesNoti.geteNodeBName(), vesNoti.getNetconfParameters()); + if (null != event) { + EventMessage evMsg = new EventMessage(); + evMsg.setEvent(event); + + ObjectMapper mapper = new ObjectMapper(); + + String requestBody = mapper.writeValueAsString(evMsg); + if (requestBody.isEmpty()) { + logger.debug("VES Event body is empty"); + } + logger.debug("VES message for PnfRegistration : {}", requestBody); + String url = config.getPnfRegVesUrl(); + return sender.postRequest(url, requestBody); + } else { + return new VESNotificationResponse(-1, + "unable to prepare ves event due to insufficient data"); + } + } + + public VESNotificationResponse handlePnfRegNotificationOnRestart(VESNotification vesNoti) + throws JsonProcessingException { + Event event = convertNotificationToVESEventOnRestart(vesNoti.getNetconfDetails()); + + EventMessage evMsg = new EventMessage(); + evMsg.setEvent(event); + + ObjectMapper mapper = new ObjectMapper(); + + String requestBody = mapper.writeValueAsString(evMsg); + if (requestBody.isEmpty()) { + logger.debug("VES Event body is empty"); + } + + String url = config.getPnfRegVesUrl(); + return sender.postRequest(url, requestBody); + } + + Event convertNotificationToVESEvent(DeviceInform notification, + NetConfServerDetails netconfServerDetails, String eNodeBName, + List netconfParameters) { + logger.debug("Converting Notification to VES pnfevent started"); + Parser parser = new Parser(); + + + Event regEvent = new Event(); + CommonEventHeader eventHeader = new CommonEventHeader(); + + eventHeader.setDomain("pnfRegistration"); + eventHeader.setEventId( + "PnfReg" + notification.getDeviceDetails().getDeviceId() + System.currentTimeMillis()); + eventHeader.setEventName("pnfReg_" + notification.getDeviceDetails().getProductClass() + "-" + + config.getVendorName()); + eventHeader.setEventType(config.getPnfRegEventType()); + eventHeader.setPriority("High"); + EventUtil.populateEventHeaderFields(eventHeader, notification, eNodeBName, config); + regEvent.setCommonEventHeader(eventHeader); + + PnfRegEventFields pnfRegistrationFields = + parser.parseNotificationParams(notification.getParameters()); + populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields, netconfParameters); + pnfRegistrationFields.setModelNumber(notification.getDeviceDetails().getProductClass()); + + regEvent.setPnfRegistrationFields(pnfRegistrationFields); + logger.debug("Converting Notification to VES pnfevent completed"); + return regEvent; + } + + Event convertNotificationToVESEventOnRestart(NetConfServerDetails netconfServerDetails) { + logger.debug("Converting Notification to VES pnfevent started"); + + Event regEvent = new Event(); + CommonEventHeader eventHeader = new CommonEventHeader(); + + if (null == netconfServerDetails) { + logger.error("netconf server details as received as null"); + return null; + } + eventHeader.setDomain("pnfRegistration"); + eventHeader + .setEventId("PnfReg" + netconfServerDetails.getDeviceId() + System.currentTimeMillis()); + eventHeader.setEventName( + "pnfReg_" + netconfServerDetails.getDeviceId() + "-" + config.getVendorName()); + eventHeader.setEventType(config.getPnfRegEventType()); + eventHeader.setLastEpochMicrosec(System.currentTimeMillis()); + + eventHeader.setPriority("High"); + eventHeader.setSequence(0); + + if (netconfServerDetails.getEnodeBName() == null) { + eventHeader.setReportingEntityName(netconfServerDetails.getDeviceId()); + eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId()); + eventHeader.setSourceId(netconfServerDetails.getDeviceId()); + eventHeader.setSourceName(netconfServerDetails.getDeviceId()); + } else { + eventHeader.setReportingEntityName(netconfServerDetails.getEnodeBName()); + eventHeader.setSourceName(netconfServerDetails.getEnodeBName()); + + eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId()); + eventHeader.setSourceId(netconfServerDetails.getDeviceId()); + } + + eventHeader.setStartEpochMicrosec(System.currentTimeMillis() * 1000); + eventHeader.setVersion(config.getEventVersion()); + eventHeader.setNfNamingCode(""); + eventHeader.setNfcNamingCode(""); + eventHeader.setNfVendorName(config.getVendorName()); + eventHeader.setVesEventListenerVersion(config.getVesVersion()); + regEvent.setCommonEventHeader(eventHeader); + PnfRegEventFields pnfRegistrationFields = new PnfRegEventFields(); + regEvent.setPnfRegistrationFields( + populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields, new ArrayList<>())); + logger.debug("Converting Notification to VES pnfevent completed"); + return regEvent; + } + + private PnfRegEventFields populatePnfRegFeilds(NetConfServerDetails netconfServerDetails, + PnfRegEventFields pnfRegistrationFields, List netconfParameters) { + + pnfRegistrationFields.setSerialNumber(netconfServerDetails.getDeviceId()); + pnfRegistrationFields.setPnfRegistrationFieldsVersion(config.getPnfFeildVersion()); + pnfRegistrationFields.setMacAddress(netconfServerDetails.getDeviceId()); + pnfRegistrationFields.setVendorName(config.getVendorName()); + pnfRegistrationFields.setSoftwareVersion(netconfServerDetails.getSwVersion()); + + pnfRegistrationFields.setOamV4IpAddress(netconfServerDetails.getListenAddress()); + // TODO: since not supporting 1pv6 we are configuring empty value + pnfRegistrationFields.setOamV6IpAddress(""); + + pnfRegistrationFields.setManufactureDate(""); + pnfRegistrationFields.setUnitType(config.getUnitType()); + pnfRegistrationFields.setUnitFamily(config.getUnitFamily()); + pnfRegistrationFields.setLastServiceDate(new SimpleDateFormat("ddMMyyyy").format(new Date())); + + // Add additional attributes and device parameters to the VES message in additionalFields + HashMap additionalFieldsMap = new HashMap<>(); + PnfRegEventAdditionalFeilds additionalFields = new PnfRegEventAdditionalFeilds(); + additionalFields.setOamPort(netconfServerDetails.getListenPort()); + additionalFields.setProtocol("SSH"); + additionalFields.setUsername(SSH_USERNAME); + additionalFields.setPassword(SSH_PSSWORD); + additionalFields.setReconnectOnChangedSchema(Boolean.FALSE.toString()); + additionalFields.setSleepfactor("1.5"); + additionalFields.setTcpOnly(Boolean.FALSE.toString()); + additionalFields.setConnectionTimeout("20000"); + additionalFields.setMaxConnectionAttempts("100"); + additionalFields.setBetweenAttemptsTimeout("2000"); + additionalFields.setKeepaliveDelay("120"); + + ObjectMapper mapper = new ObjectMapper(); + String additionalFieldsString; + try { + additionalFieldsString = mapper.writeValueAsString(additionalFields); + HashMap pnfAdditionalFieldsMap = new HashMap<>(); + pnfAdditionalFieldsMap = + mapper.readValue(additionalFieldsString, pnfAdditionalFieldsMap.getClass()); + additionalFieldsMap.putAll(pnfAdditionalFieldsMap); + } catch (JsonProcessingException e) { + logger.error("Failed to add pnf Reg Additional fields {}", e.getMessage()); + } + + if (null != netconfParameters) { + for (ParameterDTO param : netconfParameters) { + additionalFieldsMap.put(param.getParamName(), param.getParamValue()); + } + } + + pnfRegistrationFields.setAdditionalFields(additionalFieldsMap); + return pnfRegistrationFields; + + } + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/entity/DeviceDataEntity.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/entity/DeviceDataEntity.java index 07b50a7..63af6df 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/entity/DeviceDataEntity.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/entity/DeviceDataEntity.java @@ -16,117 +16,117 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.entity; - -import com.google.gson.Gson; - -import java.util.Date; -import java.util.Map; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; - -@Entity -@Table(name = "VES_DEVICE_DATA", - uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID", "ATTR_GROUP"})) -public class DeviceDataEntity { - - @Id - @Column(name = "ID") - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(name = "DEVICE_ID", length = 30) - private String deviceId; - - @Column(name = "ENODEB_NAME", length = 100) - private String eNodeBName; - - @Column(name = "OUI", length = 30) - private String oui; - - @Column(name = "PRODUCT_CLASS", length = 100) - private String productClass; - - @Column(name = "ATTR_JSON", length = 4000) - private String attrJson; - - @Column(name = "ATTR_GROUP", length = 255) - private String attrGroup; - - @Column(name = "LAST_UPDATED_TIME") - private Date lastUpdateTime = new Date(); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getDeviceId() { - return deviceId; - } - - public void setDeviceId(String deviceId) { - this.deviceId = deviceId; - } - - public String geteNodeBName() { - return eNodeBName; - } - - public void seteNodeBName(String eNodeBName) { - this.eNodeBName = eNodeBName; - } - - public String getOui() { - return oui; - } - - public void setOui(String oui) { - this.oui = oui; - } - - public String getProductClass() { - return productClass; - } - - public void setProductClass(String productClass) { - this.productClass = productClass; - } - - public String getAttrJson() { - return attrJson; - } - - public void setAttrJson(String attrJson) { - this.attrJson = attrJson; - } - - public String getAttrGroup() { - return attrGroup; - } - - public void setAttrGroup(String attrGroup) { - this.attrGroup = attrGroup; - } - - public Date getLastUpdateTime() { - return lastUpdateTime; - } - - public void setLastUpdateTime(Date lastUpdateTime) { - this.lastUpdateTime = lastUpdateTime; - } - +package org.commscope.tr069adapter.vesagent.entity; + +import com.google.gson.Gson; + +import java.util.Date; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.persistence.UniqueConstraint; + +@Entity +@Table(name = "VES_DEVICE_DATA", + uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID", "ATTR_GROUP"})) +public class DeviceDataEntity { + + @Id + @Column(name = "ID") + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "DEVICE_ID", length = 30) + private String deviceId; + + @Column(name = "ENODEB_NAME", length = 100) + private String eNodeBName; + + @Column(name = "OUI", length = 30) + private String oui; + + @Column(name = "PRODUCT_CLASS", length = 100) + private String productClass; + + @Column(name = "ATTR_JSON", length = 4000) + private String attrJson; + + @Column(name = "ATTR_GROUP", length = 255) + private String attrGroup; + + @Column(name = "LAST_UPDATED_TIME") + private Date lastUpdateTime = new Date(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String geteNodeBName() { + return eNodeBName; + } + + public void seteNodeBName(String eNodeBName) { + this.eNodeBName = eNodeBName; + } + + public String getOui() { + return oui; + } + + public void setOui(String oui) { + this.oui = oui; + } + + public String getProductClass() { + return productClass; + } + + public void setProductClass(String productClass) { + this.productClass = productClass; + } + + public String getAttrJson() { + return attrJson; + } + + public void setAttrJson(String attrJson) { + this.attrJson = attrJson; + } + + public String getAttrGroup() { + return attrGroup; + } + + public void setAttrGroup(String attrGroup) { + this.attrGroup = attrGroup; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + @Transient private Long startEpochMicrosec; @@ -136,24 +136,24 @@ public class DeviceDataEntity { public void setStartEpochMicrosec(Long startEpochMicrosec) { this.startEpochMicrosec = startEpochMicrosec; - } - - @Transient - public void setAttributesMap(Map attributesMap) { - if (null == attributesMap || attributesMap.isEmpty()) { - return; - } - - this.attrJson = new Gson().toJson(attributesMap); - - } - - @Transient - public Map getAttributesMap() { - Map attributesMap = null; - if (null != this.attrJson && !this.attrJson.isEmpty()) { - attributesMap = new Gson().fromJson(this.attrJson, Map.class); - } - return attributesMap; - } -} + } + + @Transient + public void setAttributesMap(Map attributesMap) { + if (null == attributesMap || attributesMap.isEmpty()) { + return; + } + + this.attrJson = new Gson().toJson(attributesMap); + + } + + @Transient + public Map getAttributesMap() { + Map attributesMap = null; + if (null != this.attrJson && !this.attrJson.isEmpty()) { + attributesMap = new Gson().fromJson(this.attrJson, Map.class); + } + return attributesMap; + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/exception/VesAgentException.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/exception/VesAgentException.java index 77afc65..f5cb14c 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/exception/VesAgentException.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/exception/VesAgentException.java @@ -16,84 +16,81 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.exception; - -/** - * - * @version 1.0 - * @since May 21, 2020 - * @author Prashant - */ -public class VesAgentException extends Exception { - private static final long serialVersionUID = -3742697051389101875L; - - private static final String ERRORMSG_PREFIX = "ves-agent"; - - private String[] arguments; - - private String errorCode; - private String message; - - // index of the error occurred in the given list or in the given file - protected int errorIndex = -1; - - - /** - * Constructs a VesOperationException with no detail message. - * - */ - public VesAgentException() { - super(); - } - - /** - * Constructs a VesOperationException with the specified detail message. - * - * @param s as the details message - */ - public VesAgentException(String s) { - super(s); - } - - public VesAgentException(String... args) { - super(); - arguments = args; - setErrorMessage(getErrorMessage()); - } - - public VesAgentException(String errorCode, String errorMsg) { - super(); - this.errorCode = errorCode; - setErrorMessage(getErrorMessage()); - } - - public int getErrorIndex() { - return errorIndex; - } - - public void setErrorIndex(int errorIndex) { - this.errorIndex = errorIndex; - } - - - public String getMessage() { - return message; - } - - private String getErrorMessage() { - String key = ERRORMSG_PREFIX + "."; - return key; - } - - private void setErrorMessage(String message) { - this.message = message; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } -} +package org.commscope.tr069adapter.vesagent.exception; + +/** + * + * @version 1.0 + * @since May 21, 2020 + * @author Prashant + */ +public class VesAgentException extends Exception { + private static final long serialVersionUID = -3742697051389101875L; + + private static final String ERRORMSG_PREFIX = "ves-agent"; + + + private String errorCode; + private String message; + + // index of the error occurred in the given list or in the given file + protected int errorIndex = -1; + + + /** + * Constructs a VesOperationException with no detail message. + * + */ + public VesAgentException() { + super(); + } + + /** + * Constructs a VesOperationException with the specified detail message. + * + * @param s as the details message + */ + public VesAgentException(String s) { + super(s); + } + + public VesAgentException(String... args) { + super(); + setErrorMessage(getErrorMessage()); + } + + public VesAgentException(String errorCode, String errorMsg) { + super(); + this.errorCode = errorCode; + setErrorMessage(getErrorMessage()); + } + + public int getErrorIndex() { + return errorIndex; + } + + public void setErrorIndex(int errorIndex) { + this.errorIndex = errorIndex; + } + + @Override + public String getMessage() { + return message; + } + + private String getErrorMessage() { + return ERRORMSG_PREFIX + "."; + } + + private void setErrorMessage(String message) { + this.message = message; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/mapper/MapperRequestSender.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/mapper/MapperRequestSender.java index 37d8729..fa66da9 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/mapper/MapperRequestSender.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/mapper/MapperRequestSender.java @@ -16,49 +16,44 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.mapper; - -import java.util.concurrent.Future; - -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; -import org.commscope.tr069adapter.vesagent.VesConfiguration; -import org.commscope.tr069adapter.vesagent.async.WaitForNotifications; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.scheduling.annotation.AsyncResult; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -@Component -// @EnableAsync -public class MapperRequestSender { - private static final Logger LOG = LoggerFactory.getLogger(MapperRequestSender.class); - private RestTemplate restTemplate = new RestTemplate(); - - @Autowired - VesConfiguration config; - - @Autowired - WaitForNotifications waitForNotifications; - - // public DeviceRPCResponse sendRequest(DeviceRPCRequest deviceRPCRequest) { - // return restTemplate.postForObject(config.getMapperPath(), deviceRPCRequest, - // DeviceRPCResponse.class); - // } - - @Async("threadPoolTaskExecutor2") - public Future sendRequest(DeviceRPCRequest deviceRPCRequest) { - LOG.info("Sending device connectivity request to ACS for device {}", - deviceRPCRequest.getDeviceDetails().getDeviceId()); - DeviceRPCResponse response = restTemplate.postForObject(config.getMapperPath(), - deviceRPCRequest, DeviceRPCResponse.class); - - waitForNotifications.notifyResult(response); - - return new AsyncResult<>(response); - } - -} +package org.commscope.tr069adapter.vesagent.mapper; + +import java.util.concurrent.Future; + +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.DeviceRPCResponse; +import org.commscope.tr069adapter.vesagent.VesConfiguration; +import org.commscope.tr069adapter.vesagent.async.WaitForNotifications; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.AsyncResult; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +// @EnableAsync +public class MapperRequestSender { + private static final Logger LOG = LoggerFactory.getLogger(MapperRequestSender.class); + private RestTemplate restTemplate = new RestTemplate(); + + @Autowired + VesConfiguration config; + + @Autowired + WaitForNotifications waitForNotifications; + + @Async("threadPoolTaskExecutor2") + public Future sendRequest(DeviceRPCRequest deviceRPCRequest) { + LOG.info("Sending device connectivity request to ACS for device {}", + deviceRPCRequest.getDeviceDetails().getDeviceId()); + DeviceRPCResponse response = restTemplate.postForObject(config.getMapperPath(), + deviceRPCRequest, DeviceRPCResponse.class); + + waitForNotifications.notifyResult(response); + + return new AsyncResult<>(response); + } + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/CommonEventHeader.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/CommonEventHeader.java index c1d0750..f8b6a85 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/CommonEventHeader.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/CommonEventHeader.java @@ -1,213 +1,226 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class CommonEventHeader implements Serializable { - @JsonProperty("version") - private String version; - @JsonProperty("vesEventListenerVersion") - private String vesEventListenerVersion; - @JsonProperty("domain") - private String domain; - @JsonProperty("eventName") - private String eventName; - @JsonProperty("eventType") - private String eventType; - @JsonProperty("eventId") - private String eventId; - @JsonProperty("sequence") - private Integer sequence; - @JsonProperty("priority") - private String priority; - @JsonProperty("reportingEntityId") - private String reportingEntityId; - @JsonProperty("reportingEntityName") - private String reportingEntityName; - @JsonProperty("sourceId") - private String sourceId; - @JsonProperty("sourceName") - private String sourceName; - @JsonProperty("nfVendorName") - private String nfVendorName; - @JsonProperty("nfNamingCode") - private String nfNamingCode; - @JsonProperty("nfcNamingCode") - private String nfcNamingCode; - @JsonProperty("startEpochMicrosec") - private long startEpochMicrosec; - @JsonProperty("lastEpochMicrosec") - private long lastEpochMicrosec; - @JsonProperty("timeZoneOffset") - private String timeZoneOffset; - - public String getEventId() { - return eventId; - } - - public void setEventId(String eventId) { - this.eventId = eventId; - } - - public String getEventName() { - return eventName; - } - - public void setEventName(String eventName) { - this.eventName = eventName; - } - - public String getDomain() { - return domain; - } - - public void setDomain(String domain) { - this.domain = domain; - } - - public String getSourceName() { - return sourceName; - } - - public void setSourceName(String sourceName) { - this.sourceName = sourceName; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public int getSequence() { - return sequence; - } - - public void setSequence(int sequence) { - this.sequence = sequence; - } - - public String getVesEventListenerVersion() { - return vesEventListenerVersion; - } - - public void setVesEventListenerVersion(String vesEventListenerVersion) { - this.vesEventListenerVersion = vesEventListenerVersion; - } - - public long getStartEpochMicrosec() { - return startEpochMicrosec; - } - - public void setStartEpochMicrosec(long startEpochMicrosec) { - this.startEpochMicrosec = startEpochMicrosec; - } - - public long getLastEpochMicrosec() { - return lastEpochMicrosec; - } - - public void setLastEpochMicrosec(long lastEpochMicrosec) { - this.lastEpochMicrosec = lastEpochMicrosec; - } - - public String getReportingEntityName() { - return reportingEntityName; - } - - public void setReportingEntityName(String reportingEntityName) { - this.reportingEntityName = reportingEntityName; - } - - public void setSequence(Integer sequence) { - this.sequence = sequence; - } - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public String getNfNamingCode() { - return nfNamingCode; - } - - public void setNfNamingCode(String nfNamingCode) { - this.nfNamingCode = nfNamingCode; - } - - public String getReportingEntityId() { - return reportingEntityId; - } - - public void setReportingEntityId(String reportingEntityId) { - this.reportingEntityId = reportingEntityId; - } - - public String getSourceId() { - return sourceId; - } - - public void setSourceId(String sourceId) { - this.sourceId = sourceId; - } - - public String getNfVendorName() { - return nfVendorName; - } - - public void setNfVendorName(String nfVendorName) { - this.nfVendorName = nfVendorName; - } - - public String getTimeZoneOffset() { - return timeZoneOffset; - } - - public void setTimeZoneOffset(String timeZoneOffset) { - this.timeZoneOffset = timeZoneOffset; - } - - public String getNfcNamingCode() { - return nfcNamingCode; - } - - public void setNfcNamingCode(String nfcNamingCode) { - this.nfcNamingCode = nfcNamingCode; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CommonEventHeader implements Serializable { + @JsonProperty("version") + private String version; + @JsonProperty("vesEventListenerVersion") + private String vesEventListenerVersion; + @JsonProperty("domain") + private String domain; + @JsonProperty("eventName") + private String eventName; + @JsonProperty("eventType") + private String eventType; + @JsonProperty("eventId") + private String eventId; + @JsonProperty("sequence") + private Integer sequence; + @JsonProperty("priority") + private String priority; + @JsonProperty("reportingEntityId") + private String reportingEntityId; + @JsonProperty("reportingEntityName") + private String reportingEntityName; + @JsonProperty("sourceId") + private String sourceId; + @JsonProperty("sourceName") + private String sourceName; + @JsonProperty("nfVendorName") + private String nfVendorName; + @JsonProperty("nfNamingCode") + private String nfNamingCode; + @JsonProperty("nfcNamingCode") + private String nfcNamingCode; + @JsonProperty("startEpochMicrosec") + private long startEpochMicrosec; + @JsonProperty("lastEpochMicrosec") + private long lastEpochMicrosec; + @JsonProperty("timeZoneOffset") + private String timeZoneOffset; + + public String getEventId() { + return eventId; + } + + public void setEventId(String eventId) { + this.eventId = eventId; + } + + public String getEventName() { + return eventName; + } + + public void setEventName(String eventName) { + this.eventName = eventName; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getPriority() { + return priority; + } + + public void setPriority(String priority) { + this.priority = priority; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public int getSequence() { + return sequence; + } + + public void setSequence(int sequence) { + this.sequence = sequence; + } + + public String getVesEventListenerVersion() { + return vesEventListenerVersion; + } + + public void setVesEventListenerVersion(String vesEventListenerVersion) { + this.vesEventListenerVersion = vesEventListenerVersion; + } + + public long getStartEpochMicrosec() { + return startEpochMicrosec; + } + + public void setStartEpochMicrosec(long startEpochMicrosec) { + this.startEpochMicrosec = startEpochMicrosec; + } + + public long getLastEpochMicrosec() { + return lastEpochMicrosec; + } + + public void setLastEpochMicrosec(long lastEpochMicrosec) { + this.lastEpochMicrosec = lastEpochMicrosec; + } + + public String getReportingEntityName() { + return reportingEntityName; + } + + public void setReportingEntityName(String reportingEntityName) { + this.reportingEntityName = reportingEntityName; + } + + public void setSequence(Integer sequence) { + this.sequence = sequence; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String getNfNamingCode() { + return nfNamingCode; + } + + public void setNfNamingCode(String nfNamingCode) { + this.nfNamingCode = nfNamingCode; + } + + public String getReportingEntityId() { + return reportingEntityId; + } + + public void setReportingEntityId(String reportingEntityId) { + this.reportingEntityId = reportingEntityId; + } + + public String getSourceId() { + return sourceId; + } + + public void setSourceId(String sourceId) { + this.sourceId = sourceId; + } + + public String getNfVendorName() { + return nfVendorName; + } + + public void setNfVendorName(String nfVendorName) { + this.nfVendorName = nfVendorName; + } + + public String getTimeZoneOffset() { + return timeZoneOffset; + } + + public void setTimeZoneOffset(String timeZoneOffset) { + this.timeZoneOffset = timeZoneOffset; + } + + public String getNfcNamingCode() { + return nfcNamingCode; + } + + public void setNfcNamingCode(String nfcNamingCode) { + this.nfcNamingCode = nfcNamingCode; + } + + @Override + public String toString() { + return "CommonEventHeader [version=" + version + ", vesEventListenerVersion=" + + vesEventListenerVersion + ", domain=" + domain + ", eventName=" + eventName + + ", eventType=" + eventType + ", eventId=" + eventId + ", sequence=" + sequence + + ", priority=" + priority + ", reportingEntityId=" + reportingEntityId + + ", reportingEntityName=" + reportingEntityName + ", sourceId=" + sourceId + + ", sourceName=" + sourceName + ", nfVendorName=" + nfVendorName + ", nfNamingCode=" + + nfNamingCode + ", nfcNamingCode=" + nfcNamingCode + ", startEpochMicrosec=" + + startEpochMicrosec + ", lastEpochMicrosec=" + lastEpochMicrosec + ", timeZoneOffset=" + + timeZoneOffset + "]"; + } + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/EventMessage.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/EventMessage.java index d9f83e6..e5a213f 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/EventMessage.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/EventMessage.java @@ -1,41 +1,47 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.model; - -public class EventMessage { - - private Event event; - - public EventMessage() { - super(); - } - - public EventMessage(Event event) { - this.event = event; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.model; + +public class EventMessage { + + private Event event; + + public EventMessage() { + super(); + } + + public EventMessage(Event event) { + this.event = event; + } + + public Event getEvent() { + return event; + } + + public void setEvent(Event event) { + this.event = event; + } + + @Override + public String toString() { + return "EventMessage [event=" + event + "]"; + } + + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/HeartbeatFields.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/HeartbeatFields.java index e491fa7..01e39e2 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/HeartbeatFields.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/HeartbeatFields.java @@ -16,28 +16,33 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.model; - -import com.fasterxml.jackson.annotation.JsonInclude; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class HeartbeatFields { - public String heartbeatFieldsVersion; - public int heartbeatInterval; - - public String getHeartbeatFieldsVersion() { - return heartbeatFieldsVersion; - } - - public void setHeartbeatFieldsVersion(String heartbeatFieldsVersion) { - this.heartbeatFieldsVersion = heartbeatFieldsVersion; - } - - public int getHeartbeatInterval() { - return heartbeatInterval; - } - - public void setHeartbeatInterval(int heartbeatInterval) { - this.heartbeatInterval = heartbeatInterval; - } -} +package org.commscope.tr069adapter.vesagent.model; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class HeartbeatFields implements Serializable { + + private static final long serialVersionUID = -4654513718975538805L; + + private String heartbeatFieldsVersion; + private int heartbeatInterval; + + public String getHeartbeatFieldsVersion() { + return heartbeatFieldsVersion; + } + + public void setHeartbeatFieldsVersion(String heartbeatFieldsVersion) { + this.heartbeatFieldsVersion = heartbeatFieldsVersion; + } + + public int getHeartbeatInterval() { + return heartbeatInterval; + } + + public void setHeartbeatInterval(int heartbeatInterval) { + this.heartbeatInterval = heartbeatInterval; + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventAdditionalFeilds.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventAdditionalFeilds.java index 95b871a..c6a98b9 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventAdditionalFeilds.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventAdditionalFeilds.java @@ -1,132 +1,143 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PnfRegEventAdditionalFeilds implements Serializable { - /** - * - */ - private static final long serialVersionUID = 5368863118681551950L; - private String oamPort; - private String protocol; - private String username; - private String password; - private String reconnectOnChangedSchema; - @JsonProperty("sleep-factor") - private String sleepfactor; - private String tcpOnly; - private String connectionTimeout; - private String maxConnectionAttempts; - private String betweenAttemptsTimeout; - private String keepaliveDelay; - - public String getOamPort() { - return oamPort; - } - - public void setOamPort(String oamPort) { - this.oamPort = oamPort; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getReconnectOnChangedSchema() { - return reconnectOnChangedSchema; - } - - public void setReconnectOnChangedSchema(String reconnectOnChangedSchema) { - this.reconnectOnChangedSchema = reconnectOnChangedSchema; - } - - public String getSleepfactor() { - return sleepfactor; - } - - public void setSleepfactor(String sleepfactor) { - this.sleepfactor = sleepfactor; - } - - public String getTcpOnly() { - return tcpOnly; - } - - public void setTcpOnly(String tcpOnly) { - this.tcpOnly = tcpOnly; - } - - public String getConnectionTimeout() { - return connectionTimeout; - } - - public void setConnectionTimeout(String connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - public String getMaxConnectionAttempts() { - return maxConnectionAttempts; - } - - public void setMaxConnectionAttempts(String maxConnectionAttempts) { - this.maxConnectionAttempts = maxConnectionAttempts; - } - - public String getBetweenAttemptsTimeout() { - return betweenAttemptsTimeout; - } - - public void setBetweenAttemptsTimeout(String betweenAttemptsTimeout) { - this.betweenAttemptsTimeout = betweenAttemptsTimeout; - } - - public String getKeepaliveDelay() { - return keepaliveDelay; - } - - public void setKeepaliveDelay(String keepaliveDelay) { - this.keepaliveDelay = keepaliveDelay; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PnfRegEventAdditionalFeilds implements Serializable { + /** + * + */ + private static final long serialVersionUID = 5368863118681551950L; + private String oamPort; + private String protocol; + private String username; + private String password; + private String reconnectOnChangedSchema; + @JsonProperty("sleep-factor") + private String sleepfactor; + private String tcpOnly; + private String connectionTimeout; + private String maxConnectionAttempts; + private String betweenAttemptsTimeout; + private String keepaliveDelay; + + public String getOamPort() { + return oamPort; + } + + public void setOamPort(String oamPort) { + this.oamPort = oamPort; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getReconnectOnChangedSchema() { + return reconnectOnChangedSchema; + } + + public void setReconnectOnChangedSchema(String reconnectOnChangedSchema) { + this.reconnectOnChangedSchema = reconnectOnChangedSchema; + } + + public String getSleepfactor() { + return sleepfactor; + } + + public void setSleepfactor(String sleepfactor) { + this.sleepfactor = sleepfactor; + } + + public String getTcpOnly() { + return tcpOnly; + } + + public void setTcpOnly(String tcpOnly) { + this.tcpOnly = tcpOnly; + } + + public String getConnectionTimeout() { + return connectionTimeout; + } + + public void setConnectionTimeout(String connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + public String getMaxConnectionAttempts() { + return maxConnectionAttempts; + } + + public void setMaxConnectionAttempts(String maxConnectionAttempts) { + this.maxConnectionAttempts = maxConnectionAttempts; + } + + public String getBetweenAttemptsTimeout() { + return betweenAttemptsTimeout; + } + + public void setBetweenAttemptsTimeout(String betweenAttemptsTimeout) { + this.betweenAttemptsTimeout = betweenAttemptsTimeout; + } + + public String getKeepaliveDelay() { + return keepaliveDelay; + } + + public void setKeepaliveDelay(String keepaliveDelay) { + this.keepaliveDelay = keepaliveDelay; + } + + @Override + public String toString() { + return "PnfRegEventAdditionalFeilds [oamPort=" + oamPort + ", protocol=" + protocol + + ", username=" + username + ", password=" + password + ", reconnectOnChangedSchema=" + + reconnectOnChangedSchema + ", sleepfactor=" + sleepfactor + ", tcpOnly=" + tcpOnly + + ", connectionTimeout=" + connectionTimeout + ", maxConnectionAttempts=" + + maxConnectionAttempts + ", betweenAttemptsTimeout=" + betweenAttemptsTimeout + + ", keepaliveDelay=" + keepaliveDelay + "]"; + } + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventFields.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventFields.java index 4d98ab3..a045d52 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventFields.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/model/PnfRegEventFields.java @@ -1,150 +1,162 @@ -/* - * ============LICENSE_START======================================================================== - * ONAP : tr-069-adapter - * ================================================================================================= - * Copyright (C) 2020 CommScope Inc Intellectual Property. - * ================================================================================================= - * This tr-069-adapter software file is distributed by CommScope Inc 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 - * - * This file 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.commscope.tr069adapter.vesagent.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.Serializable; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PnfRegEventFields implements Serializable { - /** - * - */ - private static final long serialVersionUID = 2183003488649290852L; - private String pnfRegistrationFieldsVersion; - private String serialNumber; - private String vendorName; - private String oamV4IpAddress; - private String oamV6IpAddress; - private String softwareVersion; - private String unitType; - private String unitFamily; - private String modelNumber; - private String manufactureDate; - private String macAddress; - private String lastServiceDate; - @JsonProperty("additionalFields") - private PnfRegEventAdditionalFeilds additionalFields = null; - - public String getPnfRegistrationFieldsVersion() { - return pnfRegistrationFieldsVersion; - } - - public void setPnfRegistrationFieldsVersion(String pnfRegistrationFieldsVersion) { - this.pnfRegistrationFieldsVersion = pnfRegistrationFieldsVersion; - } - - public String getSerialNumber() { - return serialNumber; - } - - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } - - public String getVendorName() { - return vendorName; - } - - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } - - public String getOamV4IpAddress() { - return oamV4IpAddress; - } - - public void setOamV4IpAddress(String oamV4IpAddress) { - this.oamV4IpAddress = oamV4IpAddress; - } - - public String getOamV6IpAddress() { - return oamV6IpAddress; - } - - public void setOamV6IpAddress(String oamV6IpAddress) { - this.oamV6IpAddress = oamV6IpAddress; - } - - public String getSoftwareVersion() { - return softwareVersion; - } - - public void setSoftwareVersion(String softwareVersion) { - this.softwareVersion = softwareVersion; - } - - public String getUnitType() { - return unitType; - } - - public void setUnitType(String unitType) { - this.unitType = unitType; - } - - public String getUnitFamily() { - return unitFamily; - } - - public void setUnitFamily(String unitFamily) { - this.unitFamily = unitFamily; - } - - public String getModelNumber() { - return modelNumber; - } - - public void setModelNumber(String modelNumber) { - this.modelNumber = modelNumber; - } - - public String getManufactureDate() { - return manufactureDate; - } - - public void setManufactureDate(String manufactureDate) { - this.manufactureDate = manufactureDate; - } - - public String getMacAddress() { - return macAddress; - } - - public void setMacAddress(String macAddress) { - this.macAddress = macAddress; - } - - public String getLastServiceDate() { - return lastServiceDate; - } - - public void setLastServiceDate(String lastServiceDate) { - this.lastServiceDate = lastServiceDate; - } - - public PnfRegEventAdditionalFeilds getAdditionalFields() { - return additionalFields; - } - - public void setAdditionalFields(PnfRegEventAdditionalFeilds additionalFields) { - this.additionalFields = additionalFields; - } -} +/* + * ============LICENSE_START======================================================================== + * ONAP : tr-069-adapter + * ================================================================================================= + * Copyright (C) 2020 CommScope Inc Intellectual Property. + * ================================================================================================= + * This tr-069-adapter software file is distributed by CommScope Inc 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 + * + * This file 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.commscope.tr069adapter.vesagent.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PnfRegEventFields implements Serializable { + /** + * + */ + private static final long serialVersionUID = 2183003488649290852L; + private String pnfRegistrationFieldsVersion; + private String serialNumber; + private String vendorName; + private String oamV4IpAddress; + private String oamV6IpAddress; + private String softwareVersion; + private String unitType; + private String unitFamily; + private String modelNumber; + private String manufactureDate; + private String macAddress; + private String lastServiceDate; + @JsonProperty("additionalFields") + private Serializable additionalFields = null; + + public String getPnfRegistrationFieldsVersion() { + return pnfRegistrationFieldsVersion; + } + + public void setPnfRegistrationFieldsVersion(String pnfRegistrationFieldsVersion) { + this.pnfRegistrationFieldsVersion = pnfRegistrationFieldsVersion; + } + + public String getSerialNumber() { + return serialNumber; + } + + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getOamV4IpAddress() { + return oamV4IpAddress; + } + + public void setOamV4IpAddress(String oamV4IpAddress) { + this.oamV4IpAddress = oamV4IpAddress; + } + + public String getOamV6IpAddress() { + return oamV6IpAddress; + } + + public void setOamV6IpAddress(String oamV6IpAddress) { + this.oamV6IpAddress = oamV6IpAddress; + } + + public String getSoftwareVersion() { + return softwareVersion; + } + + public void setSoftwareVersion(String softwareVersion) { + this.softwareVersion = softwareVersion; + } + + public String getUnitType() { + return unitType; + } + + public void setUnitType(String unitType) { + this.unitType = unitType; + } + + public String getUnitFamily() { + return unitFamily; + } + + public void setUnitFamily(String unitFamily) { + this.unitFamily = unitFamily; + } + + public String getModelNumber() { + return modelNumber; + } + + public void setModelNumber(String modelNumber) { + this.modelNumber = modelNumber; + } + + public String getManufactureDate() { + return manufactureDate; + } + + public void setManufactureDate(String manufactureDate) { + this.manufactureDate = manufactureDate; + } + + public String getMacAddress() { + return macAddress; + } + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + public String getLastServiceDate() { + return lastServiceDate; + } + + public void setLastServiceDate(String lastServiceDate) { + this.lastServiceDate = lastServiceDate; + } + + public Serializable getAdditionalFields() { + return additionalFields; + } + + public void setAdditionalFields(Serializable additionalFields) { + this.additionalFields = additionalFields; + } + + @Override + public String toString() { + return "PnfRegEventFields [pnfRegistrationFieldsVersion=" + pnfRegistrationFieldsVersion + + ", serialNumber=" + serialNumber + ", vendorName=" + vendorName + ", oamV4IpAddress=" + + oamV4IpAddress + ", oamV6IpAddress=" + oamV6IpAddress + ", softwareVersion=" + + softwareVersion + ", unitType=" + unitType + ", unitFamily=" + unitFamily + + ", modelNumber=" + modelNumber + ", manufactureDate=" + manufactureDate + ", macAddress=" + + macAddress + ", lastServiceDate=" + lastServiceDate + ", additionalFields=" + + additionalFields + "]"; + } + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/service/VesAgentServiceHelper.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/service/VesAgentServiceHelper.java index 2f3f9df..2a30b7d 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/service/VesAgentServiceHelper.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/service/VesAgentServiceHelper.java @@ -16,306 +16,315 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.service; - -import com.google.gson.Gson; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; - -import org.commscope.tr069adapter.acs.common.DeviceDetails; -import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; -import org.commscope.tr069adapter.acs.common.ParameterDTO; -import org.commscope.tr069adapter.mapper.model.VESNotification; -import org.commscope.tr069adapter.vesagent.async.WaitForNotifications; -import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; -import org.commscope.tr069adapter.vesagent.exception.VesAgentException; -import org.commscope.tr069adapter.vesagent.repository.VesDataRepository; -import org.commscope.tr069adapter.vesagent.timer.HeartBeatTimeoutTask; -import org.commscope.tr069adapter.vesagent.timer.ScheduleInfo; -import org.commscope.tr069adapter.vesagent.timer.ScheduleTaskService; -import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; -import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class VesAgentServiceHelper { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private Function beanFactory; - - public HeartBeatTimeoutTask getBeanInstance(String name) { - return beanFactory.apply(name); - } - - @Autowired - VesDataRepository vesDataRepository; - - @Autowired - WaitForNotifications waitForNotifications; - - @Autowired - ScheduleTaskService timerService; - - private boolean saveDeviceDataEntity(DeviceDetails deviceDetails, String eNodeBName, - String heartBeatPeriod) throws VesAgentException { - - List deviceDataEntityList = vesDataRepository - .findByDeviceIdAndAttrGroup(deviceDetails.getDeviceId(), VesAgentConstants.HEART_BEAT); - - DeviceDataEntity deviceDataEntity = null; - Map attrJsonMap = null; - - if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) { - deviceDataEntity = new DeviceDataEntity(); - - deviceDataEntity.setDeviceId(deviceDetails.getDeviceId()); - deviceDataEntity.seteNodeBName(eNodeBName); - deviceDataEntity.setOui(deviceDetails.getOui()); - deviceDataEntity.setProductClass(deviceDetails.getProductClass()); - deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT); - - attrJsonMap = new HashMap<>(); - } else { - deviceDataEntity = deviceDataEntityList.get(0); - attrJsonMap = deviceDataEntity.getAttributesMap(); - } - - String existingHeartBeatPeriod = attrJsonMap.get(VesAgentConstants.HEART_BEAT_PERIOD); - - if (null == heartBeatPeriod - && (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(existingHeartBeatPeriod)) - || existingHeartBeatPeriod - .equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL))) { - return false; - } - - if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) { - attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, heartBeatPeriod); - } - - deviceDataEntity.setAttributesMap(attrJsonMap); - - vesDataRepository.save(deviceDataEntity); - - return true; - } - - public void processHeartBeatSetRequest(DeviceRPCRequest deviceRPCRequest, String heartBeatPeriod, - String countDownTimer) throws VesAgentException { - - String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); - - VesAgentUtils.validateDeviceId(deviceId); - - if (VesAgentUtils.isNullOrEmpty(heartBeatPeriod) - && VesAgentUtils.isNullOrEmpty(countDownTimer)) { - String errorMsg = - "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId; - logger.error(errorMsg); - throw new VesAgentException(VesAgentConstants.INVALID_PARAMETER_VALUE, errorMsg); - } - - Object eNodeBNameObj = deviceRPCRequest.getContext().get(VesAgentConstants.ENODEB_NAME); - - String eNodeBName = null; - if (null != eNodeBNameObj) { - eNodeBName = (String) eNodeBNameObj; - } - - boolean resetTimerJob = - saveDeviceDataEntity(deviceRPCRequest.getDeviceDetails(), eNodeBName, heartBeatPeriod); - - if (resetTimerJob) { - resetTimerJob(deviceId, heartBeatPeriod, countDownTimer); - abortRunningDeviceConnectivityCheck(deviceRPCRequest); - } - - } - - public void processHeartBeatGetRequest(DeviceRPCRequest deviceRPCRequest) { - - String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); - List deviceDataEntityList = - vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT); - - if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList) - || VesAgentUtils.isNullOrEmpty(deviceDataEntityList.get(0).getAttributesMap())) { - return; - } - - DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0); - - List resultparamDTOList = null; - List paramDTOList = deviceRPCRequest.getOpDetails().getParmeters(); - - for (ParameterDTO paramDTO : paramDTOList) { - resultparamDTOList = ifDataTypeObject(paramDTO, deviceDataEntity); - - if (!resultparamDTOList.isEmpty()) { - break; - } - - if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) { - paramDTO.setParamValue(getCountDownTimerParam(deviceDataEntity).getParamValue()); - } else { - paramDTO.setParamValue(deviceDataEntity.getAttributesMap().get(paramDTO.getParamName())); - } - } - - if (null != resultparamDTOList && !resultparamDTOList.isEmpty()) { - deviceRPCRequest.getOpDetails().setParmeters(resultparamDTOList); - } - } - - public void processHeartBeatDeleteRequest(VESNotification vesNotification) { - List paramDTOList = vesNotification.getOperationDetails().getParmeters(); - - for (ParameterDTO paramDTO : paramDTOList) { - if (Boolean.TRUE.equals(VesAgentUtils.isVesNotificationRequest(paramDTO))) { - List deviceDataEntityList = vesDataRepository.findByDeviceIdAndAttrGroup( - vesNotification.geteNodeBName(), VesAgentConstants.HEART_BEAT); - - if (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) { - return; - } - vesDataRepository.delete(deviceDataEntityList.get(0)); - timerService.cancelSchedule(vesNotification.geteNodeBName()); - break; - } - } - } - - private List ifDataTypeObject(ParameterDTO paramDTO, - DeviceDataEntity deviceDataEntity) { - List paramDTOList = new ArrayList<>(); - - if (null != paramDTO.getDataType() - && paramDTO.getDataType().equalsIgnoreCase(VesAgentConstants.OBJECT_DATA_TYPE.toLowerCase()) - && paramDTO.getParamName().toLowerCase() - .contains(VesAgentConstants.HEART_BEAT.toLowerCase())) { - - Map attrMap = deviceDataEntity.getAttributesMap(); - - for (Map.Entry entry : attrMap.entrySet()) { - ParameterDTO param = new ParameterDTO(); - param.setParamName(entry.getKey()); - param.setParamValue(entry.getValue()); - - paramDTOList.add(param); - } - - ParameterDTO countDownParam = getCountDownTimerParam(deviceDataEntity); - paramDTOList.add(countDownParam); - } - - return paramDTOList; - } - - private ParameterDTO getCountDownTimerParam(DeviceDataEntity deviceDataEntity) { - Long countDownTimerVal = timerService - .getTimeRemainingTillNextExecution(deviceDataEntity.getDeviceId(), TimeUnit.MINUTES); - - ParameterDTO param = new ParameterDTO(); - param.setParamName(VesAgentConstants.COUNT_DOWN_TIMER); - - if (null != countDownTimerVal) { - param.setParamValue(countDownTimerVal.toString()); - } - - return param; - } - - - public void processHeartBeatGetRequest(String deviceId, Integer HeartBeatPeriod, - Integer countDownTimer) throws VesAgentException { - VesAgentUtils.validateDeviceId(deviceId); - - - if (null == HeartBeatPeriod && null == countDownTimer) {// this should just check if heartbeat - // is null - String errorMsg = - "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId; - logger.error(errorMsg); - throw new VesAgentException(errorMsg); - } - - List deviceDataEntityList = - vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT); - - DeviceDataEntity deviceDataEntity = null; - Map attrJsonMap = null; - - if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) { - deviceDataEntity = new DeviceDataEntity(); - deviceDataEntity.setDeviceId(deviceId); - deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT); - - attrJsonMap = new HashMap(); - } else { - deviceDataEntity = deviceDataEntityList.get(0); - attrJsonMap = new Gson().fromJson(deviceDataEntity.getAttrJson(), Map.class); - } - - - if (null != HeartBeatPeriod) { - attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, HeartBeatPeriod.toString()); - } - - if (null != countDownTimer) { - attrJsonMap.put(VesAgentConstants.COUNT_DOWN_TIMER, countDownTimer.toString()); - } - - String attrJson = new Gson().toJson(attrJsonMap); - deviceDataEntity.setAttrJson(attrJson); - - vesDataRepository.save(deviceDataEntity); - } - - private void resetTimerJob(String deviceId, String heartBeatPeriod, String countDownTimer) { - if (null == heartBeatPeriod || heartBeatPeriod.isEmpty()) { - scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer)); - } else if (heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { - timerService.cancelSchedule(deviceId); - } else { - if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(countDownTimer))) { - scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer)); - } else { - scheduleTimerJob(deviceId, Integer.parseInt(heartBeatPeriod)); - } - } - } - - private void scheduleTimerJob(String deviceId, Integer timeoutInterval) { - ScheduleInfo scheduleInfo = new ScheduleInfo(); - scheduleInfo.setInterval(timeoutInterval); - scheduleInfo.setTimeUnit(TimeUnit.MINUTES); - - HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceId); - - timerService.schedule(deviceId, scheduleInfo, callbackTask); - } - - private void abortRunningDeviceConnectivityCheck(DeviceRPCRequest deviceRPCRequest) { - waitForNotifications.notifyResult(VesAgentUtils.getErrorResponse(deviceRPCRequest, null, null)); - } - - public List getAllDeviceDataEntity() { - return (List) vesDataRepository.findAll(); - } - - public List findByDeviceIdAndGroup(String deviceId, String attrGroup) { - return vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, attrGroup); - } - - - -} +package org.commscope.tr069adapter.vesagent.service; + +import com.google.gson.Gson; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import org.commscope.tr069adapter.acs.common.DeviceDetails; +import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; +import org.commscope.tr069adapter.acs.common.ParameterDTO; +import org.commscope.tr069adapter.mapper.model.VESNotification; +import org.commscope.tr069adapter.vesagent.async.WaitForNotifications; +import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; +import org.commscope.tr069adapter.vesagent.exception.VesAgentException; +import org.commscope.tr069adapter.vesagent.repository.VesDataRepository; +import org.commscope.tr069adapter.vesagent.timer.HeartBeatTimeoutTask; +import org.commscope.tr069adapter.vesagent.timer.ScheduleInfo; +import org.commscope.tr069adapter.vesagent.timer.ScheduleTaskService; +import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; +import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class VesAgentServiceHelper { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private Function beanFactory; + + public HeartBeatTimeoutTask getBeanInstance(String name) { + return beanFactory.apply(name); + } + + @Autowired + VesDataRepository vesDataRepository; + + @Autowired + WaitForNotifications waitForNotifications; + + @Autowired + ScheduleTaskService timerService; + + private boolean saveDeviceDataEntity(DeviceDetails deviceDetails, String eNodeBName, + String heartBeatPeriod, String countDownTimer) throws VesAgentException { + + List deviceDataEntityList = vesDataRepository + .findByDeviceIdAndAttrGroup(deviceDetails.getDeviceId(), VesAgentConstants.HEART_BEAT); + + DeviceDataEntity deviceDataEntity = null; + Map attrJsonMap = null; + + if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) { + deviceDataEntity = new DeviceDataEntity(); + + deviceDataEntity.setDeviceId(deviceDetails.getDeviceId()); + deviceDataEntity.seteNodeBName(eNodeBName); + deviceDataEntity.setOui(deviceDetails.getOui()); + deviceDataEntity.setProductClass(deviceDetails.getProductClass()); + deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT); + + attrJsonMap = new HashMap<>(); + } else { + deviceDataEntity = deviceDataEntityList.get(0); + attrJsonMap = deviceDataEntity.getAttributesMap(); + } + + String existingHeartBeatPeriod = attrJsonMap.get(VesAgentConstants.HEART_BEAT_PERIOD); + + if (null == heartBeatPeriod + && (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(existingHeartBeatPeriod)) + || existingHeartBeatPeriod + .equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL))) { + return false; + } + if (null != countDownTimer + && !countDownTimer.equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER_ZERO)) { + if (null == heartBeatPeriod || heartBeatPeriod.equalsIgnoreCase(existingHeartBeatPeriod)) { + String exceptionReason = "Can't change timer value if heartbeat value is same"; + throw new VesAgentException(VesAgentConstants.INVALID_PARAMETER_VALUE, exceptionReason); + } + + } + + if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) { + attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, heartBeatPeriod); + } + + deviceDataEntity.setAttributesMap(attrJsonMap); + + vesDataRepository.save(deviceDataEntity); + + return true; + } + + public void processHeartBeatSetRequest(DeviceRPCRequest deviceRPCRequest, String heartBeatPeriod, + String countDownTimer) throws VesAgentException { + + String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); + + VesAgentUtils.validateDeviceId(deviceId); + + if (VesAgentUtils.isNullOrEmpty(heartBeatPeriod) + && VesAgentUtils.isNullOrEmpty(countDownTimer)) { + String errorMsg = + "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId; + errorMsg = errorMsg.replaceAll("[\n|\r|\t]", "_"); + logger.error(errorMsg); + throw new VesAgentException(VesAgentConstants.INVALID_PARAMETER_VALUE, errorMsg); + } + + Object eNodeBNameObj = deviceRPCRequest.getContext().get(VesAgentConstants.ENODEB_NAME); + + String eNodeBName = null; + if (null != eNodeBNameObj) { + eNodeBName = (String) eNodeBNameObj; + } + + boolean resetTimerJob = saveDeviceDataEntity(deviceRPCRequest.getDeviceDetails(), eNodeBName, + heartBeatPeriod, countDownTimer); + + if (resetTimerJob) { + resetTimerJob(deviceId, heartBeatPeriod, countDownTimer); + abortRunningDeviceConnectivityCheck(deviceRPCRequest); + } + + } + + public void processHeartBeatGetRequest(DeviceRPCRequest deviceRPCRequest) { + + String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId(); + List deviceDataEntityList = + vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT); + + if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList) + || VesAgentUtils.isNullOrEmpty(deviceDataEntityList.get(0).getAttributesMap())) { + return; + } + + DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0); + + List resultparamDTOList = null; + List paramDTOList = deviceRPCRequest.getOpDetails().getParmeters(); + + for (ParameterDTO paramDTO : paramDTOList) { + resultparamDTOList = ifDataTypeObject(paramDTO, deviceDataEntity); + + if (!resultparamDTOList.isEmpty()) { + break; + } + + if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) { + paramDTO.setParamValue(getCountDownTimerParam(deviceDataEntity).getParamValue()); + } else { + paramDTO.setParamValue(deviceDataEntity.getAttributesMap().get(paramDTO.getParamName())); + } + } + + if (null != resultparamDTOList && !resultparamDTOList.isEmpty()) { + deviceRPCRequest.getOpDetails().setParmeters(resultparamDTOList); + } + } + + public void processHeartBeatDeleteRequest(VESNotification vesNotification) { + List paramDTOList = vesNotification.getOperationDetails().getParmeters(); + + for (ParameterDTO paramDTO : paramDTOList) { + if (Boolean.TRUE.equals(VesAgentUtils.isVesNotificationRequest(paramDTO))) { + List deviceDataEntityList = vesDataRepository.findByDeviceIdAndAttrGroup( + vesNotification.geteNodeBName(), VesAgentConstants.HEART_BEAT); + + if (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) { + return; + } + vesDataRepository.delete(deviceDataEntityList.get(0)); + timerService.cancelSchedule(vesNotification.geteNodeBName()); + break; + } + } + } + + private List ifDataTypeObject(ParameterDTO paramDTO, + DeviceDataEntity deviceDataEntity) { + List paramDTOList = new ArrayList<>(); + + if (null != paramDTO.getDataType() + && paramDTO.getDataType().equalsIgnoreCase(VesAgentConstants.OBJECT_DATA_TYPE.toLowerCase()) + && paramDTO.getParamName().toLowerCase() + .contains(VesAgentConstants.HEART_BEAT.toLowerCase())) { + + Map attrMap = deviceDataEntity.getAttributesMap(); + + for (Map.Entry entry : attrMap.entrySet()) { + ParameterDTO param = new ParameterDTO(); + param.setParamName(entry.getKey()); + param.setParamValue(entry.getValue()); + + paramDTOList.add(param); + } + + ParameterDTO countDownParam = getCountDownTimerParam(deviceDataEntity); + paramDTOList.add(countDownParam); + } + + return paramDTOList; + } + + private ParameterDTO getCountDownTimerParam(DeviceDataEntity deviceDataEntity) { + Long countDownTimerVal = timerService + .getTimeRemainingTillNextExecution(deviceDataEntity.getDeviceId(), TimeUnit.MINUTES); + + ParameterDTO param = new ParameterDTO(); + param.setParamName(VesAgentConstants.COUNT_DOWN_TIMER); + + if (null != countDownTimerVal) { + param.setParamValue(countDownTimerVal.toString()); + } + + return param; + } + + + public void processHeartBeatGetRequest(String deviceId, Integer heartBeatPeriod, + Integer countDownTimer) throws VesAgentException { + VesAgentUtils.validateDeviceId(deviceId); + + + if (null == heartBeatPeriod && null == countDownTimer) {// this should just check if heartbeat + // is null + String errorMsg = + "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId; + logger.error(errorMsg); + throw new VesAgentException(errorMsg); + } + + List deviceDataEntityList = + vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT); + + DeviceDataEntity deviceDataEntity = null; + Map attrJsonMap = null; + + if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) { + deviceDataEntity = new DeviceDataEntity(); + deviceDataEntity.setDeviceId(deviceId); + deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT); + + attrJsonMap = new HashMap<>(); + } else { + deviceDataEntity = deviceDataEntityList.get(0); + attrJsonMap = new Gson().fromJson(deviceDataEntity.getAttrJson(), Map.class); + } + + + if (null != heartBeatPeriod) { + attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, heartBeatPeriod.toString()); + } + + if (null != countDownTimer) { + attrJsonMap.put(VesAgentConstants.COUNT_DOWN_TIMER, countDownTimer.toString()); + } + + String attrJson = new Gson().toJson(attrJsonMap); + deviceDataEntity.setAttrJson(attrJson); + + vesDataRepository.save(deviceDataEntity); + } + + private void resetTimerJob(String deviceId, String heartBeatPeriod, String countDownTimer) { + if (null == heartBeatPeriod || heartBeatPeriod.isEmpty()) { + scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer)); + } else if (heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { + timerService.cancelSchedule(deviceId); + } else { + if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(countDownTimer))) { + scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer)); + } else { + scheduleTimerJob(deviceId, Integer.parseInt(heartBeatPeriod)); + } + } + } + + private void scheduleTimerJob(String deviceId, Integer timeoutInterval) { + ScheduleInfo scheduleInfo = new ScheduleInfo(); + scheduleInfo.setInterval(timeoutInterval); + scheduleInfo.setTimeUnit(TimeUnit.MINUTES); + + HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceId); + + timerService.schedule(deviceId, scheduleInfo, callbackTask); + } + + private void abortRunningDeviceConnectivityCheck(DeviceRPCRequest deviceRPCRequest) { + waitForNotifications.notifyResult(VesAgentUtils.getErrorResponse(deviceRPCRequest, null, null)); + } + + public List getAllDeviceDataEntity() { + return (List) vesDataRepository.findAll(); + } + + public List findByDeviceIdAndGroup(String deviceId, String attrGroup) { + return vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, attrGroup); + } + + + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/timer/StartupTimerService.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/timer/StartupTimerService.java index 465b6dc..dd1a028 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/timer/StartupTimerService.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/timer/StartupTimerService.java @@ -16,71 +16,74 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.timer; - -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; - -import javax.annotation.PostConstruct; - -import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; -import org.commscope.tr069adapter.vesagent.repository.VesDataRepository; -import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; -import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class StartupTimerService { - private static final Logger logger = LoggerFactory.getLogger(StartupTimerService.class); - - @Autowired - private Function beanFactory; - - public HeartBeatTimeoutTask getBeanInstance(String name) { - return beanFactory.apply(name); - } - - @Autowired - VesDataRepository vesDataRepository; - - @Autowired - ScheduleTaskService timerService; - - @PostConstruct - public void initializeDeviceReachabilityCheckTimers() { - logger.debug("Initializing all device connectivity check timer tasks."); - List deviceDataEntityList = - vesDataRepository.findByAttrGroup(VesAgentConstants.HEART_BEAT); - - if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList)) { - logger.debug("No device reachability check timer tasks exist."); - return; - } - - for (DeviceDataEntity deviceDataEntity : deviceDataEntityList) { - String heartBeatPeriod = null; - - if (null != deviceDataEntity.getAttributesMap()) { - heartBeatPeriod = - deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD); - } - - if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod) - && !heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { - logger.info("Creating device connectivity check timer tasks for device {}.", - deviceDataEntity.getDeviceId()); - ScheduleInfo scheduleInfo = new ScheduleInfo(); - scheduleInfo.setInterval(Integer.parseInt(heartBeatPeriod)); - scheduleInfo.setTimeUnit(TimeUnit.SECONDS); - - HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceDataEntity.getDeviceId()); - - timerService.schedule(deviceDataEntity.getDeviceId(), scheduleInfo, callbackTask); - } - } - } -} +package org.commscope.tr069adapter.vesagent.timer; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import javax.annotation.PostConstruct; + +import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity; +import org.commscope.tr069adapter.vesagent.repository.VesDataRepository; +import org.commscope.tr069adapter.vesagent.util.VesAgentConstants; +import org.commscope.tr069adapter.vesagent.util.VesAgentUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class StartupTimerService { + private static final Logger logger = LoggerFactory.getLogger(StartupTimerService.class); + + @Autowired + private Function beanFactory; + + public HeartBeatTimeoutTask getBeanInstance(String name) { + return beanFactory.apply(name); + } + + @Autowired + VesDataRepository vesDataRepository; + + @Autowired + ScheduleTaskService timerService; + + @PostConstruct + public void initializeDeviceReachabilityCheckTimers() { + logger.debug("Initializing all device connectivity check timer tasks."); + List deviceDataEntityList = + vesDataRepository.findByAttrGroup(VesAgentConstants.HEART_BEAT); + + if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList)) { + logger.debug("No device reachability check timer tasks exist."); + return; + } + + for (DeviceDataEntity deviceDataEntity : deviceDataEntityList) { + String heartBeatPeriod = null; + + if (null != deviceDataEntity.getAttributesMap()) { + heartBeatPeriod = + deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD); + } + if (heartBeatPeriod == null) { + logger.info("Heartbeat is null"); + return; + } + if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod) + && !heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) { + logger.info("Creating device connectivity check timer tasks for device {}.", + deviceDataEntity.getDeviceId()); + ScheduleInfo scheduleInfo = new ScheduleInfo(); + scheduleInfo.setInterval(Integer.parseInt(heartBeatPeriod)); + scheduleInfo.setTimeUnit(TimeUnit.SECONDS); + + HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceDataEntity.getDeviceId()); + + timerService.schedule(deviceDataEntity.getDeviceId(), scheduleInfo, callbackTask); + } + } + } +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentConstants.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentConstants.java index 7fe33c8..ce9ff80 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentConstants.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentConstants.java @@ -16,37 +16,39 @@ * ===============LICENSE_END======================================================================= */ -package org.commscope.tr069adapter.vesagent.util; - -/** - * - * @version 1.0 - * @since June 5, 2020 - * @author Prashant Kumar - */ - -public class VesAgentConstants { - - public static final String HEART_BEAT = "heartbeat"; - - public static final String HEART_BEAT_PERIOD = "heartbeat.heartbeatPeriod"; - public static final String HEART_BEAT_PERIOD_DEFAULT_VAL = "5"; // IN MIUTES - - public static final String COUNT_DOWN_TIMER = "heartbeat.countDownTimer"; - - public static final String ENODEB_NAME = "ENODEB_NAME"; - - public static final String OBJECT_DATA_TYPE = "object"; - - public static final String REMOVE_HEART_BEAT_TIMER_VAL = "0"; - public static final int DEVICE_IS_REACHABLE = 100; - public static final String ABORTED_BY_BOOT_BOOTSTRAP = "8002"; - - public static final int RPC_SUCCESS = 0; - public static final int RPC_FAILED = 1; - public static final String INVALID_ARGUMENTS = "9003"; - public static final String INVALID_PARAMETER_NAME = "9005"; - public static final String INVALID_PARAMETER_VALUE = "9007"; - - -} +package org.commscope.tr069adapter.vesagent.util; + +/** + * + * @version 1.0 + * @since June 5, 2020 + * @author Prashant Kumar + */ + +public class VesAgentConstants { + private VesAgentConstants() {} + + public static final String HEART_BEAT = "heartbeat"; + + public static final String HEART_BEAT_PERIOD = "heartbeat.heartbeatPeriod"; + public static final String HEART_BEAT_PERIOD_DEFAULT_VAL = "5"; // IN MIUTES + + public static final String COUNT_DOWN_TIMER = "heartbeat.countDownTimer"; + + public static final String ENODEB_NAME = "ENODEB_NAME"; + + public static final String OBJECT_DATA_TYPE = "object"; + public static final String COUNT_DOWN_TIMER_ZERO = "0"; + + public static final String REMOVE_HEART_BEAT_TIMER_VAL = "0"; + public static final int DEVICE_IS_REACHABLE = 100; + public static final String ABORTED_BY_BOOT_BOOTSTRAP = "8002"; + + public static final int RPC_SUCCESS = 0; + public static final int RPC_FAILED = 1; + public static final String INVALID_ARGUMENTS = "9003"; + public static final String INVALID_PARAMETER_NAME = "9005"; + public static final String INVALID_PARAMETER_VALUE = "9007"; + + +} diff --git a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentUtils.java b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentUtils.java index ae43e1f..a1b35a2 100644 --- a/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentUtils.java +++ b/ves-agent/src/main/java/org/commscope/tr069adapter/vesagent/util/VesAgentUtils.java @@ -21,6 +21,7 @@ package org.commscope.tr069adapter.vesagent.util; import java.util.Calendar; import java.util.List; import java.util.Map; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.commscope.tr069adapter.acs.common.DeviceRPCRequest; @@ -33,6 +34,8 @@ import org.commscope.tr069adapter.vesagent.exception.VesAgentException; public class VesAgentUtils { + private VesAgentUtils() {} + private static final Log logger = LogFactory.getLog(VesAgentUtils.class); private static String errorMsg = null; -- 2.16.6