tr-069 adapter to support tr-069 compliant RPCs.
Fixed code smell issues.
Issue-Id: OAM-152
Signed-off-by: ravi.setti <Ravi.Setti@commscope.com>
Change-Id: Ib9e0ed925a5c8602841a8b3ebdd009b93c187fc2
<skipTests>false</skipTests>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <!-- attached to Maven test phase -->
+ <execution>
+ <id>report</id>
+ <phase>test</phase>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.booter;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_Q;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q;\r
-\r
-import java.util.Arrays;\r
-\r
-import javax.jms.ConnectionFactory;\r
-\r
-import org.apache.activemq.ActiveMQConnectionFactory;\r
-import org.apache.activemq.RedeliveryPolicy;\r
-import org.apache.activemq.broker.BrokerService;\r
-import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap;\r
-import org.apache.activemq.command.ActiveMQQueue;\r
-import org.apache.catalina.connector.Connector;\r
-import org.springframework.beans.factory.annotation.Value;\r
-import org.springframework.boot.SpringApplication;\r
-import org.springframework.boot.autoconfigure.SpringBootApplication;\r
-import org.springframework.boot.autoconfigure.domain.EntityScan;\r
-import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;\r
-import org.springframework.boot.web.client.RestTemplateBuilder;\r
-import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;\r
-import org.springframework.boot.web.servlet.FilterRegistrationBean;\r
-import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;\r
-import org.springframework.context.annotation.Bean;\r
-import org.springframework.context.annotation.ComponentScan;\r
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories;\r
-import org.springframework.jms.annotation.EnableJms;\r
-import org.springframework.jms.config.DefaultJmsListenerContainerFactory;\r
-import org.springframework.jms.config.JmsListenerContainerFactory;\r
-import org.springframework.jms.listener.MessageListenerContainer;\r
-import org.springframework.jms.support.converter.MappingJackson2MessageConverter;\r
-import org.springframework.jms.support.converter.MessageConverter;\r
-import org.springframework.jms.support.converter.MessageType;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@EnableJms\r
-@SpringBootApplication\r
-@ComponentScan({"org.commscope.tr069adapter.acs", "org.commscope.tr069adapter.common"})\r
-@EnableJpaRepositories("org.commscope.tr069adapter.acs")\r
-@EntityScan("org.commscope.tr069adapter.acs.requestprocessor.entity")\r
-public class ACSServiceBooter {\r
-\r
- public static void main(String[] args) {\r
- SpringApplication.run(ACSServiceBooter.class, args);\r
- }\r
-\r
- @Bean\r
- public RestTemplate restTemplate(RestTemplateBuilder builder) {\r
- return builder.build();\r
- }\r
-\r
-\r
- /*\r
- * JMS Configuration Defining the connection factories used in the application Setting the\r
- * Re-delivery configuration goes here\r
- */\r
- @Bean\r
- public BrokerService broker() throws Exception {\r
- final BrokerService broker = new BrokerService();\r
- broker.addConnector("tcp://localhost:61616");\r
- broker.addConnector("vm://localhost");\r
- broker.setPersistent(false);\r
- return broker;\r
- }\r
-\r
- @Bean\r
- public ConnectionFactory jmsConnectionFactory() {\r
- ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();\r
- connectionFactory\r
- .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter"));\r
- connectionFactory.setMaxThreadPoolSize(7);\r
-\r
- ActiveMQQueue tr069nbiReqQueue = new ActiveMQQueue(TR069_NBI_REQUEST_Q);\r
- RedeliveryPolicy tr069nbiReqQueuePolicy = new RedeliveryPolicy();\r
- tr069nbiReqQueuePolicy.setInitialRedeliveryDelay(30000);\r
- tr069nbiReqQueuePolicy.setUseCollisionAvoidance(true);\r
- tr069nbiReqQueuePolicy.setRedeliveryDelay(30000);\r
- tr069nbiReqQueuePolicy.setUseExponentialBackOff(false);\r
- tr069nbiReqQueuePolicy.setMaximumRedeliveries(3);\r
- tr069nbiReqQueuePolicy.setDestination(tr069nbiReqQueue);\r
-\r
- ActiveMQQueue crQueue = new ActiveMQQueue(CR_REQ_Q);\r
- RedeliveryPolicy crQueuePolicy = new RedeliveryPolicy();\r
- crQueuePolicy.setInitialRedeliveryDelay(18000);\r
- crQueuePolicy.setUseCollisionAvoidance(true);\r
- crQueuePolicy.setRedeliveryDelay(18000);\r
- crQueuePolicy.setUseExponentialBackOff(true);\r
- crQueuePolicy.setBackOffMultiplier(2);\r
- crQueuePolicy.setMaximumRedeliveries(4);\r
- crQueuePolicy.setDestination(crQueue);\r
-\r
- ActiveMQQueue notificationQueue = new ActiveMQQueue(NBI_NOTIFICATION_Q);\r
- RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy();\r
- notificationQueuePolicy.setInitialRedeliveryDelay(30000);\r
- notificationQueuePolicy.setUseCollisionAvoidance(true);\r
- notificationQueuePolicy.setRedeliveryDelay(30000);\r
- notificationQueuePolicy.setUseExponentialBackOff(false);\r
- notificationQueuePolicy.setMaximumRedeliveries(5);\r
- notificationQueuePolicy.setDestination(notificationQueue);\r
-\r
- ActiveMQQueue opResQueue = new ActiveMQQueue(NBI_OP_RESULT_Q);\r
- RedeliveryPolicy opResQueuePolicy = new RedeliveryPolicy();\r
- opResQueuePolicy.setInitialRedeliveryDelay(30000);\r
- opResQueuePolicy.setUseCollisionAvoidance(true);\r
- opResQueuePolicy.setRedeliveryDelay(30000);\r
- opResQueuePolicy.setUseExponentialBackOff(false);\r
- opResQueuePolicy.setMaximumRedeliveries(3);\r
- opResQueuePolicy.setDestination(opResQueue);\r
-\r
- RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap();\r
- rdMap.put(tr069nbiReqQueue, tr069nbiReqQueuePolicy);\r
- rdMap.put(crQueue, crQueuePolicy);\r
- rdMap.put(notificationQueue, notificationQueuePolicy);\r
- rdMap.put(opResQueue, opResQueuePolicy);\r
-\r
- return connectionFactory;\r
- }\r
- // End\r
-\r
- @Bean\r
- public JmsListenerContainerFactory<MessageListenerContainer> tr069NBIRequestCF(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- return handleJMSCommonConfiguration(connectionFactory, configurer);\r
- }\r
-\r
- @Bean\r
- public JmsListenerContainerFactory<MessageListenerContainer> tr069DeviceResponseCF(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- return handleJMSCommonConfiguration(connectionFactory, configurer);\r
- }\r
-\r
- @Bean\r
- public JmsListenerContainerFactory<MessageListenerContainer> nbiNotificationCF(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- return handleJMSCommonConfiguration(connectionFactory, configurer);\r
- }\r
-\r
- @Bean\r
- public JmsListenerContainerFactory<MessageListenerContainer> nbiOpResultCF(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- return handleJMSCommonConfiguration(connectionFactory, configurer);\r
- }\r
-\r
- public JmsListenerContainerFactory handleJMSCommonConfiguration(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();\r
- configurer.configure(factory, connectionFactory);\r
- return factory;\r
- }\r
-\r
- /*\r
- * JMS Configuration ends here\r
- */\r
-\r
- /*\r
- * JMS serializing and de-serializing used Jackson JMS message converter Serialize message content\r
- * to json using TextMessage\r
- */\r
- @Bean\r
- public MessageConverter jacksonJmsMessageConverter() {\r
- MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();\r
- converter.setTargetType(MessageType.TEXT);\r
- converter.setTypeIdPropertyName("_type");\r
- return converter;\r
- }\r
-\r
- /*\r
- * Exposing an addition HTTP port for Netconf mapper to access And making the default port to be\r
- * TLS secured which shall be used in the hems url\r
- */\r
- @Value("${server.additional.http.port}")\r
- private String additionalHttpPort;\r
-\r
- @Value("${server.port}")\r
- private String serverPort;\r
-\r
- @Bean\r
- public ConfigurableServletWebServerFactory tomcatEmbeddedServletContainerFactory() {\r
- final TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();\r
- final Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);\r
- connector.setScheme("https");\r
- connector.setPort(Integer.valueOf(this.additionalHttpPort));\r
- factory.addAdditionalTomcatConnectors(connector);\r
- return factory;\r
- }\r
-\r
- @Bean\r
- public FilterRegistrationBean<FilterInsecuredRequests> loggingFilter() {\r
- FilterRegistrationBean<FilterInsecuredRequests> registrationBean =\r
- new FilterRegistrationBean<>();\r
- registrationBean.setFilter(new FilterInsecuredRequests(serverPort));\r
- registrationBean.addUrlPatterns("/CPEMgmt/*");\r
- return registrationBean;\r
- }\r
-\r
-}\r
+/*
+ * ============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<MessageListenerContainer> tr069NBIRequestCF(
+ ConnectionFactory connectionFactory,
+ DefaultJmsListenerContainerFactoryConfigurer configurer) {
+ return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10");
+ }
+
+ @Bean
+ public JmsListenerContainerFactory<MessageListenerContainer> tr069DeviceResponseCF(
+ ConnectionFactory connectionFactory,
+ DefaultJmsListenerContainerFactoryConfigurer configurer) {
+ return handleJMSCommonConfiguration(connectionFactory, configurer, "10-20");
+ }
+
+ @Bean
+ public JmsListenerContainerFactory<MessageListenerContainer> nbiNotificationCF(
+ ConnectionFactory connectionFactory,
+ DefaultJmsListenerContainerFactoryConfigurer configurer) {
+ return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10");
+ }
+
+ @Bean
+ public JmsListenerContainerFactory<MessageListenerContainer> nbiOpResultCF(
+ ConnectionFactory connectionFactory,
+ DefaultJmsListenerContainerFactoryConfigurer configurer) {
+ return handleJMSCommonConfiguration(connectionFactory, configurer, "5-10");
+ }
+
+ public JmsListenerContainerFactory<MessageListenerContainer> handleJMSCommonConfiguration(
+ ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer,
+ String threadCoutRange) {
+ DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
+ configurer.configure(factory, connectionFactory);
+ factory.setConcurrency(threadCoutRange);
+ JmsListenerContainerFactory<MessageListenerContainer> 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<FilterInsecuredRequests> loggingFilter() {
+ FilterRegistrationBean<FilterInsecuredRequests> registrationBean =
+ new FilterRegistrationBean<>();
+ registrationBean.setFilter(new FilterInsecuredRequests(serverPort));
+ registrationBean.addUrlPatterns("/CPEMgmt/*");
+ return registrationBean;
+ }
+
+}
SW_VERSION varchar(20),\r
HW_VERSION varchar(20),\r
CONNECTION_REQUEST_URL varchar(1024),\r
- LAST_UPDATED_TIME Timestamp\r
+ LAST_UPDATED_TIME Timestamp,\r
+ LAST_FAILED_ATTEMPT_TIME Timestamp,\r
+ CONN_STATUS BOOLEAN,\r
+ ERROR_MESSGAE varchar(256)\r
);\r
\r
\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe.deviceconnection;\r
-\r
-import static org.junit.Assert.assertTrue;\r
-import static org.junit.Assert.fail;\r
-\r
-import java.io.Serializable;\r
-\r
-import org.apache.activemq.broker.BrokerService;\r
-import org.commscope.tr069adapter.acs.booter.ACSServiceBooter;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.utils.AcsConstants;\r
-import org.commscope.tr069adapter.acs.cpe.handler.ConnectionReqEventHandler;\r
-import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector;\r
-import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI;\r
-import org.junit.After;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.boot.test.mock.mockito.MockBean;\r
-import org.springframework.test.context.ContextConfiguration;\r
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\r
-\r
-@SpringBootTest(classes = {ACSServiceBooter.class})\r
-@RunWith(SpringJUnit4ClassRunner.class)\r
-@AutoConfigureMockMvc\r
-@ContextConfiguration\r
-public class DeviceConnectTest {\r
-\r
- @Autowired\r
- ConnectionReqEventHandler connectionReqEventHandler;\r
-\r
- @MockBean\r
- private DeviceConnector deviceConnector;\r
-\r
- @MockBean\r
- private TimerServiceManagerAPI timerServiceManagerAPI;\r
-\r
- @Autowired\r
- BrokerService broker;\r
-\r
- @Test\r
- public void deviceConnect() {\r
- try {\r
- Mockito.doNothing().when(timerServiceManagerAPI).startTimer(Mockito.anyString(),\r
- Mockito.anyString(), Mockito.anyLong(), Mockito.any(Serializable.class));\r
-\r
- DeviceRPCResponse response = new DeviceRPCResponse();\r
- OperationResponse operationResponse = new OperationResponse();\r
- operationResponse.setOperationCode(TR069OperationCode.INITIATE_CR);\r
- operationResponse.setStatus(AcsConstants.HTTP_STATUS_OK);\r
- response.setOperationResponse(operationResponse);\r
- Mockito.when(deviceConnector.requestConnectionHttp(Mockito.any(TR069DeviceDetails.class)))\r
- .thenReturn(response);\r
-\r
- TR069DeviceDetails deviceDetails = new TR069DeviceDetails();\r
- deviceDetails.setDeviceId("0005B9AAAA22");\r
- deviceDetails.setConnectionRequestURL("http://10.10.10.10:8888/connect/device");\r
-\r
- connectionReqEventHandler.onMessage(deviceDetails);\r
-\r
- assertTrue(true);\r
- } catch (Exception e) {\r
- fail(e.getMessage());\r
- }\r
-\r
- }\r
-\r
- @After\r
- public void stopBroker() throws Exception {\r
- try {\r
- System.out.println("Tearing down the broker");\r
- broker.stop();\r
- broker.waitUntilStopped();\r
- broker = null;\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-}\r
+/*
+ * ============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();
+ }
+ }
+}
package org.commscope.tr069adapter.acs.common;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
import java.io.Serializable;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class DeviceDetails implements Serializable {\r
\r
private static final long serialVersionUID = -2127021632952200894L;\r
package org.commscope.tr069adapter.acs.common;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
import java.io.Serializable;\r
import java.util.List;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class DeviceInform implements Serializable {\r
\r
private static final long serialVersionUID = 1215967892463095850L;\r
package org.commscope.tr069adapter.acs.common;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
import java.io.Serializable;\r
import java.util.List;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class OperationDetails implements Serializable {\r
\r
private static final long serialVersionUID = -3405001463223998757L;\r
package org.commscope.tr069adapter.acs.common;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
import java.io.Serializable;\r
import java.util.List;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class OperationResponse implements Serializable {\r
\r
private static final long serialVersionUID = 6086073521990872907L;\r
package org.commscope.tr069adapter.acs.common;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
+\r
import java.io.Serializable;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class ParameterDTO implements Serializable {\r
\r
private static final long serialVersionUID = 1460021542834472410L;\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.common.dto;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-\r
-public class TR069DeviceDetails extends DeviceDetails {\r
-\r
- private static final long serialVersionUID = 8067939584181214835L;\r
-\r
- // Device credentials\r
- private String username;\r
- private String password;\r
-\r
- // Device connection request URL\r
- private String connectionRequestURL;\r
-\r
- public String getUsername() {\r
- return username;\r
- }\r
-\r
- public void setUsername(String username) {\r
- this.username = username;\r
- }\r
-\r
- public String getPassword() {\r
- return password;\r
- }\r
-\r
- public void setPassword(String password) {\r
- this.password = password;\r
- }\r
-\r
- public String getConnectionRequestURL() {\r
- return connectionRequestURL;\r
- }\r
-\r
- public void setConnectionRequestURL(String connectionRequestURL) {\r
- this.connectionRequestURL = connectionRequestURL;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.common.exception;\r
-\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.common.utils.Utility;\r
-\r
-public class ACSException extends Exception {\r
-\r
- private static final long serialVersionUID = 9116478433222830454L;\r
-\r
- private static final String ERRORMSG_PREFIX = "TR069";\r
-\r
- private ErrorCode errorCode;\r
-\r
- private String[] arguments;\r
-\r
- private String message;\r
-\r
- /**\r
- * @param s\r
- */\r
- public ACSException(String s) {\r
- super(s);\r
- }\r
-\r
- /**\r
- * @param errorCode\r
- */\r
- public ACSException(ErrorCode errorCode) {\r
- super();\r
- this.errorCode = errorCode;\r
- setErrorMessage(getErrorMessage());\r
- }\r
-\r
- /**\r
- * @param errorCode\r
- * @param args\r
- */\r
- public ACSException(ErrorCode errorCode, String... args) {\r
- super();\r
- this.errorCode = errorCode;\r
- arguments = args;\r
- setErrorMessage(getErrorMessage());\r
- }\r
-\r
- public ErrorCode getErrorCode() {\r
- return errorCode;\r
- }\r
-\r
- public void setErrorCode(ErrorCode errorCode) {\r
- this.errorCode = errorCode;\r
- }\r
-\r
- @Override\r
- public String getMessage() {\r
- return message;\r
- }\r
-\r
- /**\r
- * All the error messages defined in the TR069 ErrorMessage properties must have prefix "TR069"\r
- * \r
- * @return\r
- */\r
- private String getErrorMessage() {\r
- String key = ERRORMSG_PREFIX + "." + errorCode.getErrorCodeKey();\r
- return Utility.getMessage(key, arguments);\r
- }\r
-\r
- private void setErrorMessage(String message) {\r
- this.message = message;\r
- }\r
-}\r
+/*
+ * ============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);
+ }
+
+}
package org.commscope.tr069adapter.acs.common.inform;\r
\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
import org.commscope.tr069adapter.acs.common.DeviceInform;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public abstract class AbstractDeviceInform extends DeviceInform {\r
\r
private static final long serialVersionUID = -487248664548665087L;\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.common.requestprocessor.service;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse;\r
-\r
-public interface TR069DeviceEventHandler {\r
-\r
- /**\r
- * @param deviceNotification\r
- * @return\r
- */\r
- public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification) throws Exception;\r
-\r
- /**\r
- * Return type can be null, such case Empty HTTP response to be sent to the device\r
- * \r
- * @param operationResult\r
- * @return\r
- */\r
- public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult)\r
- throws Exception;\r
-\r
- /**\r
- * Return type can be null, such case Empty HTTP response to be sent to the device\r
- * \r
- * @return\r
- */\r
- public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails)\r
- throws Exception;\r
-\r
- /**\r
- * @param sessionId\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId)\r
- throws SessionManagerException;\r
-\r
- /**\r
- * @param deviceId\r
- * @return\r
- * @throws DeviceOperationException\r
- */\r
- public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException;\r
-\r
-}\r
+/*
+ * ============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);
+
+}
--- /dev/null
+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 + "]";
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.ACS_SESSIONID;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CWMP_VERSION;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.INFORM;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TRANSFER_COMPLETE;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.InputStreamReader;\r
-import java.io.OutputStream;\r
-import java.io.OutputStreamWriter;\r
-import java.io.PipedInputStream;\r
-import java.io.PipedOutputStream;\r
-import java.io.Reader;\r
-import java.io.UnsupportedEncodingException;\r
-import java.io.Writer;\r
-import java.net.URLDecoder;\r
-import java.nio.charset.StandardCharsets;\r
-import java.util.Enumeration;\r
-\r
-import javax.servlet.http.Cookie;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-import javax.ws.rs.core.Context;\r
-import javax.xml.soap.MessageFactory;\r
-import javax.xml.soap.MimeHeaders;\r
-import javax.xml.soap.SOAPException;\r
-import javax.xml.soap.SOAPMessage;\r
-\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.cpe.handler.DeviceEventHandler;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Fault;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Inform;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.InformResponse;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.TransferCompleteResponse;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestMapping;\r
-import org.springframework.web.bind.annotation.RestController;\r
-\r
-@RestController\r
-@RequestMapping("/CPEMgmt")\r
-public class CPEManagementService {\r
-\r
- private static final String UTF_8 = "UTF-8";\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(CPEManagementService.class);\r
-\r
- private static final int MY_MAX_ENVELOPES = 1;\r
-\r
- @Autowired\r
- DeviceEventHandler deviceEventHandler;\r
-\r
- /**\r
- * @param request\r
- * @param response\r
- */\r
- @SuppressWarnings("static-access")\r
- @PostMapping("/acs")\r
- public void processDeviceEvent(@Context HttpServletRequest request,\r
- @Context HttpServletResponse response) {\r
-\r
- logger.debug("A device event occurred");\r
- logHeaderElements(request.getHeaderNames());\r
-\r
- try {\r
- Boolean isEmptyCPERequest = true;\r
- SOAPMessage soapMsg = null;\r
- ByteArrayOutputStream out = new ByteArrayOutputStream();\r
-\r
- String ct = request.getContentType();\r
- int csix = -1;\r
- String csFrom = "ISO-8859-1";\r
- if (ct != null) {\r
- csix = ct.indexOf("charset=");\r
- response.setContentType(ct);\r
- } else {\r
- response.setContentType("text/xml;charset=UTF-8");\r
- }\r
-\r
- if (csix != -1)\r
- csFrom = ct.substring(csix + 8).replaceAll("\"", "");\r
-\r
- Cookie[] cookies = request.getCookies();\r
- String acsSessionID = getACSSessionCookieData(cookies);\r
- String cwmpVersion = getCWMPVersionCookieData(cookies);\r
-\r
- XmlFilterInputStream f =\r
- new XmlFilterInputStream(request.getInputStream(), request.getContentLength());\r
- MessageFactory mf = getSOAPMessageFactory();\r
- while (f.next()) {\r
- isEmptyCPERequest = false;\r
- MimeHeaders hdrs = new MimeHeaders();\r
- hdrs.setHeader("Content-Type", "text/xml; charset=UTF-8");\r
- InputStream in = getInputStream(csFrom, f);\r
- soapMsg = mf.createMessage(hdrs, in);\r
-\r
- logSoapMsg(soapMsg);\r
-\r
- TR069RPC msg = null;\r
- msg = TR069RPC.parse(soapMsg);\r
-\r
- String reqType = getRequestType(msg);\r
- logger.info("Event notified by the device is of type: {}", reqType);\r
-\r
- if (reqType != null) {\r
- if (reqType.equals(INFORM)) {\r
- processDeviceInform(msg, request, response, out);\r
- } else if (reqType.equals(TRANSFER_COMPLETE)) {\r
- processTransferComplete(msg, response, out);\r
- } else {\r
- processOperationResult(msg, response, reqType, acsSessionID, out);\r
- }\r
- }\r
- }\r
-\r
- if (isEmptyCPERequest.booleanValue()) {\r
- processEmptyCPERequest(response, cwmpVersion, acsSessionID, out);\r
- }\r
-\r
- if (out.size() < 1) {// To delete dm_sessionId cookie\r
- clearCookies(cookies, response);\r
- }\r
-\r
- response.setContentLength(out.size());\r
- response.setHeader("SOAPAction", "");\r
- String sout = out.toString().trim();\r
- logger.info(sout);\r
- response.getOutputStream().print(sout);\r
- response.getOutputStream().flush();\r
- logger.debug("End of processing");\r
-\r
- } catch (Exception e) {\r
- logger.error("An error occurred while processing device event, Exception: {}",\r
- e.getMessage());\r
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\r
- }\r
-\r
- logger.debug("End of processing the HTTP post request");\r
- }\r
-\r
- private InputStream getInputStream(String csFrom, XmlFilterInputStream f) throws IOException {\r
- InputStream in = null;\r
- if (csFrom.equalsIgnoreCase(UTF_8)) {\r
- in = new XmlFilterNS(f);\r
- } else {\r
- in = new CharsetConverterInputStream(csFrom, UTF_8, new XmlFilterNS(f));\r
- }\r
- return in;\r
- }\r
-\r
- private void processDeviceInform(TR069RPC msg, HttpServletRequest request,\r
- HttpServletResponse response, ByteArrayOutputStream out) throws IOException {\r
- Inform inform = (Inform) msg;\r
- DeviceInformResponse deviceInformResponse = null;\r
- try {\r
- deviceInformResponse =\r
- deviceEventHandler.processDeviceInform(inform, request.getHeader("Authorization"));\r
- Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId());\r
- Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion());\r
- response.addCookie(cookie);\r
- response.addCookie(cwmpVerCookie);\r
- } catch (TR069EventProcessingException tr069ex) {\r
- ErrorCode errorCode = tr069ex.getErrorCode();\r
- if (ErrorCode.OUI_OR_PC_MISMATCH.equals(errorCode)) {\r
- sendFault(response, out, Fault.FCODE_ACS_REQUEST_DENIED, "OUIandProductClassNotValid",\r
- inform.getId());\r
- } else {\r
- int httpStatusCode = deviceEventHandler.handleException(tr069ex);\r
- response.setStatus(httpStatusCode);\r
- }\r
- int httpStatusCode = deviceEventHandler.handleException(tr069ex);\r
- response.setStatus(httpStatusCode);\r
- }\r
-\r
- InformResponse resp = new InformResponse(inform.getId(), MY_MAX_ENVELOPES);\r
- resp.setCWMPVersion(msg.getCWMPVersion());\r
- resp.writeTo(out);\r
- }\r
-\r
- private void processTransferComplete(TR069RPC msg, HttpServletResponse response,\r
- ByteArrayOutputStream out) {\r
- TransferComplete tc = (TransferComplete) msg;\r
- try {\r
- DeviceInformResponse deviceInformResponse = deviceEventHandler.processTransferComplete(tc);\r
- Cookie cookie = new Cookie(ACS_SESSIONID, deviceInformResponse.getSessionId());\r
- Cookie cwmpVerCookie = new Cookie(CWMP_VERSION, msg.getCWMPVersion() + ";");\r
- response.addCookie(cookie);\r
- response.addCookie(cwmpVerCookie);\r
- } catch (Exception e) {\r
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\r
- return;\r
- }\r
- TransferCompleteResponse tr = new TransferCompleteResponse(tc.getId());\r
- tr.setCWMPVersion(msg.getCWMPVersion());\r
- tr.writeTo(out);\r
- }\r
-\r
- private void processOperationResult(TR069RPC msg, HttpServletResponse response, String reqType,\r
- String acsSessionID, ByteArrayOutputStream out) {\r
- logger.debug("Received Operation Result response {}", msg);\r
- if (null == acsSessionID) {\r
- logger.error("Received response without session ID, response: {}", reqType);\r
- } else {\r
- try {\r
- TR069RPC message = deviceEventHandler.processRPCResponse(msg, acsSessionID);\r
- if (null != message) {\r
- message.setCWMPVersion(msg.getCWMPVersion());\r
- message.writeTo(out);\r
- } else {\r
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);\r
- }\r
- } catch (TR069EventProcessingException tr069ex) {\r
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\r
- }\r
- }\r
- }\r
-\r
- private void processEmptyCPERequest(HttpServletResponse response, String cwmpVersion,\r
- String acsSessionID, ByteArrayOutputStream out) {\r
- if (null == acsSessionID) {\r
- logger.error("Received empty response without session ID");\r
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\r
- return;\r
- }\r
-\r
- try {\r
- logger.info("Received Empty Device response");\r
- TR069RPC message = deviceEventHandler.processEmptyRequest(acsSessionID);\r
- if (null != message) {\r
- message.setCWMPVersion(cwmpVersion);\r
- message.writeTo(out);\r
- } else {\r
- response.setStatus(HttpServletResponse.SC_NO_CONTENT);\r
- }\r
- } catch (TR069EventProcessingException tr069ex) {\r
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\r
- }\r
- }\r
-\r
- private void clearCookies(Cookie[] cookies, HttpServletResponse response) {\r
- Cookie cookieToDelete = null;\r
- if (null != cookies) {\r
- logger.debug("Clearing the cookies");\r
- for (int i = 0; i < cookies.length; i++) {\r
- if (cookies[i].getName().equals(ACS_SESSIONID)\r
- || cookies[i].getName().equals(CWMP_VERSION)) {\r
- cookieToDelete = cookies[i];\r
- cookieToDelete.setMaxAge(0);\r
- response.addCookie(cookieToDelete);\r
- }\r
- }\r
- }\r
- }\r
-\r
- private static class XmlFilterInputStream extends InputStream {\r
-\r
- private InputStream istream;\r
- private int lvl;\r
- private int lastchar;\r
- @SuppressWarnings("unused")\r
- private int len;\r
- private int nextchar;\r
- private boolean intag = false;\r
- private StringBuilder buff = new StringBuilder(16);\r
-\r
- /** Creates a new instance of xmlFilterInputStream */\r
- public XmlFilterInputStream(InputStream is, int l) {\r
- len = l;\r
- istream = is;\r
- }\r
-\r
- @Override\r
- public int read() throws IOException {\r
- if (lastchar == '>' && lvl == 0) {\r
- return -1;\r
- }\r
- int l = lastchar;\r
- if (!readLastChar())\r
- return lastchar;\r
-\r
- if (!intag && lastchar == '&') {\r
- int amppos = buff.length();\r
- updateBuffer();\r
- String s = buff.substring(amppos);\r
- replaceSpecialChars(s, amppos);\r
- return read();\r
- }\r
-\r
- if (l == '<') {\r
- intag = true;\r
- if (lastchar == '/') {\r
- lvl--;\r
- } else {\r
- lvl++;\r
- }\r
- }\r
-\r
- len--;\r
- return lastchar;\r
- }\r
-\r
- public boolean next() throws IOException {\r
- if ((nextchar = istream.read()) == -1) {\r
- logger.debug("Next char is {}", nextchar);\r
- lvl = 0;\r
- lastchar = 0;\r
- }\r
- return (nextchar != -1);\r
- }\r
-\r
- private boolean readLastChar() throws IOException {\r
- if (nextchar != -1) {\r
- lastchar = nextchar;\r
- nextchar = -1;\r
- } else {\r
- if (buff.length() > 0) {\r
- lastchar = buff.charAt(0);\r
- buff.deleteCharAt(0);\r
- return false;\r
- } else {\r
- lastchar = istream.read();\r
- }\r
- }\r
-\r
- if (lastchar == '<') {\r
- intag = true;\r
- } else if (lastchar == '>') {\r
- intag = false;\r
- }\r
-\r
- return true;\r
- }\r
-\r
- private void updateBuffer() throws IOException {\r
- // fix up broken xml not encoding &\r
- buff.append((char) lastchar);\r
- for (int c = 0; c < 10; c++) {\r
- int ch = istream.read();\r
- boolean breakLoop = false;\r
- if (ch == -1) {\r
- breakLoop = true;\r
- }\r
- if (ch == '&') {\r
- nextchar = ch;\r
- breakLoop = true;\r
- }\r
- if (breakLoop)\r
- break;\r
-\r
- buff.append((char) ch);\r
- }\r
- }\r
-\r
- private void replaceSpecialChars(String s, int amppos) {\r
- if (!s.startsWith("&") && !s.startsWith("<") && !s.startsWith(">")\r
- && !s.startsWith("'") && !s.startsWith(""") && !s.startsWith("&#")) {\r
- buff.replace(amppos, amppos + 1, "&");\r
- }\r
- }\r
- }\r
-\r
- private static class XmlFilterNS extends InputStream {\r
- // Dumb class to filter out declaration of default xmlns\r
-\r
- private String pat = "xmlns=\"urn:dslforum-org:cwmp-1-0\"";\r
- private String pat2 = "xmlns=\"urn:dslforum-org:cwmp-1-1\"";\r
- private int length = 0;\r
- private int pos = 0;\r
- private boolean f = false;\r
- private byte[] buff = new byte[1024];\r
- private InputStream is;\r
-\r
- @Override\r
- public int read() throws IOException {\r
- if (!f) {\r
- length = is.read(buff);\r
- if (length < buff.length) {\r
- byte[] b2 = new byte[length];\r
- System.arraycopy(buff, 0, b2, 0, length);\r
- buff = b2;\r
- }\r
-\r
- String b = new String(buff, StandardCharsets.UTF_8);\r
- b = b.replace(pat, "");\r
- b = b.replace(pat2, "");\r
- buff = b.getBytes(StandardCharsets.UTF_8);\r
- length = buff.length;\r
- f = true;\r
- }\r
-\r
- if (pos < length) {\r
- return buff[pos++] & 0xFF;\r
- }\r
- return is.read();\r
- }\r
-\r
- public XmlFilterNS(InputStream is) {\r
- this.is = is;\r
- }\r
- }\r
-\r
- private static class CharsetConverterInputStream extends InputStream {\r
-\r
- @SuppressWarnings("unused")\r
- private InputStream in;\r
- private PipedInputStream pipein;\r
- private OutputStream pipeout;\r
- private Reader r;\r
- private Writer w;\r
-\r
- public CharsetConverterInputStream(String csFrom, String csTo, InputStream in)\r
- throws IOException {\r
- this.in = in;\r
- r = new InputStreamReader(in, csFrom);\r
- pipein = new PipedInputStream();\r
- pipeout = new PipedOutputStream(pipein);\r
- w = new OutputStreamWriter(pipeout, csTo);\r
- }\r
-\r
- @Override\r
- public int read() throws IOException {\r
- if (pipein.available() > 0) {\r
- return pipein.read();\r
- }\r
- int c = r.read();\r
- if (c == -1) {\r
- return -1;\r
- }\r
- w.write(c);\r
- w.flush();\r
- return pipein.read();\r
- }\r
- }\r
-\r
- /**\r
- * @return\r
- * @throws Exception\r
- */\r
- private MessageFactory getSOAPMessageFactory() throws SOAPException {\r
- MessageFactory mf = null;\r
- mf = MessageFactory.newInstance();\r
- return mf;\r
- }\r
-\r
- /**\r
- * @param cookies\r
- * @return\r
- */\r
- private String getACSSessionCookieData(Cookie[] cookies) {\r
- String acsSessionID = null;\r
- if (null != cookies) {\r
- for (Cookie cookie : cookies) {\r
- if (cookie.getName().equals(ACS_SESSIONID)) {\r
- acsSessionID = cookie.getValue();\r
- logger.debug("The session id is {}", acsSessionID);\r
- }\r
- }\r
- }\r
- return acsSessionID;\r
- }\r
-\r
- /**\r
- * @param cookies\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- private String getCWMPVersionCookieData(Cookie[] cookies) throws TR069EventProcessingException {\r
- String cwmpVersion = null;\r
- try {\r
- if (null != cookies) {\r
- for (Cookie cookie : cookies) {\r
- if (cookie.getName().equals(CWMP_VERSION)) {\r
- cwmpVersion = cookie.getValue();\r
- if (cwmpVersion != null) {\r
- cwmpVersion = URLDecoder.decode(cwmpVersion, StandardCharsets.UTF_8.name());\r
- }\r
- logger.debug("The CWMP version supported by the device is: {}", cwmpVersion);\r
- }\r
- }\r
- }\r
- } catch (UnsupportedEncodingException e) {\r
- logger.error(e.getMessage());\r
- TR069EventProcessingException ex = new TR069EventProcessingException(\r
- ErrorCode.UNSUPPORTED_CHARACTER_ENCODING, StandardCharsets.UTF_8.name());\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
- return cwmpVersion;\r
- }\r
-\r
- /**\r
- * @param soapMsg\r
- */\r
- private void logSoapMsg(SOAPMessage soapMsg) {\r
- StringBuilder buffer = new StringBuilder();\r
- buffer.append(soapMsg.toString());\r
- ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
- try {\r
- soapMsg.writeTo(baos);\r
- } catch (SOAPException | IOException e) {\r
- logger.error("Error while writting soap message");\r
- }\r
- buffer.append(baos);\r
- String soapMessage = buffer.toString();\r
- logger.debug(soapMessage);\r
- }\r
-\r
- /**\r
- * @param response\r
- * @param out\r
- * @param fcodeAcsRequestDenied\r
- * @param faultString\r
- * @param id\r
- * @throws IOException\r
- */\r
- private void sendFault(HttpServletResponse response, ByteArrayOutputStream out,\r
- String fcodeAcsRequestDenied, String faultString, String id) throws IOException {\r
- Fault fault = new Fault(fcodeAcsRequestDenied, faultString, id);\r
- fault.writeTo(out);\r
- response.setContentLength(out.size());\r
- String sout = out.toString(UTF_8);\r
- sout = sout.replace('\'', '"');\r
- response.getOutputStream().print(sout);\r
- }\r
-\r
- private void logHeaderElements(Enumeration<String> headerName) {\r
- while (headerName.hasMoreElements()) {\r
- String requestHeader = headerName.nextElement();\r
- logger.debug("Request Headers {}", requestHeader);\r
- }\r
- }\r
-\r
- private String getRequestType(TR069RPC msg) {\r
- String requestType = msg.getName();\r
- if (requestType == null)\r
- requestType = "Empty Request";\r
-\r
- return requestType;\r
- }\r
-\r
- /******************************************************************************************************************/\r
-\r
- public DeviceEventHandler getDeviceEventHandler() {\r
- return deviceEventHandler;\r
- }\r
-\r
- public void setDeviceEventHandler(DeviceEventHandler deviceEventHandler) {\r
- this.deviceEventHandler = deviceEventHandler;\r
- }\r
-\r
-}\r
+/*
+ * ============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<String> 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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-\r
-package org.commscope.tr069adapter.acs.cpe;\r
-\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-import java.io.Serializable;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.Random;\r
-\r
-import javax.xml.soap.MessageFactory;\r
-import javax.xml.soap.Name;\r
-import javax.xml.soap.Node;\r
-import javax.xml.soap.SOAPBody;\r
-import javax.xml.soap.SOAPBodyElement;\r
-import javax.xml.soap.SOAPElement;\r
-import javax.xml.soap.SOAPEnvelope;\r
-import javax.xml.soap.SOAPException;\r
-import javax.xml.soap.SOAPFactory;\r
-import javax.xml.soap.SOAPHeader;\r
-import javax.xml.soap.SOAPHeaderElement;\r
-import javax.xml.soap.SOAPMessage;\r
-import javax.xml.soap.SOAPPart;\r
-\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Fault;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-public abstract class TR069RPC implements Serializable {\r
-\r
- private static final String HTTP_SCHEMA_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/";\r
-\r
- private static final long serialVersionUID = 7270475819053880884L;\r
-\r
- protected static final Logger logger = LoggerFactory.getLogger(TR069RPC.class);\r
-\r
- private Random mrandom = new Random();\r
-\r
- /** Creates a new instance of Message */\r
- public TR069RPC() {}\r
-\r
- public static final String ENVELOPE_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/";\r
-\r
- protected abstract void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException;\r
-\r
- protected abstract void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException;\r
-\r
- protected class ArrayType {\r
-\r
- public ArrayType() {\r
- super();\r
- }\r
-\r
- private String type;\r
-\r
- public String getType() {\r
- return type;\r
- }\r
-\r
- public Name getType(SOAPBodyElement body, SOAPFactory spf) throws SOAPException {\r
- int i = type.indexOf(':');\r
- if (i == -1) {\r
- return spf.createName(type);\r
- } else {\r
- String prefix = type.substring(0, i);\r
- SOAPBody b = (SOAPBody) body.getParentElement();\r
- SOAPEnvelope e = (SOAPEnvelope) b.getParentElement();\r
- SOAPHeader h = e.getHeader();\r
- String uri = null;\r
- try {\r
- uri = h.lookupNamespaceURI(prefix);\r
- } catch (Exception ee) {\r
- logger.error("While geting namespace URI 1 {}", ee.toString());\r
- }\r
- if (uri == null) {\r
- try {\r
- uri = e.lookupNamespaceURI(prefix);\r
- } catch (Exception ee) {\r
- logger.error("While geting namespace URI 2 {}", ee.toString());\r
- }\r
- }\r
- if (uri == null) {\r
- try {\r
- uri = b.lookupNamespaceURI(prefix);\r
- } catch (Exception ee) {\r
- logger.error("While geting namespace URI {} ", ee.toString());\r
- }\r
- }\r
- return spf.createName(type.substring(i + 1), prefix, uri);\r
- }\r
- }\r
-\r
- public void setType(String type) {\r
- this.type = type;\r
- }\r
- }\r
-\r
- public static SOAPBodyElement getRequest(SOAPMessage msg) throws SOAPException {\r
- SOAPBodyElement request = null;\r
- Iterator<Node> i1 = msg.getSOAPBody().getChildElements();\r
- while (i1.hasNext()) {\r
- Node n = i1.next();\r
- if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {\r
- request = (SOAPBodyElement) n;\r
- }\r
- }\r
- return request;\r
- }\r
-\r
- private static String getRequestName(SOAPMessage msg) throws SOAPException {\r
- if (msg.getSOAPBody().hasFault()) {\r
- return "Fault";\r
- }\r
- String name = "";\r
- SOAPBodyElement element = getRequest(msg);\r
- if (element != null) {\r
- name = element.getNodeName();\r
- }\r
- if (name.startsWith("cwmp:")) {\r
- name = name.substring(5);\r
- } else if (name.startsWith("cwmp_x:")) {\r
- name = name.substring(7);\r
- } else if (name.indexOf(':') != -1) {\r
- name = name.substring(name.indexOf(':') + 1, name.length());\r
- }\r
- return name;\r
- }\r
-\r
- public static TR069RPC parse(SOAPMessage soapMsg)\r
- throws SOAPException, InstantiationException, IllegalAccessException, ClassNotFoundException {\r
- String reqname = TR069RPC.getRequestName(soapMsg);\r
-\r
- TR069RPC msg = null;\r
- try {\r
- msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname)\r
- .newInstance();\r
- } catch (Exception e) {\r
- msg = (TR069RPC) Class.forName("org.commscope.tr069adapter.acs.cpe.rpc." + reqname)\r
- .newInstance();\r
- }\r
- msg = msg.parseSoapMessage(soapMsg);\r
- return msg;\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- private TR069RPC parseSoapMessage(SOAPMessage soapMsg) throws SOAPException {\r
- SOAPEnvelope env = soapMsg.getSOAPPart().getEnvelope();\r
-\r
- Iterator<String> pfxs = env.getNamespacePrefixes();\r
- while (pfxs.hasNext()) {\r
- String pfx = pfxs.next();\r
- String uri = env.getNamespaceURI(pfx);\r
- if (uri.startsWith("urn:dslforum-org:cwmp-")) {\r
- urnCWMP = uri;\r
- }\r
- }\r
- SOAPFactory spf = SOAPFactory.newInstance();\r
- SOAPBodyElement soaprequest = getRequest(soapMsg);\r
- SOAPHeader hdr = soapMsg.getSOAPHeader();\r
- id = "device_did_not_send_id"; // or make it null?...\r
- if (hdr != null) {\r
- try {\r
- id = getHeaderElement(spf, hdr, "ID");\r
- } catch (Exception e) {\r
- logger.error("While parsing the soap message {}", e.toString());\r
- }\r
- }\r
- name = getRequestName(soapMsg);\r
- if (soaprequest != null) {\r
- Fault fault = parseSOAPRequest(soaprequest, spf);\r
- if (fault != null)\r
- return fault;\r
- }\r
- return this;\r
- }\r
-\r
- private Fault parseSOAPRequest(SOAPBodyElement soaprequest, SOAPFactory spf)\r
- throws SOAPException {\r
- if (soaprequest != null) {\r
- try {\r
- parseBody(soaprequest, spf);\r
- } catch (Exception e) {\r
- SOAPElement se = getRequestChildElement(spf, soaprequest, FAULT_CODE);\r
- String fc = (se != null) ? se.getValue() : "0";\r
- SOAPElement se2 = getRequestChildElement(spf, soaprequest, FAULT_STRING);\r
- String fs = (se2 != null) ? se2.getValue() : "0";\r
-\r
- if (se != null || se2 != null) {\r
- return new Fault(fc, fs, id);\r
- }\r
- throw e;\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- public void writeTo(OutputStream out) {\r
- try {\r
- SOAPFactory spf = SOAPFactory.newInstance();\r
- MessageFactory factory = MessageFactory.newInstance();\r
- SOAPMessage soapMsg = factory.createMessage();\r
- SOAPPart part = soapMsg.getSOAPPart();\r
-\r
- SOAPEnvelope envelope = part.getEnvelope();\r
- SOAPHeader header = envelope.getHeader();\r
- SOAPBody body = envelope.getBody();\r
-\r
- String responseId = getId();\r
-\r
- envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");\r
- envelope.addNamespaceDeclaration("cwmp", urnCWMP);\r
- envelope.addNamespaceDeclaration("SOAP-ENC", HTTP_SCHEMA_ENCODING);\r
- envelope.addNamespaceDeclaration("SOAP-ENV", ENVELOPE_NAMESPACE);\r
- envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");\r
-\r
- SOAPElement element = header.addChildElement(spf.createName("ID", "cwmp", urnCWMP));\r
- element.addAttribute(spf.createName("mustUnderstand", "SOAP-ENV", ENVELOPE_NAMESPACE),\r
- responseId);\r
- element.addTextNode("1");\r
-\r
- body.setEncodingStyle(HTTP_SCHEMA_ENCODING);\r
- SOAPBodyElement bd = body.addBodyElement(spf.createName(name, CWMP, urnCWMP));\r
-\r
- if (name == null || name.equals("")) {\r
- name = this.getClass().getSimpleName();\r
- }\r
- createBody(bd, spf, id);\r
-\r
- soapMsg.writeTo(out);\r
- } catch (SOAPException ex) {\r
- logger.error("Exception occurred while constructing SOAP message: {}", ex.getMessage());\r
- } catch (IOException e) {\r
- logger.error("Exception occurred while constructing SOAP message: {}", e.getMessage());\r
- }\r
- }\r
-\r
- protected void createBody(SOAPBodyElement body, SOAPFactory spf, String key)\r
- throws SOAPException {\r
- logger.debug("Key element is: {}", key);\r
- createBody(body, spf);\r
- }\r
-\r
- protected SOAPElement getRequestChildElement(SOAPFactory f, SOAPElement req, String name) {\r
- @SuppressWarnings("unchecked")\r
- Iterator<Object> i = req.getChildElements();\r
- f.getClass();\r
- while (i.hasNext()) {\r
- Object o = i.next();\r
- try {\r
- Node nn = (Node) o;\r
- String n = nn.getLocalName();\r
- if (n != null && n.equals(name)) {\r
- return (SOAPElement) o;\r
- }\r
- } catch (Exception e) {\r
- logger.debug("Exception: {}, {}", e.getMessage(), e.getClass().getName());\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- protected SOAPElement getRequestChildElement2(SOAPFactory f, SOAPElement req, String name)\r
- throws SOAPException {\r
- return (SOAPElement) req.getChildElements(f.createName(name, CWMP, urnCWMP)).next();\r
- }\r
-\r
- protected String getRequestElement(SOAPFactory f, SOAPElement req, String name) {\r
- return getRequestChildElement(f, req, name).getValue();\r
- }\r
-\r
- protected String getRequestElement(SOAPFactory f, SOAPElement req, String name, String def) {\r
- String v = getRequestChildElement(f, req, name).getValue();\r
- return (v != null) ? v : def;\r
- }\r
-\r
- protected SOAPElement getRequestChildElement(SOAPElement req, Name name) {\r
- return (SOAPElement) req.getChildElements(name).next();\r
- }\r
-\r
- protected String getRequestElement(SOAPElement req, Name name) {\r
- return getRequestChildElement(req, name).getValue();\r
- }\r
-\r
- protected String getHeaderElement(SOAPFactory f, SOAPHeader hdr, String name)\r
- throws SOAPException {\r
- return ((SOAPHeaderElement) hdr.getChildElements(f.createName(name, CWMP, urnCWMP)).next())\r
- .getValue();\r
- }\r
-\r
- protected HashMap<String, String> parseParamList(SOAPElement body, SOAPFactory spf)\r
- throws SOAPException {\r
- return parseParamList(body, spf, "ParameterValueStruct", "Value");\r
- }\r
-\r
- protected HashMap<String, String> parseParamList(SOAPElement body, SOAPFactory spf, String sn,\r
- String vn) throws SOAPException {\r
- Iterator<SOAPElement> pi =\r
- getRequestChildElement(spf, body, "ParameterList").getChildElements(spf.createName(sn));\r
- Name nameKey = spf.createName("Name");\r
- Name nameValue = spf.createName(vn);\r
- HashMap<String, String> pl = new HashMap<>();\r
- while (pi.hasNext()) {\r
- SOAPElement param = pi.next();\r
- String key = getRequestElement(param, nameKey);\r
- String value = getRequestElement(param, nameValue);\r
- if (value == null) {\r
- value = "";\r
- }\r
- pl.put(key, value);\r
- }\r
- return pl;\r
- }\r
-\r
- protected int getArrayCount(SOAPFactory spf, SOAPElement e) throws SOAPException {\r
- return getArrayCount(spf, e, null);\r
- }\r
-\r
- protected int getArrayCount(SOAPFactory spf, SOAPElement e, ArrayType type) throws SOAPException {\r
- Name nameArray = spf.createName("arrayType", "soap-enc", HTTP_SCHEMA_ENCODING);\r
- String attr = e.getAttributeValue(nameArray);\r
- if (attr == null) {\r
- return 0;\r
- }\r
- attr = attr.replace(" ", "");\r
- int i = attr.indexOf('[');\r
- String c = attr.substring(i + 1, attr.length() - 1);\r
- if (type != null) {\r
- type.setType(attr.substring(0, i));\r
- }\r
- return Integer.parseInt(c);\r
- }\r
-\r
- public boolean isFault() {\r
- return name.equals("Fault");\r
- }\r
-\r
- protected String b2s(boolean b) {\r
- return (b) ? "1" : "0";\r
- }\r
-\r
- protected String name;\r
-\r
- public String getName() {\r
- return name;\r
- }\r
-\r
- protected String id;\r
-\r
- public String getId() {\r
- if (id == null) {\r
- id = "" + mrandom.nextInt(99999);\r
- }\r
- return id;\r
- }\r
-\r
- protected void println(StringBuilder b, String n, String v) {\r
- b.append(n);\r
- b.append(": ");\r
- b.append(v);\r
- b.append("\n");\r
- }\r
-\r
- protected void println(StringBuilder b, String n, String n2, String v) {\r
- b.append(n);\r
- println(b, n2, v);\r
- }\r
-\r
- public String getCWMPVersion() {\r
- return urnCWMP;\r
- }\r
-\r
- public void setCWMPVersion(String cwmpVersion) {\r
- urnCWMP = cwmpVersion;\r
- }\r
-\r
- protected String urnCWMP = "urn:dslforum-org:cwmp-1-0";\r
- protected static final String CWMP = "cwmp";\r
- protected static final String PARAMETER_KEY = "ParameterKey";\r
- protected static final String COMMAND_KEY = "CommandKey";\r
- protected static final String XSI_TYPE = "xsi:type";\r
- protected static final String XSD_STRING = "xsd:string";\r
- protected static final String XSD_UNSIGNEDINT = "xsd:unsignedInt";\r
- protected static final String XSD_INT = "xsd:int";\r
- protected static final String XSD_BOOLEAN = "xsd:boolean";\r
- protected static final String XSD_DATETIME = "xsd:dateTime";\r
- protected static final String XSD_BASE64 = "xsd:base64";\r
- protected static final String SOAP_ARRAY_TYPE = "SOAP-ENC:arrayType";\r
- public static final String FAULT_CODE = "FaultCode";\r
- public static final String FAULT_STRING = "FaultString";\r
- public static final String TYPE_OBJECT = "object";\r
- public static final String TYPE_STRING = "string";\r
- public static final String TYPE_BOOLEAN = "boolean";\r
- public static final String TYPE_DATETIME = "dateTime";\r
- public static final String TYPE_UNSIGNEDINT = "unsignedInt";\r
- public static final String TYPE_INT = "int";\r
- public static final String TYPE_BASE64 = "base64";\r
-\r
- public String getXmlType(String type) {\r
- if (type.equals(TYPE_BASE64)) {\r
- return TR069RPC.XSD_BASE64;\r
- } else if (type.equals(TYPE_BOOLEAN)) {\r
- return TR069RPC.XSD_BOOLEAN;\r
- } else if (type.equals(TYPE_DATETIME)) {\r
- return TR069RPC.XSD_DATETIME;\r
- } else if (type.equals(TYPE_INT)) {\r
- return TR069RPC.XSD_INT;\r
- } else if (type.equals(TYPE_OBJECT)) {\r
- return "";\r
- } else if (type.equals(TYPE_STRING)) {\r
- return TR069RPC.XSD_STRING;\r
- } else if (type.equals(TYPE_UNSIGNEDINT)) {\r
- return TR069RPC.XSD_UNSIGNEDINT;\r
- }\r
- return type;\r
- }\r
-}\r
+/*
+ * ============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<Node> 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<String> 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<Object> 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<String, String> parseParamList(SOAPElement body, SOAPFactory spf)
+ throws SOAPException {
+ return parseParamList(body, spf, "ParameterValueStruct", "Value");
+ }
+
+ protected HashMap<String, String> parseParamList(SOAPElement body, SOAPFactory spf, String sn,
+ String vn) throws SOAPException {
+ Iterator<SOAPElement> pi =
+ getRequestChildElement(spf, body, "ParameterList").getChildElements(spf.createName(sn));
+ Name nameKey = spf.createName("Name");
+ Name nameValue = spf.createName(vn);
+ HashMap<String, String> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe.builder;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.OperationCode;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.cpe.TR069RPC;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.AddObject;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.DeleteObject;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Download;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.FactoryReset;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterAttributes;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.GetParameterValues;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Reboot;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterAttributes;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.SetParameterValues;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class DeviceRPCBuilder {\r
-\r
- /**\r
- * @param deviceRPCRequest\r
- * @return\r
- */\r
- public TR069RPC constructDeviceRPC(DeviceRPCRequest deviceRPCRequest) {\r
- TR069RPC message = null;\r
-\r
- OperationDetails opDetails = deviceRPCRequest.getOpDetails();\r
- if (null == opDetails || null == opDetails.getOpCode()) {\r
- return null;\r
- }\r
-\r
- OperationCode opCode = opDetails.getOpCode();\r
- if (opCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) {\r
- message = buildSetParameterValues(opDetails);\r
- } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) {\r
- message = buildGetParameterValues(opDetails);\r
- } else if (opCode.equals(TR069OperationCode.SET_PARAMETER_ATTRIBUTES)) {\r
- message = buildSetParameterAttributes(opDetails);\r
- } else if (opCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) {\r
- message = buildGetParameterAttributes(opDetails);\r
- } else if (opCode.equals(TR069OperationCode.ADD_OBJECT)) {\r
- List<ParameterDTO> poarameterDTOs = opDetails.getParmeters();\r
- for (ParameterDTO param : poarameterDTOs) {\r
- AddObject addObject = new AddObject(param.getParamName(), String.valueOf(hashCode()));\r
- message = addObject;\r
- }\r
- } else if (opCode.equals(TR069OperationCode.DELETE_OBJECT)) {\r
- List<ParameterDTO> poarameterDTOs = opDetails.getParmeters();\r
- for (ParameterDTO param : poarameterDTOs) {\r
- DeleteObject deleteObject =\r
- new DeleteObject(param.getParamName(), String.valueOf(hashCode()));\r
- message = deleteObject;\r
- }\r
- } else if (opCode.equals(TR069OperationCode.DOWNLOAD)) {\r
- String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId();\r
- List<ParameterDTO> poarameterDTOs = opDetails.getParmeters();\r
- message = populateDownloadParams(deviceId, poarameterDTOs);\r
- } else if (opCode.equals(TR069OperationCode.FACTORY_RESET)) {\r
- message = new FactoryReset();\r
- } else if (opCode.equals(TR069OperationCode.REBOOT)) {\r
- message = new Reboot();\r
- }\r
-\r
- return message;\r
- }\r
-\r
- /**\r
- * @param poarameterDTOs\r
- * @return\r
- */\r
- private Download populateDownloadParams(String deviceId, List<ParameterDTO> poarameterDTOs) {\r
- Download download = new Download();\r
- for (ParameterDTO param : poarameterDTOs) {\r
- if (param.getParamName().equals("FileType")) {\r
- download.setFileType(param.getParamValue());\r
- } else if (param.getParamName().equals("URL")) {\r
- download.setUrl(param.getParamValue());\r
- } else if (param.getParamName().equals("Username")) {\r
- download.setUserName(param.getParamValue());\r
- } else if (param.getParamName().equals("Password")) {\r
- download.setPassword(param.getParamValue());\r
- } else if (param.getParamName().equals("FileSize")) {\r
- download.setFileSize(Long.parseLong(param.getParamValue()));\r
- } else if (param.getParamName().equals("TargetFileName")) {\r
- download.setTargetFileName(param.getParamValue());\r
- } else if (param.getParamName().equals("DelaySeconds")) {\r
- download.setDelaySeconds(Integer.parseInt(param.getParamValue()));\r
- } else if (param.getParamName().equals("SuccessURL")) {\r
- download.setSuccessUrl(param.getParamValue());\r
- } else if (param.getParamName().equals("FailureURL")) {\r
- download.setFailureUrl(param.getParamValue());\r
- }\r
- }\r
- download.setCommandKey(String.valueOf(deviceId));\r
-\r
- return download;\r
- }\r
-\r
- private SetParameterValues buildSetParameterValues(OperationDetails opDetails) {\r
- SetParameterValues spv = new SetParameterValues();\r
- List<ParameterDTO> parmeters = opDetails.getParmeters();\r
- for (ParameterDTO param : parmeters) {\r
- spv.addValue(param.getParamName(), param.getParamValue(), param.getDataType());\r
- }\r
-\r
- return spv;\r
- }\r
-\r
- private GetParameterValues buildGetParameterValues(OperationDetails opDetails) {\r
- GetParameterValues gpv = new GetParameterValues();\r
- List<ParameterDTO> parmeters = opDetails.getParmeters();\r
- List<String> paramNamelist = new ArrayList<>();\r
- for (ParameterDTO param : parmeters) {\r
- paramNamelist.add(param.getParamName());\r
- }\r
- String[] parameterNames = new String[paramNamelist.size()];\r
- for (int i = 0; i < paramNamelist.size(); i++) {\r
- parameterNames[i] = paramNamelist.get(i);\r
- }\r
- gpv.setParameterNames(parameterNames);\r
- return gpv;\r
- }\r
-\r
- private SetParameterAttributes buildSetParameterAttributes(OperationDetails opDetails) {\r
- SetParameterAttributes spa = new SetParameterAttributes();\r
- List<ParameterDTO> parameterAttributes = opDetails.getParmeters();\r
- for (ParameterDTO parameterDTO : parameterAttributes) {\r
- ParameterAttributeDTO parameterAttributeDTO = (ParameterAttributeDTO) parameterDTO;\r
- spa.addAttribute(parameterAttributeDTO.getParamName(),\r
- parameterAttributeDTO.getNotificationChange(), parameterAttributeDTO.getNotification(),\r
- parameterAttributeDTO.getAccesslistChange(), parameterAttributeDTO.getAccessList());\r
- }\r
- return spa;\r
- }\r
-\r
- private GetParameterAttributes buildGetParameterAttributes(OperationDetails opDetails) {\r
- GetParameterAttributes gpa = new GetParameterAttributes();\r
- List<ParameterDTO> poarameterDTOs = opDetails.getParmeters();\r
- List<String> paramNamelist = new ArrayList<>();\r
- for (ParameterDTO param : poarameterDTOs) {\r
- paramNamelist.add(param.getParamName());\r
- }\r
- String[] parameterNames = new String[paramNamelist.size()];\r
- for (int i = 0; i < paramNamelist.size(); i++) {\r
- parameterNames[i] = paramNamelist.get(i);\r
- }\r
- gpa.setParameterNames(parameterNames);\r
-\r
- return gpa;\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> parmeters = opDetails.getParmeters();
+ List<String> 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<ParameterDTO> 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<ParameterDTO> poarameterDTOs = opDetails.getParmeters();
+ List<String> 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;
+ }
+}
\r
import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_CF;\r
import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_REQ_Q;\r
+\r
import java.io.IOException;\r
+\r
import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
import org.commscope.tr069adapter.acs.cpe.processor.ConnectionReqEventProcessor;\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe.handler;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR;\r
-\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Set;\r
-\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.common.inform.AbstractDeviceInform;\r
-import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform;\r
-import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler;\r
-import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.cpe.TR069RPC;\r
-import org.commscope.tr069adapter.acs.cpe.builder.DeviceInformBuilder;\r
-import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCBuilder;\r
-import org.commscope.tr069adapter.acs.cpe.builder.DeviceRPCResponseBuilder;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Fault;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.Inform;\r
-import org.commscope.tr069adapter.acs.cpe.rpc.TransferComplete;\r
-import org.commscope.tr069adapter.common.timer.TimerException;\r
-import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class DeviceEventHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DeviceEventHandler.class);\r
-\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- private DeviceInformBuilder deviceInformBuilder;\r
-\r
- @Autowired\r
- private DeviceRPCBuilder deviceRPCBuilder;\r
-\r
- @Autowired\r
- private DeviceRPCResponseBuilder deviceRPCResponseBuilder;\r
-\r
- @Autowired\r
- private TR069DeviceEventHandler tr069DeviceEventHandler;\r
-\r
- @Autowired\r
- private TimerServiceManagerAPI timerServiceManagerAPI;\r
-\r
- @Autowired\r
- private DeviceValidator deviceValidtor;\r
-\r
- private static Map<String, List<String>> informParameter = null;\r
-\r
- static {\r
- informParameter = new HashMap<>();\r
- List<String> parameters = new ArrayList<>();\r
- parameters.add("InternetGatewayDevice.DeviceInfo.HardwareVersion");\r
- parameters.add("InternetGatewayDevice.DeviceInfo.SoftwareVersion");\r
- parameters.add("InternetGatewayDevice.DeviceInfo.ProvisioningCode");\r
- parameters.add("InternetGatewayDevice.ManagementServer.ConnectionRequestURL");\r
- parameters.add("InternetGatewayDevice.ManagementServer.ParameterKey");\r
- informParameter.put("InternetGatewayDevice", parameters);\r
-\r
- List<String> deviceParameters = new ArrayList<>();\r
- deviceParameters.add("Device.DeviceInfo.HardwareVersion");\r
- deviceParameters.add("Device.DeviceInfo.SoftwareVersion");\r
- deviceParameters.add("Device.DeviceInfo.ProvisioningCode");\r
- deviceParameters.add("Device.ManagementServer.ConnectionRequestURL");\r
- deviceParameters.add("Device.ManagementServer.ParameterKey");\r
- informParameter.put("Device", deviceParameters);\r
- }\r
-\r
- /**\r
- * @param inform\r
- * @param authorizationHeader\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- public DeviceInformResponse processDeviceInform(Inform inform, String authorizationHeader)\r
- throws TR069EventProcessingException {\r
-\r
- DeviceInformResponse deviceInformResponse = null;\r
- try {\r
- String deviceId = inform.getSn();\r
- MDC.put(CLIENT_STR, deviceId);\r
-\r
- logger.info("Processing the device Inform event");\r
-\r
- logger.debug("Authorization header received in the request -> {}", authorizationHeader);\r
- Boolean isAuthorized = deviceValidtor.isDeviceAuthorized(inform, authorizationHeader);\r
- logger.info("Is device authentication successful: {}", isAuthorized);\r
- if (!isAuthorized.booleanValue()) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.UNAUTHORIZED_EVENT, "Authorization failed");\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
-\r
- logger.debug("The root element is: {}", inform.getRoot());\r
- // Canceling any connection initiator timer running, due to inform event\r
- stopConnectionInitiatorTimer(inform.getSn());\r
-\r
- if (!deviceValidtor.validateDevice(inform.getSn(), inform.getOui(), inform.getProductClass())\r
- .booleanValue()) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.OUI_OR_PC_MISMATCH);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
-\r
- if (!validateInformParameters(inform)) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
-\r
- AbstractDeviceInform deviceInform = deviceInformBuilder.constructDeviceInform(inform);\r
- if (deviceInform == null) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.INVALID_PARAMS_IN_INFORM);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
-\r
- logger.debug("Sending the device inform to TR069 Request Processor to process");\r
- deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(deviceInform);\r
-\r
- } catch (TR069EventProcessingException tr069Ex) {\r
- throw tr069Ex;\r
- } catch (Exception e) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage());\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
-\r
- return deviceInformResponse;\r
-\r
- }\r
-\r
- /**\r
- * @param tc\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- public DeviceInformResponse processTransferComplete(TransferComplete tc)\r
- throws TR069EventProcessingException {\r
-\r
- logger.debug("Processing Transfer Complete");\r
-\r
- String startTime = tc.getStartTime();\r
- String completeTime = tc.getCompleteTime();\r
- int faultCode = tc.getFaultCode();\r
- String faultString = tc.getFaultString();\r
- String commandKey = tc.getCommandKey();\r
-\r
- DeviceInformResponse deviceInformResponse = null;\r
-\r
- try {\r
- MDC.put(CLIENT_STR, commandKey);\r
- TransferCompleteInform transferCompleteInform = new TransferCompleteInform();\r
- transferCompleteInform.setCommandKey(tc.getCommandKey());\r
- transferCompleteInform.setCompleteTime(completeTime);\r
- transferCompleteInform.setFaultCode(faultCode);\r
- transferCompleteInform.setFaultString(faultString);\r
- transferCompleteInform.setStartTime(startTime);\r
-\r
- logger.debug("TransferComplete inform received with Start time");\r
-\r
- transferCompleteInform.setDeviceDetails(tr069DeviceEventHandler.getDeviceDetails(commandKey));\r
- deviceInformResponse = tr069DeviceEventHandler.processDeviceInform(transferCompleteInform);\r
- logger.debug("Successfully processed the TRANSFER COMPLETE Inform");\r
-\r
- } catch (Exception e) {\r
- throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_INFORM, e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
-\r
- return deviceInformResponse;\r
- }\r
-\r
- /**\r
- * @param msg\r
- * @param sessionId\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- public TR069RPC processRPCResponse(TR069RPC msg, String sessionId)\r
- throws TR069EventProcessingException {\r
- DeviceOperationRequestDetails deviceOperationRequestDetails = null;\r
- try {\r
- deviceOperationRequestDetails =\r
- tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId);\r
- if (null == deviceOperationRequestDetails\r
- || null == deviceOperationRequestDetails.getDeviceDetails()) {\r
- logger.error("Response with invalid session ID: {}", sessionId);\r
- return null;\r
- }\r
-\r
- String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId();\r
- MDC.put(CLIENT_STR, deviceId);\r
- DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse();\r
- deviceRPCResponse.setDeviceDetails(deviceOperationRequestDetails.getDeviceDetails());\r
- deviceRPCResponse.setOperationId(deviceOperationRequestDetails.getOperationId());\r
- OperationResponse operationResponse = null;\r
- if (msg instanceof Fault) {\r
- Fault values = (Fault) msg;\r
- logger.info("{} ID->{} faultCode->{} faultString->{}", values.getName(), values.getId(),\r
- values.getCwmpFaultCode(), values.getFaultStringCwmp());\r
- deviceRPCResponse.setFaultKey(values.getCwmpFaultCode());\r
- deviceRPCResponse.setFaultString(\r
- values.getFaultStringCwmp() + ": Error code: " + values.getCwmpFaultCode());\r
-\r
- TR069OperationCode operationCode =\r
- (TR069OperationCode) deviceOperationRequestDetails.getOpCode();\r
- operationResponse = constructResponseForFault(operationCode);\r
- if (operationResponse != null) {\r
- operationResponse.setStatus(1);\r
- operationResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- }\r
- } else {\r
- operationResponse = deviceRPCResponseBuilder.constructDeviceRPCResponse(msg);\r
- }\r
- deviceRPCResponse.setOperationResponse(operationResponse);\r
-\r
- DeviceRPCRequest deviceRPCRequest =\r
- tr069DeviceEventHandler.processDeviceRPCResponse(deviceRPCResponse);\r
- if (null != deviceRPCRequest) {\r
- return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest);\r
- }\r
- } catch (SessionManagerException e) {\r
- logger.error("Error while getting device detail for the session id: {}", sessionId);\r
- } catch (Exception e) {\r
- throw new TR069EventProcessingException(ErrorCode.FAILED_PROCESSING_RPC_RESPONSE,\r
- msg.getName(), e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
-\r
- return null;\r
- }\r
-\r
- /**\r
- * @param sessionId\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- public TR069RPC processEmptyRequest(String sessionId) throws TR069EventProcessingException {\r
- try {\r
- DeviceOperationRequestDetails deviceOperationRequestDetails =\r
- tr069DeviceEventHandler.getOpRequestDetailsBySessionId(sessionId);\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- String deviceId = deviceOperationRequestDetails.getDeviceDetails().getDeviceId();\r
- MDC.put(CLIENT_STR, deviceId);\r
- deviceRPCRequest = tr069DeviceEventHandler\r
- .processEmptyDeviceRequest(deviceOperationRequestDetails.getDeviceDetails());\r
- if (null == deviceRPCRequest) {\r
- return null;\r
- } else {\r
- logger.debug("There exists a NBI request to process.");\r
- return deviceRPCBuilder.constructDeviceRPC(deviceRPCRequest);\r
- }\r
- } catch (SessionManagerException e) {\r
- logger.error("Error while processing empty request, reason: {}", e.getMessage());\r
- } catch (Exception e) {\r
- throw new TR069EventProcessingException(ErrorCode.EMPTY_REQUEST_PROCESSING_ERROR,\r
- e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- return null;\r
- }\r
-\r
- /**\r
- * @param operationCode\r
- * @return\r
- */\r
- private OperationResponse constructResponseForFault(TR069OperationCode operationCode) {\r
- OperationResponse operationResponse = null;\r
- if (operationCode.equals(TR069OperationCode.ADD_OBJECT)) {\r
- operationResponse = new org.commscope.tr069adapter.acs.common.response.AddObjectResponse();\r
- } else if (operationCode.equals(TR069OperationCode.DELETE_OBJECT)) {\r
- operationResponse = new org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse();\r
- } else if (operationCode.equals(TR069OperationCode.SET_PARAMETER_VALUES)) {\r
- operationResponse =\r
- new org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse();\r
- } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_VALUES)) {\r
- operationResponse =\r
- new org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse();\r
- } else if (operationCode.equals(TR069OperationCode.GET_PARAMETER_ATTRIBUTES)) {\r
- operationResponse =\r
- new org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse();\r
- }\r
- return operationResponse;\r
- }\r
-\r
- /**\r
- * @param serialNumber\r
- */\r
- public void stopConnectionInitiatorTimer(String serialNumber) {\r
- String timerId = serialNumber + SEPERATOR + CONNECTION_REQUEST;\r
- try {\r
- logger\r
- .debug("Canceling the Connection initiation timer, as Inform is been sent by the device");\r
- timerServiceManagerAPI.stopTimer(timerId);\r
- } catch (TimerException e) {\r
- logger.error(\r
- "An exception occurred while stopping the connection initiator session timer, Reason: {}",\r
- e.getMessage());\r
- }\r
- }\r
-\r
- /**\r
- * @param lastInform\r
- * @return\r
- */\r
- private boolean validateInformParameters(Inform lastInform) {\r
- boolean validate = false;\r
- String root = lastInform.getRoot();\r
- if (!informParameter.containsKey(root))\r
- return validate;\r
- List<String> params = informParameter.get(root);\r
- Set<String> keySet = lastInform.getParams().keySet();\r
- validate = true;\r
- for (String param : params) {\r
- if (!keySet.contains(param)) {\r
- logger.warn("This param Not found in the inform {}", param);\r
- validate = false;\r
- break;\r
- }\r
- }\r
- return validate;\r
- }\r
-\r
- /**\r
- * @param tr069ex\r
- * @return\r
- */\r
- public int handleException(TR069EventProcessingException tr069ex) {\r
-\r
- int errorresponseCode = 0;\r
-\r
- ErrorCode errorCode = tr069ex.getErrorCode();\r
- switch (errorCode) {\r
- case UNSUPPORTED_CHARACTER_ENCODING:\r
- case INVALID_PARAMS_IN_INFORM:\r
- case FAILED_PROCESSING_INFORM:\r
- errorresponseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;\r
- break;\r
- case UNAUTHORIZED_EVENT:\r
- errorresponseCode = HttpServletResponse.SC_UNAUTHORIZED;\r
- break;\r
- default:\r
- break;\r
- }\r
-\r
- return errorresponseCode;\r
- }\r
-\r
- /***************************************************************************************************************************/\r
-\r
- public void setDeviceInformBuilder(DeviceInformBuilder deviceInformBuilder) {\r
- this.deviceInformBuilder = deviceInformBuilder;\r
- }\r
-\r
- public void setDeviceRPCBuilder(DeviceRPCBuilder deviceRPCBuilder) {\r
- this.deviceRPCBuilder = deviceRPCBuilder;\r
- }\r
-\r
- public void setDeviceRPCResponseBuilder(DeviceRPCResponseBuilder deviceRPCResponseBuilder) {\r
- this.deviceRPCResponseBuilder = deviceRPCResponseBuilder;\r
- }\r
-\r
- public void setTr069DeviceEventHandler(TR069DeviceEventHandler tr069DeviceEventHandler) {\r
- this.tr069DeviceEventHandler = tr069DeviceEventHandler;\r
- }\r
-\r
- public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) {\r
- this.timerServiceManagerAPI = timerServiceManagerAPI;\r
- }\r
-\r
- public void setDeviceAuthenticator(DeviceValidator deviceAuthenticator) {\r
- this.deviceValidtor = deviceAuthenticator;\r
- }\r
-\r
-}\r
+/*
+ * ============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<String, List<String>> informParameter = null;
+
+ static {
+ informParameter = new HashMap<>();
+ List<String> 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<String> 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<String> params = informParameter.get(root);
+ Set<String> 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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe.processor;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_REQUEST;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CONNECTION_RETRY_SLEEP_TIME;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.CR_TIMEOUT_CALLBACK;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.HTTP_OP_FAILED;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAX_CONNECT_RETRY_COUNT;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SEPERATOR;\r
-\r
-import java.io.IOException;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.cpe.utils.DeviceConnector;\r
-import org.commscope.tr069adapter.common.timer.TimerException;\r
-import org.commscope.tr069adapter.common.timer.TimerServiceManagerAPI;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class ConnectionReqEventProcessor {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(ConnectionReqEventProcessor.class);\r
-\r
- @Autowired\r
- private DeviceConnector deviceConnector;\r
-\r
- @Autowired\r
- private TimerServiceManagerAPI timerServiceManagerAPI;\r
-\r
- public void initiateConnectionRequest(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry)\r
- throws SessionManagerException, IOException {\r
- DeviceRPCResponse deviceRPCResponse = null;\r
-\r
- for (int retryCount = 0; retryCount < MAX_CONNECT_RETRY_COUNT; retryCount++) {\r
- logger.info("Initiating connection request on the device. Connection request URL is : {}",\r
- tr069DeviceDetails.getConnectionRequestURL());\r
- deviceRPCResponse = deviceConnector.requestConnectionHttp(tr069DeviceDetails);\r
-\r
- if (deviceRPCResponse.getOperationResponse().getStatus() == HTTP_OP_FAILED) {\r
- onFailedHTTPGetOperation(deviceRPCResponse);\r
- logger.debug("Connection Request Retry attempt - {}", retryCount + 1);\r
-\r
- if ((retryCount + 1) == MAX_CONNECT_RETRY_COUNT) {\r
- SessionManagerException e = new SessionManagerException(\r
- ErrorCode.SESSION_INITIATION_FAILED, tr069DeviceDetails.getDeviceId());\r
- logger.error(e.getMessage());\r
- throw e;\r
- }\r
- } else {\r
- onSuccessHTTPGetOperation(tr069DeviceDetails, isRetry);\r
- break;\r
- }\r
- }\r
- }\r
-\r
- private void onFailedHTTPGetOperation(DeviceRPCResponse deviceRPCResponse) {\r
- logger.warn("Connection request failed with device, Error: {}",\r
- deviceRPCResponse.getFaultString());\r
- logger.debug("Waiting for " + CONNECTION_RETRY_SLEEP_TIME + " millisec before retry");\r
- try {\r
- Thread.sleep(CONNECTION_RETRY_SLEEP_TIME);\r
- } catch (InterruptedException e1) {\r
- logger.error("Interrupted exception while waiting for CR retry");\r
- Thread.currentThread().interrupt();\r
- }\r
- }\r
-\r
- private void onSuccessHTTPGetOperation(TR069DeviceDetails tr069DeviceDetails, Boolean isRetry) {\r
- try {\r
- String timerId = tr069DeviceDetails.getDeviceId() + SEPERATOR + CONNECTION_REQUEST;\r
- if (isRetry.booleanValue()) {\r
- timerServiceManagerAPI.modifyTimer(timerId, CR_TIMEOUT, tr069DeviceDetails);\r
- } else {\r
- timerServiceManagerAPI.startTimer(timerId, CR_TIMEOUT_CALLBACK, CR_TIMEOUT,\r
- tr069DeviceDetails);\r
- }\r
- logger.debug(\r
- "Successfully started the timer task for connection request initiation on device : {}",\r
- tr069DeviceDetails.getDeviceId());\r
- } catch (TimerException e) {\r
- logger.error("Couldn't start the timer task for connection request initiation on device : {}",\r
- tr069DeviceDetails.getDeviceId());\r
- }\r
- }\r
-\r
- public DeviceConnector getDeviceConnector() {\r
- return deviceConnector;\r
- }\r
-\r
- public void setDeviceConnector(DeviceConnector deviceConnector) {\r
- this.deviceConnector = deviceConnector;\r
- }\r
-\r
- public TimerServiceManagerAPI getTimerServiceManagerAPI() {\r
- return timerServiceManagerAPI;\r
- }\r
-\r
- public void setTimerServiceManagerAPI(TimerServiceManagerAPI timerServiceManagerAPI) {\r
- this.timerServiceManagerAPI = timerServiceManagerAPI;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.cpe.rpc;\r
-\r
-import javax.xml.soap.SOAPBodyElement;\r
-import javax.xml.soap.SOAPException;\r
-import javax.xml.soap.SOAPFactory;\r
-\r
-import org.commscope.tr069adapter.acs.cpe.TR069RPC;\r
-\r
-public class Upload extends TR069RPC {\r
-\r
- private static final long serialVersionUID = -3096728959585163928L;\r
-\r
- /** Creates a new instance of Upload */\r
- public Upload() {\r
- name = "Upload";\r
- username = "";\r
- password = "";\r
- delaySeconds = 0;\r
- fileType = FT_CONFIG;\r
- url = "http://192.168.1.1:8080/acs-war/upload/tst.cfg";\r
- commandKey = "default.command.key";\r
- }\r
-\r
- protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException {\r
- body.addChildElement(COMMAND_KEY).setValue(commandKey);\r
- body.addChildElement("FileType").setValue(fileType);\r
-\r
- body.addChildElement("URL").setValue(url);\r
- body.addChildElement("Username").setValue(username);\r
- body.addChildElement("Password").setValue(password);\r
- body.addChildElement("DelaySeconds").setValue(String.valueOf(delaySeconds));\r
- }\r
-\r
- protected void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException {\r
- logger.isDebugEnabled();\r
- }\r
-\r
- private String commandKey;\r
- private String fileType;\r
- private String url;\r
- private String username;\r
- private String password;\r
- private int delaySeconds;\r
- public static final String FT_CONFIG = "1 Vendor Configuration File";\r
- public static final String FT_LOG = "2 Vendor Log File";\r
-}\r
+/*
+ * ============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";
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.nbi.impl;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.exception.MapperServiceException;\r
-import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI;\r
-import org.commscope.tr069adapter.acs.nbi.util.OperationIdGenerator;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.core.JmsTemplate;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component(MAPPER_SERVICE_QUALILFIER)\r
-public class ACSServiceAPIImpl implements ACSServiceAPI {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(ACSServiceAPIImpl.class);\r
-\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- private OperationIdGenerator opIdGenerator;\r
-\r
- @Autowired\r
- private JmsTemplate jmsTemplate;\r
-\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.commscope.tr069adapter.acs.mapper.ACSServiceAPI#performDeviceOperation(org.commscope.\r
- * tr069adapter.acs.DeviceRPCRequest)\r
- */\r
- @Override\r
- public long performDeviceOperation(DeviceRPCRequest deviceRPCRequest)\r
- throws MapperServiceException {\r
-\r
- Long opId = 0l;\r
- try {\r
- if (deviceRPCRequest != null && deviceRPCRequest.getDeviceDetails() != null) {\r
- MDC.put(CLIENT_STR, deviceRPCRequest.getDeviceDetails().getDeviceId());\r
- }\r
-\r
- // validate the request and reject if not valid.\r
- if (null == deviceRPCRequest) {\r
- logger.error("Received null Mapper Request.");\r
- throw new MapperServiceException("Received null Mapper Request.");\r
- } else if (null == deviceRPCRequest.getOpDetails()) {\r
- logger.error("Received null operation details.");\r
- throw new MapperServiceException("Received null operation details.");\r
- } else if (null == deviceRPCRequest.getOpDetails().getOpCode()) {\r
- logger.error("Received null operation code.");\r
- throw new MapperServiceException("Received null operation code.");\r
- }\r
-\r
- logger.info("Received request to perform device operation. OperationCode: {}",\r
- deviceRPCRequest.getOpDetails().getOpCode());\r
- opId = opIdGenerator.generateOpId();\r
- logger.debug("The operation ID generated for processing the Device RPC request is - {}",\r
- opId);\r
- // set opId and forward the request\r
- deviceRPCRequest.setOperationId(opId);\r
- jmsTemplate.convertAndSend(TR069_NBI_REQUEST_Q, deviceRPCRequest);\r
-\r
- logger.debug(\r
- "Successfully posted the Mapper Request to Queue with OperationId : {} OperationCode : {}",\r
- deviceRPCRequest.getOperationId(), deviceRPCRequest.getOpDetails().getOpCode());\r
- } catch (Exception ex) {\r
- MapperServiceException mapperEx =\r
- new MapperServiceException("ACS Internal Error. Unknown Exception. Details :", ex);\r
- logger.error(mapperEx.getMessage());\r
- throw mapperEx;\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
-\r
- return opId;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.nbi.impl;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_CF;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.annotation.JmsListener;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.transaction.annotation.Transactional;\r
-\r
-@Component\r
-public class DeviceInformForwarder {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DeviceInformForwarder.class);\r
-\r
- @Autowired\r
- private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService;\r
-\r
- @JmsListener(destination = NBI_NOTIFICATION_Q, containerFactory = NBI_NOTIFICATION_CF)\r
- @Transactional(rollbackFor = Exception.class)\r
- public void onMessage(DeviceInform notification) {\r
- if (null != notification) {\r
- logger.debug(\r
- "DeviceNotification message is received for deviceId : {} , Notification Type(s): {}",\r
- notification.getDeviceDetails().getDeviceId(), notification.getInformTypeList());\r
- deviceEventsMapperNotificationService.processDeviceNotification(notification);\r
- logger.debug("Successfully processed device notification.");\r
- } else {\r
- logger.error("Null device response is received!!!");\r
- }\r
- }\r
-}\r
+/*
+ * ============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!!!");
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.nbi.impl;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_CF;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.nbi.mapper.service.DeviceEventsMapperNotificationService;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.annotation.JmsListener;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.transaction.annotation.Transactional;\r
-\r
-@Component\r
-public class DeviceRPCResponseForwarder {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DeviceRPCResponseForwarder.class);\r
-\r
- @Autowired\r
- private DeviceEventsMapperNotificationService deviceEventsMapperNotificationService;\r
-\r
- @JmsListener(destination = NBI_OP_RESULT_Q, containerFactory = NBI_OP_RESULT_CF)\r
- @Transactional(rollbackFor = Exception.class)\r
- public void onMessage(DeviceRPCResponse opResult) {\r
- if (null != opResult) {\r
- logger.debug("NBIOperationResult message is received for deviceId : {}, , OprationId: {}",\r
- opResult.getDeviceDetails().getDeviceId(), opResult.getOperationId());\r
- deviceEventsMapperNotificationService.processOperationResponse(opResult);\r
- logger.debug("Successfully processed NBI operation result.");\r
- } else {\r
- logger.error("Null device response is received!!!");\r
- }\r
- }\r
-}\r
+/*
+ * ============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!!!");
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.nbi.mapper.service;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.MAPPER_SERVICE_QUALILFIER;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.exception.MapperServiceException;\r
-import org.commscope.tr069adapter.acs.common.mapper.ACSServiceAPI;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.beans.factory.annotation.Qualifier;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestBody;\r
-import org.springframework.web.bind.annotation.RequestMapping;\r
-import org.springframework.web.bind.annotation.RestController;\r
-\r
-@RestController\r
-@RequestMapping("/MapperService")\r
-public class MapperRequestRESTService {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(MapperRequestRESTService.class);\r
-\r
- @Qualifier(value = MAPPER_SERVICE_QUALILFIER)\r
- @Autowired\r
- ACSServiceAPI acsServiceAPI;\r
-\r
- @PostMapping("/initiateDeviceOperation")\r
- public Long initiateDeviceOperation(@RequestBody DeviceRPCRequest deviceRPCRequest) {\r
- logger.debug("Received a Device operation request from Mapper");\r
- Long operationId = 0l;\r
- try {\r
- operationId = acsServiceAPI.performDeviceOperation(deviceRPCRequest);\r
- logger.debug(\r
- "Successfully initiated device operation, The operation id for the request is: {}",\r
- operationId);\r
- } catch (MapperServiceException e) {\r
- logger.error("An exception occurred while calling the device operation, Reason: {}",\r
- e.getMessage());\r
- }\r
-\r
- return operationId;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.*;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.requestprocessor.service.TR069DeviceEventHandler;\r
-import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse;\r
-import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.transaction.annotation.Isolation;\r
-import org.springframework.transaction.annotation.Propagation;\r
-import org.springframework.transaction.annotation.Transactional;\r
-\r
-@Component\r
-public class TR069DeviceEventHandlerImpl implements TR069DeviceEventHandler {\r
-\r
- private static final String RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST =\r
- "Retry limit reached and failing the device unregister request";\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(TR069DeviceEventHandlerImpl.class);\r
-\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- private TR069RequestProcessEngine tr069RequestProcessEngine;\r
-\r
- public TR069RequestProcessEngine getProcessEngine() {\r
- return tr069RequestProcessEngine;\r
- }\r
-\r
- public void setProcessEngine(TR069RequestProcessEngine processEngine) {\r
- this.tr069RequestProcessEngine = processEngine;\r
- }\r
-\r
- @Override\r
- @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300,\r
- rollbackFor = RuntimeException.class)\r
- public DeviceInformResponse processDeviceInform(final DeviceInform deviceNotification)\r
- throws Exception {\r
- DeviceInformResponse deviceNotificationResponse = null;\r
- try {\r
- String deviceId = deviceNotification.getDeviceDetails().getDeviceId();\r
- MDC.put(CLIENT_STR, deviceId);\r
- deviceNotificationResponse =\r
- processDeviceInformWithRetryOnConcurrentAccess(deviceNotification);\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
-\r
- return deviceNotificationResponse;\r
- }\r
-\r
- @Override\r
- @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300,\r
- rollbackFor = RuntimeException.class)\r
- public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse operationResult)\r
- throws Exception {\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- try {\r
- String deviceId = operationResult.getDeviceDetails().getDeviceId();\r
- MDC.put(CLIENT_STR, deviceId);\r
- deviceRPCRequest = processDeviceRPCResponseWithRetryOnConcurrentAccess(operationResult);\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- return deviceRPCRequest;\r
- }\r
-\r
- @Override\r
- @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300,\r
- rollbackFor = RuntimeException.class)\r
- public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails)\r
- throws Exception {\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- try {\r
- String deviceId = deviceDetails.getDeviceId();\r
- MDC.put(CLIENT_STR, deviceId);\r
- deviceRPCRequest = processEmptyDeviceRequestWithRetryOnConcurrentAccess(deviceDetails);\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- return deviceRPCRequest;\r
- }\r
-\r
- @Override\r
- @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300,\r
- rollbackFor = RuntimeException.class)\r
- public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId)\r
- throws SessionManagerException {\r
- return tr069RequestProcessEngine.getOpRequestDetailsBySessionId(sessionId);\r
- }\r
-\r
- @Override\r
- @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, timeout = 300,\r
- rollbackFor = RuntimeException.class)\r
- public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException {\r
- return tr069RequestProcessEngine.getDeviceDetails(deviceId);\r
- }\r
-\r
- /**\r
- * @param deviceNotification\r
- * @return\r
- * @throws InterruptedException\r
- */\r
- private DeviceInformResponse processDeviceInformWithRetryOnConcurrentAccess(\r
- DeviceInform deviceNotification)\r
- throws SessionConcurrentAccessException, InterruptedException {\r
- logger.debug("Processing Device Inform Event");\r
- DeviceInformResponse deviceNotificationResponse = null;\r
- for (int i = 0; i < MAX_RETRY_LIMIT; i++) {\r
- try {\r
- deviceNotificationResponse =\r
- tr069RequestProcessEngine.processDeviceInform(deviceNotification);\r
- logger.debug("Successfully processed Device Inform Event");\r
- break;\r
- } catch (SessionConcurrentAccessException scae) {\r
- if ((i + 1) == MAX_RETRY_LIMIT) {\r
- logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST);\r
- throw scae;\r
- }\r
- Long delay = (i == 0) ? DELAY : DELAY * i;\r
- Thread.sleep(delay);\r
- }\r
- }\r
- return deviceNotificationResponse;\r
- }\r
-\r
- /**\r
- * @param operationResult\r
- * @return\r
- * @throws InterruptedException\r
- * @throws Exception\r
- */\r
- private DeviceRPCRequest processDeviceRPCResponseWithRetryOnConcurrentAccess(\r
- DeviceRPCResponse operationResult)\r
- throws SessionConcurrentAccessException, InterruptedException {\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- logger.debug("Processing Device operation response");\r
- for (int i = 0; i < MAX_RETRY_LIMIT; i++) {\r
- try {\r
- deviceRPCRequest = tr069RequestProcessEngine.processDeviceRPCResponse(operationResult);\r
- logger.debug("Successfully processed Device operation response");\r
- break;\r
- } catch (SessionConcurrentAccessException scae) {\r
- if ((i + 1) == MAX_RETRY_LIMIT) {\r
- logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST);\r
- throw scae;\r
- }\r
- Long delay = (i == 0) ? DELAY : DELAY * i;\r
- Thread.sleep(delay);\r
- }\r
- }\r
- return deviceRPCRequest;\r
- }\r
-\r
- /**\r
- * @param deviceDetails\r
- * @return\r
- * @throws InterruptedException\r
- * @throws Exception\r
- */\r
- private DeviceRPCRequest processEmptyDeviceRequestWithRetryOnConcurrentAccess(\r
- TR069DeviceDetails deviceDetails)\r
- throws SessionConcurrentAccessException, InterruptedException {\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- logger.debug("Processing Empty request");\r
- for (int i = 0; i < MAX_RETRY_LIMIT; i++) {\r
- try {\r
- deviceRPCRequest = tr069RequestProcessEngine.processEmptyDeviceRequest(deviceDetails);\r
- logger.debug("Successfully processed Empty request");\r
- break;\r
- } catch (SessionConcurrentAccessException scae) {\r
- if ((i + 1) == MAX_RETRY_LIMIT) {\r
- logger.error(RETRY_LIMIT_REACHED_AND_FAILING_THE_DEVICE_UNREGISTER_REQUEST);\r
- throw scae;\r
- }\r
- Long delay = (i == 0) ? DELAY : DELAY * i;\r
- Thread.sleep(delay);\r
- }\r
- }\r
- return deviceRPCRequest;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.custom;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NUMBER_REGEX;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SUCCESS;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.common.response.AddObjectResponse;\r
-import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse;\r
-import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse;\r
-import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData;\r
-import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity;\r
-import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine;\r
-import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component("ConfigureMultipleObject")\r
-public class ConfigureMultipleObject implements CustomOperation {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(ConfigureMultipleObject.class);\r
-\r
- @Autowired\r
- TR069RequestProcessEngine tr069ProcessEngine;\r
-\r
- @Autowired\r
- protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper;\r
-\r
- public CustomOperationData executeCustomLogic(CustomOperationData customOperationData)\r
- throws TR069EventProcessingException {\r
-\r
- TR069DeviceDetails deviceDetails = customOperationData.getDeviceDetails();\r
- DeviceRPCResponse deviceRPCResponse = customOperationData.getDeviceRPCResponse();\r
- DeviceRPCRequest nbiDeviceOperationRequest = customOperationData.getDeviceRPCRequest();\r
-\r
- logger.debug("Started processing Configure multiple object");\r
- DeviceRPCRequest operRequest = null;\r
- Long responseOperationId = null;\r
- if (deviceRPCResponse != null && deviceRPCResponse.getOperationId() != null) {\r
- responseOperationId = deviceRPCResponse.getOperationId();\r
- if (deviceRPCResponse.getFaultKey() != null && responseOperationId != null\r
- && responseOperationId.equals(nbiDeviceOperationRequest.getOperationId())) {\r
- logger.error("The Configure Multiple Object operation has failed, Reason: {}",\r
- deviceRPCResponse.getFaultString());\r
-\r
- logger.debug(\r
- "Deleting the NBI operation request for custom operation configureMultipleObjects with operation ID: {}",\r
- responseOperationId);\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntityList =\r
- deviceRPCRequestRepositoryHelper\r
- .findByDeviceIdAndOperationId(deviceDetails.getDeviceId(), responseOperationId);\r
- for (TR069DeviceRPCRequestEntity tr069DeviceRPCRequestEntity : tr069DeviceRPCRequestEntityList) {\r
- tr069DeviceRPCRequestEntity.setIsProcessed(Integer.valueOf(1));\r
- }\r
- deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList);\r
-\r
- OperationResponse operationResponse = new GetParameterValueResponse();\r
- operationResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- operationResponse.setStatus(1);\r
- deviceRPCResponse.setOperationResponse(operationResponse);\r
-\r
- customOperationData.setDeviceRPCResponse(deviceRPCResponse);\r
- customOperationData.setDeviceRPCRequest(null);\r
- logger.debug("Finished processing Configure multiple object");\r
- return customOperationData;\r
- }\r
- }\r
-\r
- TR069OperationDetails tr069OperationDetails =\r
- (TR069OperationDetails) nbiDeviceOperationRequest.getOpDetails();\r
- List<ParameterDTO> tr069deleteParamList = tr069OperationDetails.getDeleteParamList();\r
- List<ParameterDTO> tr069modifyParamList = tr069OperationDetails.getModifyParamList();\r
- List<ParameterDTO> tr069setParamList = tr069OperationDetails.getSetParamList();\r
-\r
- OperationOrder nextOperation = null;\r
- boolean isPendingOperationExists = true;\r
- final String NXT_OPERATION = "Next operation to be executed is : ";\r
-\r
- if ((responseOperationId == null) || (responseOperationId != null\r
- && !responseOperationId.equals(nbiDeviceOperationRequest.getOperationId()))) {\r
- // Must be called from Empty HTTP request, First operation to be called\r
-\r
- // Must be called from a different user operation, First operation to be called\r
- // if response operation id is different from current\r
- // nbiDevOperRequest operation id then first step is deleteObject\r
-\r
- nextOperation = OperationOrder.DELETE_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- } else {\r
- // Since the responseOperation is not null and equivalent, find the\r
- // response type and the take next action\r
- OperationResponse opResponse = deviceRPCResponse.getOperationResponse();\r
- if (opResponse instanceof DeleteObjectResponse) {\r
- logger.debug("Received delete object response");\r
- if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) {\r
- int i = 0;\r
- for (ParameterDTO deleteParam : tr069deleteParamList) {\r
- i++;\r
- if (!deleteParam.isProcessed()) {\r
- deleteParam.setProcessed(true);\r
- } else {\r
- continue;\r
- }\r
- logger.debug("Persisting the NBI request for deleteObject");\r
- // Update the existing NBI request\r
- List<TR069DeviceRPCRequestEntity> entityList =\r
- deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(\r
- deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId());\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntityList =\r
- TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest);\r
- for (int j = 0; j < entityList.size(); j++) {\r
- tr069DeviceRPCRequestEntityList.get(j).setId(entityList.get(j).getId());\r
- }\r
- deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList);\r
-\r
- if (tr069deleteParamList.size() > i) {\r
- nextOperation = OperationOrder.DELETE_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- break;\r
- } else {\r
- nextOperation = OperationOrder.ADD_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- }\r
- } else {\r
- nextOperation = OperationOrder.ADD_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- } else if (opResponse instanceof AddObjectResponse) {\r
- logger.debug("Received Add object response");\r
- if (null != tr069setParamList && !tr069setParamList.isEmpty()) {\r
- long instanceNumber;\r
- boolean addParamExist = false;\r
- AddObjectResponse addObjResponse =\r
- (AddObjectResponse) deviceRPCResponse.getOperationResponse();\r
- List<ParameterDTO> modifyParamList = new ArrayList<>();\r
- List<ParameterDTO> removeParamList = new ArrayList<>();\r
- ParameterDTO addParam = null;\r
-\r
- if (null != addObjResponse) {\r
- instanceNumber = addObjResponse.getInstanceNumber();\r
- String replaceIndex = null;\r
- String replaceParam = null;\r
-\r
- for (ParameterDTO setParam : tr069setParamList) {\r
- if (!setParam.isProcessed()) {\r
- String paramName = setParam.getParamName();\r
- final Matcher matcher = Pattern.compile(NUMBER_REGEX).matcher(paramName);\r
- String index = null;\r
- String modifyParamName = null;\r
- String subString = null;\r
- while (matcher.find()) {\r
- index = matcher.group().substring(1, matcher.group().length() - 1);\r
- StringBuilder sb = new StringBuilder(paramName);\r
- int lastIndex = paramName.lastIndexOf(matcher.group());\r
- modifyParamName = (sb.replace(lastIndex, lastIndex + matcher.group().length(),\r
- "." + instanceNumber + ".")).toString();\r
- subString = paramName.substring(0, matcher.start()) + ".";\r
- }\r
- if (null == replaceIndex)\r
- replaceIndex = index;\r
- if (null == replaceParam)\r
- replaceParam = subString;\r
- if (null != replaceIndex && null != index && replaceIndex.equals(index)\r
- && replaceParam.equalsIgnoreCase(subString)) {\r
- setParam.setProcessed(true);\r
- modifyParamList.add(prepareParamDTO(modifyParamName, null, setParam));\r
- removeParamList.add(prepareParamDTO(null, null, setParam));\r
- } else {\r
- addParamExist = true;\r
- }\r
- if (null == addParam) {\r
- logger.debug(\r
- "The device index chosen is {} for adding the NBI tab parameter with index {}",\r
- instanceNumber, replaceIndex);\r
- addParam = prepareParamDTO(subString + replaceIndex,\r
- String.valueOf(instanceNumber), setParam);\r
- }\r
- }\r
- }\r
- }\r
- // Replace index with instance number and add in modify param list\r
- if (!modifyParamList.isEmpty()) {\r
- tr069modifyParamList.addAll(modifyParamList);\r
- }\r
- // Prepare add object param and add in set param list\r
- if (null != addParam) {\r
- addParam.setDataType("1");\r
- tr069setParamList.add(addParam);\r
- }\r
- // Remove all processed set params from set param list\r
- if (!removeParamList.isEmpty()) {\r
- tr069setParamList.removeAll(removeParamList);\r
- }\r
-\r
- logger.debug("Persisting the NBI request for addObject");\r
- List<TR069DeviceRPCRequestEntity> entityList =\r
- deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(\r
- deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId());\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntityList =\r
- TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest);\r
- for (int i = 0; i < entityList.size(); i++) {\r
- tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId());\r
- }\r
- deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList);\r
-\r
- if (addParamExist) {\r
- nextOperation = OperationOrder.ADD_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- } else {\r
- nextOperation = OperationOrder.SET_PARAMETER_VALUE;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- } else {\r
- nextOperation = OperationOrder.SET_PARAMETER_VALUE;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- } else if (opResponse instanceof SetParameterValueResponse) {\r
- logger.debug("Received Set parameter value response");\r
- isPendingOperationExists = false;\r
- for (ParameterDTO setParam : tr069modifyParamList) {\r
- if (Boolean.TRUE.equals(setParam.isInitiated())\r
- && Boolean.FALSE.equals(setParam.isProcessed())) {\r
- setParam.setInitiated(Boolean.FALSE);\r
- setParam.setProcessed(Boolean.TRUE);\r
- } else if (Boolean.FALSE.equals(setParam.isInitiated())\r
- && Boolean.FALSE.equals(setParam.isProcessed())) {\r
- isPendingOperationExists = true;\r
- nextOperation = OperationOrder.SET_PARAMETER_VALUE;\r
- }\r
- }\r
-\r
- updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest);\r
- logger.debug("Next operation to be executed is : {}", nextOperation);\r
- }\r
- }\r
-\r
- if (isPendingOperationExists) {\r
- boolean checkForNextoperation = true;\r
- while (checkForNextoperation) {\r
- switch (nextOperation) {\r
- case DELETE_OBJECT:\r
- if (null != tr069deleteParamList && !tr069deleteParamList.isEmpty()) {\r
- logger.debug("Started executing delete object request");\r
- checkForNextoperation = false;\r
- DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest);\r
- List<ParameterDTO> deleteParamList = new ArrayList<>();\r
- // Just take the first not processed delete object from the list\r
- for (ParameterDTO deleteParam : tr069deleteParamList) {\r
- if (!deleteParam.isProcessed()) {\r
- deleteParamList.add(deleteParam);\r
- break;\r
- }\r
- }\r
- clonedOpRequest.setOpDetails(null);\r
- OperationDetails opDetails = new OperationDetails();\r
- opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT);\r
- opDetails.setParmeters(deleteParamList);\r
- clonedOpRequest.setOpDetails(opDetails);\r
- operRequest = clonedOpRequest;\r
- } else {\r
- nextOperation = OperationOrder.ADD_OBJECT;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- break;\r
- case ADD_OBJECT:\r
- if (null != tr069setParamList && !tr069setParamList.isEmpty()) {\r
- logger.debug("Started executing Add object request");\r
- checkForNextoperation = false;\r
- DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest);\r
- List<ParameterDTO> addParamList = new ArrayList<>();\r
- // Just take the first not processed delete object from the list\r
- for (ParameterDTO addParam : tr069setParamList) {\r
- if (!addParam.isProcessed()) {\r
- String addParamMO = null;\r
- final Matcher matcher =\r
- Pattern.compile(NUMBER_REGEX).matcher(addParam.getParamName());\r
- while (matcher.find()) {\r
- addParamMO = addParam.getParamName().substring(0, matcher.start()) + ".";\r
- }\r
- if (null != addParamMO) {\r
- addParamList.add(prepareParamDTO(addParamMO, null, addParam));\r
- }\r
- break;\r
- }\r
- }\r
- clonedOpRequest.setOpDetails(null);\r
- OperationDetails opDetails = new OperationDetails();\r
- opDetails.setOpCode(TR069OperationCode.ADD_OBJECT);\r
- opDetails.setParmeters(addParamList);\r
- clonedOpRequest.setOpDetails(opDetails);\r
- operRequest = clonedOpRequest;\r
- } else {\r
- nextOperation = OperationOrder.SET_PARAMETER_VALUE;\r
- logger.debug(NXT_OPERATION, nextOperation);\r
- }\r
- break;\r
- case SET_PARAMETER_VALUE:\r
- checkForNextoperation = false;\r
- if (null != tr069modifyParamList && !tr069modifyParamList.isEmpty()) {\r
- logger.debug("Started executing SPV request");\r
- DeviceRPCRequest clonedOpRequest = cloneNBIRequest(nbiDeviceOperationRequest);\r
- clonedOpRequest.setOpDetails(null);\r
- OperationDetails opDetails = new OperationDetails();\r
- opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES);\r
- List<ParameterDTO> unprocessedParamList = new ArrayList<>();\r
- ParameterDTO adminStateParam = null;\r
- for (ParameterDTO paramDTO : tr069modifyParamList) {\r
- if (!paramDTO.isProcessed()) {\r
- if (isAdminStateExists(paramDTO)) {\r
- adminStateParam = paramDTO;\r
- } else {\r
- unprocessedParamList.add(paramDTO);\r
- }\r
- }\r
- }\r
-\r
- if (null != adminStateParam && isAdminStateFalse(adminStateParam.getParamValue())) {\r
- List<ParameterDTO> adminStateParamList = new ArrayList<>();\r
- adminStateParam.setInitiated(Boolean.TRUE);\r
- adminStateParamList.add(adminStateParam);\r
- opDetails.setParmeters(adminStateParamList);\r
- updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest);\r
- } else if (!unprocessedParamList.isEmpty()) {\r
- setInititedFlagTrue(unprocessedParamList);\r
- opDetails.setParmeters(unprocessedParamList);\r
- updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest);\r
- } else if (null != adminStateParam\r
- && isAdminStateTrue(adminStateParam.getParamValue())) {\r
- List<ParameterDTO> paramList = new ArrayList<>();\r
- adminStateParam.setInitiated(Boolean.TRUE);\r
- paramList.add(adminStateParam);\r
- opDetails.setParmeters(paramList);\r
- updateParamChangedFlagInDb(deviceDetails.getDeviceId(), nbiDeviceOperationRequest);\r
- } else {\r
- isPendingOperationExists = false;\r
- }\r
-\r
- clonedOpRequest.setOpDetails(opDetails);\r
- operRequest = clonedOpRequest;\r
- } else {\r
- isPendingOperationExists = false;\r
- operRequest = null;\r
- }\r
- break;\r
- default:\r
- isPendingOperationExists = false;\r
- operRequest = null;\r
- }\r
- }\r
- }\r
-\r
- if (!isPendingOperationExists) {\r
- logger.debug(\r
- "No pending operation exists, hence marking the operation as processed with id {} "\r
- + "and sending GetParameterValueResponse for ConfigureMultipleObjects",\r
- responseOperationId);\r
- List<ParameterDTO> responseParamList = new ArrayList<>();\r
-\r
- if (tr069deleteParamList != null) {\r
- for (ParameterDTO delete : tr069deleteParamList) {\r
- delete.setParamValue(SUCCESS);\r
- delete.setDataType("2");\r
- responseParamList.add(delete);\r
- }\r
- }\r
-\r
- if (tr069modifyParamList != null) {\r
- for (ParameterDTO modify : tr069modifyParamList) {\r
- modify.setParamValue(SUCCESS);\r
- modify.setDataType("4");\r
- responseParamList.add(modify);\r
- }\r
- }\r
-\r
- responseParamList.addAll(tr069setParamList);\r
-\r
- OperationResponse operationResponse = new GetParameterValueResponse();\r
- operationResponse.setParameterDTOs(responseParamList);\r
- if (deviceRPCResponse != null) {\r
- deviceRPCResponse.setDeviceDetails(deviceDetails);\r
- deviceRPCResponse.setOperationResponse(operationResponse);\r
- deviceRPCResponse.setOperationId(responseOperationId);\r
- }\r
-\r
- logger.debug(\r
- "Prepared operation result for custom operation Configure Multiple Objects, hence marking as processed the corresponding NBI Operation request record");\r
- deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceDetails.getDeviceId(),\r
- responseOperationId);\r
- }\r
-\r
- customOperationData.setDeviceRPCResponse(deviceRPCResponse);\r
- customOperationData.setDeviceRPCRequest(operRequest);\r
- logger.debug("Finished processing Configure multiple object");\r
- return customOperationData;\r
- }\r
-\r
-\r
- enum OperationOrder {\r
-\r
- SET_PARAMETER_VALUE(null), ADD_OBJECT(SET_PARAMETER_VALUE), DELETE_OBJECT(ADD_OBJECT);\r
-\r
- OperationOrder nextOperation;\r
-\r
- OperationOrder(OperationOrder nextOperation) {\r
- this.nextOperation = nextOperation;\r
- }\r
-\r
- public OperationOrder getNextOperation() {\r
- return nextOperation;\r
- }\r
-\r
- }\r
-\r
- private DeviceRPCRequest cloneNBIRequest(DeviceRPCRequest nbiDeviceOperationRequest) {\r
- return new DeviceRPCRequest(nbiDeviceOperationRequest);\r
- }\r
-\r
- private ParameterDTO prepareParamDTO(String name, String value, ParameterDTO paramDTO) {\r
- ParameterDTO parameterDTO = new ParameterDTO();\r
- if (null != name) {\r
- parameterDTO.setParamName(name);\r
- } else {\r
- parameterDTO.setParamName(paramDTO.getParamName());\r
- }\r
- if (null != value) {\r
- parameterDTO.setParamValue(value);\r
- } else {\r
- parameterDTO.setParamValue(paramDTO.getParamValue());\r
- }\r
- parameterDTO.setDataType(paramDTO.getDataType());\r
- parameterDTO.setProcessed(paramDTO.isProcessed());\r
-\r
- return parameterDTO;\r
- }\r
-\r
- private boolean isAdminStateExists(ParameterDTO paramDTO) {\r
- return (paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATE)\r
- || paramDTO.getParamName().contains(TR069RequestProcessorUtility.ADMIN_STATUS));\r
- }\r
-\r
- private void updateParamChangedFlagInDb(String deviceId,\r
- DeviceRPCRequest nbiDeviceOperationRequest) throws TR069EventProcessingException {\r
- List<TR069DeviceRPCRequestEntity> entityList = deviceRPCRequestRepositoryHelper\r
- .findByDeviceIdAndOperationId(deviceId, nbiDeviceOperationRequest.getOperationId());\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntityList =\r
- TR069RequestProcessorUtility.convertToEntity(nbiDeviceOperationRequest);\r
- for (int i = 0; i < entityList.size(); i++) {\r
- tr069DeviceRPCRequestEntityList.get(i).setId(entityList.get(i).getId());\r
- }\r
- deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntityList);\r
- }\r
-\r
- private void setInititedFlagTrue(List<ParameterDTO> unprocessedParamList) {\r
- for (ParameterDTO paramDTO : unprocessedParamList) {\r
- paramDTO.setInitiated(Boolean.TRUE);\r
- }\r
- }\r
-\r
- private boolean isAdminStateFalse(String adminState) {\r
- return (null != adminState && (adminState.equalsIgnoreCase(Boolean.FALSE.toString())\r
- || adminState.equalsIgnoreCase("0")));\r
- }\r
-\r
- private boolean isAdminStateTrue(String adminState) {\r
- return (null != adminState && (adminState.equalsIgnoreCase(Boolean.TRUE.toString())\r
- || adminState.equalsIgnoreCase("1")));\r
- }\r
-\r
-}\r
+/*
+ * ============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<TR069DeviceRPCRequestEntity> 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<ParameterDTO> tr069deleteParamList = tr069OperationDetails.getDeleteParamList();
+ List<ParameterDTO> tr069modifyParamList = tr069OperationDetails.getModifyParamList();
+ List<ParameterDTO> 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<TR069DeviceRPCRequestEntity> entityList =
+ deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(
+ deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId());
+ List<TR069DeviceRPCRequestEntity> 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<ParameterDTO> modifyParamList = new ArrayList<>();
+ List<ParameterDTO> 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<TR069DeviceRPCRequestEntity> entityList =
+ deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(
+ deviceDetails.getDeviceId(), nbiDeviceOperationRequest.getOperationId());
+ List<TR069DeviceRPCRequestEntity> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<TR069DeviceRPCRequestEntity> entityList = deviceRPCRequestRepositoryHelper
+ .findByDeviceIdAndOperationId(deviceId, nbiDeviceOperationRequest.getOperationId());
+ List<TR069DeviceRPCRequestEntity> 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<ParameterDTO> 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")));
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.entity;\r
-\r
-import java.io.Serializable;\r
-import java.util.Date;\r
-\r
-import javax.persistence.Column;\r
-import javax.persistence.Entity;\r
-import javax.persistence.GeneratedValue;\r
-import javax.persistence.GenerationType;\r
-import javax.persistence.Id;\r
-import javax.persistence.Table;\r
-import javax.persistence.UniqueConstraint;\r
-\r
-/**\r
- * The persistent class for the TR069_DEVICE_ database table.\r
- * \r
- */\r
-@Entity\r
-@Table(name = "TR069_DEVICE", uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"}))\r
-public class TR069DeviceEntity implements Serializable {\r
-\r
- private static final long serialVersionUID = -2696584252283707720L;\r
-\r
- @Id\r
- @GeneratedValue(strategy = GenerationType.AUTO)\r
- @Column(name = "ID")\r
- private Long id;\r
-\r
- @Column(name = "DEVICE_ID", length = 30)\r
- private String deviceId;\r
-\r
- @Column(name = "USER_NAME", length = 256)\r
- private String userName;\r
-\r
- @Column(name = "PASSWORD", length = 256)\r
- private String password;\r
-\r
- @Column(name = "HW_VERSION", length = 20)\r
- private String hwVersion;\r
-\r
- @Column(name = "SW_VERSION", length = 20)\r
- private String swVersion;\r
-\r
- @Column(name = "CONNECTION_REQUEST_URL", length = 1024)\r
- private String connectionReqURL;\r
-\r
- @Column(name = "LAST_UPDATED_TIME")\r
- private Date lastUpdatedTime;\r
-\r
- public TR069DeviceEntity() {\r
- super();\r
- }\r
-\r
- public Long getId() {\r
- return id;\r
- }\r
-\r
- public void setId(Long id) {\r
- this.id = id;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceID) {\r
- this.deviceId = deviceID;\r
- }\r
-\r
- public String getUserName() {\r
- return userName;\r
- }\r
-\r
- public void setUserName(String userName) {\r
- this.userName = userName;\r
- }\r
-\r
- public String getPassword() {\r
- return password;\r
- }\r
-\r
- public void setPassword(String password) {\r
- this.password = password;\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public String getConnectionReqURL() {\r
- return connectionReqURL;\r
- }\r
-\r
- public void setConnectionReqURL(String connectionReqURL) {\r
- this.connectionReqURL = connectionReqURL;\r
- }\r
-\r
- public Date getLastUpdatedTime() {\r
- return lastUpdatedTime;\r
- }\r
-\r
- public void setLastUpdatedTime(Date rowUpdatedTime) {\r
- this.lastUpdatedTime = rowUpdatedTime;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.handler;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_CF;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.TR069_NBI_REQUEST_Q;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException;\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.requestprocessor.impl.TR069RequestProcessEngine;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.annotation.JmsListener;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.transaction.annotation.Transactional;\r
-\r
-@Component\r
-public class DeviceRPCRequestHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DeviceRPCRequestHandler.class);\r
-\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- private TR069RequestProcessEngine tr069RequestProcessEngine;\r
-\r
- @JmsListener(destination = TR069_NBI_REQUEST_Q, containerFactory = TR069_NBI_REQUEST_CF)\r
- @Transactional(rollbackFor = Exception.class)\r
- public void onMessage(DeviceRPCRequest mapperDeviceOperationRequest)\r
- throws SessionConcurrentAccessException, TR069EventProcessingException {\r
- logger.debug("Received a JMS message from Mapper for TR069 Device RPC operation");\r
- try {\r
- if (mapperDeviceOperationRequest != null) {\r
- MDC.put(CLIENT_STR, mapperDeviceOperationRequest.getDeviceDetails().getDeviceId());\r
- logger.debug("Received a TR069 operation request from Mapper with operation ID: {} ",\r
- mapperDeviceOperationRequest.getOperationId());\r
- tr069RequestProcessEngine.processDeviceRPCRequest(mapperDeviceOperationRequest);\r
- logger.debug("Processed a TR069 operation request from Mapper with operation ID: {} ",\r
- mapperDeviceOperationRequest.getOperationId());\r
-\r
- }\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- logger.debug("Processed JMS message from Mapper for TR069 Device RPC operation");\r
-\r
- }\r
-\r
-}\r
+/*
+ * ============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");
+
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.helper;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.OPERATION_EXPIRATION_TIMEOUT;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode;\r
-import org.commscope.tr069adapter.acs.common.response.AddObjectResponse;\r
-import org.commscope.tr069adapter.acs.common.response.DeleteObjectResponse;\r
-import org.commscope.tr069adapter.acs.common.response.DownloadResponse;\r
-import org.commscope.tr069adapter.acs.common.response.FactoryResetResponse;\r
-import org.commscope.tr069adapter.acs.common.response.GetParameterAttributeResponse;\r
-import org.commscope.tr069adapter.acs.common.response.GetParameterValueResponse;\r
-import org.commscope.tr069adapter.acs.common.response.RebootResponse;\r
-import org.commscope.tr069adapter.acs.common.response.SetParameterAttributeResponse;\r
-import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class TR069RequestProcessEngineUtility {\r
-\r
- private static final Logger logger =\r
- LoggerFactory.getLogger(TR069RequestProcessEngineUtility.class);\r
-\r
- /**\r
- * Builds a operation aborted operation request\r
- * \r
- * @param deviceDetails\r
- * @param nbiDeviceOperationrequest\r
- * @param acsFaultCode\r
- * @return\r
- */\r
- public DeviceRPCResponse buildAbortedOperationresult(DeviceDetails deviceDetails,\r
- DeviceRPCRequest nbiDeviceOperationrequest, AcsFaultCode acsFaultCode) {\r
- Long operationId = nbiDeviceOperationrequest.getOperationId();\r
-\r
- TR069OperationCode operationCode = null;\r
- if (nbiDeviceOperationrequest.getOpDetails().getOpCode() instanceof CustomOperationCode) {\r
- operationCode = TR069OperationCode.GET_PARAMETER_VALUES;\r
- } else {\r
- operationCode = (TR069OperationCode) nbiDeviceOperationrequest.getOpDetails().getOpCode();\r
- }\r
-\r
- return buildOperationresult(deviceDetails, operationId, operationCode, acsFaultCode);\r
-\r
- }\r
-\r
- /**\r
- * @param deviceDetails\r
- * @param operationId\r
- * @param operationCode\r
- * @return\r
- */\r
- public DeviceRPCResponse buildTimedOutOperationResult(DeviceDetails deviceDetails,\r
- DeviceRPCRequest deviceRPCRequest) {\r
- Long operationId = deviceRPCRequest.getOperationId();\r
-\r
- TR069OperationCode operationCode = null;\r
- if (deviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) {\r
- CustomOperationCode customOperationCode =\r
- (CustomOperationCode) deviceRPCRequest.getOpDetails().getOpCode();\r
- if (CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS.equals(customOperationCode)) {\r
- operationCode = TR069OperationCode.GET_PARAMETER_VALUES;\r
- } else if (CustomOperationCode.CONNECT.equals(customOperationCode)) {\r
- operationCode = TR069OperationCode.INITIATE_CR;\r
- }\r
- } else {\r
- operationCode = (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode();\r
- }\r
- DeviceRPCResponse deviceRPCResponse = buildOperationresult(deviceDetails, operationId,\r
- operationCode, AcsFaultCode.FAULT_CODE_8003);\r
- OperationResponse operationResponse = deviceRPCResponse.getOperationResponse();\r
- operationResponse.setStatus(OPERATION_EXPIRATION_TIMEOUT);\r
- return deviceRPCResponse;\r
- }\r
-\r
- /**\r
- * Builds a operation aborted operation request\r
- * \r
- * @param deviceDetails\r
- * @param nbiDeviceOperationrequest\r
- * @param acsFaultCode\r
- * @return\r
- */\r
- private DeviceRPCResponse buildOperationresult(DeviceDetails deviceDetails, Long operationId,\r
- TR069OperationCode operationCode, AcsFaultCode acsFaultCode) {\r
- DeviceRPCResponse deviceRPCResponse = new DeviceRPCResponse();\r
- deviceRPCResponse.setDeviceDetails(deviceDetails);\r
- deviceRPCResponse.setOperationId(operationId);\r
-\r
- deviceRPCResponse.setFaultKey(acsFaultCode.getFaultKey());\r
- deviceRPCResponse.setFaultString(acsFaultCode.getFaultString());\r
-\r
- OperationResponse opResponse = null;\r
- switch (operationCode) {\r
- case GET_RPC_METHODS:\r
- case GET_PARAMETER_NAMES:\r
- break;\r
- case SET_PARAMETER_VALUES:\r
- opResponse = new SetParameterValueResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case GET_PARAMETER_VALUES:\r
- case INITIATE_CR:\r
- opResponse = new GetParameterValueResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case SET_PARAMETER_ATTRIBUTES:\r
- opResponse = new SetParameterAttributeResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case GET_PARAMETER_ATTRIBUTES:\r
- opResponse = new GetParameterAttributeResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case ADD_OBJECT:\r
- opResponse = new AddObjectResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case DELETE_OBJECT:\r
- opResponse = new DeleteObjectResponse();\r
- opResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
- break;\r
- case REBOOT:\r
- opResponse = new RebootResponse();\r
- break;\r
- case DOWNLOAD:\r
- opResponse = new DownloadResponse();\r
- break;\r
- case SCHEDULE_DOWNLOAD:\r
- case UPLOAD:\r
- case FACTORY_RESET:\r
- opResponse = new FactoryResetResponse();\r
- break;\r
- default:\r
- String operationCodeName = operationCode.name();\r
- logger.debug("An unsupported operation: {}, hence returning without response object",\r
- operationCodeName);\r
- break;\r
- }\r
- deviceRPCResponse.setOperationResponse(opResponse);\r
-\r
- return deviceRPCResponse;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.impl;\r
-\r
-import com.fasterxml.uuid.EthernetAddress;\r
-import com.fasterxml.uuid.Generators;\r
-import com.fasterxml.uuid.impl.TimeBasedGenerator;\r
-\r
-import java.util.Optional;\r
-import java.util.UUID;\r
-\r
-import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dao.SessionRepository;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState;\r
-import org.commscope.tr069adapter.acs.requestprocessor.entity.SessionManagerEntity;\r
-import org.commscope.tr069adapter.acs.requestprocessor.util.SessionManagerUtility;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class SessionManager {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);\r
-\r
- @Autowired\r
- SessionRepository sessionRepository;\r
-\r
- /**\r
- * @param deviceId\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public SessionDTO getSession(String deviceId) {\r
- SessionManagerEntity session = null;\r
- Optional<SessionManagerEntity> optionalSessionData = sessionRepository.findById(deviceId);\r
- if (optionalSessionData.isPresent()) {\r
- session = optionalSessionData.get();\r
- }\r
- return SessionManagerUtility.convertToDTO(session);\r
- }\r
-\r
- /**\r
- * @param sessionId\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public SessionDTO getSessionBySessionId(String sessionId) throws SessionManagerException {\r
-\r
- SessionManagerEntity sessionManagerEntity = sessionRepository.findBySessionId(sessionId);\r
- if (sessionManagerEntity == null || SessionState.TERMINATED\r
- .equals(SessionState.getByValue(sessionManagerEntity.getState()))) {\r
- throw new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId);\r
- }\r
- return SessionManagerUtility.convertToDTO(sessionManagerEntity);\r
- }\r
-\r
- /**\r
- * @param session\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public SessionDTO createSession(SessionDTO session) throws SessionManagerException {\r
- if (session == null) {\r
- SessionManagerException sme = new SessionManagerException(ErrorCode.SESSION_CREATION_ERROR,\r
- "Session object cannot be null");\r
- logger.error(sme.getMessage());\r
- throw sme;\r
- }\r
- logger.debug("Creating a new session for the device");\r
- return SessionManagerUtility\r
- .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(session)));\r
- }\r
-\r
- /**\r
- * @param dto\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public SessionDTO updateSession(SessionDTO dto) {\r
- return SessionManagerUtility\r
- .convertToDTO(sessionRepository.save(SessionManagerUtility.convertToEntity(dto)));\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @throws SessionConcurrentAccessException\r
- */\r
- public void deleteSession(String deviceId) {\r
- sessionRepository.deleteById(deviceId);\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public SessionDTO getLockedSession(String deviceId) {\r
- logger.debug("Acquiring the session lock for the device");\r
- return SessionManagerUtility.convertToDTO(sessionRepository.findByDeviceId(deviceId));\r
- }\r
-\r
- /**\r
- * @return\r
- */\r
- public String generateUniqueSessionID() {\r
- EthernetAddress addr = EthernetAddress.fromInterface();\r
- TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(addr);\r
- UUID uuid = uuidGenerator.generate();\r
- return uuid.toString();\r
- }\r
-\r
-}\r
+/*
+ * ============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<SessionManagerEntity> 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();
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.impl;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_NOTIFICATION_Q;\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.NBI_OP_RESULT_Q;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069InformType;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.core.JmsTemplate;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class TR069EventNotificationService {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(TR069EventNotificationService.class);\r
-\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- private JmsTemplate jmsTemplate;\r
-\r
- /**\r
- * @param deviceNotification\r
- */\r
- public void sendDeviceInformToNBI(DeviceInform deviceNotification) {\r
- String deviceId = deviceNotification.getDeviceDetails().getDeviceId();\r
- try {\r
- MDC.put(CLIENT_STR, deviceId);\r
- TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType();\r
-\r
- logger.debug("Device Inform Event received: '{}'", notificationType.getNotificationCode());\r
- jmsTemplate.convertAndSend(NBI_NOTIFICATION_Q, deviceNotification);\r
- logger.debug("Successfully posted the device inform event to DM to forward to NBI");\r
- } catch (Exception e) {\r
- logger.error("Posting Device Inform event to mapper failed, Reason: {}", e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- }\r
-\r
- /**\r
- * @param deviceRPCResponse\r
- */\r
- public void sendOperationResultToNBI(DeviceRPCResponse deviceRPCResponse) {\r
- String deviceId = deviceRPCResponse.getDeviceDetails().getDeviceId();\r
- try {\r
- MDC.put(CLIENT_STR, deviceId);\r
- if (deviceRPCResponse.getOperationResponse()\r
- .getOperationCode() instanceof TR069OperationCode) {\r
- TR069OperationCode operCode =\r
- (TR069OperationCode) deviceRPCResponse.getOperationResponse().getOperationCode();\r
- logger.debug("Device RPC Response received for operation: '" + operCode.name()\r
- + "' with operation ID:" + deviceRPCResponse.getOperationId());\r
- } else if (deviceRPCResponse.getOperationResponse()\r
- .getOperationCode() instanceof CustomOperationCode) {\r
- CustomOperationCode operCode =\r
- (CustomOperationCode) deviceRPCResponse.getOperationResponse().getOperationCode();\r
- logger.debug("Device RPC Response received for operation: '" + operCode.getJndiName()\r
- + "' with operation ID:" + deviceRPCResponse.getOperationId());\r
- }\r
- jmsTemplate.convertAndSend(NBI_OP_RESULT_Q, deviceRPCResponse);\r
- logger.debug("Successfully posted the operation result event to DM to forward to NBI");\r
- } catch (Exception e) {\r
- logger.error("Posting Device RPC response event to mapper failed, Reason: {}",\r
- e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- }\r
-\r
-}\r
+/*
+ * ============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);
+ }
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.impl;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.SESSION_ID;\r
-\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationCode;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.DeviceOperationRequestDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069InformType;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.DeviceOperationException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionConcurrentAccessException;\r
-import org.commscope.tr069adapter.acs.common.exception.SessionManagerException;\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.common.faults.AcsFaultCode;\r
-import org.commscope.tr069adapter.acs.common.inform.BootInform;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.acs.common.response.DeviceInformResponse;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.requestprocessor.DeviceOperationInterface;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dao.DeviceRPCRequestRepositoryHelper;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.CustomOperationData;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionDTO;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.SessionState;\r
-import org.commscope.tr069adapter.acs.requestprocessor.dto.TR069RequestProcessorData;\r
-import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity;\r
-import org.commscope.tr069adapter.acs.requestprocessor.helper.TR069RequestProcessEngineHelper;\r
-import org.commscope.tr069adapter.acs.requestprocessor.util.TR069RequestProcessorUtility;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class TR069RequestProcessEngine extends TR069RequestProcessEngineHelper {\r
-\r
- private static final String PENDING_RPC_CHECK =\r
- "Checking if any pending Device RPC requests exists for the device";\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(TR069RequestProcessEngine.class);\r
-\r
- @Autowired\r
- TR069EventNotificationService tr069EventNotificationService;\r
-\r
- @Autowired\r
- DeviceOperationInterface deviceOperationInterface;\r
-\r
- @Autowired\r
- protected DeviceRPCRequestRepositoryHelper deviceRPCRequestRepositoryHelper;\r
-\r
- /**\r
- * @param deviceRPCRequest\r
- * @throws TR069EventProcessingException\r
- * @throws SessionConcurrentAccessException\r
- */\r
- public void processDeviceRPCRequest(DeviceRPCRequest deviceRPCRequest)\r
- throws TR069EventProcessingException, SessionConcurrentAccessException {\r
-\r
- DeviceRPCResponse deviceRPCResponse = null;\r
- String deviceId = null;\r
-\r
- try {\r
- if (deviceRPCRequest == null) {\r
- TR069EventProcessingException ex =\r
- new TR069EventProcessingException(ErrorCode.INVALID_NBI_REQUEST);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
-\r
- Long operationId = deviceRPCRequest.getOperationId();\r
- logger.info("A Mapper request is received with operationID: {}", operationId);\r
- TR069DeviceDetails tr069DeviceDetails = null;\r
- deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId();\r
- try {\r
- tr069DeviceDetails = deviceOperationInterface.getDeviceDetails(deviceId);\r
- deviceRPCResponse = checkForDeviceAvailabilityRequest(deviceRPCRequest, tr069DeviceDetails);\r
- if (null != deviceRPCResponse) {\r
- return;\r
- }\r
- } catch (DeviceOperationException | SessionManagerException deo) {\r
- logger.error(deo.getMessage());\r
- deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult(\r
- tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8000);\r
- return;\r
- }\r
-\r
- try {\r
- SessionDTO sessionDTO = acquireSessionLockWithRetryOnFailure(deviceId, operationId);\r
-\r
- logger.debug("Persisting the Device RPC request, with operation ID: {}", operationId);\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntities =\r
- TR069RequestProcessorUtility.convertToEntity(deviceRPCRequest);\r
- deviceRPCRequestRepositoryHelper.saveAll(tr069DeviceRPCRequestEntities);\r
- logger.info("Successfully persisted the Device RPC request");\r
-\r
- if (sessionDTO != null) {\r
- if (SessionState.TERMINATED.equals(sessionDTO.getSessionState())) {\r
- logger.debug("No active session exists, hence requesting for Connection request");\r
- requestForConnectionRequestInform(tr069DeviceDetails);\r
-\r
- // Start Request Timer\r
- startDeviceRPCRequestTimer(deviceId, deviceRPCRequest.getOperationId(),\r
- deviceRPCRequest.getOptions().getExecutionTimeout());\r
- } else {\r
- logger.debug(\r
- "Session is in processing state, Will be notified to session manager to pick the request on session availability");\r
- }\r
- } else {\r
- logger.warn(\r
- "The device is not activated yet, hence the NBI Operation result cannot be processed!");\r
- deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult(\r
- tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8001);\r
- }\r
- } catch (SessionConcurrentAccessException scae) {\r
- throw scae;\r
- } catch (Exception e) {\r
- logger.error("An unknown exception occurred while processing the NBI request, Reason: {}",\r
- e.getMessage());\r
- deviceRPCResponse = tr069RequestProcessEngineUtility.buildAbortedOperationresult(\r
- tr069DeviceDetails, deviceRPCRequest, AcsFaultCode.FAULT_CODE_8004);\r
- }\r
- } finally {\r
- if (deviceRPCResponse != null) {\r
- logger.debug("Sending failed operation result for this NBI request");\r
- tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse);\r
- // Marking the NBI Request as processed\r
- deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId,\r
- deviceRPCRequest.getOperationId());\r
- }\r
- }\r
- }\r
-\r
- private DeviceRPCResponse checkForDeviceAvailabilityRequest(DeviceRPCRequest deviceRPCRequest,\r
- TR069DeviceDetails tr069DeviceDetails) throws SessionManagerException {\r
- DeviceRPCResponse deviceRPCResponse = null;\r
-\r
- if (!deviceRPCRequest.getOpDetails().getOpCode().equals(CustomOperationCode.CONNECT)) {\r
- return deviceRPCResponse;\r
- }\r
-\r
- SessionDTO sessionDTO = getSession(tr069DeviceDetails.getDeviceId());\r
-\r
- if (null != sessionDTO && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) {\r
- logger.debug("Device is reachable as device tr069 session is in {} state.",\r
- sessionDTO.getSessionState());\r
-\r
- deviceRPCResponse = new DeviceRPCResponse();\r
- deviceRPCResponse.setDeviceDetails(tr069DeviceDetails);\r
- deviceRPCResponse.setOperationId(deviceRPCRequest.getOperationId());\r
-\r
- OperationResponse operationResponse = new OperationResponse();\r
- // device reachable...change value 1 to some constant or enum\r
- operationResponse.setStatus(TR069RequestProcessorUtility.DEVICE_REACHABLE_STATUS_CODE);\r
- operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode());\r
-\r
- deviceRPCResponse.setOperationResponse(operationResponse);\r
- }\r
-\r
- return deviceRPCResponse;\r
- }\r
-\r
- /**\r
- * Common Step 1. Since there can exist only one Inform from any device, which will be the\r
- * initiator of the session, following steps to be followed a. Stop the session timer for this\r
- * device if any running. b. Get the lock by reading the session record for this device from DB\r
- * and load the session object in Thread Local Cache c. Create a new session id from\r
- * SessionManager, and update the session object with new Session id and change the state to\r
- * PROCESSING. 2. Read the Device record from the DB, and load the device DTO also in the\r
- * ThreadLocalCache\r
- * \r
- * Common Notification Specific Step 1. Take the connection request URL from the\r
- * deviceNotification object 2. Update the Device DTO object with connection request URL,\r
- * swVersion, hwVersion if there is a difference. Update the last updated time if updated 3. Send\r
- * this Inform to the NBI, by calling the ProcessDeviceInform method on TR069NBIService module. 4.\r
- * Create the Inform response Object and update the sessionID used for this transaction in the\r
- * response which will be used in the cookie of the HTTP response 5. Post the message into\r
- * Response Queue 6. Change the session state to LOCKED 7. Save the Session and device records\r
- * with the values in ThreadLocalCache 8. Start the session timer and default request timer (As\r
- * configured for all the requests from device) 8. All the above steps to be executed in a single\r
- * transaction.\r
- * \r
- * @param deviceNotification\r
- * @return\r
- * @throws SessionConcurrentAccessException\r
- */\r
- public DeviceInformResponse processDeviceInform(DeviceInform deviceNotification)\r
- throws SessionConcurrentAccessException {\r
-\r
- String deviceId = deviceNotification.getDeviceDetails().getDeviceId();\r
- TR069InformType notificationType = (TR069InformType) deviceNotification.getInformType();\r
- logger.info("Processing the Device Inform Event: '{}'", notificationType.getNotificationCode());\r
- String newSessionId = null;\r
- SessionDTO session = null;\r
- TR069DeviceDetails deviceDetails = null;\r
- DeviceInformResponse informResponse = null;\r
-\r
- try {\r
-\r
- SessionDTO sessionDTO = getSession(deviceId);\r
- if (sessionDTO != null && !SessionState.TERMINATED.equals(sessionDTO.getSessionState())) {\r
- String sessionId = sessionDTO.getSessionId();\r
- logger.debug(\r
- "The session with session id {} is not terminated, hence stopping the associated timer",\r
- sessionId);\r
- stopSessionTimer(sessionDTO.getSessionId());\r
- }\r
-\r
- // To stop the request timer if any running for this device, and send failed operation\r
- // result for any such pending cases. Requests pending in DB should not be cleared\r
-\r
- /*\r
- * Read any pending records in TR069_NBI_REQUEST table for this device. Send abort operation\r
- * result for all the pending requests Delete the records from the TR069_NBI_Request table for\r
- * this device.\r
- */\r
- if (deviceNotification instanceof BootstrapInform\r
- || deviceNotification instanceof BootInform) {\r
- sendAbortedOperationResultForPendingRPCRequests(deviceNotification.getDeviceDetails(),\r
- notificationType);\r
- }\r
-\r
- session = acquireSessionLock(deviceId, notificationType, true);\r
- deviceDetails = getPersistedDeviceDetails(deviceId, deviceNotification);\r
-\r
- newSessionId = session.getSessionId();\r
- logger.debug("The session id generated to process the device notification request is: {} ",\r
- newSessionId);\r
-\r
- initThreadLocalCache(deviceDetails, session);\r
- TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData();\r
- updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId);\r
-\r
- logger.debug("Sending the Device Inform Event to the Mapper");\r
- tr069EventNotificationService.sendDeviceInformToNBI(deviceNotification);\r
-\r
- updateDeviceDetailsFromInform(tr069RequestProcessorData, deviceNotification);\r
-\r
- logger.debug("Updating the session for the device with newly generated session id");\r
- changeSessionState(tr069RequestProcessorData, SessionState.LOCKED);\r
- updateSession(session);\r
-\r
- // Start session timer - Get a default timeout for session.\r
- startSessionTimer(session.getSessionId());\r
-\r
- informResponse =\r
- new DeviceInformResponse(newSessionId, deviceNotification.getDeviceDetails());\r
- } catch (\r
-\r
- DeviceOperationException doe) {\r
- logger.error(doe.getMessage());\r
- } catch (SessionConcurrentAccessException scae) {\r
- throw scae;\r
- } catch (Exception e) {\r
- throw new SessionConcurrentAccessException(ErrorCode.UNKNOWN_ERROR, e.getMessage());\r
- }\r
- return informResponse;\r
- }\r
-\r
- /**\r
- * \r
- * 1. Stop the request timer for this device using the session ID received in the cookie of the\r
- * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the\r
- * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check\r
- * if any pending request being notified for the device using in memory cache - Not planned for\r
- * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request\r
- * is pending.\r
- * \r
- * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the\r
- * response object and update the sessionID used for this transaction in the response which will\r
- * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4.\r
- * Change the session state to LOCKED and update the OPERATION_ID in the session table with the\r
- * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6.\r
- * Start the session timer and request timer (available in the request) } else { 1. Move the\r
- * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record\r
- * with the values in ThreadLocalCache. 3. Start the session timer. }\r
- * \r
- * 6. All the above steps to be executed in a single transaction\r
- * \r
- * @param deviceRPCResponse\r
- * @return\r
- * @throws SessionConcurrentAccessException\r
- */\r
- public DeviceRPCRequest processDeviceRPCResponse(DeviceRPCResponse deviceRPCResponse)\r
- throws SessionConcurrentAccessException {\r
- TR069DeviceDetails deviceDetails = (TR069DeviceDetails) deviceRPCResponse.getDeviceDetails();\r
- String deviceId = deviceDetails.getDeviceId();\r
- logger.info("Processing the operation response from device");\r
-\r
- SessionDTO session;\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- try {\r
- session = acquireSessionLock(deviceId, null, false);\r
- String newSessionId = session.getSessionId();\r
- logger.debug("The session id used to process the device RPC response is: {}", newSessionId);\r
-\r
- initThreadLocalCache(deviceDetails, session);\r
- TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData();\r
- updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId);\r
-\r
- Long operationId = deviceRPCResponse.getOperationId();\r
-\r
- deviceRPCRequest = getNextRPCRequest(deviceId, operationId);\r
-\r
- if (deviceRPCRequest != null) {\r
- OperationDetails opDetails = deviceRPCRequest.getOpDetails();\r
- if (opDetails != null) {\r
- OperationCode opCode = opDetails.getOpCode();\r
- if (opCode instanceof CustomOperationCode) {\r
- CustomOperationCode customOperationCode = (CustomOperationCode) opCode;\r
- String customOperationCodeName = customOperationCode.name();\r
- logger.info(\r
- "The Device RPC request is of custom type, the custom operation to be performed is: {}",\r
- customOperationCodeName);\r
- String jndiName = customOperationCode.getJndiName();\r
- CustomOperationData customOperationData =\r
- new CustomOperationData(deviceDetails, deviceRPCResponse, deviceRPCRequest);\r
- customOperationData = executeCustomOperation(jndiName, customOperationData);\r
-\r
- DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest();\r
- deviceRPCResponse = customOperationData.getDeviceRPCResponse();\r
- if (operationRequest != null) {\r
- return handleOperationRequest(deviceRPCResponse, session, deviceRPCRequest,\r
- newSessionId, tr069RequestProcessorData, operationRequest);\r
- } else {\r
- logger.debug(PENDING_RPC_CHECK);\r
- deviceRPCRequest =\r
- deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId);\r
- }\r
- }\r
- }\r
- }\r
-\r
- if (deviceRPCRequest != null) {\r
- logger.info("A pending Device RPC request exists for the device with operation ID: {}",\r
- deviceRPCRequest.getOperationId());\r
- updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId());\r
- changeSessionState(tr069RequestProcessorData, SessionState.LOCKED);\r
-\r
- deviceRPCRequest.addContextParam(SESSION_ID, newSessionId);\r
-\r
- } else {\r
- logger.info(\r
- "No pending Device RPC request exists for the device, hence empty response will be sent to the device");\r
- logger.debug("Updating the session to terminated state");\r
- // To stop the session timer if any running for this device.\r
- stopSessionTimer(newSessionId);\r
- changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED);\r
- }\r
-\r
- // To stop the request timer if any running for this operation.\r
- stopDeviceRPCRequestTimer(deviceId, deviceRPCResponse.getOperationId());\r
-\r
- // Sending the operation response to NBI\r
- logger.debug("Sending the Device RPC Response to the Mapper");\r
- tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse);\r
-\r
- updateSession(session);\r
- } catch (DeviceOperationException doe) {\r
- logger.error(doe.getMessage());\r
- } catch (SessionConcurrentAccessException scae) {\r
- throw scae;\r
- }\r
-\r
- return deviceRPCRequest;\r
- }\r
-\r
- private DeviceRPCRequest handleOperationRequest(DeviceRPCResponse deviceRPCResponse,\r
- SessionDTO session, DeviceRPCRequest deviceRPCRequest, String newSessionId,\r
- TR069RequestProcessorData tr069RequestProcessorData, DeviceRPCRequest operationRequest) {\r
- operationRequest.addContextParam(SESSION_ID, newSessionId);\r
- updateSessionCurOpId(tr069RequestProcessorData, deviceRPCRequest.getOperationId());\r
- changeSessionState(tr069RequestProcessorData, SessionState.LOCKED);\r
- updateSession(session);\r
- if (deviceRPCResponse != null && operationRequest.getOperationId() != null\r
- && !operationRequest.getOperationId().equals(deviceRPCResponse.getOperationId())) {\r
- logger\r
- .debug("Sending the Device RPC response for a configure Multiple object prior operation");\r
- // Sending the operation response to NBI\r
- tr069EventNotificationService.sendOperationResultToNBI(deviceRPCResponse);\r
- }\r
- return operationRequest;\r
- }\r
-\r
- /**\r
- * \r
- * 1. Stop the request timer for this device using the session ID received in the cookie of the\r
- * request 2. Read the session record from the session table into ThreadLocalCache 3. Move the\r
- * session state to PROCESSING and update the OPERATION_ID as null. 4a. Session Manager to check\r
- * if any pending request being notified for the device using in memory cache - Not planned for\r
- * this Drop 4. As an interim solution for drop1, Check the TR069_NBI_REQUEST table if any request\r
- * is pending.\r
- * \r
- * if (anyPendingRequestExists) { 1. Pick the request with the least created_time 2. Create the\r
- * response object and update the sessionID used for this transaction in the response which will\r
- * be used in the cookie of the HTTP response 3. Post the response object into Response Queue 4.\r
- * Change the session state to LOCKED and update the OPERATION_ID in the session table with the\r
- * NBI requests OPERATION_ID. 5. Save the Session record with the values in ThreadLocalCache 6.\r
- * Start the session timer and request timer (available in the request) } else { 1. Move the\r
- * session state to PROCESSING and update the OPERATION_ID as null. 2. Save the Session record\r
- * with the values in ThreadLocalCache. 3. Start the session timer. }\r
- * \r
- * 6. All the above steps to be executed in a single transaction\r
- * \r
- * @param deviceDetails\r
- * @return\r
- * @throws SessionConcurrentAccessException\r
- */\r
- public DeviceRPCRequest processEmptyDeviceRequest(TR069DeviceDetails deviceDetails)\r
- throws SessionConcurrentAccessException {\r
- String deviceId = deviceDetails.getDeviceId();\r
- logger.info("Processing the empty request from device");\r
-\r
- SessionDTO session;\r
- DeviceRPCRequest nbiDeviceOperationRequest = null;\r
- try {\r
- session = acquireSessionLock(deviceId, null, false);\r
- String newSessionId = session.getSessionId();\r
- logger.debug("The session id used to process the empty device request is: {}", newSessionId);\r
-\r
- initThreadLocalCache(deviceDetails, session);\r
- TR069RequestProcessorData tr069RequestProcessorData = getTR069RequestProcessorData();\r
- updateSessionOnDeviceNotification(tr069RequestProcessorData, newSessionId);\r
-\r
- logger.debug(PENDING_RPC_CHECK);\r
- nbiDeviceOperationRequest =\r
- deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId);\r
- if (nbiDeviceOperationRequest != null) {\r
- Long operationId = nbiDeviceOperationRequest.getOperationId();\r
- OperationDetails opDetails = nbiDeviceOperationRequest.getOpDetails();\r
- if (opDetails != null) {\r
- OperationCode opCode = opDetails.getOpCode();\r
- if (opCode instanceof CustomOperationCode) {\r
- CustomOperationCode customOperationCode = (CustomOperationCode) opCode;\r
- String customOperationCodeName = customOperationCode.name();\r
- logger.info(\r
- "The Device RPC operation request is of custom type, the custom operation to be performed is: {}",\r
- customOperationCodeName);\r
- String jndiName = customOperationCode.getJndiName();\r
- CustomOperationData customOperationData =\r
- new CustomOperationData(deviceDetails, null, nbiDeviceOperationRequest);\r
- customOperationData = executeCustomOperation(jndiName, customOperationData);\r
-\r
- DeviceRPCRequest operationRequest = customOperationData.getDeviceRPCRequest();\r
- if (operationRequest != null) {\r
- operationRequest.addContextParam(SESSION_ID, newSessionId);\r
- updateSessionCurOpId(tr069RequestProcessorData, operationId);\r
- changeSessionState(tr069RequestProcessorData, SessionState.LOCKED);\r
- updateSession(session);\r
- return operationRequest;\r
- } else {\r
- logger.debug(PENDING_RPC_CHECK);\r
- nbiDeviceOperationRequest =\r
- deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId);\r
- }\r
- }\r
- }\r
- }\r
-\r
- if (nbiDeviceOperationRequest != null) {\r
- Long operationId = nbiDeviceOperationRequest.getOperationId();\r
- logger.info("A pending Device RPC request exists for the device with operation ID: {}",\r
- operationId);\r
- updateSessionCurOpId(tr069RequestProcessorData, operationId);\r
- changeSessionState(tr069RequestProcessorData, SessionState.LOCKED);\r
-\r
- nbiDeviceOperationRequest.addContextParam(SESSION_ID, newSessionId);\r
-\r
- } else {\r
- logger.info(\r
- "No pending Device RPC request exists for the device, hence empty device response will be sent to the device");\r
- logger.debug("Updating the session to terminated state");\r
- // To stop the session timer if any running for this device.\r
- stopSessionTimer(newSessionId);\r
- changeSessionState(tr069RequestProcessorData, SessionState.TERMINATED);\r
- }\r
-\r
- updateSession(session);\r
- } catch (DeviceOperationException doe) {\r
- logger.error(doe.getMessage());\r
- } catch (SessionConcurrentAccessException scae) {\r
- throw scae;\r
- }\r
-\r
- return nbiDeviceOperationRequest;\r
- }\r
-\r
- /**\r
- * @param sessionId\r
- * @return\r
- * @throws SessionManagerException\r
- */\r
- public DeviceOperationRequestDetails getOpRequestDetailsBySessionId(String sessionId)\r
- throws SessionManagerException {\r
- DeviceOperationRequestDetails deviceOperationRequestDetails =\r
- new DeviceOperationRequestDetails();\r
-\r
- logger.debug("Fetching Operation request details for session: {}", sessionId);\r
- SessionDTO session = getSessionBySessionId(sessionId);\r
- String deviceId = session.getDeviceId();\r
- TR069DeviceDetails deviceDetails = null;\r
- try {\r
- deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId);\r
- if (session.getCurrentOperationId() == null) {\r
- logger.debug("There exists no pending operation request for the session: {}", sessionId);\r
- } else {\r
- logger.debug("There exists pending operation request for the session: {}", sessionId);\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntityList =\r
- deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId,\r
- session.getCurrentOperationId());\r
- if (tr069DeviceRPCRequestEntityList == null) {\r
- SessionManagerException ex =\r
- new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
- DeviceRPCRequest deviceRPCRequest =\r
- TR069RequestProcessorUtility.convertToDTO(tr069DeviceRPCRequestEntityList);\r
- OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode();\r
-\r
- String operationName = null;\r
-\r
- if (opCode instanceof TR069OperationCode) {\r
- operationName = ((TR069OperationCode) opCode).name();\r
- } else {\r
- operationName = ((CustomOperationCode) opCode).name();\r
- TR069OperationDetails tr069OperationDetails =\r
- (TR069OperationDetails) deviceRPCRequest.getOpDetails();\r
- opCode = getCustomOperationCode(tr069OperationDetails);\r
- }\r
- logger.info("The pending operation request for the session is of operation {}",\r
- operationName);\r
- deviceOperationRequestDetails.setOpCode(opCode);\r
- deviceOperationRequestDetails.setOperationId(deviceRPCRequest.getOperationId());\r
- }\r
- deviceOperationRequestDetails.setDeviceDetails(deviceDetails);\r
- } catch (DeviceOperationException e) {\r
- SessionManagerException ex =\r
- new SessionManagerException(ErrorCode.DEVICE_NOT_EXISTS, deviceId);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- } catch (Exception e) {\r
- logger.error(e.getMessage());\r
- SessionManagerException ex =\r
- new SessionManagerException(ErrorCode.SESSION_EXPIRED, sessionId);\r
- logger.error(ex.getMessage());\r
- throw ex;\r
- }\r
- return deviceOperationRequestDetails;\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @return\r
- * @throws DeviceOperationException\r
- */\r
- public TR069DeviceDetails getDeviceDetails(String deviceId) throws DeviceOperationException {\r
- return deviceOperationInterface.getDeviceDetails(deviceId);\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param operationId\r
- * @return\r
- * @throws DeviceOperationException\r
- * @throws SessionConcurrentAccessException\r
- * @throws InterruptedException\r
- */\r
- private SessionDTO acquireSessionLockWithRetryOnFailure(String deviceId, Long operationId)\r
- throws DeviceOperationException, SessionConcurrentAccessException, InterruptedException {\r
- int sessionLockAcquireRetryCount = 0;\r
- SessionDTO sessionDTO = null;\r
- do {\r
- try {\r
- sessionDTO = acquireSessionLock(deviceId, null, false);\r
- logger.info(\r
- "Successfully acquired the session lock for processing NBI request with operation ID: {}",\r
- operationId);\r
- break;\r
- } catch (SessionConcurrentAccessException ex) {\r
- sessionLockAcquireRetryCount++;\r
- if (sessionLockAcquireRetryCount == 3) {\r
- logger.error("Failed acquiring the lock after retry, rolling back the transaction");\r
- throw ex;\r
- }\r
- logger.warn(\r
- "Session lock acquiring failed with SessionConcurrentAccessException, hence retrying");\r
- Thread.sleep(1000L);\r
- }\r
- } while (sessionLockAcquireRetryCount < 3);\r
-\r
- return sessionDTO;\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param deviceNotification\r
- * @return\r
- * @throws DeviceOperationException\r
- */\r
- private TR069DeviceDetails getPersistedDeviceDetails(String deviceId,\r
- DeviceInform deviceNotification) throws DeviceOperationException {\r
- TR069DeviceDetails deviceDetails = null;\r
- try {\r
- deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId);\r
- } catch (DeviceOperationException doe) {\r
- if (ErrorCode.DEVICE_NOT_EXISTS.equals(doe.getErrorCode())) {\r
- logger.info(\r
- "Creating the device record in TR069_DEVICE_ table, as the device is authenticated successfully.");\r
- createDevice(deviceNotification.getDeviceDetails());\r
- deviceDetails = deviceOperationInterface.getDeviceDetails(deviceId);\r
- }\r
- }\r
-\r
- return deviceDetails;\r
- }\r
-\r
- /**\r
- * @param deviceDetails\r
- * @param notificationType\r
- * @throws TR069EventProcessingException\r
- */\r
- private void sendAbortedOperationResultForPendingRPCRequests(DeviceDetails deviceDetails,\r
- TR069InformType notificationType) throws TR069EventProcessingException {\r
- String deviceId = deviceDetails.getDeviceId();\r
- String notificationName = notificationType.name();\r
- logger.debug(\r
- "Device Inform event received is {}, hence aborting all the pending operations if any exists",\r
- notificationName);\r
-\r
- List<DeviceRPCRequest> deviceRPCRequestList =\r
- deviceRPCRequestRepositoryHelper.findAllDeviceRPCRequests(deviceId);\r
-\r
- for (DeviceRPCRequest pendingDeviceRPCRequest : deviceRPCRequestList) {\r
- DeviceRPCResponse deviceOpResult =\r
- tr069RequestProcessEngineUtility.buildAbortedOperationresult(deviceDetails,\r
- pendingDeviceRPCRequest, AcsFaultCode.FAULT_CODE_8002);\r
- String operationName = null;\r
- if (pendingDeviceRPCRequest.getOpDetails().getOpCode() instanceof CustomOperationCode) {\r
- CustomOperationCode operationCode =\r
- (CustomOperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode();\r
- operationName = operationCode.name();\r
- } else {\r
- TR069OperationCode operationCode =\r
- (TR069OperationCode) pendingDeviceRPCRequest.getOpDetails().getOpCode();\r
- operationName = operationCode.name();\r
- }\r
- Long operationId = pendingDeviceRPCRequest.getOperationId();\r
- logger.debug("Aborting the NBI Operation request with operation Id : {} for operation: {}",\r
- operationId, operationName);\r
- tr069EventNotificationService.sendOperationResultToNBI(deviceOpResult);\r
- // Marking the NBI Request as processed\r
- deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId);\r
- stopDeviceRPCRequestTimer(deviceId, operationId);\r
- }\r
- }\r
-\r
- /**\r
- * @param tr069RequestProcessorData\r
- * @param deviceNotification\r
- */\r
- private void updateDeviceDetailsFromInform(TR069RequestProcessorData tr069RequestProcessorData,\r
- DeviceInform deviceNotification) {\r
- Boolean isDeviceDataChanged =\r
- isDeviceUpdateExists(tr069RequestProcessorData, deviceNotification);\r
- if (isDeviceDataChanged.booleanValue()) {\r
- updateDeviceDetails(tr069RequestProcessorData, deviceNotification);\r
- try {\r
- logger.info(\r
- "The device data like connection request URL/ Device SW/HW version has changed, hence updating the device details");\r
- deviceOperationInterface\r
- .updateDeviceDetails(tr069RequestProcessorData.getTr069DeviceDetails());\r
- } catch (DeviceOperationException e) {\r
- logger.error("Updating the device details with the notification details failed, Reason: {}",\r
- e.getMessage());\r
- logger.error(e.getMessage());\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param operationId\r
- * @return\r
- */\r
- private DeviceRPCRequest getNextRPCRequest(String deviceId, Long operationId) {\r
- DeviceRPCRequest deviceRPCRequest = null;\r
- try {\r
- List<TR069DeviceRPCRequestEntity> entityList =\r
- deviceRPCRequestRepositoryHelper.findByDeviceIdAndOperationId(deviceId, operationId);\r
- Integer operationCode = entityList.get(0).getOpCode();\r
- if (CustomOperationCode.getByOperationCode(operationCode) == null) {\r
- logger.info("Marking the Device RPC request with operation id - {} as processed.",\r
- operationId);\r
- deviceRPCRequestRepositoryHelper.markDeviceRPCRequestAsProcessed(deviceId, operationId);\r
- }\r
- logger.debug(PENDING_RPC_CHECK);\r
- deviceRPCRequest = deviceRPCRequestRepositoryHelper.findOldestDeviceRPCRequest(deviceId);\r
- } catch (TR069EventProcessingException e) {\r
- logger.error("An unknown exception occurred while fetching the NBI request, Reason: {}",\r
- e.getMessage());\r
- }\r
-\r
- return deviceRPCRequest;\r
- }\r
-\r
- /**\r
- * Creates the device in the DM module if factory imported already\r
- * \r
- * @param deviceDetails\r
- * @throws DeviceOperationException\r
- */\r
- private void createDevice(DeviceDetails deviceDetails) throws DeviceOperationException {\r
- deviceOperationInterface.updateDeviceDetails(deviceDetails);\r
- }\r
-}\r
+/*
+ * ============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<TR069DeviceRPCRequestEntity> 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<TR069DeviceRPCRequestEntity> 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<DeviceRPCRequest> 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<TR069DeviceRPCRequestEntity> 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);
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.util;\r
-\r
-import java.util.Date;\r
-\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceEntity;\r
-\r
-public class TR069NBIUtility {\r
-\r
- private TR069NBIUtility() {\r
- super();\r
- }\r
-\r
- /**\r
- * A utility method to convert the DTO to Domain object\r
- * \r
- * @param tr069DeviceDetails\r
- * @return\r
- */\r
-\r
- public static TR069DeviceEntity convertToEntity(TR069DeviceDetails tr069DeviceDetails) {\r
- TR069DeviceEntity tr069DeviceEntity = new TR069DeviceEntity();\r
- tr069DeviceEntity.setDeviceId(tr069DeviceDetails.getDeviceId());\r
- tr069DeviceEntity.setUserName(tr069DeviceDetails.getUsername());\r
- tr069DeviceEntity.setPassword(tr069DeviceDetails.getPassword());\r
- tr069DeviceEntity.setLastUpdatedTime(new Date());\r
-\r
- if (tr069DeviceDetails.getConnectionRequestURL() != null) {\r
- tr069DeviceEntity.setConnectionReqURL(tr069DeviceDetails.getConnectionRequestURL());\r
- }\r
- if (tr069DeviceDetails.getSoftwareVersion() != null) {\r
- tr069DeviceEntity.setSwVersion(tr069DeviceDetails.getSoftwareVersion());\r
- }\r
- if (tr069DeviceDetails.getHardwareVersion() != null) {\r
- tr069DeviceEntity.setHwVersion(tr069DeviceDetails.getHardwareVersion());\r
- }\r
-\r
- return tr069DeviceEntity;\r
- }\r
-\r
- /**\r
- * A utility method to convert the Domain object to DTO\r
- * \r
- * @param entity\r
- * @return\r
- */\r
- public static TR069DeviceDetails convertToDTO(TR069DeviceEntity entity) {\r
- TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails();\r
-\r
- tr069DeviceDetails.setDeviceId(entity.getDeviceId());\r
- tr069DeviceDetails.setUsername(entity.getUserName());\r
- tr069DeviceDetails.setPassword(entity.getPassword());\r
- tr069DeviceDetails.setSoftwareVersion(entity.getSwVersion());\r
- tr069DeviceDetails.setHardwareVersion(entity.getHwVersion());\r
- tr069DeviceDetails.setConnectionRequestURL(entity.getConnectionReqURL());\r
-\r
- return tr069DeviceDetails;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-\r
-package org.commscope.tr069adapter.acs.requestprocessor.util;\r
-\r
-import static org.commscope.tr069adapter.acs.common.utils.AcsConstants.DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS;\r
-\r
-import com.google.gson.Gson;\r
-import com.google.gson.reflect.TypeToken;\r
-\r
-import java.lang.reflect.Type;\r
-import java.util.ArrayList;\r
-import java.util.Date;\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.OperationCode;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.OperationOptions;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.ParameterAttributeDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.exception.TR069EventProcessingException;\r
-import org.commscope.tr069adapter.acs.common.utils.ErrorCode;\r
-import org.commscope.tr069adapter.acs.requestprocessor.entity.TR069DeviceRPCRequestEntity;\r
-\r
-public class TR069RequestProcessorUtility {\r
-\r
- protected static final int BLOCK_SIZE = 3999;\r
- protected static final int MAX_SIZE = 11998;\r
- public static final int DEVICE_REACHABLE_STATUS_CODE = 100;\r
- public static final String ADMIN_STATE = "FAPControl.LTE.AdminState";\r
- public static final String ADMIN_STATUS = "FAPControl.LTE.AdminStatus";\r
-\r
-\r
- private TR069RequestProcessorUtility() {\r
- super();\r
- }\r
-\r
- /**\r
- * Converts entity object to DTO\r
- * \r
- * @param entityList\r
- * @return\r
- */\r
- public static DeviceRPCRequest convertToDTO(List<TR069DeviceRPCRequestEntity> entityList) {\r
- DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest();\r
- OperationDetails operationDetails = new TR069OperationDetails();\r
-\r
- boolean isCustomOperation = true;\r
- OperationCode opCode = null;\r
-\r
- TR069DeviceRPCRequestEntity entity = entityList.get(0);\r
- if (CustomOperationCode.getByOperationCode(entity.getOpCode()) != null) {\r
- opCode = CustomOperationCode.getByOperationCode(entity.getOpCode());\r
- } else {\r
- opCode = TR069OperationCode.getByOperationCode(entity.getOpCode());\r
- isCustomOperation = false;\r
- }\r
-\r
- operationDetails.setOpCode(opCode);\r
- dtoFromEntityJson(operationDetails, entityList, isCustomOperation);\r
- deviceRPCRequest.setOpDetails(operationDetails);\r
-\r
- OperationOptions opOptions = new OperationOptions();\r
- opOptions.setExecutionTimeout(entity.getRequestTimeOut());\r
- deviceRPCRequest.setOptions(opOptions);\r
-\r
- TR069DeviceDetails deviceDetails = new TR069DeviceDetails();\r
- deviceDetails.setDeviceId(entity.getDeviceId());\r
-\r
- deviceRPCRequest.setDeviceDetails(deviceDetails);\r
- deviceRPCRequest.setOperationId(entity.getOperationId());\r
- return deviceRPCRequest;\r
- }\r
-\r
- /**\r
- * Converts DTO to entity object\r
- * \r
- * @param deviceRPCRequest\r
- * @return\r
- * @throws TR069EventProcessingException\r
- */\r
- public static List<TR069DeviceRPCRequestEntity> convertToEntity(DeviceRPCRequest deviceRPCRequest)\r
- throws TR069EventProcessingException {\r
-\r
- if (deviceRPCRequest.getOpDetails() == null\r
- || deviceRPCRequest.getOpDetails().getOpCode() == null) {\r
- throw new TR069EventProcessingException(ErrorCode.MISSING_OPERATION_DETAILS);\r
- }\r
-\r
- Integer opCode = null;\r
- boolean isCustomOperation = true;\r
- OperationCode operationCode = deviceRPCRequest.getOpDetails().getOpCode();\r
- if (CustomOperationCode.getByOperationCode(operationCode.getOperationCode()) != null) {\r
- CustomOperationCode customOperationCode =\r
- CustomOperationCode.getByOperationCode(operationCode.getOperationCode());\r
- opCode = customOperationCode.getOperationCode();\r
- } else {\r
- TR069OperationCode tr069OperationCode =\r
- (TR069OperationCode) deviceRPCRequest.getOpDetails().getOpCode();\r
- opCode = tr069OperationCode.getOperationCode();\r
- isCustomOperation = false;\r
- }\r
-\r
- String paramListJSON = paramListToJson(deviceRPCRequest, isCustomOperation);\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntities =\r
- getTR069DeviceRPCRequestEntities(paramListJSON);\r
-\r
- for (TR069DeviceRPCRequestEntity entity : tr069DeviceRPCRequestEntities) {\r
- entity.setOpCode(opCode);\r
- entity.setCreateTime(new Date());\r
- entity.setDeviceId(deviceRPCRequest.getDeviceDetails().getDeviceId());\r
- entity.setOperationId(deviceRPCRequest.getOperationId());\r
- entity.setIsProcessed(0);\r
- if (deviceRPCRequest.getOptions() != null\r
- && deviceRPCRequest.getOptions().getExecutionTimeout() != 0L) {\r
- entity.setRequestTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout());\r
- } else {\r
- entity.setRequestTimeOut(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS);\r
- OperationOptions options = new OperationOptions();\r
- options.setExecutionTimeout(DEVICE_RPC_EXECUTION_TIMEOUT_SECONDS);\r
- deviceRPCRequest.setOptions(options);\r
- }\r
- }\r
-\r
- return tr069DeviceRPCRequestEntities;\r
- }\r
-\r
- /**\r
- * @param entity\r
- * @param dto\r
- * @param isCustomOperation\r
- */\r
- private static String paramListToJson(DeviceRPCRequest dto, boolean isCustomOperation) {\r
- String attrJsonString = null;\r
- if (isCustomOperation) {\r
- TR069OperationDetails operationDetails = (TR069OperationDetails) dto.getOpDetails();\r
- StringBuilder buffer = new StringBuilder();\r
-\r
- List<ParameterDTO> deletParamList = operationDetails.getDeleteParamList();\r
- List<ParameterDTO> modifyParamList = operationDetails.getModifyParamList();\r
- List<ParameterDTO> setParamList = operationDetails.getSetParamList();\r
-\r
- if (deletParamList != null && !deletParamList.isEmpty()) {\r
- convertBooleanValues(deletParamList);\r
- buffer.append(toJson(deletParamList));\r
- } else {\r
- buffer.append(toJson(new ArrayList<>()));\r
- }\r
-\r
- if (modifyParamList != null && !modifyParamList.isEmpty()) {\r
- convertBooleanValues(modifyParamList);\r
- buffer.append(toJson(modifyParamList));\r
- } else {\r
- buffer.append(toJson(new ArrayList<>()));\r
- }\r
-\r
- if (setParamList != null && !setParamList.isEmpty()) {\r
- convertBooleanValues(setParamList);\r
- buffer.append(toJson(setParamList));\r
- } else {\r
- buffer.append(toJson(new ArrayList<>()));\r
- }\r
-\r
- attrJsonString = buffer.toString();\r
- } else {\r
- List<ParameterDTO> parameterDTOs = dto.getOpDetails().getParmeters();\r
- attrJsonString = toJson(parameterDTOs);\r
- }\r
-\r
- return attrJsonString;\r
- }\r
-\r
- /**\r
- * @param paramListJSON\r
- * @return\r
- */\r
- private static List<TR069DeviceRPCRequestEntity> getTR069DeviceRPCRequestEntities(\r
- String paramListJSON) {\r
- List<TR069DeviceRPCRequestEntity> tr069DeviceRPCRequestEntities = new ArrayList<>();\r
-\r
- if (paramListJSON.length() < MAX_SIZE) {\r
- TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity();\r
- entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, 0));\r
- entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, 1));\r
- entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, 2));\r
-\r
- tr069DeviceRPCRequestEntities.add(entity);\r
- } else {\r
- int noOfEntities = 0;\r
- while (true) {\r
- int i = 3 * noOfEntities;\r
- TR069DeviceRPCRequestEntity entity = new TR069DeviceRPCRequestEntity();\r
- entity.setAttributeJson1(getAttriuteJsonData(paramListJSON, i));\r
- entity.setAttributeJson2(getAttriuteJsonData(paramListJSON, ++i));\r
- entity.setAttributeJson3(getAttriuteJsonData(paramListJSON, ++i));\r
-\r
- if (entity.getAttributeJson1() != null) {\r
- tr069DeviceRPCRequestEntities.add(entity);\r
- }\r
-\r
- if (entity.getAttributeJson1() == null || entity.getAttributeJson2() == null\r
- || entity.getAttributeJson3() == null) {\r
- break;\r
- }\r
-\r
- noOfEntities++;\r
- }\r
-\r
- }\r
- return tr069DeviceRPCRequestEntities;\r
- }\r
-\r
- /**\r
- * @param eventData\r
- * @param blockNum\r
- * @return\r
- */\r
- private static String getAttriuteJsonData(String eventData, int blockNum) {\r
- int eventDataSize = eventData.length();\r
- int startIndex = blockNum * BLOCK_SIZE;\r
- if (startIndex > eventDataSize) {\r
- return null;\r
- }\r
- int endIndex = startIndex + BLOCK_SIZE;\r
- endIndex = endIndex < eventDataSize ? endIndex : eventDataSize;\r
- return eventData.substring(startIndex, endIndex);\r
- }\r
-\r
- /**\r
- * @param opDetails\r
- * @param entity\r
- * @param isCustomOperation\r
- */\r
- private static void dtoFromEntityJson(OperationDetails opDetails,\r
- List<TR069DeviceRPCRequestEntity> entityList, boolean isCustomOperation) {\r
- StringBuilder sb = new StringBuilder();\r
- for (TR069DeviceRPCRequestEntity entity : entityList) {\r
- append(sb, entity.getAttributeJson1());\r
- append(sb, entity.getAttributeJson2());\r
- append(sb, entity.getAttributeJson3());\r
- }\r
-\r
- if (isCustomOperation) {\r
- String[] splitStringArray = sb.toString().split("]\\[");\r
- List<ParameterDTO> deleteParamList = new ArrayList<>();\r
- List<ParameterDTO> modifyParamList = new ArrayList<>();\r
- List<ParameterDTO> setParamList = new ArrayList<>();\r
- for (int i = 0; i < splitStringArray.length; i++) {\r
- String data = splitStringArray[i];\r
- if (i == 0) {\r
- data = data + "]";\r
- deleteParamList.addAll(fromJson(data));\r
- } else if ((i + 1) == splitStringArray.length) {\r
- data = "[" + data;\r
- setParamList.addAll(fromJson(data));\r
- } else {\r
- data = "[" + data + "]";\r
- modifyParamList.addAll(fromJson(data));\r
- }\r
- }\r
- TR069OperationDetails tr069OperationDetails = (TR069OperationDetails) opDetails;\r
- tr069OperationDetails.setDeleteParamList(deleteParamList);\r
- tr069OperationDetails.setModifyParamList(modifyParamList);\r
- tr069OperationDetails.setSetParamList(setParamList);\r
- } else {\r
- if (TR069OperationCode.SET_PARAMETER_ATTRIBUTES.equals(opDetails.getOpCode())) {\r
- List<ParameterDTO> list = fromJsonToParameterAttribute(sb.toString());\r
- opDetails.setParmeters(list);\r
- } else {\r
- List<ParameterDTO> list = fromJson(sb.toString());\r
- opDetails.setParmeters(list);\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * @param sb\r
- * @param temp\r
- */\r
- private static void append(StringBuilder sb, String temp) {\r
- if (temp != null && !temp.isEmpty()) {\r
- sb.append(temp);\r
- }\r
- }\r
-\r
- /**\r
- * @param jsonString\r
- * @return\r
- */\r
- private static List<ParameterDTO> fromJson(String jsonString) {\r
- Gson gson = new Gson();\r
- Type collectionType = new TypeToken<List<ParameterDTO>>() {}.getType();\r
- return gson.fromJson(jsonString, collectionType);\r
- }\r
-\r
- /**\r
- * @param jsonString\r
- * @return\r
- */\r
- private static List<ParameterDTO> fromJsonToParameterAttribute(String jsonString) {\r
- Gson gson = new Gson();\r
- Type collectionType = new TypeToken<List<ParameterAttributeDTO>>() {}.getType();\r
- return gson.fromJson(jsonString, collectionType);\r
- }\r
-\r
- /**\r
- * @param entity\r
- * @return\r
- */\r
- private static <T> String toJson(T entity) {\r
- Gson gson = new Gson();\r
- return gson.toJson(entity);\r
- }\r
-\r
- /**\r
- * @param parameterDTOs\r
- */\r
- private static void convertBooleanValues(List<ParameterDTO> parameterDTOs) {\r
- for (ParameterDTO param : parameterDTOs) {\r
- if (param.getDataType() != null && param.getDataType().equalsIgnoreCase("boolean")) {\r
- if (param.getParamValue() != null && (param.getParamValue().equalsIgnoreCase("true")\r
- || param.getParamValue().equalsIgnoreCase("1"))) {\r
- param.setParamValue("1");\r
- } else {\r
- param.setParamValue("0");\r
- }\r
- }\r
- }\r
- }\r
-\r
-}\r
+/*
+ * ============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<TR069DeviceRPCRequestEntity> 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<TR069DeviceRPCRequestEntity> 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<TR069DeviceRPCRequestEntity> 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<ParameterDTO> deletParamList = operationDetails.getDeleteParamList();
+ List<ParameterDTO> modifyParamList = operationDetails.getModifyParamList();
+ List<ParameterDTO> 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<ParameterDTO> parameterDTOs = dto.getOpDetails().getParmeters();
+ attrJsonString = toJson(parameterDTOs);
+ }
+
+ return attrJsonString;
+ }
+
+ /**
+ * @param paramListJSON
+ * @return
+ */
+ private static List<TR069DeviceRPCRequestEntity> getTR069DeviceRPCRequestEntities(
+ String paramListJSON) {
+ List<TR069DeviceRPCRequestEntity> 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<TR069DeviceRPCRequestEntity> 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<ParameterDTO> deleteParamList = new ArrayList<>();
+ List<ParameterDTO> modifyParamList = new ArrayList<>();
+ List<ParameterDTO> 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<ParameterDTO> list = fromJsonToParameterAttribute(sb.toString());
+ opDetails.setParmeters(list);
+ } else {
+ List<ParameterDTO> 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<ParameterDTO> fromJson(String jsonString) {
+ Gson gson = new Gson();
+ Type collectionType = new TypeToken<List<ParameterDTO>>() {}.getType();
+ return gson.fromJson(jsonString, collectionType);
+ }
+
+ /**
+ * @param jsonString
+ * @return
+ */
+ private static List<ParameterDTO> fromJsonToParameterAttribute(String jsonString) {
+ Gson gson = new Gson();
+ Type collectionType = new TypeToken<List<ParameterAttributeDTO>>() {}.getType();
+ return gson.fromJson(jsonString, collectionType);
+ }
+
+ /**
+ * @param entity
+ * @return
+ */
+ private static <T> String toJson(T entity) {
+ Gson gson = new Gson();
+ return gson.toJson(entity);
+ }
+
+ /**
+ * @param parameterDTOs
+ */
+ private static void convertBooleanValues(List<ParameterDTO> 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");
+ }
+ }
+ }
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.common.deviceversion;\r
-\r
-import java.io.Serializable;\r
-import java.util.Comparator;\r
-\r
-public class DeviceVersion implements Serializable, Comparable<DeviceVersion> {\r
-\r
- /**\r
- * \r
- */\r
- private static final long serialVersionUID = -7251276716604249440L;\r
- private int svMajorVersion = 0;\r
- private int svMinorVersion = 0;\r
- private int svPatchVersion = 0;\r
- private String swVersion;\r
- private boolean isGenericVersion = false;\r
- private boolean isHwRegex = false;\r
- private boolean isSwRegex = false;\r
-\r
- public DeviceVersion(String swVersion, String hwVersion) {\r
- super();\r
- setSwVersion(swVersion);\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- public DeviceVersion(String swVersion, String hwVersion, boolean isSwRegex,\r
- boolean isHwRegex) {\r
- super();\r
- this.hwVersion = hwVersion;\r
- this.swVersion = swVersion;\r
- this.isHwRegex = isHwRegex;\r
- this.isSwRegex = isSwRegex;\r
- if (!isSwRegex) {\r
- setSwVersion(swVersion);\r
- }\r
- }\r
-\r
- public String getSwVersion() {\r
- if (!isSwRegex)\r
- return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion;\r
- else\r
- return this.swVersion;\r
- }\r
-\r
- public boolean isHwRegex() {\r
- return isHwRegex;\r
- }\r
-\r
- public boolean isSwRegex() {\r
- return isSwRegex;\r
- }\r
-\r
- private void setSwVersion(String swVersion) {\r
- if (swVersion.indexOf(".") > 0) {\r
- String[] verArray = swVersion.split("\\.");\r
-\r
- for (int i = 0; i < verArray.length; i++) {\r
-\r
- if (verArray[i].equals("*")) {\r
- verArray[i] = "0";\r
- }\r
- }\r
- try {\r
- svMajorVersion = Integer.parseInt(verArray[0]);\r
- svMinorVersion = Integer.parseInt(verArray[1]);\r
- svPatchVersion = Integer.parseInt(verArray[2]);\r
- } catch (Exception e) {\r
- // TODO: handle exception\r
- }\r
-\r
- } else if (swVersion.indexOf("x") > 0) {\r
- swVersion = "*";\r
- } else if (swVersion.equals("*")) {\r
- isGenericVersion = true;\r
- }\r
-\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- private String hwVersion;\r
-\r
- public int getSvMajorVersion() {\r
- return svMajorVersion;\r
- }\r
-\r
- public int getSvMinorVersion() {\r
- return svMinorVersion;\r
- }\r
-\r
- public int getSvPatchVersion() {\r
- return svPatchVersion;\r
- }\r
-\r
- private long deviceTypeId;\r
-\r
- public long getDeviceTypeId() {\r
- return deviceTypeId;\r
- }\r
-\r
- public boolean isGenericVersion() {\r
- return isGenericVersion;\r
- }\r
-\r
- public static Comparator<DeviceVersion> softwareComparator = new Comparator<DeviceVersion>() {\r
- @Override\r
- public int compare(DeviceVersion d1, DeviceVersion d2) {\r
- if (d1.getSvMajorVersion() != d2.getSvMajorVersion()) {\r
- return (d1.getSvMajorVersion() - d2.getSvMajorVersion());\r
- } else if (d1.getSvMinorVersion() != d2.getSvMinorVersion()) {\r
- return d1.getSvMinorVersion() - d2.getSvMinorVersion();\r
- } else\r
- return d1.getSvPatchVersion() - d2.getSvPatchVersion();\r
- }\r
- };\r
-\r
- @Override\r
- public int compareTo(DeviceVersion o) {\r
- if (deviceTypeId != o.deviceTypeId)\r
- return -1;\r
-\r
- if (isSwRegex) {\r
- return this.hashCode() - o.hashCode();\r
- } else {\r
- if (svMajorVersion != o.svMajorVersion) {\r
- return (svMajorVersion - o.svMajorVersion);\r
- } else if (svMinorVersion != o.svMinorVersion) {\r
- return svMinorVersion - o.svMinorVersion;\r
- } else if (svPatchVersion != o.svPatchVersion) {\r
- return svPatchVersion - o.svPatchVersion;\r
- } else {\r
- return hwVersion.compareToIgnoreCase(o.hwVersion);\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public int hashCode() {\r
- final int prime = 31;\r
- int result = 1;\r
- result = prime * result + (int) (deviceTypeId ^ (deviceTypeId >>> 32));\r
- result = prime * result + ((hwVersion == null) ? 0 : hwVersion.hashCode());\r
- result = prime * result + (isGenericVersion ? 1231 : 1237);\r
- result = prime * result + (isHwRegex ? 1231 : 1237);\r
- result = prime * result + (isSwRegex ? 1241 : 1247);\r
- result = prime * result + svMajorVersion;\r
- result = prime * result + svMinorVersion;\r
- result = prime * result + svPatchVersion;\r
- return result;\r
- }\r
-}\r
+/*
+ * ============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<DeviceVersion> {
+
+ /**
+ *
+ */
+ 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<DeviceVersion> softwareComparator =
+ new Comparator<DeviceVersion>() {
+ @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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.common.deviceversion;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.InputStreamReader;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map.Entry;\r
-import java.util.TreeMap;\r
-import java.util.stream.Collectors;\r
-import javax.annotation.PostConstruct;\r
-import org.springframework.stereotype.Component;\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-\r
-@Component\r
-public class DeviceVersionManagerImpl implements DeviceVersionManager {\r
-\r
- TreeMap<DeviceVersion, String> deviceVersionMap = new TreeMap<>();\r
- TreeMap<String, ProfileDefinition> profileDefinitionMap = new TreeMap<>();\r
-\r
- @PostConstruct\r
- public void loadProfileConfiguration() throws IOException {\r
- ObjectMapper objectMapper = new ObjectMapper();\r
- String contents;\r
- try (\r
- InputStream inputStream =\r
- getClass().getResourceAsStream("/profile-definition-mapping.json");\r
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {\r
- contents = reader.lines().collect(Collectors.joining(System.lineSeparator()));\r
- }\r
-\r
- ProfileDefinitions versions;\r
- try {\r
- versions = objectMapper.readValue(contents, ProfileDefinitions.class);\r
-\r
- List<ProfileDefinition> definitionList = versions.getProfileDefinition();\r
- for (ProfileDefinition definition : definitionList) {\r
- DeviceVersion versionDTO =\r
- new DeviceVersion(definition.getSoftwareVersion(), definition.getHardwareVersion());\r
- String profileId = definition.getProfileId();\r
- deviceVersionMap.put(versionDTO, profileId);\r
- profileDefinitionMap.put(profileId, definition);\r
- }\r
- } catch (IOException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- public static void main(String[] args) {\r
- System.out.println("started loading the json file");\r
- DeviceVersionManagerImpl impl = new DeviceVersionManagerImpl();\r
- try {\r
- impl.loadProfileConfiguration();\r
- System.out.println(impl.getAssociatedProfileId("4.3.0.0", "*"));\r
- } catch (Exception e) {\r
- System.out.println("Exception While loading the file");\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- System.out.println("File loading is completed");\r
- }\r
-\r
- @Override\r
- public String getNetconfYangSchemaPath(String swVersion, String hwVersion) {\r
- String profileId = getAssociatedProfileId(swVersion, hwVersion);\r
- ProfileDefinition profileDefinition = profileDefinitionMap.get(profileId);\r
- return profileDefinition.getNetConfSchemaPath();\r
- }\r
-\r
- @Override\r
- public String getBaseNetconfYangSchemaPath() {\r
- return profileDefinitionMap.firstEntry().getValue().getNetConfSchemaPath();\r
- }\r
-\r
- @Override\r
- public ProfileDefinition getProfileDefinition(String swVersion, String hwVersion) {\r
- String profileId = getAssociatedProfileId(swVersion, hwVersion);\r
- return profileDefinitionMap.get(profileId);\r
- }\r
-\r
- @Override\r
- public List<ProfileDefinition> getSupportedProfileDefinitions() {\r
- List<ProfileDefinition> proDeflist = new ArrayList<>();\r
- for (Iterator<String> iterator = profileDefinitionMap.keySet().iterator(); iterator\r
- .hasNext();) {\r
- String key = iterator.next();\r
- proDeflist.add(profileDefinitionMap.get(key));\r
- }\r
- return proDeflist;\r
- }\r
-\r
- @Override\r
- public String getAssociatedProfileId(String swVersion, String hwVersion) {\r
- String profileId = null;\r
- if (null != swVersion) // TODO: Consider hardware version also.\r
- profileId = getProfileName(deviceVersionMap, swVersion, hwVersion);\r
-\r
- if (profileId == null) {\r
- profileId = profileDefinitionMap.firstEntry().getValue().getProfileId();\r
- }\r
-\r
- return profileId;\r
- }\r
-\r
- private String getProfileName(TreeMap<DeviceVersion, String> deviceVersionMap, String swVersion,\r
- String hwVersion) {\r
- DeviceVersion deviceVersion = new DeviceVersion(swVersion, hwVersion, false, false);\r
- ArrayList<DeviceVersion> mSoftwareList = new ArrayList<>();\r
-\r
- for (Iterator<Entry<DeviceVersion, String>> iterator =\r
- deviceVersionMap.entrySet().iterator(); iterator.hasNext();) {\r
- Entry<DeviceVersion, String> entry = iterator.next();\r
- DeviceVersion profileVersion = entry.getKey();\r
- if (profileVersion.isHwRegex() || profileVersion.isSwRegex()) {\r
- if (profileVersion.isSwRegex()) {\r
- if (deviceVersion.getSwVersion().equalsIgnoreCase(profileVersion.getSwVersion())\r
- || deviceVersion.getSwVersion().matches(profileVersion.getSwVersion())) {\r
- if (profileVersion.isHwRegex()) {\r
- if (deviceVersion.getHwVersion() != null) {\r
-\r
- if ("*".equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) {\r
- return entry.getValue();\r
- }\r
- } else {\r
-\r
- }\r
- } else {\r
- // Check Strict match of Hardware\r
- if ("*".equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) {\r
- return entry.getValue();\r
- }\r
- }\r
- }\r
- } else if (profileVersion.isHwRegex()) {\r
- if (deviceVersion.getHwVersion() != null) {\r
- if ("*".equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().matches(profileVersion.getHwVersion())) {\r
- // Add all software version which matching\r
- if (profileVersion.getSwVersion()\r
- .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) {\r
- mSoftwareList.add(profileVersion);\r
- }\r
- }\r
- }\r
- }\r
- } else {\r
- // Check Strict match of Hardware\r
- if ("*".equalsIgnoreCase(profileVersion.getHwVersion())\r
- || deviceVersion.getHwVersion().equalsIgnoreCase(profileVersion.getHwVersion())) {\r
- if (profileVersion.getSwVersion()\r
- .compareToIgnoreCase(deviceVersion.getSwVersion()) <= 0) {\r
- mSoftwareList.add(profileVersion);\r
- }\r
- }\r
- }\r
- }\r
-\r
- if (mSoftwareList.size() > 0) {\r
- // return the least matched software version profile\r
- Collections.sort(mSoftwareList, DeviceVersion.softwareComparator);\r
- return deviceVersionMap.get(mSoftwareList.get(mSoftwareList.size() - 1));\r
- }\r
-\r
- return null;\r
- }\r
-}\r
+/*
+ * ============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<DeviceVersion, String> deviceVersionMap = new TreeMap<>();
+ TreeMap<String, ProfileDefinition> 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<ProfileDefinition> 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<ProfileDefinition> getSupportedProfileDefinitions() {
+ List<ProfileDefinition> proDeflist = new ArrayList<>();
+ for (Iterator<String> 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<DeviceVersion, String> deviceVersionMap, String swVersion,
+ String hwVersion) {
+ DeviceVersion deviceVersion = new DeviceVersion(swVersion, hwVersion, false, false);
+ ArrayList<DeviceVersion> mSoftwareList = new ArrayList<>();
+
+ for (Iterator<Entry<DeviceVersion, String>> iterator =
+ deviceVersionMap.entrySet().iterator(); iterator.hasNext();) {
+ Entry<DeviceVersion, String> 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;
+ }
+}
<skipTests>false</skipTests>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <!-- attached to Maven test phase -->
+ <execution>
+ <id>report</id>
+ <phase>test</phase>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-\r
-package org.commscope.tr069adapter.config.controllers;\r
-\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Optional;\r
-import org.commscope.tr069adapter.acs.common.dto.ConfigurationData;\r
-import org.commscope.tr069adapter.config.constants.ConfigurationServiceConstant;\r
-import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException;\r
-import org.commscope.tr069adapter.config.service.ConfigurationDataService;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.util.StringUtils;\r
-import org.springframework.web.bind.annotation.GetMapping;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestParam;\r
-import org.springframework.web.bind.annotation.RestController;\r
-import org.springframework.web.multipart.MultipartFile;\r
-\r
-@RestController\r
-public class ConfugurationDataController {\r
- private final Logger logger = LoggerFactory.getLogger(this.getClass());\r
-\r
- @Autowired\r
- ConfigurationDataService configDataService;\r
-\r
- @GetMapping("/isActive")\r
- public String getMessage() {\r
- return "Application is running";\r
- }\r
-\r
- @PostMapping("/getConfig")\r
- public ConfigurationData viewConfigurationData(@RequestParam String macId,\r
- @RequestParam String swVersion, @RequestParam String hwVersion)\r
- throws InvalidConfigurationServiceException {\r
- logger.info("Processing request to get configuration data for device {}", macId);\r
- Optional<ConfigurationData> configData = configDataService.getConfigurationData(macId, swVersion, hwVersion);\r
- if (configData.isPresent()) {\r
- return configData.get();\r
- }\r
-\r
- logger.info("Configuration data doesn't exist for device {}", macId);\r
- return null;\r
- }\r
-\r
- @PostMapping("/importConfig")\r
- public String uploadMultipleFiles(@RequestParam("files") MultipartFile[] files)\r
- throws InvalidConfigurationServiceException {\r
-\r
- if (null == files || files.length == 0) {\r
- logger.info("No file given for import");\r
- return "No file given for import";\r
- }\r
-\r
- List<MultipartFile> fileList = Arrays.asList(files);\r
-\r
- MultipartFile file = fileList.get(0);\r
- String fileName = StringUtils.cleanPath(file.getOriginalFilename());\r
-\r
- logger.debug("Importing file {}", fileName);\r
- if (!fileName.endsWith(ConfigurationServiceConstant.CONFIG_FILE_EXTENSION)) {\r
- throw new InvalidConfigurationServiceException("Unsupported file format for file " + fileName\r
- + ". Only XML file is supported. Ignoring file import for file " + fileName);\r
- }\r
-\r
- try {\r
- configDataService.saveConfigFileContents(file);\r
- } catch (InvalidConfigurationServiceException ex) {\r
- throw new InvalidConfigurationServiceException(\r
- "Error occurred while import file " + fileName + ". Cause : " + ex.getMessage());\r
- } catch (Exception ex) {\r
- throw new InvalidConfigurationServiceException(\r
- "UNKNOWN error occurred while import file " + fileName + ". Cause : " + ex.getMessage());\r
- }\r
-\r
- return "File " + fileName + " imported successfully";\r
- }\r
-\r
-}\r
+/*
+ * ============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<ConfigurationData> 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<MultipartFile> 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";
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-\r
-package org.commscope.tr069adapter.config.model;\r
-\r
-import java.io.Serializable;\r
-import javax.persistence.Column;\r
-import javax.persistence.Entity;\r
-import javax.persistence.GeneratedValue;\r
-import javax.persistence.GenerationType;\r
-import javax.persistence.Id;\r
-import javax.persistence.Table;\r
-import javax.persistence.UniqueConstraint;\r
-\r
-@Entity\r
-@Table(name = "config_file_content",\r
- uniqueConstraints = @UniqueConstraint(columnNames = {"MACID", "SW_VERSION", "HW_VERSION"}))\r
-public class ConfigFileContent implements Serializable {\r
- private static final long serialVersionUID = -5435735270835950132L;\r
-\r
- @Id\r
- @GeneratedValue(strategy = GenerationType.AUTO)\r
- @Column(name = "ID")\r
- private Long id;\r
-\r
- @Column(name = "MACID", length = 255)\r
- private String macId;\r
-\r
- @Column(name = "FILE_CONTENT", columnDefinition = "MEDIUMTEXT")\r
- private String fileContent;\r
-\r
- @Column(name = "SW_VERSION", length = 64)\r
- private String swVersion;\r
-\r
- @Column(name = "HW_VERSION", length = 64)\r
- private String hwVersion;\r
-\r
- public ConfigFileContent() {\r
- super();\r
- }\r
-\r
- public String getMacId() {\r
- return macId;\r
- }\r
-\r
- public void setMacId(String macId) {\r
- this.macId = macId;\r
- }\r
-\r
- public String getFileContent() {\r
- return fileContent;\r
- }\r
-\r
- public void setFileContent(String fileContent) {\r
- this.fileContent = fileContent;\r
- }\r
-\r
- public Long getId() {\r
- return id;\r
- }\r
-\r
- public void setId(Long id) {\r
- this.id = id;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.config.repository;\r
-\r
-import java.util.List;\r
-import org.commscope.tr069adapter.config.model.ConfigFileContent;\r
-import org.springframework.data.repository.CrudRepository;\r
-import org.springframework.stereotype.Repository;\r
-\r
-@Repository\r
-public interface ConfigurationDataRepository extends CrudRepository<ConfigFileContent, String> {\r
- public List<ConfigFileContent> findByMacId(String macId);\r
-\r
- public ConfigFileContent findByMacIdAndSwVersionAndHwVersion(String macId, String swVersion,\r
- String hwVersion);\r
-}\r
+/*
+ * ============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<ConfigFileContent, String> {
+ public List<ConfigFileContent> findByMacId(String macId);
+
+ public ConfigFileContent findByMacIdAndSwVersionAndHwVersion(String macId, String swVersion,
+ String hwVersion);
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.config.service;\r
-\r
-import java.nio.charset.StandardCharsets;\r
-import java.util.List;\r
-import java.util.Map.Entry;\r
-import java.util.Optional;\r
-import java.util.TreeMap;\r
-import org.commscope.tr069adapter.acs.common.dto.ConfigurationData;\r
-import org.commscope.tr069adapter.config.constants.Utility;\r
-import org.commscope.tr069adapter.config.exceptions.InvalidConfigurationServiceException;\r
-import org.commscope.tr069adapter.config.model.ConfigFileContent;\r
-import org.commscope.tr069adapter.config.parser.ConfigurationXMLDataParser;\r
-import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Service;\r
-import org.springframework.util.StringUtils;\r
-import org.springframework.web.multipart.MultipartFile;\r
-\r
-@Service\r
-public class ConfigurationDataService {\r
- private final Logger logger = LoggerFactory.getLogger(this.getClass());\r
-\r
- @Autowired\r
- ConfigurationDataRepository configDataRepository;\r
-\r
- @Autowired\r
- ConfigurationXMLDataParser configurationXMLDataParser;\r
-\r
- public void saveConfigFileContent(ConfigFileContent configFileContent) {\r
- configDataRepository.save(configFileContent);\r
- }\r
-\r
- public Iterable<ConfigFileContent> getAllConfigFileContent() {\r
- return configDataRepository.findAll();\r
- }\r
-\r
- public Optional<ConfigFileContent> getConfigFileContent(String macId) {\r
- return configDataRepository.findById(macId);\r
- }\r
-\r
- public Optional<ConfigurationData> getConfigurationData(String macId, String swVersion,\r
- String hwVersion) throws InvalidConfigurationServiceException {\r
- ConfigurationData configurationData = null;\r
- List<ConfigFileContent> configFileContentList = configDataRepository.findByMacId(macId);\r
- TreeMap<DeviceVersion, ConfigurationData> configDataMap = new TreeMap<>();\r
- if (!configFileContentList.isEmpty()) {\r
- logger.debug("Parsing configuration file for device {}", macId);\r
- for (ConfigFileContent configFileContent : configFileContentList) {\r
- ConfigurationData cfgData = configurationXMLDataParser.parseFile(configFileContent);\r
- DeviceVersion dVersion =\r
- new DeviceVersion(cfgData.getSoftwareVersion(), cfgData.getHardwareVersion());\r
- configDataMap.put(dVersion, cfgData);\r
- }\r
- DeviceVersion inputVersion = new DeviceVersion(swVersion, hwVersion);\r
- Entry<DeviceVersion, ConfigurationData> floorEntry = configDataMap.floorEntry(inputVersion);\r
-\r
- if (null == floorEntry) {\r
- logger.error("Configuration file is not available for device {}", macId);\r
- return Optional.ofNullable(configurationData);\r
- }\r
-\r
- DeviceVersion floor = floorEntry.getKey();\r
- configurationData = configDataMap.get(floor);\r
- logger.debug("Parsing of device configuration file is completed");\r
- } else {\r
- logger.error("Configuration file is not available for device {}", macId);\r
- return Optional.ofNullable(configurationData);\r
- }\r
- return Optional.ofNullable(configurationData);\r
- }\r
-\r
- public void saveConfigFileContents(MultipartFile file)\r
- throws InvalidConfigurationServiceException {\r
- String fileName = StringUtils.cleanPath(file.getOriginalFilename());\r
-\r
- if (fileName.contains("..")) {\r
- throw new InvalidConfigurationServiceException(\r
- "Filename contains invalid path sequence " + fileName);\r
- }\r
-\r
- ConfigFileContent configFileContent = new ConfigFileContent();\r
-\r
- try {\r
- configFileContent.setFileContent(new String(file.getBytes(), StandardCharsets.UTF_8));\r
- configFileContent.setMacId(Utility.getMacId(fileName));\r
-\r
- if (!configFileContent.getFileContent().contains("<configDataFile>")) {\r
- logger.error(\r
- "File {} is not a valid configuration file as it doesn't contain tag \"<configDataFile>\"",\r
- fileName);\r
- throw new InvalidConfigurationServiceException(\r
- "File is not a valid configuration file as it doesn't contain tag \"<configDataFile>\"");\r
- }\r
-\r
- } catch (Exception e) {\r
- throw new InvalidConfigurationServiceException(\r
- "Error occurred while reading file content. Reason: " + e.getMessage());\r
- }\r
-\r
- configurationXMLDataParser.validateFile(configFileContent);\r
-\r
- ConfigurationData configurationData = configurationXMLDataParser.parseFile(configFileContent);\r
- configFileContent.setSwVersion(configurationData.getSoftwareVersion());\r
- configFileContent.setHwVersion(configurationData.getHardwareVersion());\r
-\r
- logger.debug("Saving configuration file {} content for device of macId {}", fileName,\r
- Utility.getMacId(fileName));\r
- ConfigFileContent configFileContentEntity =\r
- configDataRepository.findByMacIdAndSwVersionAndHwVersion(configFileContent.getMacId(),\r
- configFileContent.getSwVersion(), configFileContent.getHwVersion());\r
-\r
- if (configFileContentEntity != null) {\r
- configFileContentEntity.setFileContent(configFileContent.getFileContent());\r
- saveConfigFileContent(configFileContentEntity);\r
- } else {\r
- saveConfigFileContent(configFileContent);\r
- }\r
-\r
- logger.debug("Configuration file content saved successfully");\r
- }\r
-\r
- class DeviceVersion implements Comparable<DeviceVersion> {\r
- private static final long serialVersionUID = -7251276716604249440L;\r
- private int svMajorVersion = 0;\r
- private int svMinorVersion = 0;\r
- private int svPatchVersion = 0;\r
- private boolean isGenericVersion = false;\r
-\r
- public DeviceVersion(String swVersion, String hwVersion) {\r
- super();\r
- setSwVersion(swVersion);\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- public String getSwVersion() {\r
- return svMajorVersion + "." + svMinorVersion + "." + svPatchVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- // TODO: conversion to integers\r
-\r
- if (swVersion.indexOf(".") > 0) {\r
- String[] verArray = swVersion.split("\\.");\r
-\r
-\r
- for (int i = 0; i < verArray.length; i++) {\r
-\r
- if (verArray[i].equals("*")) {\r
- verArray[i] = "0";\r
- }\r
- }\r
- svMajorVersion = Integer.parseInt(verArray[0]);\r
- svMinorVersion = Integer.parseInt(verArray[1]);\r
- svPatchVersion = Integer.parseInt(verArray[2]);\r
-\r
- } else if (swVersion.indexOf("x") > 0) {\r
- swVersion = "*";\r
- } else if (swVersion.equals("*")) {\r
- isGenericVersion = true;\r
- }\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- private String hwVersion;\r
-\r
- public int getSvMajorVersion() {\r
- return svMajorVersion;\r
- }\r
-\r
- public void setSvMajorVersion(int svMajorVersion) {\r
- this.svMajorVersion = svMajorVersion;\r
- }\r
-\r
- public int getSvMinorVersion() {\r
- return svMinorVersion;\r
- }\r
-\r
- public void setSvMinorVersion(int svMinorVersion) {\r
- this.svMinorVersion = svMinorVersion;\r
- }\r
-\r
- public int getSvPatchVersion() {\r
- return svPatchVersion;\r
- }\r
-\r
- public void setSvPatchVersion(int svPatchVersion) {\r
- this.svPatchVersion = svPatchVersion;\r
- }\r
-\r
- public boolean isGenericVersion() {\r
- return isGenericVersion;\r
- }\r
-\r
- public void setGenericVersion(boolean isGenericVersion) {\r
- this.isGenericVersion = isGenericVersion;\r
- }\r
-\r
- @Override\r
- public int compareTo(DeviceVersion o) {\r
-\r
- if (svMajorVersion != o.svMajorVersion) {\r
- return (svMajorVersion - o.svMajorVersion);\r
- } else if (svMinorVersion != o.svMinorVersion) {\r
- return svMinorVersion - o.svMinorVersion;\r
- } else {\r
- return svPatchVersion - o.svPatchVersion;\r
- }\r
- }\r
- }\r
-\r
-}\r
+/*
+ * ============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<ConfigFileContent> getAllConfigFileContent() {
+ return configDataRepository.findAll();
+ }
+
+ public Optional<ConfigFileContent> getConfigFileContent(String macId) {
+ return configDataRepository.findById(macId);
+ }
+
+ public Optional<ConfigurationData> getConfigurationData(String macId, String swVersion,
+ String hwVersion) throws InvalidConfigurationServiceException {
+ ConfigurationData configurationData = null;
+ List<ConfigFileContent> configFileContentList = configDataRepository.findByMacId(macId);
+ TreeMap<DeviceVersion, ConfigurationData> 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<DeviceVersion, ConfigurationData> 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("<configDataFile>")) {
+ logger.error(
+ "File {} is not a valid configuration file as it doesn't contain tag \"<configDataFile>\"",
+ fileName);
+ throw new InvalidConfigurationServiceException(
+ "File is not a valid configuration file as it doesn't contain tag \"<configDataFile>\"");
+ }
+
+ } 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<DeviceVersion> {
+ 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;
+ }
+ }
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.config;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.commscope.tr069adapter.config.model.ConfigFileContent;\r
-\r
-public class ConfigDataTestsUtils {\r
-\r
- private ConfigDataTestsUtils() {}\r
-\r
- public static final String SERVER_URI = "http://localhost:9000/";\r
- public static final String macId = "testMacId";\r
- public static final String OUI = "0005B9";\r
- public static final String PRODUCT_CLASS = "LTE_Enterprise_C-RANSC_Cntrl";\r
- public static final String HAEDWARE_VERSION = "1.1.1.1";\r
- public static final String SW_VERSION = "4.5.00.001";\r
-\r
- public static final String CONFIG_FILE_NAME = macId + ".xml";\r
-\r
- // public static ConfigurationData getConfigurationData() {\r
- // ConfigurationData configData = new ConfigurationData();\r
- //\r
- // configData.setHardwareVersion(HAEDWARE_VERSION);\r
- // configData.setSoftwareVersion(SW_VERSION);\r
- // configData.setLocalDn(macId);\r
- // configData.setOUI(OUI);\r
- // configData.setProductClass(PRODUCT_CLASS);\r
- //\r
- //// Map<String, String> map = new HashMap<String, String>();\r
- //// map.put(", value)\r
- //// configData.set\r
- // return configData;\r
- // }\r
-\r
-\r
- public static List<ConfigFileContent> getConfigFileContent() {\r
- List<ConfigFileContent> data = new ArrayList<>();\r
-\r
- for (int i = 0; i < 5; i++) {\r
- ConfigFileContent configFileContent = new ConfigFileContent();\r
- configFileContent.setFileContent(getFileContent());\r
- configFileContent.setMacId(macId);\r
- configFileContent.setSwVersion("4." + i);\r
- }\r
-\r
- return data;\r
- }\r
-\r
-\r
- public static String getFileContent() {\r
- String fileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<configDataFile>\r\n"\r
- + " <fileHeader fileFormatVersion=\"32.594 V14.0.0\" vendorName=\"Commscope\"/>\r\n"\r
- + " <configData>\r\n"\r
- + " <managedElement swVersion=\"4.3.00.038\" localDn=\"0005B95196D0\" hwVersion=\"750742.00.04\" ProductClass=\"LTE_Enterprise_C-RANSC_Cntrl\" OUI=\"0005B9\"/>\r\n"\r
- + " <Device>\r\n" + " <FAP>\r\n" + " <GPS>\r\n"\r
- + " <AGPSServerConfig>\r\n" + " <Enable>1</Enable>\r\n"\r
- + " <Password>dmsuser</Password>\r\n"\r
- + " <ServerPort>7001</ServerPort>\r\n"\r
- + " <ServerURL>NONE</ServerURL>\r\n"\r
- + " <Username>dmsuser</Username>\r\n" + " </AGPSServerConfig>\r\n"\r
- + " <GPSReset>0</GPSReset>\r\n" + " </GPS>\r\n" + " </FAP>\r\n"\r
- + " </Device>\r\n" + " </configData>\r\n"\r
- + " <fileFooter dateTime=\"2019-07-16T17:32:35+05:30\"/>\r\n" + "</configDataFile>";\r
-\r
- return fileContent;\r
- }\r
-}\r
+/*
+ * ============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<String, String> map = new HashMap<String, String>();
+ //// map.put(", value)
+ //// configData.set
+ // return configData;
+ // }
+
+
+ public static List<ConfigFileContent> getConfigFileContent() {
+ List<ConfigFileContent> 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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<configDataFile>\r\n"
+ + " <fileHeader fileFormatVersion=\"32.594 V14.0.0\" vendorName=\"Commscope\"/>\r\n"
+ + " <configData>\r\n"
+ + " <managedElement swVersion=\"4.3.00.038\" localDn=\"0005B95196D0\" hwVersion=\"750742.00.04\" ProductClass=\"LTE_Enterprise_C-RANSC_Cntrl\" OUI=\"0005B9\"/>\r\n"
+ + " <Device>\r\n" + " <FAP>\r\n" + " <GPS>\r\n"
+ + " <AGPSServerConfig>\r\n" + " <Enable>1</Enable>\r\n"
+ + " <Password>dmsuser</Password>\r\n"
+ + " <ServerPort>7001</ServerPort>\r\n"
+ + " <ServerURL>NONE</ServerURL>\r\n"
+ + " <Username>dmsuser</Username>\r\n" + " </AGPSServerConfig>\r\n"
+ + " <GPSReset>0</GPSReset>\r\n" + " </GPS>\r\n" + " </FAP>\r\n"
+ + " </Device>\r\n" + " </configData>\r\n"
+ + " <fileFooter dateTime=\"2019-07-16T17:32:35+05:30\"/>\r\n" + "</configDataFile>";
+
+ return fileContent;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.config;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertThat;\r
-import static org.junit.jupiter.api.Assertions.fail;\r
-import org.commscope.tr069adapter.config.repository.ConfigurationDataRepository;\r
-import org.hamcrest.CoreMatchers;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.boot.test.mock.mockito.MockBean;\r
-import org.springframework.http.HttpStatus;\r
-import org.springframework.http.MediaType;\r
-import org.springframework.mock.web.MockHttpServletResponse;\r
-import org.springframework.mock.web.MockMultipartFile;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-import org.springframework.test.web.servlet.MockMvc;\r
-import org.springframework.test.web.servlet.MvcResult;\r
-import org.springframework.test.web.servlet.RequestBuilder;\r
-import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;\r
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\r
-\r
-@RunWith(SpringRunner.class)\r
-@SpringBootTest(classes = {ConfigDataServiceApplication.class}) // , args = "--schemas-dir\r
- // test-schemas --debug true\r
- // --starting-port 17830")\r
-@AutoConfigureMockMvc\r
-public class ConfugurationDataControllerTests {\r
-\r
- @Autowired\r
- private MockMvc mockMvc;\r
-\r
- @MockBean\r
- ConfigurationDataRepository configDataRepository;\r
-\r
- @Test\r
- public void getMessageTest() {\r
- RequestBuilder requestBuilder =\r
- MockMvcRequestBuilders.get("/isActive").accept(MediaType.APPLICATION_JSON);\r
-\r
- MvcResult result = null;\r
- String resultString = null;\r
- try {\r
- result = mockMvc.perform(requestBuilder).andReturn();\r
- resultString = result.getResponse().getContentAsString();\r
- } catch (Exception e) {\r
- fail(e.getMessage());\r
- }\r
-\r
- assertEquals("Application is running", resultString);\r
- }\r
-\r
- @Test\r
- public void uploadMultipleFilesTest() {\r
- MockMultipartFile multiFile =\r
- new MockMultipartFile("files", ConfigDataTestsUtils.CONFIG_FILE_NAME,\r
- MediaType.APPLICATION_XML_VALUE, ConfigDataTestsUtils.getFileContent().getBytes());\r
- MockHttpServletRequestBuilder requestBuilder =\r
- MockMvcRequestBuilders.multipart("/importConfig").file(multiFile);// .contentType(MediaType.MULTIPART_FORM_DATA_VALUE);\r
-\r
- MvcResult result = null;\r
- String resultString = null;\r
- try {\r
- result = mockMvc.perform(requestBuilder).andReturn();\r
- MockHttpServletResponse response = result.getResponse();\r
- resultString = response.getContentAsString();\r
- } catch (Exception e) {\r
- fail(e.getMessage());\r
- }\r
-\r
- String expectedResult =\r
- "File " + ConfigDataTestsUtils.CONFIG_FILE_NAME + " imported successfully";\r
- assertEquals(expectedResult, resultString);\r
- }\r
-\r
- @Test\r
- public void viewConfigurationDataTest() {\r
- Mockito.when(configDataRepository.findByMacId(ConfigDataTestsUtils.macId))\r
- .thenReturn(ConfigDataTestsUtils.getConfigFileContent());\r
-\r
- MockHttpServletRequestBuilder requestBuilder =\r
- MockMvcRequestBuilders.post("/getConfig").param("macId", "0005B95196D0")\r
- .param("swVersion", "4.5").param("hwVersion", "1.1").accept(MediaType.APPLICATION_JSON);\r
-\r
- MvcResult result = null;\r
- try {\r
- result = mockMvc.perform(requestBuilder).andReturn();\r
- MockHttpServletResponse response = result.getResponse();\r
- assertEquals(200, response.getStatus());\r
- } catch (Exception e) {\r
- fail(e.getMessage());\r
- }\r
- }\r
-}\r
+/*
+ * ============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());
+ }
+ }
+}
<skipTests>false</skipTests>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <!-- attached to Maven test phase -->
+ <execution>
+ <id>report</id>
+ <phase>test</phase>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<skipTests>false</skipTests>\r
</configuration>\r
</plugin>\r
+ <plugin>\r
+ <groupId>org.jacoco</groupId>\r
+ <artifactId>jacoco-maven-plugin</artifactId>\r
+ <executions>\r
+ <execution>\r
+ <goals>\r
+ <goal>prepare-agent</goal>\r
+ </goals>\r
+ </execution>\r
+ <!-- attached to Maven test phase -->\r
+ <execution>\r
+ <id>report</id>\r
+ <phase>test</phase>\r
+ <goals>\r
+ <goal>report</goal>\r
+ </goals>\r
+ </execution>\r
+ </executions>\r
+ </plugin>\r
<plugin>\r
<artifactId>maven-failsafe-plugin</artifactId>\r
</plugin>\r
<system>JIRA</system>\r
<url>https://jira.o-ran-sc.org/</url>\r
</issueManagement>\r
-</project>\r
+</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="m-101">\r
- <software-download xmlns="urn:o-ran:software-management:1.0">\r
- <remote-file-path>sftp://root@10.208.224.201/root/vishal/BCRP_OneImage_4.3.00.158.signed.bin</remote-file-path>\r
- <password>\r
- <password>airvana123</password>\r
- </password>\r
- </software-download>\r
-</rpc>
\ No newline at end of file
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import org.springframework.boot.context.properties.ConfigurationProperties;\r
-import org.springframework.context.annotation.Configuration;\r
-\r
-@Configuration\r
-@ConfigurationProperties(prefix = "config")\r
-public class MapperConfigProperties {\r
-\r
- private String requesTimeout;\r
-\r
- private String preConfigureOnPNP;\r
-\r
- private String sbiUri;\r
-\r
- private String configDBUri;\r
-\r
- private String nbiNotificationUri;\r
- private String nbiServerManagerUri;\r
- private String vesUri;\r
-\r
- private String netConfServerIP;\r
- private String netConfServerPort;\r
-\r
- private String alarmMORegex;\r
-\r
- private String verConfigUri;\r
- private String vendorName;\r
-\r
- public String getRequesTimeout() {\r
- return requesTimeout;\r
- }\r
-\r
- public void setRequesTimeout(String requesTimeout) {\r
- this.requesTimeout = requesTimeout;\r
- }\r
-\r
- public String getPreConfigureOnPNP() {\r
- return preConfigureOnPNP;\r
- }\r
-\r
- public void setPreConfigureOnPNP(String preConfigureOnPNP) {\r
- this.preConfigureOnPNP = preConfigureOnPNP;\r
- }\r
-\r
- public String getSbiUri() {\r
- return sbiUri;\r
- }\r
-\r
- public void setSbiUri(String sbiUri) {\r
- this.sbiUri = sbiUri;\r
- }\r
-\r
- public String getConfigDBUri() {\r
- return configDBUri;\r
- }\r
-\r
- public void setConfigDBUri(String configDBUri) {\r
- this.configDBUri = configDBUri;\r
- }\r
-\r
- public String getNbiNotificationUri() {\r
- return nbiNotificationUri;\r
- }\r
-\r
- public void setNbiNotificationUri(String nbiNotificationUri) {\r
- this.nbiNotificationUri = nbiNotificationUri;\r
- }\r
-\r
- public String getNbiServerManagerUri() {\r
- return nbiServerManagerUri;\r
- }\r
-\r
- public void setNbiServerManagerUri(String nbiServerManagerUri) {\r
- this.nbiServerManagerUri = nbiServerManagerUri;\r
- }\r
-\r
- public String getVesUri() {\r
- return vesUri;\r
- }\r
-\r
- public void setVesUri(String vesUri) {\r
- this.vesUri = vesUri;\r
- }\r
-\r
- public String getNetConfServerIP() {\r
- return netConfServerIP;\r
- }\r
-\r
- public void setNetConfServerIP(String netConfServerIP) {\r
- this.netConfServerIP = netConfServerIP;\r
- }\r
-\r
- public String getNetConfServerPort() {\r
- return netConfServerPort;\r
- }\r
-\r
- public void setNetConfServerPort(String netConfServerPort) {\r
- this.netConfServerPort = netConfServerPort;\r
- }\r
-\r
- public String getAlarmMORegex() {\r
- return alarmMORegex;\r
- }\r
-\r
- public void setAlarmMORegex(String alarmMORegex) {\r
- this.alarmMORegex = alarmMORegex;\r
- }\r
-\r
- public String getVerConfigUri() {\r
- return verConfigUri;\r
- }\r
-\r
- public void setVerConfigUri(String verConfigUri) {\r
- this.verConfigUri = verConfigUri;\r
- }\r
-\r
- public String getVendorName() {\r
- return vendorName;\r
- }\r
-\r
- public void setVendorName(String vendorName) {\r
- this.vendorName = vendorName;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.acs;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-public class ACSRequestSender {\r
-\r
- private RestTemplate restTemplate = new RestTemplate();\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- public Long sendRequest(DeviceRPCRequest deviceRPCRequest) {\r
- String uri = getUri();\r
- return restTemplate.postForObject(uri, deviceRPCRequest, Long.class);\r
- }\r
-\r
- private String getUri() {\r
- return config.getSbiUri();\r
- }\r
-\r
-}\r
+/*
+ * ============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<String> entity = new HttpEntity<>(deviceId, headers);
+ return restTemplate.postForObject(getUriForConnStatus(), entity, ConnectionStatusPOJO.class);
+ }
+
+ private String getUri() {
+ return config.getSbiUri();
+ }
+
+ private String getUriForConnStatus() {
+ return config.getConnStatusUri();
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.acs.impl;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.InformType;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069InformType;\r
-import org.commscope.tr069adapter.acs.common.inform.BootInform;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.acs.common.inform.ConnectionRequestInform;\r
-import org.commscope.tr069adapter.acs.common.inform.PeriodicInform;\r
-import org.commscope.tr069adapter.acs.common.inform.TransferCompleteInform;\r
-import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform;\r
-import org.commscope.tr069adapter.mapper.MOMetaData;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.acs.ACSNotificationHandler;\r
-import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO;\r
-import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager;\r
-import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler;\r
-import org.commscope.tr069adapter.mapper.util.FirwareUpgradeErrorCode;\r
-import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus;\r
-import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil;\r
-import org.commscope.tr069adapter.mapper.ves.VESNotificationSender;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class ACSNotificationHandlerImpl implements ACSNotificationHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(ACSNotificationHandlerImpl.class);\r
- private static final String SOFT_MGMT_NS_URI = "urn:o-ran:software-management:1.0";\r
-\r
- @Autowired\r
- SynchronizedRequestHandler syncHandler;\r
-\r
- @Autowired\r
- MOMetaDataUtil metaDataUtil;\r
-\r
- @Autowired\r
- PnPPreProvisioningHandler pnpPreProvisioningHandler;\r
-\r
- @Autowired\r
- VESNotificationSender vesnotiSender;\r
-\r
- @Autowired\r
- NetConfNotificationSender notiSender;\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- @Autowired\r
- NetConfServerManager netconfManager;\r
-\r
- @Autowired\r
- DeviceOperationsDAO deviceOperDAO;\r
-\r
- @Override\r
- public void handleOperationResponse(DeviceRPCResponse opResult) {\r
- opResult.getOperationResponse().setParameterDTOs(\r
- filterUnsupportedParameters(opResult.getOperationResponse().getParameterDTOs(),\r
- opResult.getDeviceDetails().getSoftwareVersion(),\r
- opResult.getDeviceDetails().getHardwareVersion()));\r
- syncHandler.notifyResult(opResult);\r
- }\r
-\r
- @Override\r
- public void handleNotification(DeviceInform notification) {\r
- boolean isAlarmVC = isAlarmVC(notification);\r
-\r
- if (notification instanceof BootstrapInform) {\r
- logger.info("BootStrap notification received");\r
- BootstrapInform bootstrapNotification = (BootstrapInform) notification;\r
-\r
- DeviceOperationDetails deviceDetails =\r
- deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId());\r
- if (deviceDetails == null) {\r
- deviceDetails = new DeviceOperationDetails();\r
- deviceDetails.setDeviceId(notification.getDeviceDetails().getDeviceId());\r
- deviceDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion());\r
- deviceOperDAO.save(deviceDetails);\r
- }\r
-\r
- checkForActivateNotification(notification);\r
-\r
- // send request to create the netconf server instance for the bootstrap device\r
- // id\r
- NetConfServerDetails serverInfo = createNtConfServer(bootstrapNotification);\r
- if (serverInfo == null)\r
- return;\r
-\r
- vesnotiSender.sendNotification(bootstrapNotification, serverInfo);\r
- BootstrapInform bsInform =\r
- getDeviceBootStrapNotification(bootstrapNotification, TR069InformType.BOOTSTRAP);\r
- ValueChangeInform vcInform = null;\r
- if (bootstrapNotification.getValueChangeNotification() != null) {\r
- logger.info("Bootstrap notification received along with VC");\r
- vcInform =\r
- getDeviceValueChangeNotification(bootstrapNotification, TR069InformType.VALUECHANGE);\r
- processVCNotification(vcInform, isAlarmVC);\r
- }\r
- notiSender.sendNotification(bsInform);\r
- if (vcInform != null)\r
- processVCNotification(vcInform, isAlarmVC);\r
- } else if (notification instanceof BootInform) {\r
- logger.info("Boot notification received");\r
-\r
- NetConfServerDetails serverInfo = createNtConfServer(notification);\r
- if (serverInfo == null)\r
- return;\r
-\r
- checkForActivateNotification(notification);\r
- BootInform bootNotification = (BootInform) notification;\r
- BootInform bInform = getDeviceBootNotification(bootNotification, TR069InformType.BOOT);\r
- ValueChangeInform vcInform = null;\r
- if (bootNotification.getValueChangeNotification() != null) {\r
- logger.info("Boot notification received along with VC");\r
- vcInform = getDeviceValueChangeNotification(bootNotification, TR069InformType.VALUECHANGE);\r
- }\r
- notiSender.sendNotification(bInform);\r
- processVCNotification(vcInform, isAlarmVC);\r
- } else if (notification instanceof PeriodicInform) {\r
- PeriodicInform pINotificaiton = (PeriodicInform) notification;\r
- vesnotiSender.sendNotification(pINotificaiton, null);\r
- notiSender.sendNotification(pINotificaiton);\r
- logger.info("PI notification received");\r
- } else if (notification instanceof ConnectionRequestInform) {\r
- ConnectionRequestInform crNotificaiton = (ConnectionRequestInform) notification;\r
- vesnotiSender.sendNotification(crNotificaiton, null);\r
- logger.info("ConnectionRequestInform notification received");\r
- } else if (notification instanceof ValueChangeInform) {\r
- ValueChangeInform valueChgNotificaiton = (ValueChangeInform) notification;\r
- processVCNotification(valueChgNotificaiton, isAlarmVC);\r
- } else if (notification instanceof TransferCompleteInform) {\r
- TransferCompleteInform tfNotificaiton = (TransferCompleteInform) notification;\r
- if (tfNotificaiton.getCommandKey() != null && tfNotificaiton.getCommandKey()\r
- .equalsIgnoreCase(tfNotificaiton.getDeviceDetails().getDeviceId())) {\r
- logger.debug("TransferCompleteInform is recevied at mapper");\r
- processTransferCompleteInform(tfNotificaiton);\r
- logger.debug("TransferCompleteInform processing completed at mapper");\r
- }\r
- }\r
-\r
- pnpPreProvisioningHandler.onDeviceNotification(notification);\r
- }\r
-\r
- private NetConfServerDetails createNtConfServer(DeviceInform inform) {\r
- String eNodeBName = pnpPreProvisioningHandler.getEnodeBName(\r
- inform.getDeviceDetails().getDeviceId(), inform.getDeviceDetails().getSoftwareVersion(),\r
- inform.getDeviceDetails().getHardwareVersion());\r
- if (eNodeBName == null)\r
- eNodeBName = inform.getDeviceDetails().getDeviceId();\r
- NetConfServerDetails serverInfo =\r
- netconfManager.createNetconfServer(inform.getDeviceDetails().getDeviceId(), eNodeBName,\r
- inform.getDeviceDetails().getSoftwareVersion(),\r
- inform.getDeviceDetails().getHardwareVersion());\r
- if (serverInfo != null && !NetconfServerManagementError.SUCCESS.equals(serverInfo.getError())) {\r
- logger.error("Failed to handle boot/bootstrap notification. Server INFO: {}", serverInfo);\r
- logger.error("Failed to create the netconf server for device ID: {} Error: {}",\r
- inform.getDeviceDetails().getDeviceId(), serverInfo.getError());\r
- return null;\r
- } else if (serverInfo == null) {\r
- logger.error(\r
- "Failed to handle bootstrap notification. Failed to create netconf server. serverInfo is null");\r
- return null;\r
- }\r
- return serverInfo;\r
- }\r
-\r
- private void processVCNotification(ValueChangeInform valueChgNotificaiton, boolean isAlarmVC) {\r
- if (isAlarmVC) {\r
- logger.debug("Alarm VC received forwarding to VES Collector");\r
- vesnotiSender.sendNotification(valueChgNotificaiton, null);\r
- } else {\r
- logger.info("VC notification received");\r
- notiSender.sendNotification(valueChgNotificaiton);\r
- }\r
- }\r
-\r
- private boolean isAlarmVC(DeviceInform notification) {\r
- if (null != notification && null != notification.getParameters()) {\r
- for (ParameterDTO param : notification.getParameters()) {\r
- if (param.getParamName().matches(config.getAlarmMORegex())) {\r
- logger.debug("This VC contains alarm MOs");\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
-\r
- public List<ParameterDTO> filterUnsupportedParameters(List<ParameterDTO> parameters,\r
- String swVersion, String hwVersion) {\r
- List<ParameterDTO> result = new ArrayList<>();\r
- if (null != parameters) {\r
- for (ParameterDTO param : parameters) {\r
- MOMetaData metaData =\r
- metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion);\r
- if (null != metaData) {\r
- result.add(param);\r
- }\r
- }\r
- }\r
- return result;\r
- }\r
-\r
- public static BootstrapInform getDeviceBootStrapNotification(DeviceInform devNotification,\r
- TR069InformType notificationType) {\r
- BootstrapInform bsInform = new BootstrapInform();\r
- List<InformType> informTypeList = new ArrayList<>();\r
- informTypeList.add(notificationType);\r
- bsInform.setDeviceDetails(devNotification.getDeviceDetails());\r
- bsInform.setInformTypeList(informTypeList);\r
- List<ParameterDTO> paramList = new ArrayList<>();\r
- for (ParameterDTO param : devNotification.getParameters()) {\r
- paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue()));\r
- }\r
- bsInform.setParameters(paramList);\r
- return bsInform;\r
- }\r
-\r
- public static BootInform getDeviceBootNotification(DeviceInform devNotification,\r
- TR069InformType notificationType) {\r
- BootInform bInform = new BootInform();\r
- List<InformType> informTypeList = new ArrayList<>();\r
- informTypeList.add(notificationType);\r
- bInform.setDeviceDetails(devNotification.getDeviceDetails());\r
- bInform.setInformTypeList(informTypeList);\r
- List<ParameterDTO> paramList = new ArrayList<>();\r
- for (ParameterDTO param : devNotification.getParameters()) {\r
- paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue()));\r
- }\r
- bInform.setParameters(paramList);\r
- return bInform;\r
- }\r
-\r
- public static ValueChangeInform getDeviceValueChangeNotification(DeviceInform devNotification,\r
- TR069InformType notificationType) {\r
- ValueChangeInform devValChangeNotif = new ValueChangeInform();\r
- List<InformType> informTypeList = new ArrayList<>();\r
- informTypeList.add(notificationType);\r
- devValChangeNotif.setDeviceDetails(devNotification.getDeviceDetails());\r
- devValChangeNotif.setInformTypeList(informTypeList);\r
- List<ParameterDTO> paramList = new ArrayList<>();\r
- for (ParameterDTO param : devNotification.getParameters()) {\r
- paramList.add(new ParameterDTO(param.getParamName(), param.getParamValue()));\r
- }\r
- devValChangeNotif.setParameters(paramList);\r
- devValChangeNotif.setExternalIPAddress(getExternalIPAddress(devNotification.getParameters()));\r
- return devValChangeNotif;\r
- }\r
-\r
- private static String getExternalIPAddress(List<ParameterDTO> params) {\r
- ParameterDTO[] nbiParam = params.toArray(new ParameterDTO[params.size()]);\r
- String externalIpAddress = "";\r
- boolean isIPv6 = isIPv6Enabled(nbiParam);\r
-\r
- for (int index1 = 0; index1 < nbiParam.length; index1++) {\r
-\r
- if (isIPv6) {\r
- if (nbiParam[index1].getParamName().contains("IPv6Address")\r
- || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) {\r
- externalIpAddress = nbiParam[index1].getParamValue();\r
- logger.debug("device communicating is with IPV6 address");\r
- }\r
- } else {\r
- if (nbiParam[index1].getParamName().contains("IPv4Address")\r
- || nbiParam[index1].getParamName().contains("ExternalIPAddress")\r
- || nbiParam[index1].getParamName().contains(".1.IPInterfaceIPAddress")) {\r
- externalIpAddress = nbiParam[index1].getParamValue();\r
- }\r
- }\r
- if (externalIpAddress.trim().length() > 0)\r
- break;\r
- }\r
- return externalIpAddress;\r
- }\r
-\r
- private static boolean isIPv6Enabled(ParameterDTO[] nbiParam) {\r
- boolean isIPv6 = false;\r
- for (int index1 = 0; index1 < nbiParam.length; index1++) {\r
- if (nbiParam[index1].getParamName().contains("IPv6Enable")\r
- && nbiParam[index1].getParamValue().equalsIgnoreCase("1")) {\r
- isIPv6 = true;\r
- break;\r
- }\r
- }\r
- return isIPv6;\r
- }\r
-\r
- private void processTransferCompleteInform(TransferCompleteInform notification) {\r
-\r
- try {\r
- ArrayList<ParameterDTO> paramList = new ArrayList<ParameterDTO>();\r
- DeviceOperationDetails fwDetails =\r
- deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId());\r
- if (fwDetails == null || fwDetails.getFileName() == null) {\r
- logger.debug(\r
- "TransferCompleteInform recevied for invaild device, there is no entry exist in the database");\r
- return;\r
- }\r
- if (fwDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) {\r
- paramList.add(new ParameterDTO("download-event.file-name", fwDetails.getFileName()));\r
-\r
- String status = FirwareUpgradeErrorCode.getErrorCodeMapping(notification.getFaultCode());\r
- paramList.add(new ParameterDTO("download-event.status", status));\r
- if (notification.getFaultCode() != 0) {\r
- fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_FAILED.getStatus());\r
- paramList\r
- .add(new ParameterDTO("download-event.error-message", notification.getFaultString()));\r
- } else {\r
- fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus());\r
- logger.debug("downloading file completed on the device successfully.");\r
- }\r
- deviceOperDAO.save(fwDetails);\r
-\r
- logger.debug("sending download-event notification to netconfserver");\r
-\r
- if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(),\r
- paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) {\r
- logger.debug("sending download-event notification to netconfserver sucess");\r
- } else {\r
- logger.error("sending download-event notification to netconfserver failed");\r
- }\r
- } else {\r
- logger.debug(\r
- "TransferCompleteInform recevied after boot is received; already software is activated");\r
- }\r
- } catch (Exception e) {\r
- logger.debug("Exception occured while processing TransferCompleteInform " + e.toString());\r
- }\r
- }\r
-\r
- private void checkForActivateNotification(DeviceInform notification) {\r
-\r
- try {\r
- ArrayList<ParameterDTO> paramList = new ArrayList<ParameterDTO>();\r
- DeviceOperationDetails devDetails =\r
- deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId());\r
-\r
- if (devDetails == null\r
- || devDetails.getDownLoadStatus() == FirwareUpgradeStatus.NOT_STARTED.getStatus()) {\r
- logger.debug("firmware upgrade is not in progress");\r
- return;\r
- }\r
-\r
- if (!notification.getDeviceDetails().getSoftwareVersion()\r
- .equalsIgnoreCase(devDetails.getSwVersion())\r
- && devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()) {\r
- logger.debug("received the boot/bootstrap before the transfer complete recevied");\r
- TransferCompleteInform inform = new TransferCompleteInform();\r
- inform.setDeviceDetails(notification.getDeviceDetails());\r
- inform.setFaultCode(0);\r
- processTransferCompleteInform(inform);\r
- }\r
-\r
- devDetails = deviceOperDAO.findByDeviceId(notification.getDeviceDetails().getDeviceId());\r
- if (devDetails.getDownLoadStatus() == FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) {\r
- paramList.add(new ParameterDTO("activation-event.slot-name", "Active-Partion"));\r
- // check for software change\r
- if (notification.getDeviceDetails().getSoftwareVersion()\r
- .equalsIgnoreCase(devDetails.getSwVersion())) {\r
- paramList.add(new ParameterDTO("activation-event.status", "APPLICATION_ERROR"));\r
- paramList.add(new ParameterDTO("activation-event.error-message",\r
- "Same Software Version is reported after upgrade"));\r
- devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_ERROR.getStatus());\r
- } else {\r
- devDetails.setSwVersion(notification.getDeviceDetails().getSoftwareVersion());\r
- devDetails.setDownLoadStatus(FirwareUpgradeStatus.ACTIVATION_COMPLETED.getStatus());\r
- paramList.add(new ParameterDTO("activation-event.status", "COMPLETED"));\r
- }\r
- deviceOperDAO.save(devDetails);\r
-\r
- logger.debug("sending activation-event notification to netconfserver");\r
-\r
- if (notiSender.sendCustomNotification(notification.getDeviceDetails().getDeviceId(),\r
- paramList, SOFT_MGMT_NS_URI).getStatusCode().is2xxSuccessful()) {\r
- logger.debug("sending activation-event notification to netconfserver sucess");\r
- } else {\r
- logger.error("sending activation-event notification to netconfserver failed");\r
- }\r
- }\r
- } catch (Exception e) {\r
- logger.debug(\r
- "Exception occured while processing ProcessFirmWareActivateNotification " + e.toString());\r
- }\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> filterUnsupportedParameters(List<ParameterDTO> parameters,
+ String swVersion, String hwVersion) {
+ List<ParameterDTO> 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<InformType> informTypeList = new ArrayList<>();
+ informTypeList.add(notificationType);
+ bsInform.setDeviceDetails(devNotification.getDeviceDetails());
+ bsInform.setInformTypeList(informTypeList);
+ List<ParameterDTO> 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<InformType> informTypeList = new ArrayList<>();
+ informTypeList.add(notificationType);
+ bInform.setDeviceDetails(devNotification.getDeviceDetails());
+ bInform.setInformTypeList(informTypeList);
+ List<ParameterDTO> 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<InformType> informTypeList = new ArrayList<>();
+ informTypeList.add(notificationType);
+ devValChangeNotif.setDeviceDetails(devNotification.getDeviceDetails());
+ devValChangeNotif.setInformTypeList(informTypeList);
+ List<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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());
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.acs.impl;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.ConfigurationData;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.inform.BootInform;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.mapper.MOMetaData;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler;\r
-import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil;\r
-import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.HttpEntity;\r
-import org.springframework.http.HttpHeaders;\r
-import org.springframework.http.MediaType;\r
-import org.springframework.http.ResponseEntity;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.util.LinkedMultiValueMap;\r
-import org.springframework.util.MultiValueMap;\r
-import org.springframework.util.StringUtils;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-public class PnPPreProvisioningHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(PnPPreProvisioningHandler.class);\r
-\r
- private static String clientString = "client";\r
- private static final String ADMIN_STATE = "AdminState";\r
- private static final String ENODEB_NAME = "X_0005B9_eNBName";\r
-\r
- @Autowired\r
- SynchronizedRequestHandler syncHandler;\r
-\r
- @Autowired\r
- MOMetaDataUtil moMetaDataUtil;\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- private RestTemplate restTemplate = new RestTemplate();\r
-\r
- /**\r
- * @param notification\r
- */\r
- public void onDeviceNotification(DeviceInform notification) {\r
- String deviceId = null;\r
- try {\r
- if (notification instanceof BootstrapInform || notification instanceof BootInform) {\r
- logger.debug("Checking whether the PnP pre-configuration is enabled");\r
- if (isPreConfigureOnPnPEnabled()) {\r
- logger.info(\r
- "Pre-configuration during Bootstrap or Boot is enabled, hence the configuration imported in Config DB shall be provisioned to the device");\r
- } else {\r
- logger.debug("Pre-configuration on PnP is disabled!!!");\r
- return;\r
- }\r
- }\r
-\r
- if (notification instanceof BootstrapInform) {\r
- BootstrapInform bootstrapNotification = (BootstrapInform) notification;\r
- deviceId = bootstrapNotification.getDeviceDetails().getDeviceId();\r
- MDC.put(clientString, deviceId);\r
- logger.info("Bootstrap notification received");\r
- performPreProvisioning(deviceId,\r
- bootstrapNotification.getDeviceDetails().getSoftwareVersion(),\r
- bootstrapNotification.getDeviceDetails().getHardwareVersion(), false);\r
-\r
- } else if (notification instanceof BootInform) {\r
- BootInform bootNotification = (BootInform) notification;\r
- deviceId = bootNotification.getDeviceDetails().getDeviceId();\r
- MDC.put(clientString, deviceId);\r
- logger.info("Boot notification received");\r
-\r
- performPreProvisioning(deviceId, bootNotification.getDeviceDetails().getSoftwareVersion(),\r
- bootNotification.getDeviceDetails().getHardwareVersion(), true);\r
- }\r
-\r
- logger.debug("Successfully completed provisioning of PnP mandatory parameters");\r
- } finally {\r
- MDC.remove(clientString);\r
- }\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param isBoot\r
- */\r
- private void performPreProvisioning(String deviceId, String swVersion, String hwVersion,\r
- boolean isBoot) {\r
- List<DeviceRPCRequest> deviceRPCRequestList =\r
- prepareNBIDeviceOperationrequest(deviceId, swVersion, hwVersion, isBoot);\r
- if (deviceRPCRequestList.isEmpty()) {\r
- logger.debug("No Operation requests exists to perform pre provision on the device");\r
- return;\r
- }\r
-\r
- boolean isMandatoryProvFailed = false;\r
- for (DeviceRPCRequest deviceRPCRequest : deviceRPCRequestList) {\r
- logger.info("Performing PROVISION operation");\r
- DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest);\r
- logger.debug("Received Provisioning Operation result");\r
- if (deviceRPCResponse != null && !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) {\r
- logger.error("Device operation failed, Reason: {}", deviceRPCResponse.getFaultString());\r
- isMandatoryProvFailed = true;\r
- break;\r
- }\r
-\r
- logger.debug("Provisioning is successful");\r
- }\r
-\r
- if (isMandatoryProvFailed) {\r
- logger\r
- .debug("Mandatory provisioning has failed, hence provisioning Admin down on the device");\r
- provisionAdminDown(deviceRPCRequestList);\r
- logger.debug("AdminDown Provisioning is successful");\r
- }\r
- }\r
-\r
- private void provisionAdminDown(List<DeviceRPCRequest> deviceRPCRequestList) {\r
- DeviceRPCRequest adminDownOpRequest = null;\r
- for (DeviceRPCRequest nbiDeviceOperationRequest : deviceRPCRequestList) {\r
- ParameterDTO param = nbiDeviceOperationRequest.getOpDetails().getParmeters().get(0);\r
- if (param.getParamName().endsWith(ADMIN_STATE)) {\r
- adminDownOpRequest = nbiDeviceOperationRequest;\r
- break;\r
- }\r
- }\r
- if (adminDownOpRequest != null) {\r
- List<ParameterDTO> adminDownParams = adminDownOpRequest.getOpDetails().getParmeters();\r
- for (ParameterDTO adminDownParam : adminDownParams) {\r
- adminDownParam.setParamValue("0");\r
- }\r
- DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(adminDownOpRequest);\r
- if (deviceRPCResponse == null || !StringUtils.isEmpty(deviceRPCResponse.getFaultString())) {\r
- logger.error("Device operation failed, Reason: {}", ((deviceRPCResponse == null)\r
- ? "Null Operation result" : deviceRPCResponse.getFaultString()));\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param isBoot\r
- * @return\r
- */\r
- private List<DeviceRPCRequest> prepareNBIDeviceOperationrequest(String deviceId, String swVersion,\r
- String hwVersion, boolean isBoot) {\r
- logger.debug("Preparing the NBI Device Operation Request");\r
- List<DeviceRPCRequest> deviceRPCRequestList = new ArrayList<>();\r
-\r
- ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion);\r
- if (configData == null || configData.getParameterMONameValueMap().isEmpty()) {\r
- logger.debug("No configuration exists for the device");\r
- return deviceRPCRequestList;\r
- }\r
-\r
- List<ParameterDTO> configParams = new ArrayList<>();\r
- List<ParameterDTO> adminStateParams = new ArrayList<>();\r
- Map<String, String> paramNameValueMap = configData.getParameterMONameValueMap();\r
- Iterator<String> iter = paramNameValueMap.keySet().iterator();\r
- while (iter.hasNext()) {\r
- String paramName = iter.next();\r
- String paramValue = paramNameValueMap.get(paramName);\r
- MOMetaData moMetaData = moMetaDataUtil.getMetaDataByTR69Name(paramName, swVersion, hwVersion);\r
- if ((isBoot && !paramName.endsWith(ADMIN_STATE)) || moMetaData == null)\r
- continue;\r
- ParameterDTO parameterDTO = getParameterDTO(paramName, paramValue, moMetaData);\r
-\r
- if (paramName.endsWith(ADMIN_STATE)) {\r
- adminStateParams.add(parameterDTO);\r
- } else {\r
- configParams.add(parameterDTO);\r
- }\r
- logger.debug("Param -> {} Param Value: {}", paramName, paramValue);\r
- }\r
-\r
- if (configParams.isEmpty() && adminStateParams.isEmpty()) {\r
- logger.debug("Empty parameters list from config db, hence not performing pre-provision");\r
- return deviceRPCRequestList;\r
- }\r
-\r
- if (!configParams.isEmpty()) {\r
- deviceRPCRequestList.add(createNBIOperationRequest(deviceId, configParams));\r
- }\r
-\r
- if (!adminStateParams.isEmpty()) {\r
- deviceRPCRequestList.add(createNBIOperationRequest(deviceId, adminStateParams));\r
- }\r
-\r
- return deviceRPCRequestList;\r
- }\r
-\r
- private ParameterDTO getParameterDTO(String paramName, String paramValue, MOMetaData moMetaData) {\r
- String dataType = moMetaData.getDataType();\r
- if (dataType.equals("boolean")) {\r
- if (paramValue.equalsIgnoreCase("true")) {\r
- paramValue = "1";\r
- } else if (paramValue.equalsIgnoreCase("false")) {\r
- paramValue = "0";\r
- }\r
- }\r
- ParameterDTO parameterDTO = new ParameterDTO(paramName, paramValue);\r
- parameterDTO.setDataType(dataType);\r
-\r
- return parameterDTO;\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @param params\r
- * @return\r
- */\r
- private DeviceRPCRequest createNBIOperationRequest(String deviceId, List<ParameterDTO> params) {\r
- TR069OperationDetails opDetails = new TR069OperationDetails();\r
- opDetails.setOpCode(TR069OperationCode.SET_PARAMETER_VALUES);\r
-\r
- return NetconfToTr069MapperUtil.handleParamsOperation(params, opDetails, deviceId);\r
-\r
- }\r
-\r
- /**\r
- * @param deviceId\r
- * @return\r
- */\r
- private ConfigurationData getDeviceConfigurationData(String deviceId, String swVersion,\r
- String hwVersion) {\r
- String configDBURI = getConfigDBURI();\r
- logger.debug(\r
- "Device Configuration to be fetched from Config DB URI: {}, macId {}, swVersion {}, hwVersion {}",\r
- configDBURI, deviceId, swVersion, hwVersion);\r
- ConfigurationData configData = null;\r
- try {\r
-\r
- MultiValueMap<String, String> uriParams = new LinkedMultiValueMap<>();\r
- uriParams.add("macId", deviceId);\r
- uriParams.add("swVersion", swVersion);\r
- uriParams.add("hwVersion", hwVersion);\r
- HttpHeaders headers = new HttpHeaders();\r
- headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);\r
- final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(uriParams, headers);\r
-\r
- ResponseEntity<ConfigurationData> res =\r
- restTemplate.postForEntity(configDBURI, entity, ConfigurationData.class);\r
- configData = res.getBody();\r
- logger.debug("Successfully retrived config data for device id{} data {}", deviceId,\r
- configData);\r
- } catch (Exception e) {\r
- logger.error("An exception occurred to get the initial device configuration, Reason: {}",\r
- e.getMessage());\r
- }\r
- return configData;\r
- }\r
-\r
- /**\r
- * @return\r
- */\r
- private boolean isPreConfigureOnPnPEnabled() {\r
- boolean isEnabled = false;\r
- String preConfigureOnPnP = config.getPreConfigureOnPNP();\r
- if (preConfigureOnPnP != null && ("true".equalsIgnoreCase(preConfigureOnPnP)\r
- || "false".equalsIgnoreCase(preConfigureOnPnP))) {\r
- isEnabled = Boolean.valueOf(preConfigureOnPnP);\r
- }\r
-\r
- return isEnabled;\r
- }\r
-\r
- /**\r
- * @return\r
- */\r
- private String getConfigDBURI() {\r
- return config.getConfigDBUri();\r
-\r
- }\r
-\r
- /**\r
- * it will return the eNodBName if the configuration is imported\r
- * \r
- * @return String\r
- */\r
- public String getEnodeBName(String deviceId, String swVersion, String hwVersion) {\r
- String eNodeBName = null;\r
- if (isPreConfigureOnPnPEnabled()) {\r
- ConfigurationData configData = getDeviceConfigurationData(deviceId, swVersion, hwVersion);\r
- if (configData == null || configData.getParameterMONameValueMap().isEmpty()) {\r
- logger.debug("No configuration exists for the device");\r
- return eNodeBName;\r
- }\r
-\r
- Map<String, String> paramNameValueMap = configData.getParameterMONameValueMap();\r
- Iterator<String> iter = paramNameValueMap.keySet().iterator();\r
- while (iter.hasNext()) {\r
- String paramName = iter.next();\r
- if (paramName.endsWith(ENODEB_NAME)) {\r
- eNodeBName = paramNameValueMap.get(paramName);\r
- break;\r
- }\r
- }\r
- }\r
- return eNodeBName;\r
- }\r
-}\r
+/*
+ * ============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<DeviceRPCRequest> 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<DeviceRPCRequest> 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<ParameterDTO> 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<DeviceRPCRequest> prepareNBIDeviceOperationrequest(String deviceId, String swVersion,
+ String hwVersion, boolean isBoot) {
+ logger.debug("Preparing the NBI Device Operation Request");
+ List<DeviceRPCRequest> 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<ParameterDTO> configParams = new ArrayList<>();
+ List<ParameterDTO> adminStateParams = new ArrayList<>();
+ Map<String, String> paramNameValueMap = configData.getParameterMONameValueMap();
+ Iterator<String> 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<ParameterDTO> 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<String, String> 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<MultiValueMap<String, String>> entity = new HttpEntity<>(uriParams, headers);
+
+ ResponseEntity<ConfigurationData> 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<String, String> paramNameValueMap = configData.getParameterMONameValueMap();
+ Iterator<String> iter = paramNameValueMap.keySet().iterator();
+ while (iter.hasNext()) {
+ String paramName = iter.next();
+ if (paramName.endsWith(ENODEB_NAME)) {
+ eNodeBName = paramNameValueMap.get(paramName);
+ break;
+ }
+ }
+ }
+ return eNodeBName;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.boot;\r
-\r
-import org.springframework.boot.SpringApplication;\r
-import org.springframework.boot.autoconfigure.SpringBootApplication;\r
-import org.springframework.boot.autoconfigure.domain.EntityScan;\r
-import org.springframework.boot.web.client.RestTemplateBuilder;\r
-import org.springframework.context.annotation.Bean;\r
-import org.springframework.context.annotation.ComponentScan;\r
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@SpringBootApplication\r
-@ComponentScan({"org.commscope.tr069adapter.mapper", "org.commscope.tr069adapter.mapper.acs",\r
- "org.commscope.tr069adapter.mapper.ves", "org.commscope.tr069adapter.common"})\r
-@EnableJpaRepositories("org.commscope.tr069adapter.mapper.dao")\r
-@EntityScan("org.commscope.tr069adapter.mapper.entity")\r
-public class MapperServiceBooter {\r
-\r
- public static void main(String[] args) {\r
- SpringApplication.run(MapperServiceBooter.class, args);\r
- }\r
-\r
- @Bean\r
- public RestTemplate restTemplate(RestTemplateBuilder builder) {\r
- return builder.build();\r
- }\r
-\r
-}\r
+/*
+ * ============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_END=======================================================================
*/
-package org.commscope.tr069adapter.mapper.entity;\r
-\r
-import java.io.Serializable;\r
-\r
-import javax.persistence.Column;\r
-import javax.persistence.Entity;\r
-import javax.persistence.GeneratedValue;\r
-import javax.persistence.GenerationType;\r
-import javax.persistence.Id;\r
-import javax.persistence.Table;\r
-import javax.persistence.UniqueConstraint;\r
-\r
-@Entity\r
-@Table(name = "device_operation_details",\r
- uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID"}))\r
-public class DeviceOperationDetails implements Serializable {\r
- @Id\r
- @GeneratedValue(strategy = GenerationType.AUTO)\r
- private Long id;\r
-\r
- @Column(name = "DEVICE_ID", length = 30)\r
- private String deviceId;\r
-\r
- @Column(name = "SW_VERSION", length = 30)\r
- private String swVersion;\r
-\r
- @Column(name = "DOWN_LOAD_STATUS")\r
- private int downLoadStatus;\r
-\r
- @Column(name = "FIRMWARE_FILE", length = 1024)\r
- private String fileName;\r
-\r
- public Long getId() {\r
- return id;\r
- }\r
-\r
- public void setId(Long id) {\r
- this.id = id;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceId) {\r
- this.deviceId = deviceId;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public int getDownLoadStatus() {\r
- return downLoadStatus;\r
- }\r
-\r
- public void setDownLoadStatus(int downLoadStatus) {\r
- this.downLoadStatus = downLoadStatus;\r
- }\r
-\r
- public String getFileName() {\r
- return fileName;\r
- }\r
-\r
- public void setFileName(String fileName) {\r
- this.fileName = fileName;\r
- }\r
-}\r
+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;
+ }
+}
package org.commscope.tr069adapter.mapper.model;\r
\r
import java.io.Serializable;\r
+\r
import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class NetConfNotificationDTO implements Serializable {\r
\r
private static final long serialVersionUID = 4928942484595767042L;\r
- private String deviceID;\r
private String notificaiton;\r
+ private String deviceID;\r
\r
public NetConfNotificationDTO() {\r
super();\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.model;\r
-\r
-import java.io.Serializable;\r
-\r
-public class NetConfRequest implements Serializable {\r
-\r
- private static final long serialVersionUID = -7593813981401577995L;\r
-\r
- private String requestXml;\r
-\r
- // operation status\r
- private String deviceId;\r
- private String swVersion;\r
- private String hwVersion;\r
- \r
- public NetConfRequest() {\r
- super();\r
- }\r
-\r
- public NetConfRequest(String requestXml, String deviceId, String swVersion, String hwVersion) {\r
- super();\r
- this.requestXml = requestXml;\r
- this.deviceId = deviceId;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- public String getRequestXml() {\r
- return requestXml;\r
- }\r
-\r
- public void setRequestXml(String requestXml) {\r
- this.requestXml = requestXml;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceId) {\r
- this.deviceId = deviceId;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return "NetConfRequest [RequestXml=" + requestXml + ", deviceId=" + deviceId + "]";\r
- }\r
-\r
-}\r
+/*
+ * ============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 + "]";
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-package org.commscope.tr069adapter.mapper.model;\r
-\r
-import java.io.Serializable;\r
-\r
-public class NetConfServerDetails implements Serializable {\r
-\r
- private static final long serialVersionUID = -7594811982301577995L;\r
-\r
- private String deviceId;\r
- private String enodeBName;\r
- private String listenAddress;\r
- private String listenPort;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- private NetconfServerManagementError error;\r
-\r
- public NetConfServerDetails() {\r
- super();\r
- }\r
-\r
- public NetConfServerDetails(String deviceId, String listenAddress, String listenPort) {\r
- super();\r
- this.deviceId = deviceId;\r
- this.listenAddress = listenAddress;\r
- this.listenPort = listenPort;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceId) {\r
- this.deviceId = deviceId;\r
- }\r
-\r
- public String getListenAddress() {\r
- return listenAddress;\r
- }\r
-\r
- public void setListenAddress(String listenAddress) {\r
- this.listenAddress = listenAddress;\r
- }\r
-\r
- public String getListenPort() {\r
- return listenPort;\r
- }\r
-\r
- public void setListenPort(String listenPort) {\r
- this.listenPort = listenPort;\r
- }\r
-\r
- public NetconfServerManagementError getError() {\r
- return error;\r
- }\r
-\r
- public void setError(NetconfServerManagementError error) {\r
- this.error = error;\r
- }\r
-\r
- public String getEnodeBName() {\r
- return enodeBName;\r
- }\r
-\r
- public void setEnodeBName(String enodeBName) {\r
- this.enodeBName = enodeBName;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return "NetConfServerDetails [deviceId=" + deviceId + ", enodeBName=" + enodeBName\r
- + ", listenAddress=" + listenAddress + ", listenPort=" + listenPort + ", swversion="\r
- + swVersion + ", hwversion=" + hwVersion + ", error=" + error + "]";\r
- }\r
-}\r
+/*
+ * ============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 + "]";
+ }
+}
\r
package org.commscope.tr069adapter.mapper.model;\r
\r
-import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
-\r
import java.io.Serializable;\r
+import java.util.List;\r
\r
import org.commscope.tr069adapter.acs.common.DeviceInform;\r
import org.commscope.tr069adapter.acs.common.OperationDetails;\r
+import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo;\r
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;\r
\r
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
+@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")\r
public class VESNotification implements Serializable {\r
private DeviceInform devnotification;\r
private OperationDetails operationDetails;\r
private NetConfServerDetails netconfDetails;\r
+ private List<ParameterDTO> netconfParameters;\r
private String eNodeBName;\r
\r
public DeviceInform getDevnotification() {\r
this.eNodeBName = eNodeBName;\r
}\r
\r
+ public List<ParameterDTO> getNetconfParameters() {\r
+ return netconfParameters;\r
+ }\r
+\r
+ public void setNetconfParameters(List<ParameterDTO> netconfParameters) {\r
+ this.netconfParameters = netconfParameters;\r
+ }\r
+\r
}\r
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.netconf;\r
-\r
-import java.io.StringWriter;\r
-import java.text.SimpleDateFormat;\r
-import java.util.ArrayList;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.StringTokenizer;\r
-import javax.xml.parsers.DocumentBuilder;\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-import javax.xml.parsers.ParserConfigurationException;\r
-import javax.xml.transform.Transformer;\r
-import javax.xml.transform.TransformerFactory;\r
-import javax.xml.transform.dom.DOMSource;\r
-import javax.xml.transform.stream.StreamResult;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.MOMetaData;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO;\r
-import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.ResponseEntity;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.web.client.RestTemplate;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-\r
-@Component\r
-public class NetConfNotificationSender {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfNotificationSender.class);\r
- private static final String BOOLEAN_TRUE_VALUE = "1";\r
- private static final String BOOLEAN_FALSE_VALUE = "0";\r
- private static final String BOOLEAN_DATA_TYPE = "boolean";\r
- public static final String NOTIFICATION_ELEMENT_NAME = "notification";\r
- public static final String EVENT_TIME = "eventTime";\r
- private static final String INDEX_STR = "index";\r
- private static final String INDEX_REGEX = "[0-9]{1,}";\r
-\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- @Autowired\r
- MOMetaDataUtil metaDataUtil;\r
-\r
- @Autowired\r
- RestTemplate restTemplate;\r
-\r
- public ResponseEntity sendNotification(DeviceInform deviceInform) {\r
- ResponseEntity response = null;\r
- final String uri = getUri();\r
- LOG.debug("Posting notification to netconf server {}", uri);\r
-\r
- try {\r
- LOG.debug("deviceInform : {} {}", deviceInform.getInformTypeList(),\r
- deviceInform.getParameters());\r
- List<ParameterDTO> parameters = new ArrayList<>();\r
- for (ParameterDTO parameterDTO : deviceInform.getParameters()) {\r
- parameters.add(parameterDTO);\r
- }\r
-\r
- convertTR069ToNetConfParams(parameters, deviceInform.getDeviceDetails().getSoftwareVersion(),\r
- deviceInform.getDeviceDetails().getHardwareVersion());\r
-\r
- String nameSpace = metaDataUtil.getMetaDataByTR69Name(deviceInform.getInformType().toString(),\r
- deviceInform.getDeviceDetails().getSoftwareVersion(),\r
- deviceInform.getDeviceDetails().getHardwareVersion()).getURI();\r
-\r
- String notificationXml =\r
- getNetconfResponseXML(parameters, deviceInform.getInformType().toString(), nameSpace);\r
- NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO(\r
- deviceInform.getDeviceDetails().getDeviceId(), notificationXml);\r
-\r
- LOG.debug("Posting notification to netconf server");\r
- response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class);\r
- LOG.debug("Posting notification to netconf server completed ");\r
- } catch (Exception e) {\r
- LOG.error("Exception while sending the notification.", e);\r
- }\r
- return response;\r
- }\r
-\r
- public ResponseEntity sendCustomNotification(String deviceId, List<ParameterDTO> parameters,\r
- String nameSpace) {\r
- ResponseEntity response = null;\r
- final String uri = getUri();\r
- LOG.debug("Posting custom notification to netconf server " + uri);\r
- try {\r
- String notificationXml = getNetconfResponseXML(parameters, null, nameSpace);\r
- NetConfNotificationDTO netConfDTO = new NetConfNotificationDTO(deviceId, notificationXml);\r
-\r
- response = restTemplate.postForObject(uri, netConfDTO, ResponseEntity.class);\r
- LOG.debug("Posting custom notification to netconf server sucessfull");\r
- } catch (Exception e) {\r
- LOG.error("Exception while sending the custom notification.", e.toString());\r
- }\r
- return response;\r
- }\r
-\r
- private void convertTR069ToNetConfParams(List<ParameterDTO> parameters, String swVersion,\r
- String hwVersion) {\r
- List<ParameterDTO> removeList = new ArrayList<>();\r
- if (null != parameters) {\r
- for (ParameterDTO param : parameters) {\r
- if (param.getParamValue() == null || param.getParamValue().trim().length() <= 0) {\r
- removeList.add(param);\r
- continue;\r
- }\r
- handleBooleanParameters(param, swVersion, hwVersion);\r
- if (null != param.getParamName()) {\r
- String netConfMOName = metaDataUtil\r
- .getNetconfNameByTR69NameWithIndexes(param.getParamName(), swVersion, hwVersion);\r
- if (null != netConfMOName)\r
- param.setParamName(netConfMOName);\r
- else\r
- removeList.add(param); // unknown parameter found.\r
- }\r
- }\r
- parameters.removeAll(removeList);\r
- }\r
- }\r
-\r
- private void handleBooleanParameters(ParameterDTO param, String swVersion, String hwVersion) {\r
- MOMetaData metaData =\r
- metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion);\r
- if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) {\r
- if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(Boolean.TRUE.toString());\r
- } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(Boolean.FALSE.toString());\r
- }\r
- }\r
- }\r
-\r
- private String getUri() {\r
- return config.getNbiNotificationUri();\r
- }\r
-\r
- private static String getNetconfResponseXML(List<ParameterDTO> parameters,\r
- String notificationType, String nameSpace) {\r
- if (parameters == null || parameters.isEmpty()) {\r
- LOG.debug("There are no parameters found in the response.");\r
- return null;\r
- }\r
-\r
- String result = null;\r
- try {\r
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();\r
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();\r
- Document doc = docBuilder.newDocument();\r
-\r
- Map<String, Element> parentNodeMap = new HashMap<>();\r
- Element dataNode = null; // root of all nodes\r
-\r
- for (ParameterDTO paramDto : parameters) {\r
- String paramName = paramDto.getParamName();\r
- String paramValue = paramDto.getParamValue();\r
- StringTokenizer tokenizer = new StringTokenizer(paramName, ".");\r
- String parentNodeName = null;\r
- String parentNodeKey = null;\r
- Element parentNode = null;\r
- while (tokenizer.hasMoreElements()) {\r
- String nodeName = (String) tokenizer.nextElement();\r
- if (null == parentNodeName) { // construct first node or\r
- // Device node\r
- parentNodeName = nodeName;\r
- parentNodeKey = nodeName;\r
- // check if the node already exists in parentNodeMap\r
- parentNode = parentNodeMap.get(parentNodeKey);\r
- if (null == dataNode) {\r
- dataNode = parentNode;\r
- }\r
- continue;\r
- } else if (nodeName.matches(INDEX_REGEX)) { // construct\r
- // tabular and\r
- // index nodes\r
-\r
- // get parent tabular node from parent MAP\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- Element node = parentNodeMap.get(parentNodeKey);\r
-\r
- // create a tabular parent node if doesn't exit in MAP\r
- if (null == node) {\r
- node = doc.createElement(parentNodeName);\r
- parentNodeMap.put(parentNodeKey, node);\r
-\r
- // update current tabular parent node.\r
- if (null != parentNode)\r
- parentNode.appendChild(node);\r
- else\r
- parentNode = node;\r
-\r
- // prepare and add index node to tabular parent node\r
- Element indexNode = doc.createElement(INDEX_STR);\r
- indexNode.setTextContent(nodeName);\r
- node.appendChild(indexNode);\r
- }\r
- parentNode = node; // move parent to child\r
- parentNodeName = nodeName;\r
- } else if (parentNodeName.matches(INDEX_REGEX)) { // move to\r
- // next\r
- // node\r
- // if\r
- // tabular\r
- // attribute\r
- // is\r
- // found\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- parentNodeName = nodeName;\r
- } else {\r
- // construct intermediate nodes\r
- Element node = parentNodeMap.get(parentNodeKey);\r
- if (null == node) {\r
- if (null == dataNode) {\r
- node = doc.createElementNS(nameSpace, parentNodeName);\r
- dataNode = node;\r
- } else {\r
- node = doc.createElement(parentNodeName);\r
- }\r
- parentNodeMap.put(parentNodeKey, node);\r
- if (null != parentNode)\r
- parentNode.appendChild(node);\r
- }\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- parentNodeName = nodeName;\r
- parentNode = node;\r
- }\r
- }\r
- // construct leaf node\r
- Element leafNode = doc.createElement(parentNodeName);\r
- leafNode.setTextContent(paramValue);\r
- parentNode.appendChild(leafNode);\r
- }\r
-\r
- if (null != dataNode) {\r
- final Element element = doc.createElement(NOTIFICATION_ELEMENT_NAME);\r
- final Element eventTime = doc.createElement(EVENT_TIME);\r
- eventTime\r
- .setTextContent(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));\r
- element.appendChild(element.getOwnerDocument().importNode(eventTime, true));\r
-\r
- if (notificationType != null) {\r
- final Element evtTypeElement = doc.createElementNS(nameSpace, notificationType);\r
- evtTypeElement.appendChild(dataNode);\r
- element.appendChild(element.getOwnerDocument().importNode(evtTypeElement, true));\r
- } else {\r
- element.appendChild(element.getOwnerDocument().importNode(dataNode, true));\r
- }\r
-\r
- result = convertDocumentToString(element);\r
- }\r
- } catch (ParserConfigurationException pce) {\r
- LOG.error("Exception while converting the notification: {}", pce.getMessage());\r
- }\r
-\r
- return result;\r
- }\r
-\r
- public static String convertDocumentToString(Element element) {\r
- String strxml = null;\r
- try {\r
- TransformerFactory transformerFactory = TransformerFactory.newInstance();\r
- Transformer transformer = transformerFactory.newTransformer();\r
- DOMSource source = new DOMSource(element);\r
- StreamResult result = new StreamResult(new StringWriter());\r
- transformer.transform(source, result);\r
- strxml = result.getWriter().toString();\r
- } catch (Exception e) {\r
- LOG.error("Error while converting Element to String" + e);\r
- }\r
- LOG.debug("Converted XML is : {}", strxml);\r
- return strxml;\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> 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<ParameterDTO> parameters = new ArrayList<>();
+ // for (ParameterDTO parameterDTO : tcInform.getParameters()) {
+ // parameters.add(parameterDTO);
+ // }
+
+ List<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> parameters, String swVersion,
+ String hwVersion) {
+ List<ParameterDTO> 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<ParameterDTO> 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<String, Element> 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<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.netconf;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfRequest;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-\r
-public interface NetConfRequestHandler {\r
-\r
- public NetConfResponse handleSetConfigRequest(NetConfRequest request);\r
-\r
- public NetConfResponse handleGetRequest(NetConfRequest request);\r
-\r
- public NetConfResponse handleGetConfigRequest(NetConfRequest request);\r
-\r
- public NetConfResponse handleDelConfigRequest(NetConfRequest request);\r
-\r
- public boolean handelRegisterEvent(NetConfServerDetails request);\r
-\r
- public NetConfResponse handleSWDownloadRequest(NetConfRequest request);\r
-\r
-}\r
+/*
+ * ============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);
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.netconf;\r
-\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.HttpEntity;\r
-import org.springframework.http.HttpHeaders;\r
-import org.springframework.http.MediaType;\r
-import org.springframework.http.ResponseEntity;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.util.LinkedMultiValueMap;\r
-import org.springframework.util.MultiValueMap;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-public class NetConfServerManager {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManager.class);\r
-\r
- private static String createServerSVC = "createServer";\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- @Autowired\r
- RestTemplate restTemplate;\r
-\r
- public NetConfServerDetails createNetconfServer(String deviceID, String enodeBName,\r
- String swVersion, String hwVersion) {\r
-\r
- NetConfServerDetails result = null;\r
- // handle exception\r
- final String uri = getNetconfServerManagerRestUri() + "/" + createServerSVC;\r
- LOG.debug("Sending create netconf server request for device id {}", deviceID);\r
- try {\r
- MultiValueMap<String, String> uriParams = new LinkedMultiValueMap<>();\r
- uriParams.add("deviceId", deviceID);\r
- uriParams.add("enodeBName", enodeBName);\r
- uriParams.add("swVersion", swVersion);\r
- uriParams.add("hwVersion", hwVersion);\r
- HttpHeaders headers = new HttpHeaders();\r
- headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);\r
- final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(uriParams, headers);\r
- ResponseEntity<NetConfServerDetails> res =\r
- restTemplate.postForEntity(uri, entity, NetConfServerDetails.class);\r
- result = res.getBody();\r
- LOG.debug("Successfully created netconf server for device id. {} , response= {}", deviceID,\r
- result);\r
- } catch (Exception e) {\r
- LOG.error("Exception while creating netconf server request for device id {}", deviceID, e);\r
- }\r
- return result;\r
- }\r
-\r
- private String getNetconfServerManagerRestUri() {\r
- return config.getNbiServerManagerUri();\r
- }\r
-\r
-}\r
+/*
+ * ============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<String, String> 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<MultiValueMap<String, String>> entity = new HttpEntity<>(uriParams, headers);
+ ResponseEntity<NetConfServerDetails> 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();
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.netconf.controller;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfRequest;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestBody;\r
-import org.springframework.web.bind.annotation.RequestMapping;\r
-import org.springframework.web.bind.annotation.RestController;\r
-\r
-@RestController\r
-@RequestMapping("/tr069MapperNBI")\r
-public class NetConfRequestReceiver {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestReceiver.class);\r
-\r
- @Autowired\r
- NetConfRequestHandler handler;\r
-\r
- @PostMapping("/setConfig")\r
- public NetConfResponse setConfigRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for SET-CONFIG. Request : {}", request);\r
- NetConfResponse response = handler.handleSetConfigRequest(request);\r
- LOG.info("Processed SET-CONFIG request. Response : {}", response);\r
- return response;\r
- }\r
-\r
- @PostMapping("/get")\r
- public NetConfResponse getRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for GET. Request : {}", request);\r
- NetConfResponse response = handler.handleGetRequest(request);\r
- LOG.info("Processed GET request. Response : {}", response);\r
- return response;\r
- }\r
-\r
- @PostMapping("/getConfig")\r
- public NetConfResponse getConfigRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for GET-CONFIG. Request : {}", request);\r
- NetConfResponse response = handler.handleGetConfigRequest(request);\r
- LOG.info("Processed GET-CONFIG request. Response : {}", response);\r
- return response;\r
- }\r
-\r
- @PostMapping("/delConfig")\r
- public NetConfResponse delConfigRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for DEL-CONFIG. Request : {}", request);\r
- NetConfResponse response = handler.handleDelConfigRequest(request);\r
- LOG.info("Processed DEL-CONFIG request. Response : {}", response);\r
- return response;\r
- }\r
-\r
- @PostMapping("/softwareDowload")\r
- public NetConfResponse swDownloadRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for SW-DOWNLOAD. Request : {}", request);\r
- NetConfResponse response = handler.handleSWDownloadRequest(request);\r
- LOG.info("Processed SW-DOWNLOAD request. Response : ");\r
- return response;\r
- }\r
-\r
- @PostMapping("/softwareActivate")\r
- public NetConfResponse swActivateRequest(@RequestBody NetConfRequest request) {\r
- LOG.info("Received request for SW-ACTIVATE. Request : {}", request);\r
- LOG.info("Processed SW-ACTIVATE request. Response : ");\r
- return null;\r
- }\r
-\r
- @PostMapping("/registerNetconfServer")\r
- public boolean handelRegisterEvent(@RequestBody NetConfServerDetails request) {\r
- LOG.info("Received request for register event. Request : {}", request);\r
- boolean result = handler.handelRegisterEvent(request);\r
- LOG.info("Processed register event request. Response : {}", request);\r
- return result;\r
- }\r
-\r
-}\r
+/*
+ * ============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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.netconf.impl;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import java.util.Map;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationOptions;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.response.SetParameterValueResponse;\r
-import org.commscope.tr069adapter.mapper.MOMetaData;\r
-import org.commscope.tr069adapter.mapper.dao.DeviceOperationsDAO;\r
-import org.commscope.tr069adapter.mapper.entity.DeviceOperationDetails;\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfRequest;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfRequestHandler;\r
-import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler;\r
-import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil;\r
-import org.commscope.tr069adapter.mapper.util.FirwareUpgradeStatus;\r
-import org.commscope.tr069adapter.mapper.util.MOMetaDataUtil;\r
-import org.commscope.tr069adapter.mapper.util.MapperConstants;\r
-import org.commscope.tr069adapter.mapper.util.MapperValidator;\r
-import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil;\r
-import org.commscope.tr069adapter.mapper.ves.VESNotificationSender;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.HttpStatus;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.util.StringUtils;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-\r
-@Component\r
-public class NetConfRequestHandlerImpl implements NetConfRequestHandler {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfRequestHandlerImpl.class);\r
- private static final String BOOLEAN_TRUE_VALUE = "1";\r
- private static final String BOOLEAN_FALSE_VALUE = "0";\r
- private static final String BOOLEAN_DATA_TYPE = "boolean";\r
-\r
- @Autowired\r
- SynchronizedRequestHandler syncHandler;\r
-\r
- @Autowired\r
- NetconfToTr069MapperUtil mapperUtil;\r
-\r
- @Autowired\r
- MOMetaDataUtil metaDataUtil;\r
-\r
- @Autowired\r
- ErrorCodeUtil errorCodeUtil;\r
-\r
- @Autowired\r
- VESNotificationSender vesnotiSender;\r
-\r
- @Autowired\r
- DeviceOperationsDAO deviceOperDAO;\r
-\r
- @Override\r
- public NetConfResponse handleSetConfigRequest(NetConfRequest netConfRequest) {\r
- Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml());\r
- NetConfResponse response = null;\r
- DeviceRPCRequest deviceRPCRequest = NetconfToTr069MapperUtil.prepareTR069Request(\r
- netConfRequest.getDeviceId(), el, "config", TR069OperationCode.SET_PARAMETER_VALUES);\r
-\r
- if (deviceRPCRequest == null) {\r
- LOG.debug("There are no supported device parameters found for edit-config.");\r
- return getEmptyResponse();\r
- }\r
- List<ParameterDTO> requestParams = deviceRPCRequest.getOpDetails().getParmeters();\r
- List<ParameterDTO> filteredParams = new ArrayList<>();\r
- List<ParameterDTO> vesRequestParams = new ArrayList<>();\r
-\r
- if (null != requestParams) {\r
- for (ParameterDTO param : requestParams) {\r
- if (null == param.getParamValue() || StringUtils.isEmpty(param.getParamValue())) {\r
- continue;\r
- }\r
- if (isVesNotificationRequest(param)) {\r
- vesRequestParams.add(param);\r
- }\r
- filteredParams.add(param);\r
- }\r
- deviceRPCRequest.getOpDetails().setParmeters(filteredParams);\r
- }\r
-\r
- if (deviceRPCRequest.getOpDetails() == null\r
- || deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no device parameters found for edit-config.");\r
- return getEmptyResponse();\r
- } else if (deviceRPCRequest.getOpDetails() != null) {\r
- deviceRPCRequest.getOpDetails()\r
- .setParmeters(filteredSetParameters(deviceRPCRequest.getOpDetails().getParmeters(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion()));\r
- if (deviceRPCRequest.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no supported device parameters found for edit-config.");\r
- return getEmptyResponse();\r
- }\r
- }\r
-\r
- handleBooleanParametersReverse(deviceRPCRequest.getOpDetails().getParmeters(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion());\r
- LOG.debug("Prepared NBI request for edit-config {}", deviceRPCRequest);\r
-\r
- DeviceRPCResponse deviceRPCResponseVes = null;\r
- List<ParameterDTO> allParamList = deviceRPCRequest.getOpDetails().getParmeters();\r
-\r
- if (!vesRequestParams.isEmpty()) {\r
- if (!MapperValidator.isCountDownTimerValid(vesRequestParams)) {\r
- return getErrorResponse(MapperConstants.INVALID_PARAM_VAL_ERROR_CODE,\r
- MapperConstants.INVALID_COUNT_DOWN_TIMER_MSG);\r
- }\r
-\r
- deviceRPCRequest.getOpDetails().setParmeters(vesRequestParams);\r
- deviceRPCResponseVes = vesnotiSender.sendEditConfigNotification(deviceRPCRequest);\r
-\r
- if (null == deviceRPCResponseVes) {\r
- return getTimeOutResponse();\r
- }\r
- }\r
-\r
- allParamList.removeAll(vesRequestParams);\r
-\r
- DeviceRPCResponse deviceRPCResponseDevice = null;\r
- if (null != allParamList && !allParamList.isEmpty()) {\r
- deviceRPCRequest.getOpDetails().setParmeters(allParamList);\r
- if (isAdminStateOverriden(allParamList)) {\r
- deviceRPCRequest.getOpDetails().setOpCode(CustomOperationCode.CONFIGURE_MULTIPLE_OBJECTS);\r
- TR069OperationDetails tr069OperationDetails =\r
- (TR069OperationDetails) deviceRPCRequest.getOpDetails();\r
- tr069OperationDetails.setModifyParamList(allParamList);\r
- tr069OperationDetails.setSetParamList(null);\r
-\r
- deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest);\r
- convertResposeToSPVResponse(deviceRPCResponseDevice);\r
- } else {\r
- deviceRPCResponseDevice = syncHandler.performDeviceOperation(deviceRPCRequest);\r
- }\r
-\r
- if (null == deviceRPCResponseDevice) {\r
- return getTimeOutResponse();\r
- }\r
- }\r
-\r
- DeviceRPCResponse deviceRPCResponse =\r
- mergeSetConfigDeviceRPCResponse(deviceRPCResponseVes, deviceRPCResponseDevice);\r
- if (null == deviceRPCResponse) {\r
- return getTimeOutResponse();\r
- }\r
- response = mapperUtil.getNetconfResponse(deviceRPCResponse, netConfRequest.getSwVersion(),\r
- netConfRequest.getHwVersion(), false);\r
- return response;\r
- }\r
-\r
- @Override\r
- public NetConfResponse handleDelConfigRequest(NetConfRequest netConfRequest) {\r
- Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml());\r
- NetConfResponse response = null;\r
- DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request(\r
- netConfRequest.getDeviceId(), el, "config", TR069OperationCode.DELETE_OBJECT);\r
-\r
- if (request == null) {\r
- LOG.debug("There are no supported device parameters found for delete-config.");\r
- return getEmptyResponse();\r
- }\r
-\r
- List<ParameterDTO> requestParams = request.getOpDetails().getParmeters();\r
- List<ParameterDTO> filteredParams = new ArrayList<>();\r
- if (null != requestParams) {\r
- for (ParameterDTO param : requestParams) {\r
- filteredParams.add(param);\r
- }\r
- request.getOpDetails().setParmeters(filteredParams);\r
- }\r
-\r
- if (request.getOpDetails() == null || request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no device parameters found for delete-config.");\r
- return getEmptyResponse();\r
- } else if (request.getOpDetails() != null) {\r
- request.getOpDetails()\r
- .setParmeters(filteredSetParameters(request.getOpDetails().getParmeters(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion()));\r
- if (request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no supported device parameters found for delete-config.");\r
- return getEmptyResponse();\r
- }\r
- }\r
- LOG.debug("Prepared NBI request for delete-config {}", request);\r
-\r
- DeviceRPCResponse opResult;\r
- opResult = syncHandler.performDeviceOperation(request);\r
- if (null == opResult) {\r
- return getTimeOutResponse();\r
- }\r
- response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(),\r
- netConfRequest.getHwVersion(), false);\r
- return response;\r
- }\r
-\r
- @Override\r
- public NetConfResponse handleGetRequest(NetConfRequest netConfRequest) {\r
- Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml());\r
- NetConfResponse response = null;\r
- DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request(\r
- netConfRequest.getDeviceId(), el, "filter", TR069OperationCode.GET_PARAMETER_VALUES);\r
-\r
- if (request == null || request.getOpDetails() == null\r
- || request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no device parameters found for get.");\r
- return getEmptyResponse();\r
- } else if (request.getOpDetails() != null) {\r
-\r
- request.getOpDetails()\r
- .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion()));\r
-\r
- if (request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no supported device parameters found for get.");\r
- return getEmptyResponse();\r
- }\r
- }\r
- LOG.debug("Prepared NBI request for get {}", request);\r
-\r
- DeviceRPCResponse opResult;\r
- opResult = syncHandler.performDeviceOperation(request);\r
- if (null == opResult) {\r
- return getTimeOutResponse();\r
- }\r
- response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(),\r
- netConfRequest.getHwVersion(), false);\r
- return response;\r
- }\r
-\r
- @Override\r
- public NetConfResponse handleGetConfigRequest(NetConfRequest netConfRequest) {\r
- Element el = NetconfToTr069MapperUtil.convertStringToDocument(netConfRequest.getRequestXml());\r
- NetConfResponse response = null;\r
- List<ParameterDTO> vesRequestParams = new ArrayList<>();\r
-\r
- boolean isSoftwareInventory = false;\r
- if (netConfRequest.getRequestXml().contains("software-inventory")) {\r
- LOG.info("XML Contains software-inventory");\r
- isSoftwareInventory = true;\r
- }\r
-\r
- DeviceRPCRequest request = NetconfToTr069MapperUtil.prepareTR069Request(\r
- netConfRequest.getDeviceId(), el, "filter", TR069OperationCode.GET_PARAMETER_VALUES);\r
-\r
- if (request == null || request.getOpDetails() == null\r
- || request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no device parameters found for get-config.");\r
- return getEmptyResponse();\r
- } else if (request.getOpDetails() != null) {\r
- request.getOpDetails()\r
- .setParmeters(filteredGetParameters(request.getOpDetails().getParmeters(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion()));\r
-\r
- if (request.getOpDetails().getParmeters().isEmpty()) {\r
- LOG.debug("There are no supported device parameters found for get-config.");\r
- return getEmptyResponse();\r
- }\r
- for (ParameterDTO param : request.getOpDetails().getParmeters()) {\r
- if (isVesNotificationRequest(param)) {\r
- vesRequestParams.add(param);\r
- }\r
- }\r
- }\r
- LOG.debug("Prepared NBI request for get-config {}", request);\r
-\r
- DeviceRPCResponse opResultVes = null;\r
- List<ParameterDTO> allParamList = request.getOpDetails().getParmeters();\r
-\r
- if (!vesRequestParams.isEmpty()) {\r
- request.getOpDetails().setParmeters(vesRequestParams);\r
- opResultVes = vesnotiSender.sendGetConfigNotification(request);\r
-\r
- if (null == opResultVes) {\r
- return getTimeOutResponse();\r
- }\r
- }\r
-\r
-\r
- allParamList.removeAll(vesRequestParams);\r
-\r
- DeviceRPCResponse opResultDevice = null;\r
- if (!allParamList.isEmpty()) {\r
- request.getOpDetails().setParmeters(allParamList);\r
- opResultDevice = syncHandler.performDeviceOperation(request);\r
-\r
- if (null == opResultDevice) {\r
- return getTimeOutResponse();\r
- }\r
- }\r
-\r
- DeviceRPCResponse opResult = mergeGetConfigDeviceRPCResponse(opResultVes, opResultDevice);\r
-\r
- if (null == opResult) {\r
- return getTimeOutResponse();\r
- }\r
- LOG.debug("Received GPV response : FaultKey = " + opResult.getFaultKey() + ", FaultString = "\r
- + opResult.getFaultString() + ", Parameters :"\r
- + opResult.getOperationResponse().getParameterDTOs());\r
- if (null != opResult.getOperationResponse().getParameterDTOs())\r
- handleBooleanParameters(opResult.getOperationResponse().getParameterDTOs(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion());\r
-\r
- if (isSoftwareInventory) {\r
- response = mapperUtil.getNetconfResponseForSoftwareInventory(opResult,\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion());\r
- } else {\r
- response = mapperUtil.getNetconfResponse(opResult, netConfRequest.getSwVersion(),\r
- netConfRequest.getHwVersion(), false);\r
- }\r
-\r
- if (opResult.getFaultKey() != null && opResult.getFaultKey().equalsIgnoreCase("9005")) {\r
- // check for tabular\r
- LOG.debug("Tabualr Entry not exist in the device; we need to add it now");\r
- MOMetaData data = metaDataUtil.getMetaDataByTR69Name(\r
- request.getOpDetails().getParmeters().get(0).getParamName(),\r
- netConfRequest.getSwVersion(), netConfRequest.getHwVersion());\r
- if (data.isTabluarObj()) {\r
- return getEmptyResponse();\r
- }\r
- }\r
-\r
- return response;\r
- }\r
-\r
- @Override\r
- public NetConfResponse handleSWDownloadRequest(NetConfRequest request) {\r
- LOG.debug("request received fro sw-download");\r
- Document d1 = NetconfToTr069MapperUtil.convertStringToDocumentXml(request.getRequestXml());\r
- NetConfResponse response = null;\r
- Map<String, String> map =\r
- NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "software-download");\r
- if (map == null || map.size() <= 0) {\r
- LOG.debug("There are no device parameters found for get.");\r
- return getEmptyResponse();\r
- }\r
-\r
- TR069OperationDetails opDetails = new TR069OperationDetails();\r
- DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest();\r
- TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails();\r
- tr069DeviceDetails.setDeviceId(request.getDeviceId());\r
- deviceRPCRequest.setOpDetails(opDetails);\r
- deviceRPCRequest.setDeviceDetails(tr069DeviceDetails);\r
- OperationOptions options = new OperationOptions();\r
- options.setExecutionTimeout(60l);\r
- deviceRPCRequest.setOptions(options);\r
- String fileName = map.get("rpc.software-download.remote-file-path");\r
- String password = map.get("rpc.software-download.password.password");\r
-\r
- if (fileName == null || password == null || getDownloadFileURI(fileName) == null\r
- || getDownloadUserName(fileName) == null) {\r
- LOG.error(\r
- "remote-file-path value is not as per yang model reference. Allowed pattern sftp://<username>@<host>[:<port>]/path");\r
- return getOperationAbortedResponse(\r
- "remote-file-path value is not as per yang model reference. Allowed pattern sftp://<username>@<host>[:<port>]/path");\r
- }\r
-\r
- List<ParameterDTO> paramDTOList = new ArrayList<>();\r
- paramDTOList.add(new ParameterDTO("FileType", "1 Firmware Upgrade Image"));\r
- paramDTOList.add(new ParameterDTO("URL", getDownloadFileURI(fileName)));\r
- paramDTOList.add(new ParameterDTO("Username", getDownloadUserName(fileName)));\r
- paramDTOList.add(new ParameterDTO("Password", password));\r
- paramDTOList.add(new ParameterDTO("FileSize", "0"));\r
- paramDTOList.add(new ParameterDTO("TargetFileName", ""));\r
- paramDTOList.add(new ParameterDTO("DelaySeconds", "1"));\r
- paramDTOList.add(new ParameterDTO("SuccessURL", ""));\r
- paramDTOList.add(new ParameterDTO("FailureURL", ""));\r
-\r
- deviceRPCRequest.getOpDetails().setParmeters(paramDTOList);\r
- deviceRPCRequest.getOpDetails().setOpCode(TR069OperationCode.DOWNLOAD);\r
-\r
- LOG.debug("Prepared NBI request for download " + deviceRPCRequest);\r
-\r
- DeviceOperationDetails fwDetails = deviceOperDAO.findByDeviceId(request.getDeviceId());\r
- if (fwDetails == null) {\r
- String errorMsg = "TR069 device request has been aborted,due to device not identified";\r
- return getOperationAbortedResponse(errorMsg);\r
- }\r
-\r
- if (fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus()\r
- && fwDetails.getDownLoadStatus() != FirwareUpgradeStatus.DOWNLOAD_COMPLETED.getStatus()) {\r
-\r
- LOG.debug("persisting the fw details " + fwDetails.toString());\r
-\r
- DeviceRPCResponse opResult;\r
- opResult = syncHandler.performDeviceOperation(deviceRPCRequest);\r
- if (null == opResult) {\r
- return getTimeOutResponse();\r
- }\r
- fwDetails.setFileName(fileName);\r
- fwDetails.setDownLoadStatus(FirwareUpgradeStatus.DOWNLOAD_INTIATED.getStatus());\r
- deviceOperDAO.save(fwDetails);\r
- ArrayList<ParameterDTO> responseParamDTOList = new ArrayList<>();\r
-\r
- if (opResult.getOperationResponse().getStatus() == 1) {\r
- responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:status", "STARTED"));\r
- } else {\r
- responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:status", "FAILED"));\r
- responseParamDTOList\r
- .add(new ParameterDTO("rpc-reply.ns1:error-message", opResult.getFaultString()));\r
- }\r
- responseParamDTOList.add(new ParameterDTO("rpc-reply.ns1:notification-timeout", "1200"));\r
-\r
- opResult.getOperationResponse().setParameterDTOs(responseParamDTOList);\r
- response = mapperUtil.getNetconfResponse(opResult, request.getSwVersion(),\r
- request.getHwVersion(), true);\r
-\r
- LOG.debug("update the status for fw details " + fwDetails.toString());\r
- } else {\r
- LOG.debug("FirmWare Upgrade is in progress");\r
- String errorMsg = "TR069 device request has been aborted as Firmware Upgrade is inProgress";\r
- return getOperationAbortedResponse(errorMsg);\r
- }\r
-\r
- return response;\r
- }\r
-\r
- protected DeviceRPCResponse mergeGetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes,\r
- DeviceRPCResponse opResultDevice) {\r
- if (null == opResultVes) {\r
- return opResultDevice;\r
- }\r
-\r
- if (null == opResultDevice) {\r
- return opResultVes;\r
- }\r
-\r
- if (null != opResultVes.getFaultKey()\r
- && !opResultVes.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) {\r
- return opResultVes;\r
- } else if (null != opResultDevice.getFaultKey()\r
- && !opResultDevice.getFaultKey().equals(MapperConstants.RPC_SUCCESS)) {\r
- return opResultDevice;\r
- }\r
-\r
- opResultDevice.getOperationResponse().getParameterDTOs()\r
- .addAll(opResultVes.getOperationResponse().getParameterDTOs());\r
- return opResultDevice;\r
- }\r
-\r
- protected DeviceRPCResponse mergeSetConfigDeviceRPCResponse(DeviceRPCResponse opResultVes,\r
- DeviceRPCResponse opResultDevice) {\r
- if (null == opResultVes) {\r
- return opResultDevice;\r
- }\r
-\r
- if (null == opResultDevice) {\r
- return opResultVes;\r
- }\r
-\r
- return opResultDevice;\r
- }\r
-\r
- protected boolean isVesNotificationRequest(ParameterDTO param) {\r
- if (null == param.getParamName() || param.getParamName().isEmpty()) {\r
- return false;\r
- }\r
-\r
- if (param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT_PERIOD.toLowerCase())\r
- || param.getParamName().toLowerCase()\r
- .contains(MapperConstants.COUNT_DOWN_TIMER.toLowerCase())\r
- || param.getParamName().toLowerCase().contains(MapperConstants.HEART_BEAT.toLowerCase())) {\r
- return true;\r
- }\r
-\r
- return false;\r
- }\r
-\r
- protected void handleBooleanParameters(List<ParameterDTO> parameterDTOs, String swVersion,\r
- String hwVersion) {\r
-\r
- for (ParameterDTO param : parameterDTOs) {\r
- MOMetaData metaData =\r
- metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion);\r
- if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) {\r
- if (BOOLEAN_TRUE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(Boolean.TRUE.toString());\r
- } else if (BOOLEAN_FALSE_VALUE.equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(Boolean.FALSE.toString());\r
- }\r
- }\r
- }\r
- }\r
-\r
- protected void handleBooleanParametersReverse(List<ParameterDTO> parameterDTOs, String swVersion,\r
- String hwVersion) {\r
-\r
- for (ParameterDTO param : parameterDTOs) {\r
- MOMetaData metaData =\r
- metaDataUtil.getMetaDataByTR69Name(param.getParamName(), swVersion, hwVersion);\r
- if (null != metaData && BOOLEAN_DATA_TYPE.equalsIgnoreCase(metaData.getDataType())) {\r
- if (Boolean.TRUE.toString().equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(BOOLEAN_TRUE_VALUE);\r
- } else if (Boolean.FALSE.toString().equalsIgnoreCase(param.getParamValue().trim())) {\r
- param.setParamValue(BOOLEAN_FALSE_VALUE);\r
- }\r
- }\r
- }\r
- }\r
-\r
- protected NetConfResponse getEmptyResponse() {\r
- NetConfResponse response = new NetConfResponse();\r
- ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("0");\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- errorCode.setFaultCode("0");\r
- errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage());\r
- errorCode.setErrorType(errorCodeMetaData.getErrorType());\r
- errorCode.setErrorTag(errorCodeMetaData.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity());\r
- response.setErrorCode(errorCode);\r
- return response;\r
- }\r
-\r
- protected NetConfResponse getTimeOutResponse() {\r
- // prepare timeout error response\r
- NetConfResponse timeOutErrorResponse = new NetConfResponse();\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006");\r
-\r
- errorCode.setFaultCode("8006");\r
- errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage());\r
- errorCode.setErrorType(errorCodeMetaData.getErrorType());\r
- errorCode.setErrorTag(errorCodeMetaData.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity());\r
- timeOutErrorResponse.setErrorCode(errorCode);\r
- timeOutErrorResponse.setErrorMessage("TR069 device request has been timed out.");\r
- return timeOutErrorResponse;\r
- }\r
-\r
- protected NetConfResponse getErrorResponse(String errCode, String errorMsg) {\r
- NetConfResponse errorResponse = new NetConfResponse();\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006");\r
- if (errorCodeMetaData != null) {\r
- errorCode.setFaultCode(errCode);\r
- errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage());\r
- errorCode.setErrorType(errorCodeMetaData.getErrorType());\r
- errorCode.setErrorTag(errorCodeMetaData.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity());\r
- }\r
- errorResponse.setErrorCode(errorCode);\r
- errorResponse.setErrorMessage(errorMsg);\r
- return errorResponse;\r
- }\r
-\r
- protected NetConfResponse getOperationAbortedResponse(String errorMessage) {\r
- // prepare timeout error response\r
- NetConfResponse timeOutErrorResponse = new NetConfResponse();\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- ErrorCodeDetails errorCodeMetaData = errorCodeUtil.getErrorCodeMetaData("8006");\r
- if (errorCodeMetaData != null) {\r
- errorCode.setFaultCode("8002");\r
- errorCode.setErrorMessage(errorCodeMetaData.getErrorMessage());\r
- errorCode.setErrorType(errorCodeMetaData.getErrorType());\r
- errorCode.setErrorTag(errorCodeMetaData.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeMetaData.getErrorSeverity());\r
- }\r
- timeOutErrorResponse.setErrorCode(errorCode);\r
- timeOutErrorResponse.setErrorMessage(errorMessage);\r
- return timeOutErrorResponse;\r
- }\r
-\r
- public List<ParameterDTO> filteredSetParameters(List<ParameterDTO> parameters, String swVersion,\r
- String hwVersion) {\r
- List<ParameterDTO> result = new ArrayList<>();\r
- for (ParameterDTO param : parameters) {\r
- MOMetaData metaData =\r
- metaDataUtil.getMetaDataByNetConfName(param.getParamName(), swVersion, hwVersion);\r
- if (null != metaData && !metaData.isReadOnly()) {\r
- String tr069MoName =\r
- MOMetaDataUtil.getTR69MOByReplacingIndexes(param.getParamName(), metaData.getMoName());\r
- param.setDataType(metaData.getDataType());\r
- param.setParamName(tr069MoName);\r
- result.add(param);\r
- }\r
- }\r
- return result;\r
- }\r
-\r
- protected List<ParameterDTO> filteredGetParameters(List<ParameterDTO> parameters,\r
- String swVersion, String hwVersion) {\r
- return metaDataUtil.getSupportedChildParameters(parameters, swVersion, hwVersion);\r
- }\r
-\r
- @Override\r
- public boolean handelRegisterEvent(NetConfServerDetails request) {\r
- LOG.debug("processing the handelRegisterEvent started");\r
- try {\r
- VESNotificationResponse vesRsponse = vesnotiSender.sendNotification(null, request);\r
- if (HttpStatus.valueOf(vesRsponse.getStatusCode()).is2xxSuccessful()) {\r
- LOG.debug("processing the handelRegisterEvent completed");\r
- return true;\r
- } else {\r
- LOG.error("processing the handelRegisterEvent error code recevived: {}",\r
- vesRsponse.getStatusCode());\r
- return false;\r
- }\r
- } catch (Exception e) {\r
- LOG.error("processing the handelRegisterEvent exception occurred");\r
- return false;\r
- }\r
- }\r
-\r
- protected static String getDownloadFileURI(String filepath) {\r
-\r
- if (filepath.contains("@") && filepath.contains("//")) {\r
- String[] str = filepath.split("@");\r
- String[] strForUserName = str[0].split("//");\r
- if (str.length > 1) {\r
- String Url = strForUserName[0] + "//" + str[1];\r
- return Url;\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- protected static String getDownloadUserName(String filepath) {\r
-\r
- if (filepath.contains("@") && filepath.contains("//")) {\r
- String[] str = filepath.split("@");\r
- String[] strForUserName = str[0].split("//");\r
- if (strForUserName.length > 1)\r
- return strForUserName[1];\r
- }\r
- return null;\r
- }\r
-\r
- protected boolean isAdminStateOverriden(List<ParameterDTO> paramList) {\r
- for (ParameterDTO paramDTO : paramList) {\r
- if (paramDTO.getParamName().contains(MapperConstants.ADMIN_STATE)\r
- || paramDTO.getParamName().contains(MapperConstants.ADMIN_STATUS)) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
-\r
- protected void convertResposeToSPVResponse(DeviceRPCResponse deviceRPCResponse) {\r
- if (null == deviceRPCResponse) {\r
- return;\r
- }\r
-\r
- OperationResponse operationResponse = new SetParameterValueResponse();\r
- operationResponse.setParameterDTOs(new ArrayList<ParameterDTO>());\r
-\r
- if (null == deviceRPCResponse.getFaultKey()) {\r
- operationResponse.setStatus(MapperConstants.RPC_SUCCESS_CODE);\r
- } else {\r
- operationResponse.setStatus(MapperConstants.RPC_FAILED_CODE);\r
- }\r
-\r
- deviceRPCResponse.setOperationResponse(operationResponse);\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> requestParams = deviceRPCRequest.getOpDetails().getParmeters();
+ List<ParameterDTO> filteredParams = new ArrayList<>();
+ List<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> requestParams = request.getOpDetails().getParmeters();
+ List<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<String, String> 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://<username>@<host>[:<port>]/path");
+ return getOperationAbortedResponse(
+ "remote-file-path value is not as per yang model reference. Allowed pattern sftp://<username>@<host>[:<port>]/path");
+ }
+
+ List<ParameterDTO> 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<ParameterDTO> 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<String, String> 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<ParameterDTO> 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<String, String> 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<ParameterDTO> 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<String, String> 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<String, String> map =
+ NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "set-parameter-attributes");
+ if (map == null || map.size() <= 0) {
+ LOG.debug(NO_DEVICE_PARAM_FOUND);
+ return getEmptyResponse();
+ }
+ List<ParameterDTO> 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<ParameterDTO> 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<String, String> map =
+ NetconfToTr069MapperUtil.extractRequestParamters(d1, "rpc", "get-parameter-attributes");
+ if (map == null || map.size() <= 0) {
+ LOG.debug(NO_DEVICE_PARAM_FOUND);
+ return getEmptyResponse();
+ }
+ List<ParameterDTO> 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<ParameterDTO> 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<String, String> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> filteredSetParameters(List<ParameterDTO> parameters, String swVersion,
+ String hwVersion) {
+ List<ParameterDTO> 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<ParameterDTO> filteredGetParameters(List<ParameterDTO> 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<ParameterDTO> 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);
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.sync;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-import java.util.concurrent.Semaphore;\r
-import java.util.concurrent.TimeUnit;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.acs.ACSRequestSender;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class SynchronizedRequestHandler {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(SynchronizedRequestHandler.class);\r
-\r
- private static Map<String, DeviceRPCResponse> opResultMap = new HashMap<>();\r
- private static Map<String, Semaphore> semaphoreMap = new HashMap<>();\r
-\r
- @Autowired\r
- ACSRequestSender tr069RequestSender;\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) {\r
- Long acsOperationId = tr069RequestSender.sendRequest(deviceRPCRequest);\r
-\r
- if (null == acsOperationId) {\r
- LOG.error("Request could not be sent. opId is null");\r
- return null;\r
- }\r
-\r
- String mapperUniqOperId =\r
- deviceRPCRequest.getDeviceDetails().getDeviceId() + "_" + acsOperationId;\r
- LOG.debug("Received operation mapperUniqOperId = {}", mapperUniqOperId);\r
-\r
- boolean isSuccess = false;\r
- try {\r
- isSuccess = waitForResult(mapperUniqOperId);\r
- } catch (InterruptedException e) {\r
- LOG.debug(\r
- "InterruptedException while waiting for tr069 operation result for operation request {}",\r
- deviceRPCRequest);\r
- LOG.error("Exception : {}", e.getMessage());\r
- Thread.currentThread().interrupt();\r
- }\r
- DeviceRPCResponse result = null;\r
- if (!isSuccess) {\r
- LOG.error("Request got timed out for operation {}", mapperUniqOperId);\r
- semaphoreMap.remove(mapperUniqOperId);\r
- } else {\r
- result = getOperationResult(mapperUniqOperId);\r
- LOG.debug("Received operation result for mapperUniqOperId = {} result : {}", mapperUniqOperId,\r
- result);\r
- }\r
- return result;\r
-\r
- }\r
-\r
- public void notifyResult(DeviceRPCResponse opResult) {\r
- Semaphore mutex = semaphoreMap\r
- .remove(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId());\r
- if (mutex != null) {\r
- opResultMap.put(opResult.getDeviceDetails().getDeviceId() + "_" + opResult.getOperationId(),\r
- opResult);\r
- mutex.release();\r
- }\r
- }\r
-\r
- private DeviceRPCResponse getOperationResult(String mapperUniqOperId) {\r
- return opResultMap.remove(mapperUniqOperId);\r
- }\r
-\r
- private boolean waitForResult(String mapperUniqOperId) throws InterruptedException {\r
- LOG.debug("Waiting for operation result for mapperUniqOperId : {}", mapperUniqOperId);\r
- Semaphore semaphore = new Semaphore(0);\r
- semaphoreMap.put(mapperUniqOperId, semaphore);\r
- LOG.debug("Semaphore MAP size = {}", semaphoreMap.size());\r
- LOG.debug("opResultMap MAP size = {}", opResultMap.size());\r
- Integer timeout = 0;\r
- if (null != config.getRequesTimeout()) {\r
- timeout = Integer.valueOf(config.getRequesTimeout());\r
- }\r
- return semaphore.tryAcquire(timeout, TimeUnit.SECONDS);\r
- }\r
-}\r
+/*
+ * ============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<String, DeviceRPCResponse> opResultMap = new HashMap<>();
+ private static Map<String, Semaphore> 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_END=======================================================================
*/
-package org.commscope.tr069adapter.mapper.util;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-public class FirwareUpgradeErrorCode {\r
- private static Map<Integer, String> ErrorCodes = new HashMap<Integer, String>();;\r
-\r
- static {\r
- ErrorCodes.put(9019, "AUTHENTICATION_ERROR");\r
- ErrorCodes.put(9001, "AUTHENTICATION_ERROR");\r
- ErrorCodes.put(9016, "AUTHENTICATION_ERROR");\r
- ErrorCodes.put(9012, "AUTHENTICATION_ERROR");\r
- ErrorCodes.put(9015, "PROTOCOL_ERROR");\r
- ErrorCodes.put(9002, "APPLICATION_ERROR");\r
- ErrorCodes.put(9003, "APPLICATION_ERROR");\r
- ErrorCodes.put(9020, "TIMEOUT");\r
- ErrorCodes.put(0, "COMPLETED");\r
- }\r
-\r
- public static String getErrorCodeMapping(int errorCode) {\r
- return ErrorCodes.get(errorCode) != null ? ErrorCodes.get(errorCode) : "APPLICATION_ERROR";\r
- }\r
-\r
-}\r
+package org.commscope.tr069adapter.mapper.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class FirwareUpgradeErrorCode {
+ private FirwareUpgradeErrorCode() {}
+
+ private static Map<Integer, String> 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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.util;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.nio.charset.StandardCharsets;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Set;\r
-import javax.annotation.PostConstruct;\r
-import org.apache.commons.io.FileUtils;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager;\r
-import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition;\r
-import org.commscope.tr069adapter.mapper.MOMetaData;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class MOMetaDataUtil {\r
-\r
- private static final String STRING_I = ".{i}.";\r
- private static final Logger LOG = LoggerFactory.getLogger(MOMetaDataUtil.class);\r
- private static final String GENERIC_INDEX_REGEX = "\\.\\{[i-l]\\}\\.";\r
- private static final String INDEX_REGEX = "\\.[0-9]{1,}\\.";\r
- private static final String MO_META_DATA_FILE_LOCATION = "mapper-schema";\r
- private Map<String, Map<String, MOMetaData>> metaDataMap;\r
- private Map<String, Map<String, String>> metaDataReverseMap;\r
- public static final String ORAN_SW_MGMT_URI = "urn:o-ran:software-management:1.0";\r
-\r
- @Autowired\r
- DeviceVersionManager versionManager;\r
-\r
- @PostConstruct\r
- public void loadMetaData() {\r
-\r
- try {\r
- LOG.info("Loading mapper schema");\r
- if (metaDataMap != null)\r
- metaDataMap.clear();\r
- if (metaDataReverseMap != null)\r
- metaDataReverseMap.clear();\r
- getMetaDataAsMap(MO_META_DATA_FILE_LOCATION);\r
- LOG.info("Loading mapper schema successfully completed");\r
- } catch (IOException e) {\r
- LOG.error("Exception : {}", e.getMessage());\r
- }\r
- }\r
-\r
- private void getMetaDataAsMap(String fileLocation) throws IOException {\r
- metaDataMap = new HashMap<>();\r
- metaDataReverseMap = new HashMap<>();\r
-\r
- List<ProfileDefinition> profiles = versionManager.getSupportedProfileDefinitions();\r
- for (ProfileDefinition profileDefinition : profiles) {\r
- Map<String, MOMetaData> profileMetaDataMap = new HashMap<>();\r
- Map<String, String> profileMetaDataReverseMap = new HashMap<>();\r
-\r
- Collection<File> files = FileUtils.listFiles(\r
- new File(fileLocation + "/" + profileDefinition.getCsdmMappingPath()), null, false);\r
- for (File file : files) {\r
- LOG.info("Loading mapper schema from {}", file.getName());\r
- List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);\r
- for (String line : lines) {\r
- if (line != null && line.startsWith("#")) {\r
- continue;\r
- }\r
- if (line != null && line.split(",").length >= 3) {\r
- parseMetaDataLine(line, profileMetaDataMap, profileMetaDataReverseMap);\r
- }\r
- }\r
- }\r
- metaDataMap.put(profileDefinition.getProfileId(), profileMetaDataMap);\r
- metaDataReverseMap.put(profileDefinition.getProfileId(), profileMetaDataReverseMap);\r
- }\r
- }\r
-\r
- private static void parseMetaDataLine(String line, Map<String, MOMetaData> profileMetaDataMap,\r
- Map<String, String> profileMetaDataReverseMap) {\r
- String[] split = line.split(",");\r
- boolean isReadOnly = false;\r
- boolean isTabluar = false;\r
- boolean isTabObject = false;\r
- if (split[2].contains("-")) {\r
- String[] dataAttr = split[2].split("-");\r
- if ("Tabular".equalsIgnoreCase(dataAttr[0]))\r
- isTabluar = true;\r
- if ("ReadOnly".equalsIgnoreCase(dataAttr[1]))\r
- isReadOnly = true;\r
- } else if ("TabularObject".equalsIgnoreCase(split[2])) {\r
- isTabObject = true;\r
- }\r
- prepareMOMetaData(isReadOnly, isTabluar, split, isTabObject, profileMetaDataMap,\r
- profileMetaDataReverseMap);\r
- }\r
-\r
- private static void prepareMOMetaData(boolean isReadOnly, boolean isTabluar, String[] split,\r
- boolean isTabObject, Map<String, MOMetaData> profileMetaDataMap,\r
- Map<String, String> profileMetaDataReverseMap) {\r
- String dataType = "";\r
- if (split.length > 3) {\r
- dataType = split[3];\r
- }\r
- if (isTabObject) {\r
- String logMessage = split[1].substring(0, split[1].length() - 5);\r
- LOG.info("Adding Parent Objects {}", logMessage);\r
- String substring = split[0].substring(0, split[0].length() - 4);\r
- MOMetaData metaTabData =\r
- new MOMetaData(substring, dataType, isReadOnly, isTabluar, isTabObject);\r
- if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) {\r
- metaTabData.setURI(split[4]);\r
- }\r
- profileMetaDataMap.put(logMessage, metaTabData);\r
- }\r
- MOMetaData metaData = new MOMetaData(split[0], dataType, isReadOnly, isTabluar, isTabObject);\r
- if ((split.length > 4 && split[4] != null) && split[4].trim().length() > 0) {\r
- metaData.setURI(split[4]);\r
- }\r
- profileMetaDataMap.put(split[1], metaData);\r
- profileMetaDataReverseMap.put(split[0], split[1]);\r
- }\r
-\r
- public MOMetaData getMetaDataByNetConfName(String moName, String swVersion, String hwVersion) {\r
- String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I);\r
-\r
- String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion);\r
- Map<String, MOMetaData> metaData = metaDataMap.get(profileId);\r
-\r
- return metaData.get(moNameInGnrForm);\r
- }\r
-\r
- public MOMetaData getMetaDataByTR69Name(String moName, String swVersion, String hwVersion) {\r
- String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I);\r
-\r
- String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion);\r
- Map<String, String> profileReverseMetaData = metaDataReverseMap.get(profileId);\r
- Map<String, MOMetaData> profileMetaData = metaDataMap.get(profileId);\r
-\r
- String netconfMoName = profileReverseMetaData.get(moNameInGnrForm);\r
- return profileMetaData.get(netconfMoName);\r
- }\r
-\r
- public String getNetconfNameByTR69NameWithIndexes(String moName, String swVersion,\r
- String hwVersion) {\r
- String moNameInGnrForm = moName.replaceAll(INDEX_REGEX, STRING_I);\r
- String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion);\r
- Map<String, String> reverseMetaData = metaDataReverseMap.get(profileId);\r
- String netConfNMoName = reverseMetaData.get(moNameInGnrForm);\r
- return netConfNMoName != null ? getNetConfMOByReplacingIndexes(netConfNMoName, moName)\r
- : netConfNMoName;\r
- }\r
-\r
- public List<ParameterDTO> getSupportedChildParameters(List<ParameterDTO> parameters,\r
- String swVersion, String hwVersion) {\r
- List<ParameterDTO> result = new ArrayList<>();\r
- Set<MOMetaData> allMatchedChilds = new HashSet<>();\r
- String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion);\r
- Map<String, MOMetaData> profileMetaData = metaDataMap.get(profileId);\r
- for (ParameterDTO param : parameters) {\r
- String parentMONameInGnrc = param.getParamName().replaceAll(INDEX_REGEX, STRING_I);\r
- MOMetaData moData = profileMetaData.get(parentMONameInGnrc);\r
- if (moData != null) {\r
- allMatchedChilds.add(new MOMetaData(\r
- getTR69MOByReplacingIndexes(param.getParamName(), moData.getMoName()),\r
- moData.getDataType(), moData.isReadOnly(), moData.isTabluar(), moData.isTabluarObj()));\r
- }\r
- }\r
- for (MOMetaData metaData : allMatchedChilds) {\r
- ParameterDTO param = new ParameterDTO();\r
- String paramName = metaData.getMoName();\r
-\r
- param.setParamName(paramName);\r
- param.setDataType(metaData.getDataType());\r
- result.add(param);\r
- }\r
- return result;\r
- }\r
-\r
- public List<ParameterDTO> getDeviceSupportedChildParameters() {\r
- List<ParameterDTO> result = new ArrayList<>();\r
-\r
- ParameterDTO param1 = new ParameterDTO();\r
- param1.setParamName("Device.DeviceInfo.Description");\r
- param1.setParamValue("Internal");\r
- param1.setDataType("string");\r
- result.add(param1);\r
- return result;\r
- }\r
-\r
- public static String getTR69MOByReplacingIndexes(String netconfMo, String tr69Mo) {\r
-\r
- String[] split = netconfMo.split("\\.");\r
- for (int i = 0; i < split.length; i++) {\r
- if (split[i].matches("[0-9]{1,}")) {\r
- tr69Mo = tr69Mo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + ".");\r
- }\r
- }\r
- return tr69Mo;\r
- }\r
-\r
- public static String getNetConfMOByReplacingIndexes(String netconfMo, String tr69Mo) {\r
-\r
- String[] split = tr69Mo.split("\\.");\r
- for (int i = 0; i < split.length; i++) {\r
- if (split[i].matches("[0-9]{1,}")) {\r
- netconfMo = netconfMo.replaceFirst(GENERIC_INDEX_REGEX, "." + split[i] + ".");\r
- }\r
- }\r
- return netconfMo;\r
- }\r
-}\r
+/*
+ * ============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<String, Map<String, MOMetaData>> metaDataMap;
+ private Map<String, Map<String, String>> 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<ProfileDefinition> profiles = versionManager.getSupportedProfileDefinitions();
+ for (ProfileDefinition profileDefinition : profiles) {
+ Map<String, MOMetaData> profileMetaDataMap = new HashMap<>();
+ Map<String, String> profileMetaDataReverseMap = new HashMap<>();
+
+ Collection<File> files = FileUtils.listFiles(
+ new File(fileLocation + "/" + profileDefinition.getCsdmMappingPath()), null, false);
+ for (File file : files) {
+ LOG.info("Loading mapper schema from {}", file.getName());
+ List<String> 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<String, MOMetaData> profileMetaDataMap,
+ Map<String, String> 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<String, MOMetaData> profileMetaDataMap,
+ Map<String, String> 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<String, MOMetaData> 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<String, String> profileReverseMetaData = metaDataReverseMap.get(profileId);
+ Map<String, MOMetaData> 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<String, String> 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<String, MOMetaData> profileMetaData = metaDataMap.get(profileId);
+ String tr069MoName = profileMetaData.get(moNameInGnrForm).getMoName();
+ return tr069MoName != null ? getTR69MOByReplacingIndexes(netconfName, tr069MoName)
+ : tr069MoName;
+ }
+
+ public List<ParameterDTO> getSupportedChildParameters(List<ParameterDTO> parameters,
+ String swVersion, String hwVersion) {
+ List<ParameterDTO> result = new ArrayList<>();
+ Set<MOMetaData> allMatchedChilds = new HashSet<>();
+ String profileId = versionManager.getAssociatedProfileId(swVersion, hwVersion);
+ Map<String, MOMetaData> 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<ParameterDTO> getDeviceSupportedChildParameters() {
+ List<ParameterDTO> 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();
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.util;\r
-\r
-import java.io.Serializable;\r
-import java.io.StringReader;\r
-import java.io.StringWriter;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.Comparator;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.StringTokenizer;\r
-import javax.xml.XMLConstants;\r
-import javax.xml.parsers.DocumentBuilder;\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-import javax.xml.parsers.ParserConfigurationException;\r
-import javax.xml.transform.Transformer;\r
-import javax.xml.transform.TransformerFactory;\r
-import javax.xml.transform.dom.DOMSource;\r
-import javax.xml.transform.stream.StreamResult;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationOptions;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.w3c.dom.Node;\r
-import org.w3c.dom.NodeList;\r
-import org.xml.sax.InputSource;\r
-\r
-@Component\r
-public class NetconfToTr069MapperUtil {\r
-\r
- @Autowired\r
- MOMetaDataUtil metaDataUtil;\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(NetconfToTr069MapperUtil.class);\r
- private static final String INDEX_STR = "index";\r
- private static final String INDEX_REGEX = "[0-9]{1,}";\r
-\r
- @Autowired\r
- private ErrorCodeUtil errorCodeUtil;\r
-\r
- public static Element convertStringToDocument(String xmlStr) {\r
- try {\r
- Document doc = convertStringToDocumentXml(xmlStr);\r
- if (null != doc)\r
- return doc.getDocumentElement();\r
- } catch (Exception e) {\r
- logger.error("Error while converting String to element {}", e.getMessage());\r
- }\r
- return null;\r
- }\r
-\r
- public static Document convertStringToDocumentXml(String xmlStr) {\r
- try {\r
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");\r
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");\r
- DocumentBuilder builder;\r
- builder = factory.newDocumentBuilder();\r
- return builder.parse(new InputSource(new StringReader(xmlStr)));\r
- } catch (Exception e) {\r
- logger.error("Error while converting String to element {}", e.getMessage());\r
- }\r
- return null;\r
- }\r
-\r
- public static Map<String, String> extractRequestParamters(Document operationElement,\r
- String netconfTag, String filterElement) {\r
- Node requestDataNode = getParameterDataNode(operationElement, netconfTag, filterElement);\r
- Map<String, String> map = getParameterMapForNode(requestDataNode, -1);\r
- return map;\r
- }\r
-\r
- public static DeviceRPCRequest prepareTR069Request(String deviceId, Element operationElement,\r
- String netconfTag, TR069OperationCode opCode) {\r
- Node requestDataNode = getDeviceDataNode(operationElement, netconfTag);\r
- if (requestDataNode == null) {\r
- logger.debug("No matching device parameters found in the netconf request XML.");\r
- return null;\r
- }\r
- Map<String, String> map = getParameterMapForNode(requestDataNode, -1);\r
- List<ParameterDTO> params = new ArrayList<>();\r
-\r
- for (java.util.Map.Entry<String, String> entry : map.entrySet()) {\r
- if (!entry.getKey().equalsIgnoreCase("filter")) {\r
- String moName = entry.getKey();\r
- String value = entry.getValue();\r
- if (moName.endsWith("." + INDEX_STR)\r
- && (TR069OperationCode.GET_PARAMETER_VALUES.equals(opCode)\r
- || TR069OperationCode.DELETE_OBJECT.equals(opCode))) {\r
- logger.debug("Index node found : {}", moName);\r
- moName = moName.replaceFirst("." + INDEX_STR, ".");\r
- value = null;\r
-\r
- }\r
-\r
- ParameterDTO param = new ParameterDTO(moName, value);\r
- params.add(param);\r
- }\r
- }\r
-\r
- TR069OperationDetails opDetails = new TR069OperationDetails();\r
- opDetails.setOpCode(opCode);\r
- return handleParamsOperation(params, opDetails, deviceId);\r
- }\r
-\r
- public static DeviceRPCRequest handleParamsOperation(List<ParameterDTO> params,\r
- TR069OperationDetails opDetails, String deviceId) {\r
- opDetails.setParmeters(params);\r
-\r
- DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest();\r
- TR069DeviceDetails tr069DeviceDetails = new TR069DeviceDetails();\r
- tr069DeviceDetails.setDeviceId(deviceId);\r
- deviceRPCRequest.setOpDetails(opDetails);\r
- deviceRPCRequest.setDeviceDetails(tr069DeviceDetails);\r
- OperationOptions options = new OperationOptions();\r
- options.setExecutionTimeout(60l);\r
- deviceRPCRequest.setOptions(options);\r
- return deviceRPCRequest;\r
- }\r
-\r
- public NetConfResponse getNetconfResponse(DeviceRPCResponse opResult, String swVersion,\r
- String hwVersion, boolean isCustomparameter) {\r
- NetConfResponse netConfResponse = new NetConfResponse();\r
- ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey());\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- if (errorCodeDetails != null) {\r
- errorCode.setFaultCode(opResult.getFaultKey());\r
- errorCode.setErrorMessage(errorCodeDetails.getErrorMessage());\r
- errorCode.setErrorType(errorCodeDetails.getErrorType());\r
- errorCode.setErrorTag(errorCodeDetails.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity());\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage(opResult.getFaultString());\r
- } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) {\r
- errorCode.setFaultCode(opResult.getFaultKey());\r
- errorCode.setErrorMessage(opResult.getFaultString());\r
- errorCode.setErrorType("application");\r
- errorCode.setErrorTag("operation-failed");\r
- errorCode.setErrorSeverity("ERROR");\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage(opResult.getFaultString());\r
- }\r
- netConfResponse.setNetconfResponseXml(\r
- getNetconfResponseXML(opResult.getOperationResponse().getParameterDTOs(), swVersion,\r
- hwVersion, isCustomparameter));\r
- return netConfResponse;\r
- }\r
-\r
- public NetConfResponse getNetconfResponseForSoftwareInventory(DeviceRPCResponse opResult,\r
- String swVersion, String hwVersion) {\r
-\r
- NetConfResponse netConfResponse = new NetConfResponse();\r
- ErrorCodeDetails errorCodeDetails = errorCodeUtil.getErrorCodeMetaData(opResult.getFaultKey());\r
- ErrorCodeDetails errorCode = new ErrorCodeDetails();\r
- if (errorCodeDetails != null) {\r
- errorCode.setFaultCode(opResult.getFaultKey());\r
- errorCode.setErrorMessage(errorCodeDetails.getErrorMessage());\r
- errorCode.setErrorType(errorCodeDetails.getErrorType());\r
- errorCode.setErrorTag(errorCodeDetails.getErrorTag());\r
- errorCode.setErrorSeverity(errorCodeDetails.getErrorSeverity());\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage(opResult.getFaultString());\r
- return netConfResponse;\r
- } else if (opResult.getFaultKey() != null && opResult.getFaultString() != null) {\r
- errorCode.setFaultCode(opResult.getFaultKey());\r
- errorCode.setErrorMessage(opResult.getFaultString());\r
- errorCode.setErrorType("application");\r
- errorCode.setErrorTag("operation-failed");\r
- errorCode.setErrorSeverity("ERROR");\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage(opResult.getFaultString());\r
- return netConfResponse;\r
- }\r
- List<ParameterDTO> paramDTOList = new ArrayList<>();\r
-\r
- String build = null;\r
- String productClass = null;\r
- for (ParameterDTO paramDto : opResult.getOperationResponse().getParameterDTOs()) {\r
- if (paramDto.getParamName().equals("Device.DeviceInfo.SoftwareVersion"))\r
- build = paramDto.getParamValue();\r
- else if (paramDto.getParamName().equals("Device.DeviceInfo.ProductClass"))\r
- productClass = paramDto.getParamValue();\r
- }\r
-\r
- String[] arrOfBuild = build.split("\\.");\r
- String buildId = arrOfBuild[arrOfBuild.length - 1];\r
- StringBuilder buildVersion = new StringBuilder();\r
- for (int i = 0; i < arrOfBuild.length - 1; i++) {\r
- if (i == arrOfBuild.length - 2) {\r
- buildVersion.append(arrOfBuild[i]);\r
- } else {\r
- buildVersion.append(arrOfBuild[i]);\r
- buildVersion.append(".");\r
- }\r
- }\r
-\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.name", "Active Partition"));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.status", "VALID"));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.active", "true"));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.running", "true"));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.access", "READ_ONLY"));\r
- paramDTOList\r
- .add(new ParameterDTO("software-inventory.software-slot.product-code", productClass));\r
- paramDTOList.add(\r
- new ParameterDTO("software-inventory.software-slot.vendor-code", config.getVendorName()));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-id", buildId));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.build-version",\r
- buildVersion.toString()));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.name", "BC_ONE"));\r
- paramDTOList.add(new ParameterDTO("software-inventory.software-slot.files.integrity", "OK"));\r
-\r
- String XmlStr = getNetconfResponseXML(paramDTOList, swVersion, hwVersion, true);\r
-\r
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
- DocumentBuilder builder;\r
- Document doc = null;\r
- try {\r
- builder = factory.newDocumentBuilder();\r
- doc = builder.parse(new InputSource(new StringReader(XmlStr)));\r
- } catch (Exception e) {\r
- logger.error("Error while converting String to element" + e);\r
- errorCode.setFaultCode("8002");\r
- errorCode.setErrorMessage("Operation Aborted");\r
- errorCode.setErrorType("application");\r
- errorCode.setErrorTag("operation-failed");\r
- errorCode.setErrorSeverity("ERROR");\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage("Operation Aborted");\r
- return netConfResponse;\r
- }\r
-\r
- Element originalDocumentElement = doc.getDocumentElement();\r
- Element newDocumentElement = doc.createElementNS("urn:o-ran:software-management:1.0",\r
- originalDocumentElement.getNodeName());\r
- NodeList list = originalDocumentElement.getChildNodes();\r
- while (list.getLength() != 0) {\r
- newDocumentElement.appendChild(list.item(0));\r
- }\r
- // Replace the original element\r
- doc.replaceChild(newDocumentElement, originalDocumentElement);\r
-\r
- String strxml = null;\r
- try {\r
- TransformerFactory transformerFactory = TransformerFactory.newInstance();\r
- Transformer transformer = transformerFactory.newTransformer();\r
- DOMSource source = new DOMSource(doc);\r
- StreamResult result = new StreamResult(new StringWriter());\r
- transformer.transform(source, result);\r
- strxml = result.getWriter().toString();\r
- } catch (Exception e) {\r
- logger.error("Error while converting Element to String" + e);\r
- errorCode.setFaultCode("8002");\r
- errorCode.setErrorMessage("Operation Aborted");\r
- errorCode.setErrorType("application");\r
- errorCode.setErrorTag("operation-failed");\r
- errorCode.setErrorSeverity("ERROR");\r
- netConfResponse.setErrorCode(errorCode);\r
- netConfResponse.setErrorMessage("Operation Aborted");\r
- return netConfResponse;\r
- }\r
-\r
- netConfResponse.setNetconfResponseXml(strxml);\r
- logger.debug("NetConf Response XML String for software inventory: " + strxml);\r
- return netConfResponse;\r
- }\r
-\r
- private String getNetconfResponseXML(List<ParameterDTO> parameters, String swVersion,\r
- String hwVersion, boolean isCustomparameter) {\r
- if (null == parameters || parameters.isEmpty()) {\r
- // LOG.debug("There are no parameters found in the response.");\r
- return null;\r
- }\r
- Collections.sort(parameters, new SortByParamterName());\r
-\r
- String result = null;\r
- try {\r
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();\r
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();\r
- Document doc = docBuilder.newDocument();\r
-\r
- Map<String, Element> parentNodeMap = new HashMap<>();\r
- Element dataNode = null; // root of all nodes\r
-\r
- for (ParameterDTO paramDto : parameters) {\r
- String paramName = metaDataUtil.getNetconfNameByTR69NameWithIndexes(paramDto.getParamName(),\r
- swVersion, hwVersion);\r
- if (paramName == null && isCustomparameter) {\r
- paramName = paramDto.getParamName();\r
- }\r
- String paramValue = paramDto.getParamValue();\r
- if (paramValue == null || paramValue.trim().isEmpty()) {\r
- continue;\r
- }\r
- StringTokenizer tokenizer = new StringTokenizer(paramName, ".");\r
- String parentNodeName = null;\r
- String parentNodeKey = null;\r
- Element parentNode = null;\r
- while (tokenizer.hasMoreElements()) {\r
- String nodeName = (String) tokenizer.nextElement();\r
- if (null == parentNodeName) { // construct first node or\r
- // Device node\r
- parentNodeName = nodeName;\r
- parentNodeKey = nodeName;\r
- // check if the node already exists in parentNodeMap\r
- parentNode = parentNodeMap.get(parentNodeKey);\r
- if (null == dataNode) {\r
- dataNode = parentNode;\r
- }\r
- continue;\r
- } else if (nodeName.matches(INDEX_REGEX)) { // construct\r
- // tabular and\r
- // index nodes\r
-\r
- // get parent tabular node from parent MAP\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- Element node = parentNodeMap.get(parentNodeKey);\r
-\r
- // create a tabular parent node if doesn't exit in MAP\r
- if (null == node) {\r
- if (metaDataUtil.getMetaDataByNetConfName(parentNodeKey + ".", swVersion,\r
- hwVersion) != null\r
- && metaDataUtil\r
- .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion)\r
- .getURI() != null) {\r
- node = doc.createElementNS(metaDataUtil\r
- .getMetaDataByNetConfName(parentNodeKey + ".", swVersion, hwVersion).getURI(),\r
- parentNodeName);\r
- } else {\r
- node = doc.createElement(parentNodeName);\r
- }\r
- parentNodeMap.put(parentNodeKey, node);\r
-\r
- // update current tabular parent node.\r
- if (null != parentNode)\r
- parentNode.appendChild(node);\r
-\r
- // prepare and add index node to tabular parent node\r
- Element indexNode = doc.createElement(INDEX_STR);\r
- indexNode.setTextContent(nodeName);\r
- node.appendChild(indexNode);\r
- }\r
- parentNode = node; // move parent to child\r
- parentNodeName = nodeName;\r
- } else if (parentNodeName.matches(INDEX_REGEX)) { // move to\r
- // next\r
- // node\r
- // if\r
- // tabular\r
- // attribute\r
- // is\r
- // found\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- parentNodeName = nodeName;\r
- } else {\r
- // construct intermediate nodes\r
- Element node = parentNodeMap.get(parentNodeKey);\r
- if (null == node) {\r
- if (metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion) != null\r
- && metaDataUtil.getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion)\r
- .getURI() != null) {\r
- node = doc.createElementNS(metaDataUtil\r
- .getMetaDataByNetConfName(parentNodeKey, swVersion, hwVersion).getURI(),\r
- parentNodeName);\r
- if (dataNode == null)\r
- dataNode = node;\r
- } else {\r
- node = doc.createElement(parentNodeName);\r
- }\r
- parentNodeMap.put(parentNodeKey, node);\r
- if (null != parentNode)\r
- parentNode.appendChild(node);\r
-\r
- }\r
- parentNodeKey = parentNodeKey + "." + nodeName;\r
- parentNodeName = nodeName;\r
- parentNode = node;\r
- }\r
- }\r
- // construct leaf node\r
- Element leafNode = doc.createElement(parentNodeName);\r
- leafNode.setTextContent(paramValue);\r
- if (parentNode != null)\r
- parentNode.appendChild(leafNode);\r
- }\r
-\r
- if (null != dataNode) {\r
- result = convertDocumentToString(dataNode);\r
- }\r
- } catch (ParserConfigurationException pce) {\r
- logger.error("Response xml formatting is failed : {} ", pce.toString());\r
- }\r
-\r
- return result;\r
- }\r
-\r
- public static String convertDocumentToString(Element element) {\r
- String strxml = null;\r
- try {\r
- TransformerFactory transformerFactory = TransformerFactory.newInstance();\r
- transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");\r
- transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");\r
- Transformer transformer = transformerFactory.newTransformer();\r
- DOMSource source = new DOMSource(element);\r
- StreamResult result = new StreamResult(new StringWriter());\r
- transformer.transform(source, result);\r
- strxml = result.getWriter().toString();\r
- } catch (Exception e) {\r
- logger.error("Error while converting Element to String {}", e.toString());\r
- }\r
- logger.debug("Converted XML is : {} ", strxml);\r
- return strxml;\r
- }\r
-\r
- // TODO: Need to optimize the Node element logic for better performance\r
- private static Map<String, String> getParameterMapForNode(Node moRNode, int numberOfChilds) {\r
- Map<String, String> result = new HashMap<>();\r
- if (moRNode.getNodeType() == Node.ELEMENT_NODE) {\r
- NodeList childs = moRNode.getChildNodes();\r
- boolean hasChildElements = false;\r
- hasChildElements = checkMoreElements(result, childs, hasChildElements);\r
- if (!hasChildElements) {\r
- String moName = getMOName(moRNode);\r
- if (moName.equals("software-inventory")) {\r
- result.put("device.device-info.software-version", moRNode.getTextContent());\r
- result.put("device.device-info.product-class", moRNode.getTextContent());\r
- } else if (!moName.endsWith("." + INDEX_STR)) {\r
- result.put(moName, moRNode.getTextContent());\r
- } else if (numberOfChilds == 1) {\r
- result.put(moName, moRNode.getTextContent());\r
- }\r
- }\r
- }\r
-\r
- return result;\r
- }\r
-\r
- private static boolean checkMoreElements(Map<String, String> result, NodeList childs,\r
- boolean hasChildElements) {\r
- if (childs.getLength() > 0) {\r
- int counter = 0;\r
- for (int i = 0; i < childs.getLength(); i++) {\r
- Node cNode = childs.item(i);\r
- if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) {\r
- counter++;\r
- }\r
- }\r
-\r
- for (int i = 0; i < childs.getLength(); i++) {\r
- Node cNode = childs.item(i);\r
- if (cNode != null && cNode.getNodeType() == Node.ELEMENT_NODE) {\r
- hasChildElements = true;\r
- Map<String, String> subResult = getParameterMapForNode(cNode, counter);\r
- result.putAll(subResult);\r
- }\r
- }\r
- }\r
- return hasChildElements;\r
- }\r
-\r
- private static String getMOName(Node moRNode) {\r
- String result = removeNS(moRNode.getNodeName());\r
- Node pNode = moRNode;\r
- while (true) {\r
- pNode = pNode.getParentNode();\r
- if (pNode == null || pNode.getNodeType() != Node.ELEMENT_NODE\r
- || pNode.getNodeName().equals("edit-config") || pNode.getNodeName().equals("config")\r
- || pNode.getNodeName().equals("get-config") || pNode.getNodeName().equals("filter")\r
- || pNode.getNodeName().equals("get")) {\r
- return result;\r
- } else {\r
- String indexStr = getMOIndex(pNode);\r
- StringBuilder bld = new StringBuilder(removeNS(pNode.getNodeName()));\r
- bld.append(".");\r
- if (indexStr == null) {\r
- bld.append(result);\r
- result = bld.toString();\r
- } else {\r
- bld.append(indexStr);\r
- bld.append(".");\r
- bld.append(result);\r
- result = bld.toString();\r
- }\r
- }\r
- }\r
- }\r
-\r
- private static Node getParameterDataNode(Document el, String docStart, String filterElement) {\r
- NodeList nodeList = el.getElementsByTagName(docStart);\r
- if (nodeList.getLength() > 0) {\r
- nodeList = nodeList.item(0).getChildNodes();\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node node = nodeList.item(i);\r
- String nodeName = removeNS(node.getNodeName());\r
- if (nodeName.equals(filterElement)) {\r
- return node;\r
- }\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- private static Node getDeviceDataNode(Element el, String filter) {\r
- try {\r
- NodeList nodeList = el.getElementsByTagName(filter);\r
- if (nodeList.getLength() > 0) {\r
- nodeList = nodeList.item(0).getChildNodes();\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node node = nodeList.item(i);\r
- if (node.getNodeType() == Node.ELEMENT_NODE) {\r
- return node;\r
- }\r
- }\r
- }\r
- } catch (Exception e) {\r
- logger.error("exception occured while parsing the request xml {}", e.getMessage());\r
- }\r
- return null;\r
- }\r
-\r
- private static String removeNS(String nodeName) {\r
- // remove name space\r
- int li = nodeName.lastIndexOf(':');\r
- nodeName = nodeName.substring(li + 1);\r
- return nodeName;\r
- }\r
-\r
- private static String getMOIndex(Node pNode) {\r
- if (null != pNode) {\r
- NodeList nodeList = pNode.getChildNodes();\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node childNode = nodeList.item(i);\r
- String nodeName = removeNS(childNode.getNodeName());\r
- if (nodeName.equalsIgnoreCase(INDEX_STR)) {\r
- return childNode.getTextContent();\r
- }\r
- }\r
- }\r
- return null;\r
- }\r
-\r
-}\r
-\r
-\r
-class SortByParamterName implements Comparator<ParameterDTO>, Serializable {\r
- private static final long serialVersionUID = 3010693349267067945L;\r
-\r
- public int compare(ParameterDTO a, ParameterDTO b) {\r
- return a.getParamName().compareTo(b.getParamName());\r
- }\r
-}\r
+/*
+ * ============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<String, String> extractRequestParamters(Document operationElement,
+ String netconfTag, String filterElement) {
+ Node requestDataNode = getParameterDataNode(operationElement, netconfTag, filterElement);
+ Map<String, String> 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<String, String> map = getParameterMapForNode(requestDataNode, -1);
+ List<ParameterDTO> params = new ArrayList<>();
+
+ for (java.util.Map.Entry<String, String> 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<ParameterDTO> 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<ParameterDTO> 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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rpc-reply><OK>true</OK></rpc-reply>";
+ 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<ParameterDTO> 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<String, Element> 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<String, String> 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<String, String> 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<String> 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<String, String> getParameterMapForNode(Node moRNode, int numberOfChilds) {
+ Map<String, String> 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<String, String> 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<String, String> 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<ParameterDTO>, Serializable {
+ private static final long serialVersionUID = 3010693349267067945L;
+
+ public int compare(ParameterDTO a, ParameterDTO b) {
+ return a.getParamName().compareTo(b.getParamName());
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper.ves;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-public class VESNotificationSender {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(VESNotificationSender.class);\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- @Autowired\r
- PnPPreProvisioningHandler pnpPreProvisioningHandler;\r
-\r
- @Autowired\r
- VESNotificationSender vesnotiSender;\r
-\r
- @Autowired\r
- RestTemplate restTemplate;\r
-\r
- public VESNotificationResponse sendNotification(DeviceInform deviceInform,\r
- NetConfServerDetails serverInfo) {\r
- final String uri = getUri();\r
- LOG.debug("Posting ves event to ves notifier {}", uri);\r
-\r
- VESNotification vesNotifi = new VESNotification();\r
- if (deviceInform != null) {\r
- vesNotifi.seteNodeBName(\r
- pnpPreProvisioningHandler.getEnodeBName(deviceInform.getDeviceDetails().getDeviceId(),\r
- deviceInform.getDeviceDetails().getSoftwareVersion(),\r
- deviceInform.getDeviceDetails().getHardwareVersion()));\r
- } else {\r
- vesNotifi.seteNodeBName(serverInfo.getEnodeBName());\r
- }\r
- vesNotifi.setNetconfDetails(serverInfo);\r
- vesNotifi.setDevnotification(deviceInform);\r
-\r
- return restTemplate.postForObject(uri, vesNotifi, VESNotificationResponse.class);\r
- }\r
-\r
- public DeviceRPCResponse sendEditConfigNotification(DeviceRPCRequest deviceRPCRequest) {\r
- final String uri = config.getVerConfigUri() + "/editConfig";\r
- LOG.debug("Posting edit config request to ves agent {}", uri);\r
- return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class);\r
- }\r
-\r
- public DeviceRPCResponse sendGetConfigNotification(DeviceRPCRequest deviceRPCRequest) {\r
- final String uri = config.getVerConfigUri() + "/getConfig";\r
- LOG.debug("Posting get config request to ves agent {}", uri);\r
- return restTemplate.postForObject(uri, deviceRPCRequest, DeviceRPCResponse.class);\r
- }\r
-\r
-\r
- private String getUri() {\r
- return config.getVesUri();\r
- }\r
-\r
-}\r
+/*
+ * ============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<ParameterDTO> parameters = deviceInform.getParameters();
+ if (parameters != null && !parameters.isEmpty()) {
+ List<ParameterDTO> 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();
+ }
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.mapper.ves.impl;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.mapper.MapperConfigProperties;\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler;\r
-import org.commscope.tr069adapter.mapper.util.ErrorCodeUtil;\r
-import org.commscope.tr069adapter.mapper.util.MapperConstants;\r
-import org.commscope.tr069adapter.mapper.ves.VesRequestHandler;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class VesRequestHandlerImpl implements VesRequestHandler {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(VesRequestHandlerImpl.class);\r
-\r
- @Autowired\r
- SynchronizedRequestHandler syncHandler;\r
-\r
- @Autowired\r
- MapperConfigProperties config;\r
-\r
- @Autowired\r
- private ErrorCodeUtil errorCodeUtil;\r
-\r
-\r
- @Override\r
- public DeviceRPCResponse handleDeviceConnectivityRequest(DeviceRPCRequest deviceRPCRequest) {\r
- DeviceRPCResponse deviceRPCResponse = syncHandler.performDeviceOperation(deviceRPCRequest);\r
- if (null == deviceRPCResponse) {\r
- return getTimeOutResponse(deviceRPCRequest);\r
- }\r
-\r
- return deviceRPCResponse;\r
- }\r
-\r
- private DeviceRPCResponse getTimeOutResponse(DeviceRPCRequest deviceRPCRequest) {\r
- DeviceRPCResponse timeOutErrorResponse = new DeviceRPCResponse();\r
-\r
- timeOutErrorResponse.setDeviceDetails(deviceRPCRequest.getDeviceDetails());\r
-\r
- OperationResponse operationResponse = new OperationResponse();\r
- operationResponse.setStatus(MapperConstants.DEVICE_REACHABILITY_OP_FAILURE_CODE);// device\r
- // reachable...change\r
- // value 1 to\r
- // some\r
- // constant or\r
- // enum\r
- operationResponse.setOperationCode(deviceRPCRequest.getOpDetails().getOpCode());\r
-\r
- timeOutErrorResponse.setOperationResponse(operationResponse);\r
- timeOutErrorResponse.setFaultKey(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE);\r
- ErrorCodeDetails errorCodeDetails =\r
- errorCodeUtil.getErrorCodeMetaData(MapperConstants.DEVICE_TIMEOUT_STATUS_CODE);\r
- if (null != errorCodeDetails) {\r
- timeOutErrorResponse.setFaultString(errorCodeDetails.getErrorMessage());\r
- } else {\r
- timeOutErrorResponse.setFaultString(MapperConstants.DEFAULT_OP_TIMEOUT_MSG);\r
- }\r
- return timeOutErrorResponse;\r
- }\r
-}\r
+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;
+ }
+}
config.alarmMORegex=${ALARM_MO_REGEX}\r
config.preConfigureOnPNP=${preConfigureOnPNP}\r
config.sbiUri=http://${SBI_REST_HOST}:${SBI_REST_PORT}/MapperService/initiateDeviceOperation\r
+config.connStatusUri=http://${SBI_REST_HOST}:${SBI_REST_PORT}/MapperService/connectionStatusOperation\r
config.configDBUri=http://${CONFIG_DB_REST_HOST}:${CONFIG_DB_REST_PORT}/getConfig\r
config.nbiNotificationUri=http://${NBI_REST_HOST}:${NBI_REST_PORT}/netConfNotificationService/notification\r
config.nbiServerManagerUri=http://${NBI_REST_HOST}:${NBI_REST_PORT}/netConfServerManagerService\r
-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
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertNotNull;\r
-import static org.junit.Assert.assertNull;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069InformType;\r
-import org.commscope.tr069adapter.acs.common.inform.BootInform;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.acs.common.inform.ValueChangeInform;\r
-import org.commscope.tr069adapter.mapper.acs.impl.ACSNotificationHandlerImpl;\r
-import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-\r
-@SpringBootTest(classes = {MapperServiceBooter.class})\r
-@RunWith(SpringRunner.class)\r
-public class ACSNotificationHandlerImplTest {\r
-\r
- @Autowired\r
- ACSNotificationHandlerImpl aCSNotificationHandlerImpl;\r
-\r
- @Mock\r
- NetConfServerManager netConfServerManager;\r
-\r
- @Test\r
- public void testHandleBootStrapNotification() {\r
-\r
- BootstrapInform notification = new BootstrapInform();\r
- List<ParameterDTO> params = new ArrayList<ParameterDTO>();\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName("ExpeditedEvent");\r
- params.add(param);\r
- notification.setDeviceDetails(getDeviceDetails());\r
- notification.setParameters(params);\r
- NetConfServerDetails serverInfo = new NetConfServerDetails();\r
- serverInfo.setError(NetconfServerManagementError.SUCCESS);\r
- Mockito.when(netConfServerManager.createNetconfServer(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))\r
- .thenReturn(serverInfo);\r
- /*\r
- * String URI = "http://tr069adapter-netconf-server:8181/netConfServerManagerService";\r
- * Mockito.when(netConfServerManager.getNetconfServerManagerRestUri()). thenReturn(value)\r
- */\r
- aCSNotificationHandlerImpl.handleNotification(notification);\r
- assertNull(notification.getValueChangeNotification());\r
- }\r
-\r
- @Test\r
- public void testHandleBootStrapNotificationNegativeScenario() {\r
-\r
- BootstrapInform notification = new BootstrapInform();\r
- List<ParameterDTO> params = new ArrayList<ParameterDTO>();\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName("Test");\r
- params.add(param);\r
- notification.setDeviceDetails(getDeviceDetails());\r
- notification.setParameters(params);\r
- // Mockito.doReturn(null).when(netConfServerManager.createNetconfServer(Mockito.anyString(),\r
- // Mockito.anyString()));\r
- aCSNotificationHandlerImpl.handleNotification(notification);\r
- assertNull(notification.getValueChangeNotification());\r
- }\r
-\r
- @Test\r
- public void testHandleBootNotification() {\r
-\r
- BootInform notification = new BootInform();\r
- List<ParameterDTO> params = new ArrayList<ParameterDTO>();\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName("Test");\r
- params.add(param);\r
- notification.setDeviceDetails(getDeviceDetails());\r
- notification.setParameters(params);\r
- aCSNotificationHandlerImpl.handleNotification(notification);\r
- assertNull(notification.getValueChangeNotification());\r
- }\r
-\r
- @Test\r
- public void testGetDeviceBootNotification() {\r
- DeviceInform deviceInform = new DeviceInform();\r
- deviceInform.setDeviceDetails(getDeviceDetails());\r
- deviceInform.setParameters(getGeneralParams());\r
-\r
- BootInform bInform =\r
- ACSNotificationHandlerImpl.getDeviceBootNotification(deviceInform, TR069InformType.BOOT);\r
- assertEquals("00005B9A1", bInform.getDeviceDetails().getDeviceId());\r
- assertNotNull(bInform.getInformTypeList());\r
- assertEquals(TR069InformType.BOOT, bInform.getInformTypeList().get(0));\r
- }\r
-\r
- @Test\r
- public void testGetDeviceBooStraptNotification() {\r
- DeviceInform deviceInform = new DeviceInform();\r
- deviceInform.setDeviceDetails(getDeviceDetails());\r
- deviceInform.setParameters(getGeneralParams());\r
-\r
- BootstrapInform bsInform = ACSNotificationHandlerImpl\r
- .getDeviceBootStrapNotification(deviceInform, TR069InformType.BOOTSTRAP);\r
- assertEquals("00005B9A1", bsInform.getDeviceDetails().getDeviceId());\r
- assertNotNull(bsInform.getInformTypeList());\r
- assertEquals(TR069InformType.BOOTSTRAP, bsInform.getInformTypeList().get(0));\r
- }\r
-\r
- @Test\r
- public void testGetDeviceValueChangeNotification() {\r
- DeviceInform deviceInform = new DeviceInform();\r
- deviceInform.setDeviceDetails(getDeviceDetails());\r
- deviceInform.setParameters(getGeneralParams());\r
-\r
- ValueChangeInform vInform = ACSNotificationHandlerImpl\r
- .getDeviceValueChangeNotification(deviceInform, TR069InformType.VALUECHANGE);\r
- assertEquals("00005B9A1", vInform.getDeviceDetails().getDeviceId());\r
- assertNotNull(vInform.getInformTypeList());\r
- assertEquals(TR069InformType.VALUECHANGE, vInform.getInformTypeList().get(0));\r
- }\r
-\r
- private DeviceDetails getDeviceDetails() {\r
- DeviceDetails nf = new DeviceDetails();\r
- nf.setDeviceId("00005B9A1");\r
- nf.setDeviceTypeId(50);\r
- nf.setOui("0005B9");\r
- nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl");\r
- return nf;\r
- }\r
-\r
- private DeviceDetails getDeviceDetailsNegativeCase() {\r
- DeviceDetails nf = new DeviceDetails();\r
- // nf.setDeviceId("00005B9A1");\r
- nf.setDeviceTypeId(50);\r
- nf.setOui("0005B9");\r
- nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl");\r
- return nf;\r
- }\r
-\r
- private ArrayList<ParameterDTO> getGeneralParams() {\r
- ArrayList<ParameterDTO> params = new ArrayList<>();\r
- params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.HardwareVersion", "750742.00.04"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.SoftwareVersion", "4.3.00.231"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.Manufacturer", "ORAN"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.SerialNumber", "00005B9A1"));\r
- params.add(new ParameterDTO("Device.IP.Interface.1.IPv4Address.1.IPAddress", "10.211.5.55"));\r
- return params;\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> params = new ArrayList<ParameterDTO>();
+ 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<ParameterDTO> params = new ArrayList<ParameterDTO>();
+ 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<ParameterDTO> params = new ArrayList<ParameterDTO>();
+ 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<ParameterDTO> getGeneralParams() {
+ ArrayList<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import static org.junit.Assert.assertFalse;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Map;\r
-import java.util.concurrent.Semaphore;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.acs.ACSRequestSender;\r
-import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter;\r
-import org.commscope.tr069adapter.mapper.model.NetConfRequest;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.netconf.controller.NetConfRequestReceiver;\r
-import org.commscope.tr069adapter.mapper.sync.SynchronizedRequestHandler;\r
-import org.junit.Assert;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.boot.test.mock.mockito.MockBean;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-\r
-@SpringBootTest(classes = {MapperServiceBooter.class})\r
-@RunWith(SpringRunner.class)\r
-public class NetConfRequestReceiverTest {\r
-\r
- @Autowired\r
- NetConfRequestReceiver receiver;\r
-\r
- @MockBean\r
- ACSRequestSender tr069RequestSender;\r
-\r
- @MockBean\r
- Semaphore semaphore;\r
-\r
- @MockBean\r
- SynchronizedRequestHandler sync;\r
-\r
- @MockBean\r
- Map<Long, DeviceRPCResponse> opResultMap;\r
-\r
- @Test\r
- public void getConfigRequestTest() {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))\r
- .thenReturn(prepareDeviceResponseSucess());\r
-\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>");\r
- NetConfResponse nfres = receiver.getConfigRequest(req);\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertNotNull(nfres.getNetconfResponseXml());\r
- }\r
-\r
- @Test\r
- public void getConfigRequestTestTimeOut() throws InterruptedException {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(semaphore.tryAcquire(Mockito.anyInt(), Mockito.anyObject())).thenReturn(true);\r
- Mockito.when(opResultMap.remove(Mockito.anyLong())).thenReturn(prepareDeviceResponseSucess());\r
-\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>");\r
- NetConfResponse nfres = receiver.getConfigRequest(req);\r
- Assert.assertEquals("8006", nfres.getErrorCode().getFaultCode());\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("Operation Timed out", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void getConfigRequestWithNoParamTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"></filter></get-config>");\r
- NetConfResponse nfres = receiver.getConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
-\r
- }\r
-\r
- @Test\r
- public void getConfigRequestWithUnknownParamTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><Intergateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></Intergateway></filter></get-config>");\r
- NetConfResponse nfres = receiver.getRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void getRequestTest() {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))\r
- .thenReturn(prepareDeviceResponseSucess());\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get>");\r
- NetConfResponse nfres = receiver.getRequest(req);\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertNotNull(nfres.getNetconfResponseXml());\r
- }\r
-\r
- @Test\r
- public void getRequestWithNoParamTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"></filter></get>");\r
- NetConfResponse nfres = receiver.getRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void getRequestWithUnknownParamTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><Intergateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></Intergateway></filter></get>");\r
- NetConfResponse nfres = receiver.getRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void setConfigRequestTest() {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))\r
- .thenReturn(prepareSPVDeviceResponseSucess());\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");\r
- NetConfResponse nfres = receiver.setConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void setConfigRequestWithErrorResTest() {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))\r
- .thenReturn(prepareDeviceResponseError());\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");\r
- NetConfResponse nfres = receiver.setConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("9001", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Request denied", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void setConfigRequestWithNoParamTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config></config></edit-config>");\r
- NetConfResponse nfres = receiver.setConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void setConfigRequestWithUnknowParatmerTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><InternetGateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></InternetGateway></config></edit-config>");\r
- NetConfResponse nfres = receiver.setConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void setConfigRequestInvalidRequestXMLTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><confg><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false<is-primary><cell-reserved-for-operator-use>true<cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");\r
- NetConfResponse nfres = receiver.setConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- }\r
-\r
- @Test\r
- public void delConfigRequestTest() {\r
- Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);\r
- Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))\r
- .thenReturn(prepareSPVDeviceResponseSucess());\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");\r
- NetConfResponse nfres = receiver.delConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void delConfigwithUnknownParamterRequestTest() {\r
- NetConfRequest req = prepareNetConfRequest(\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><InternetGateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></InternetGateway></config></edit-config>");\r
- NetConfResponse nfres = receiver.delConfigRequest(req);\r
- Assert.assertNull(nfres.getNetconfResponseXml());\r
- Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", nfres.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void handelRegisterEventTest() {\r
- try {\r
- assertFalse(receiver\r
- .handelRegisterEvent(new NetConfServerDetails("00005BA1", "10.211.55.14", "17830")));\r
- } catch (Exception e) {\r
- }\r
-\r
- }\r
-\r
- private NetConfRequest prepareNetConfRequest(String requestXml) {\r
- NetConfRequest req = new NetConfRequest();\r
- req.setDeviceId("0005B9A1");\r
- req.setRequestXml(requestXml);\r
- req.setSwVersion("4.3.0.0");\r
- req.setHwVersion("*");\r
- return req;\r
- }\r
-\r
- private DeviceRPCResponse prepareDeviceResponseError() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("9001");\r
- opResult.setFaultString("Request denied");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- // opr.setParameterDTOs(getGeneralParams());\r
- opResult.setOperationResponse(opr);\r
- return opResult;\r
- }\r
-\r
- private DeviceRPCResponse prepareDeviceResponseSucess() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("0");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- opr.setParameterDTOs(getGeneralParams());\r
- opResult.setOperationResponse(opr);\r
- return opResult;\r
- }\r
-\r
- private DeviceRPCResponse prepareSPVDeviceResponseSucess() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("0");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- opResult.setOperationResponse(opr);\r
- return opResult;\r
- }\r
-\r
- private ArrayList<ParameterDTO> getGeneralParams() {\r
- ArrayList<ParameterDTO> params = new ArrayList<>();\r
- params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl"));\r
- params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID",\r
- "30324"));\r
- return params;\r
- }\r
-}\r
+/*
+ * ============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<Long, DeviceRPCResponse> opResultMap;
+
+ @Test
+ public void getConfigRequestTest() {
+ Mockito.when(tr069RequestSender.sendRequest(Mockito.anyObject())).thenReturn(10001L);
+ Mockito.when(sync.performDeviceOperation(Mockito.anyObject()))
+ .thenReturn(prepareDeviceResponseSucess());
+
+ NetConfRequest req = prepareNetConfRequest(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"></filter></get-config>");
+ NetConfResponse nfres = receiver.getConfigRequest(req);
+ Assert.assertNull(nfres.getNetconfResponseXml());
+ Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());
+
+ }
+
+ @Test
+ public void getConfigRequestWithUnknownParamTest() {
+ NetConfRequest req = prepareNetConfRequest(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><Intergateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></Intergateway></filter></get-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get>");
+ NetConfResponse nfres = receiver.getRequest(req);
+ Assert.assertEquals("0", nfres.getErrorCode().getFaultCode());
+ Assert.assertNotNull(nfres.getNetconfResponseXml());
+ }
+
+ @Test
+ public void getRequestWithNoParamTest() {
+ NetConfRequest req = prepareNetConfRequest(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"></filter></get>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><Intergateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></Intergateway></filter></get>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><InternetGateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><alias>cpe-131</alias><enable>true</enable></plmn-list></epc></lte></cell-config></fap-service></services></InternetGateway></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><confg><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false<is-primary><cell-reserved-for-operator-use>true<cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></device></config></edit-config>");
+ 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(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><target><candidate/></target><config><InternetGateway xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc xmlns:a=\"urn:ietf:params:xml:ns:netconf:base:1.0\" a:operation=\"replace\"><plmn-list><index>1</index><plmnid>310767</plmnid><is-primary>false</is-primary><cell-reserved-for-operator-use>true</cell-reserved-for-operator-use><name>cpe-131</name><trust>true</trust></plmn-list></epc></lte></cell-config></fap-service></services></InternetGateway></config></edit-config>");
+ 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<ParameterDTO> getGeneralParams() {
+ ArrayList<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.InformType;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069InformType;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfNotificationSender;\r
-import org.commscope.tr069adapter.mapper.netconf.NetConfServerManager;\r
-import org.commscope.tr069adapter.mapper.ves.VESNotificationSender;\r
-import org.junit.Assert;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.boot.test.mock.mockito.MockBean;\r
-import org.springframework.http.HttpStatus;\r
-import org.springframework.http.ResponseEntity;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@SpringBootTest(classes = {MapperServiceBooter.class})\r
-@RunWith(SpringRunner.class)\r
-public class NetConfServerManagerTest {\r
-\r
- @Autowired\r
- NetConfServerManager server;\r
-\r
- @Autowired\r
- NetConfNotificationSender nfSender;\r
-\r
- @Autowired\r
- VESNotificationSender vesSender;\r
-\r
- @MockBean\r
- RestTemplate restTemplate;\r
-\r
- @Test\r
- public void createServerTest() {\r
- ResponseEntity<Object> res = new ResponseEntity<Object>(\r
- new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830"), HttpStatus.ACCEPTED);\r
- Mockito.when(\r
- restTemplate.postForEntity(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()))\r
- .thenReturn(res);\r
- NetConfServerDetails nfDetails = server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*");\r
-\r
- Assert.assertNotNull(nfDetails);\r
- Assert.assertEquals("17830", nfDetails.getListenPort());\r
- }\r
-\r
- @Test\r
- public void createServerFailureWithRestCallTest() {\r
- NetConfServerDetails nfDetails = server.createNetconfServer("0005B9A1", "EnodB1", "4.3.0.0", "*");\r
- Assert.assertNull(nfDetails);\r
- }\r
-\r
- @Test\r
- public void sendNotificaionTest() {\r
- ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED);\r
- Mockito.when(\r
- restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()))\r
- .thenReturn(res);\r
- DeviceInform inform = new BootstrapInform();\r
- inform.setDeviceDetails(getDeviceDetails());\r
- ArrayList<InformType> list = new ArrayList<>();\r
- list.add(TR069InformType.BOOTSTRAP);\r
- inform.setInformTypeList(list);\r
- inform.setParameters(getGeneralParams());\r
- ResponseEntity response = nfSender.sendNotification(inform);\r
- Assert.assertNotNull(response);\r
- Assert.assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());\r
- }\r
-\r
- @Test\r
- public void sendNotificaionInformNullTest() {\r
- ResponseEntity res = new ResponseEntity<>(HttpStatus.ACCEPTED);\r
- Mockito.when(\r
- restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()))\r
- .thenReturn(res);\r
- ResponseEntity response = nfSender.sendNotification(null);\r
- Assert.assertNull(response);\r
- }\r
-\r
- @Test\r
- public void sendVesEventTest() {\r
-\r
- Mockito.when(\r
- restTemplate.postForObject(Mockito.anyString(), Mockito.anyObject(), Mockito.anyObject()))\r
- .thenReturn(new VESNotificationResponse(202, "sucess"));\r
-\r
- DeviceInform inform = new BootstrapInform();\r
- inform.setDeviceDetails(getDeviceDetails());\r
- ArrayList<InformType> list = new ArrayList<InformType>();\r
- list.add(TR069InformType.BOOTSTRAP);\r
- inform.setInformTypeList(list);\r
- inform.setParameters(getGeneralParams());\r
- VESNotificationResponse response = vesSender.sendNotification(inform,\r
- new NetConfServerDetails("0005B9A1", "10.221.55.14", "17830"));\r
- Assert.assertNotNull(response);\r
- Assert.assertEquals(202, response.getStatusCode());\r
- }\r
-\r
- private ArrayList<ParameterDTO> getGeneralParams() {\r
- ArrayList<ParameterDTO> params = new ArrayList<>();\r
- params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl"));\r
- params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID",\r
- "30324"));\r
- params.add(new ParameterDTO(\r
- "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1"));\r
- params.add(\r
- new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0"));\r
- return params;\r
- }\r
-\r
- private DeviceDetails getDeviceDetails() {\r
- DeviceDetails nf = new DeviceDetails();\r
- nf.setDeviceId("00005B9A1");\r
- nf.setDeviceTypeId(50);\r
- nf.setOui("0005B9");\r
- nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl");\r
- return nf;\r
- }\r
-}\r
+/*
+ * ============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<Object> res = new ResponseEntity<Object>(
+ 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<InformType> 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<InformType> list = new ArrayList<InformType>();
+ 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<ParameterDTO> getGeneralParams() {
+ ArrayList<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationResponse;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.mapper.util.NetconfToTr069MapperUtil;\r
-import org.junit.Assert;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-\r
-@SpringBootTest(classes = {MapperServiceBooter.class})\r
-@RunWith(SpringRunner.class)\r
-public class NetconfToTr069MapperUtilTest {\r
-\r
- @Autowired\r
- NetconfToTr069MapperUtil mapUtil;\r
-\r
- @Test\r
- public void getNetconfResponseTest() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("0");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- opr.setParameterDTOs(getGeneralParams());\r
- opResult.setOperationResponse(opr);\r
- NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false);\r
- Assert.assertNotNull(netConfRes);\r
- Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void getNetconfResponseErrorTest() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("9001");\r
- opResult.setFaultString("Request denied");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- opr.setParameterDTOs(getGeneralParams());\r
- opResult.setOperationResponse(opr);\r
- NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false);\r
- Assert.assertNotNull(netConfRes);\r
- Assert.assertEquals("9001", netConfRes.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Request denied", netConfRes.getErrorCode().getErrorMessage());\r
- }\r
-\r
- @Test\r
- public void getNetconfResponseWithoutParamtersTest() {\r
- DeviceRPCResponse opResult = new DeviceRPCResponse();\r
- opResult.setFaultKey("0");\r
- opResult.setDeviceDetails(new DeviceDetails());\r
- OperationResponse opr = new OperationResponse();\r
- opResult.setOperationResponse(opr);\r
- NetConfResponse netConfRes = mapUtil.getNetconfResponse(opResult, "4.3.0.0", "*", false);\r
- Assert.assertNotNull(netConfRes);\r
- Assert.assertEquals("0", netConfRes.getErrorCode().getFaultCode());\r
- Assert.assertEquals("Success", netConfRes.getErrorCode().getErrorMessage());\r
- Assert.assertNull(netConfRes.getNetconfResponseXml());\r
- }\r
-\r
- private ArrayList<ParameterDTO> getGeneralParams() {\r
- ArrayList<ParameterDTO> params = new ArrayList<>();\r
- params.add(new ParameterDTO("Device.DeviceInfo.ManufacturerOUI", "0005B9"));\r
- params.add(new ParameterDTO("Device.DeviceInfo.ProductClass", "LTE_Enterprise_C-RANSC_Cntrl"));\r
- params.add(new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.PLMNID",\r
- "30324"));\r
- params.add(new ParameterDTO(\r
- "Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.IsPrimary", "1"));\r
- params.add(\r
- new ParameterDTO("Device.Services.FAPService.1.CellConfig.LTE.EPC.PLMNList.1.Enable", "0"));\r
-\r
- return params;\r
- }\r
-}\r
+/*
+ * ============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<ParameterDTO> getGeneralParams() {
+ ArrayList<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.mapper;\r
-\r
-import static org.junit.Assert.assertNull;\r
-\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.ConfigurationData;\r
-import org.commscope.tr069adapter.acs.common.inform.BootInform;\r
-import org.commscope.tr069adapter.acs.common.inform.BootstrapInform;\r
-import org.commscope.tr069adapter.mapper.acs.impl.PnPPreProvisioningHandler;\r
-import org.commscope.tr069adapter.mapper.boot.MapperServiceBooter;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.Mockito;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.test.context.junit4.SpringRunner;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@SpringBootTest(classes = {MapperServiceBooter.class})\r
-@RunWith(SpringRunner.class)\r
-public class PnPPreProvisioningHandlerTest {\r
-\r
- @Autowired\r
- PnPPreProvisioningHandler pnPPreProvisioningHandler;\r
-\r
- @Mock\r
- RestTemplate restTemplate;\r
-\r
- @Test\r
- public void testGetEnodeBName() {\r
- ConfigurationData configData = new ConfigurationData();\r
- Map<String, String> paramMap = new HashMap<String, String>();\r
- paramMap.put("X_0005B9_eNBName", "Enodb1");\r
- configData.setParameterMONameValueMap(paramMap);\r
- Mockito.when(restTemplate.getForObject(Mockito.anyString(), Mockito.any()))\r
- .thenReturn(configData);\r
- String eNodeBName = pnPPreProvisioningHandler.getEnodeBName("00005B9A1", "4.3.0.0", "*");\r
- assertNull(eNodeBName);\r
- }\r
-\r
- @Test\r
- public void testOnDeviceBootStrapNotification() {\r
- BootstrapInform notification = new BootstrapInform();\r
- List<ParameterDTO> params = new ArrayList<ParameterDTO>();\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName("ExpeditedEvent");\r
- params.add(param);\r
- notification.setDeviceDetails(getDeviceDetails());\r
- notification.setParameters(params);\r
- pnPPreProvisioningHandler.onDeviceNotification(notification);\r
- assertNull(notification.getValueChangeNotification());\r
- }\r
-\r
- @Test\r
- public void testOnDeviceBootNotification() {\r
- BootInform notification = new BootInform();\r
- List<ParameterDTO> params = new ArrayList<ParameterDTO>();\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName("ExpeditedEvent");\r
- params.add(param);\r
- notification.setDeviceDetails(getDeviceDetails());\r
- notification.setParameters(params);\r
- pnPPreProvisioningHandler.onDeviceNotification(notification);\r
- assertNull(notification.getValueChangeNotification());\r
- }\r
-\r
- private DeviceDetails getDeviceDetails() {\r
- DeviceDetails nf = new DeviceDetails();\r
- nf.setDeviceId("00005B9A1");\r
- nf.setDeviceTypeId(50);\r
- nf.setOui("0005B9");\r
- nf.setProductClass("LTE_Enterprise_C-RANSC_Cntrl");\r
- return nf;\r
- }\r
-\r
-}\r
+/*
+ * ============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<String, String> paramMap = new HashMap<String, String>();
+ 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<ParameterDTO> params = new ArrayList<ParameterDTO>();
+ 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<ParameterDTO> params = new ArrayList<ParameterDTO>();
+ 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;
+ }
+
+}
<skipTests>false</skipTests>\r
</configuration>\r
</plugin>\r
+ <plugin>\r
+ <groupId>org.jacoco</groupId>\r
+ <artifactId>jacoco-maven-plugin</artifactId>\r
+ <executions>\r
+ <execution>\r
+ <goals>\r
+ <goal>prepare-agent</goal>\r
+ </goals>\r
+ </execution>\r
+ <!-- attached to Maven test phase -->\r
+ <execution>\r
+ <id>report</id>\r
+ <phase>test</phase>\r
+ <goals>\r
+ <goal>report</goal>\r
+ </goals>\r
+ </execution>\r
+ </executions>\r
+ </plugin>\r
<plugin>\r
<artifactId>maven-failsafe-plugin</artifactId>\r
</plugin>\r
--- /dev/null
+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;
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.boot;\r
-\r
-import java.util.Arrays;\r
-import javax.jms.ConnectionFactory;\r
-import org.apache.activemq.ActiveMQConnectionFactory;\r
-import org.apache.activemq.RedeliveryPolicy;\r
-import org.apache.activemq.broker.BrokerService;\r
-import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap;\r
-import org.apache.activemq.command.ActiveMQQueue;\r
-import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl;\r
-import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.boot.SpringApplication;\r
-import org.springframework.boot.autoconfigure.SpringBootApplication;\r
-import org.springframework.boot.autoconfigure.domain.EntityScan;\r
-import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;\r
-import org.springframework.context.ApplicationContext;\r
-import org.springframework.context.annotation.Bean;\r
-import org.springframework.context.annotation.ComponentScan;\r
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories;\r
-import org.springframework.jms.annotation.EnableJms;\r
-import org.springframework.jms.config.DefaultJmsListenerContainerFactory;\r
-import org.springframework.jms.config.JmsListenerContainerFactory;\r
-import org.springframework.jms.listener.MessageListenerContainer;\r
-import org.springframework.jms.support.converter.MappingJackson2MessageConverter;\r
-import org.springframework.jms.support.converter.MessageConverter;\r
-import org.springframework.jms.support.converter.MessageType;\r
-import org.springframework.retry.annotation.EnableRetry;\r
-\r
-@EnableJms\r
-@SpringBootApplication\r
-@ComponentScan({"org.commscope.tr069adapter.netconf", "org.opendaylight.netconf.test",\r
- "org.commscope.tr069adapter.common"})\r
-@EnableJpaRepositories("org.commscope.tr069adapter.netconf.dao")\r
-@EntityScan("org.commscope.tr069adapter.netconf.entity")\r
-@EnableRetry\r
-public class NetConfServiceBooter {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfServiceBooter.class);\r
-\r
- private static ApplicationContext appContext;\r
-\r
- public static void main(String[] args) {\r
- if (args != null)\r
- appContext = SpringApplication.run(NetConfServiceBooter.class, args);\r
- NetConfServerManagerImpl serverManager =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerManagerImpl.class);\r
- boolean isSchemaLoaded = serverManager.loadSchemas();\r
- if (!isSchemaLoaded) {\r
- LOG.error("Loading the schema failed while starting the container");\r
- System.exit(1);\r
- }\r
- serverManager.restartServers();\r
- }\r
-\r
- public static ApplicationContext getApplicationContext() {\r
- return appContext;\r
- }\r
-\r
- /*\r
- * JMS Configuration Defining the connection factories used in the application Setting the\r
- * Re-delivery configuration goes here\r
- */\r
- @Bean\r
- public BrokerService broker() throws Exception {\r
- final BrokerService broker = new BrokerService();\r
- broker.addConnector("tcp://localhost:61616");\r
- broker.addConnector("vm://localhost");\r
- broker.setPersistent(false);\r
- return broker;\r
- }\r
-\r
- @Bean\r
- public ConnectionFactory jmsConnectionFactory() {\r
- ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();\r
- connectionFactory\r
- .setTrustedPackages(Arrays.asList("org.commscope", "org.commscope.tr069adapter"));\r
- connectionFactory.setMaxThreadPoolSize(7);\r
-\r
- ActiveMQQueue notificationQueue = new ActiveMQQueue(NetConfServerConstants.NETCONF_NOTIFICATION_Q);\r
- RedeliveryPolicy notificationQueuePolicy = new RedeliveryPolicy();\r
- notificationQueuePolicy.setInitialRedeliveryDelay(2* 60 * 1000L);\r
- notificationQueuePolicy.setUseCollisionAvoidance(true);\r
- notificationQueuePolicy.setRedeliveryDelay(2* 60 * 1000L);\r
- notificationQueuePolicy.setUseExponentialBackOff(false);\r
- notificationQueuePolicy.setMaximumRedeliveries(3);\r
- notificationQueuePolicy.setDestination(notificationQueue);\r
-\r
- RedeliveryPolicyMap rdMap = connectionFactory.getRedeliveryPolicyMap();\r
- rdMap.put(notificationQueue, notificationQueuePolicy);\r
- return connectionFactory;\r
- }\r
-\r
- @Bean\r
- public JmsListenerContainerFactory<MessageListenerContainer> netConfNotificationCF(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- return handleJMSCommonConfiguration(connectionFactory, configurer);\r
- }\r
-\r
- public JmsListenerContainerFactory handleJMSCommonConfiguration(\r
- ConnectionFactory connectionFactory,\r
- DefaultJmsListenerContainerFactoryConfigurer configurer) {\r
- DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();\r
- configurer.configure(factory, connectionFactory);\r
- return factory;\r
- }\r
-\r
- @Bean\r
- public MessageConverter jacksonJmsMessageConverter() {\r
- MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();\r
- converter.setTargetType(MessageType.TEXT);\r
- converter.setTypeIdPropertyName("_type");\r
- return converter;\r
- }\r
-}\r
+/*
+ * ============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<MessageListenerContainer> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.entity;\r
-\r
-import java.io.Serializable;\r
-\r
-import javax.persistence.Column;\r
-import javax.persistence.Entity;\r
-import javax.persistence.GeneratedValue;\r
-import javax.persistence.GenerationType;\r
-import javax.persistence.Id;\r
-import javax.persistence.Table;\r
-\r
-@Entity\r
-@Table(name = "netconf_server_details")\r
-public class NetConfServerDetailsEntity implements Serializable {\r
-\r
- private static final long serialVersionUID = 3572178771247249366L;\r
-\r
- @Id\r
- @GeneratedValue(strategy = GenerationType.AUTO)\r
- private Long id;\r
-\r
- @Column(name = "DEVICE_ID", length = 30)\r
- private String deviceId;\r
-\r
- @Column(name = "ENODEB_NAME", length = 255)\r
- private String enodeBName;\r
-\r
- @Column(name = "PORT", length = 10)\r
- private String listenPort;\r
-\r
- @Column(name = "SW_VERSION", length = 64)\r
- private String swVersion;\r
-\r
- @Column(name = "HW_VERSION", length = 64)\r
- private String hwVersion;\r
-\r
- public Long getId() {\r
- return id;\r
- }\r
-\r
- public void setId(Long id) {\r
- this.id = id;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceId) {\r
- this.deviceId = deviceId;\r
- }\r
-\r
- public String getListenPort() {\r
- return listenPort;\r
- }\r
-\r
- public void setListenPort(String listenPort) {\r
- this.listenPort = listenPort;\r
- }\r
-\r
- public String getEnodeBName() {\r
- return enodeBName;\r
- }\r
-\r
- public void setEnodeBName(String enodeBName) {\r
- this.enodeBName = enodeBName;\r
- }\r
-\r
- public String getSwVersion() {\r
- return swVersion;\r
- }\r
-\r
- public void setSwVersion(String swVersion) {\r
- this.swVersion = swVersion;\r
- }\r
-\r
- public String getHwVersion() {\r
- return hwVersion;\r
- }\r
-\r
- public void setHwVersion(String hwVersion) {\r
- this.hwVersion = hwVersion;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.notification;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO;\r
-import org.commscope.tr069adapter.netconf.error.NetconfNotificationException;\r
-import org.commscope.tr069adapter.netconf.rpc.CreateSubscription;\r
-import org.opendaylight.netconf.api.NetconfMessage;\r
-import org.opendaylight.netconf.api.xml.XmlUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class NetConfSessionUtil {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfSessionUtil.class);\r
-\r
- public void sendNetConfNotification(NetConfNotificationDTO netConNotifDTO)\r
- throws NetconfNotificationException {\r
- NetconfMessage netconfMessage = convertToNetConfMessage(netConNotifDTO);\r
- CreateSubscription.sendNotification(netconfMessage, netConNotifDTO.getDeviceID());\r
- }\r
-\r
- private NetconfMessage convertToNetConfMessage(NetConfNotificationDTO netConNotifDTO)\r
- throws NetconfNotificationException {\r
- try {\r
- return new NetconfMessage(XmlUtil.readXmlToDocument(netConNotifDTO.getNotificaiton()));\r
- } catch (Exception e) {\r
- LOG.error("Error while converting to netcon notification ");\r
- throw new NetconfNotificationException("Cannot parse notifications", e);\r
- }\r
- }\r
-}\r
+/*
+ * ============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);
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.notification;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO;\r
-import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.jms.core.JmsTemplate;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class NotificationHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(NotificationHandler.class);\r
- private static final String CLIENT_STR = "client";\r
-\r
- @Autowired\r
- NetConfSessionUtil netConfSessionUtil;\r
-\r
- @Autowired\r
- private JmsTemplate jmsTemplate;\r
-\r
- public void handleNetConfNotification(NetConfNotificationDTO netConNotifDTO) {\r
- logger.debug("processing netconf notification {}", netConNotifDTO);\r
- try {\r
- MDC.put(CLIENT_STR, netConNotifDTO.getDeviceID());\r
-\r
- logger.debug("NetConf notificaiton reviced for {}", netConNotifDTO.getDeviceID());\r
- jmsTemplate.convertAndSend(NetConfServerConstants.NETCONF_NOTIFICATION_Q, netConNotifDTO);\r
- logger.debug("Successfully posted the notiticaiton to JMS to forward to SDNR");\r
- } catch (Exception e) {\r
- logger.error("Posting notification failed; Reason: {}", e.getMessage());\r
- } finally {\r
- MDC.remove(CLIENT_STR);\r
- }\r
- }\r
-}\r
+/*
+ * ============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);
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.operations;\r
-\r
-import com.google.common.collect.Sets;\r
-\r
-import java.util.Optional;\r
-import java.util.Set;\r
-\r
-import org.commscope.tr069adapter.netconf.rpc.CreateSubscription;\r
-import org.commscope.tr069adapter.netconf.rpc.DeleteConfigOperation;\r
-import org.commscope.tr069adapter.netconf.rpc.GetConfigOperation;\r
-import org.commscope.tr069adapter.netconf.rpc.GetOperation;\r
-import org.commscope.tr069adapter.netconf.rpc.OperationCommit;\r
-import org.commscope.tr069adapter.netconf.rpc.OperationLock;\r
-import org.commscope.tr069adapter.netconf.rpc.OperationUnLock;\r
-import org.commscope.tr069adapter.netconf.rpc.SetConfigOperation;\r
-import org.commscope.tr069adapter.netconf.rpc.SoftwareActivateOperation;\r
-import org.commscope.tr069adapter.netconf.rpc.SoftwareDownloadOperation;\r
-import org.opendaylight.netconf.api.capability.Capability;\r
-import org.opendaylight.netconf.impl.SessionIdProvider;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperation;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperationService;\r
-import org.opendaylight.netconf.test.tool.operations.OperationsCreator;\r
-import org.opendaylight.netconf.test.tool.rpc.DataList;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-public final class CustomOperationsCreator implements OperationsCreator {\r
- private static final Logger logger = LoggerFactory.getLogger(CustomOperationsCreator.class);\r
-\r
- private String macID = null;\r
-\r
- private String swVersion;\r
-\r
- private String hwVersion;\r
-\r
- private OperationService operationService;\r
-\r
- public CustomOperationsCreator(String macID, String swVersion, String hwVersion) {\r
- this.macID = macID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public NetconfOperationService getNetconfOperationService(final Set<Capability> caps,\r
- final SessionIdProvider idProvider, final String netconfSessionIdForReporting) {\r
- if (null == operationService) {\r
- operationService =\r
- new OperationService(idProvider.getCurrentSessionId(), macID, swVersion, hwVersion);\r
- }\r
- return operationService;\r
- }\r
-\r
- static class OperationService implements NetconfOperationService {\r
-\r
- private final long currentSessionId;\r
- private String macID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- OperationService(final long currentSessionId, String macID, String swVersion,\r
- String hwVersion) {\r
- this.currentSessionId = currentSessionId;\r
- this.macID = macID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public Set<NetconfOperation> getNetconfOperations() {\r
- final DataList storage = new DataList();\r
- final GetOperation oGet =\r
- new GetOperation(String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion);\r
- final GetConfigOperation oGetConfig = new GetConfigOperation(String.valueOf(currentSessionId),\r
- Optional.empty(), macID, swVersion, hwVersion);\r
- final SetConfigOperation oSetConfig =\r
- new SetConfigOperation(String.valueOf(currentSessionId), macID, swVersion, hwVersion);\r
- final DeleteConfigOperation oDelConfig = new DeleteConfigOperation(\r
- String.valueOf(currentSessionId), storage, macID, swVersion, hwVersion);\r
- final OperationCommit oCommit = new OperationCommit(String.valueOf(currentSessionId));\r
- final OperationLock oLock = new OperationLock(String.valueOf(currentSessionId));\r
- final OperationUnLock oUnlock = new OperationUnLock(String.valueOf(currentSessionId));\r
- final CreateSubscription sCreateSubs = new CreateSubscription(\r
- String.valueOf(currentSessionId), Optional.empty(), macID, swVersion, hwVersion);\r
- SoftwareDownloadOperation swDownloadOperation =\r
- new SoftwareDownloadOperation(macID, swVersion, hwVersion);\r
- SoftwareActivateOperation swActivateOperation =\r
- new SoftwareActivateOperation(macID, swVersion, hwVersion);\r
- return Sets.newHashSet(oGet, oGetConfig, oSetConfig, oDelConfig, oCommit, oLock, oUnlock,\r
- sCreateSubs, swDownloadOperation, swActivateOperation);\r
- }\r
-\r
- @Override\r
- public void close() {\r
- logger.debug("close called on CustomOperationsCreator");\r
- }\r
-\r
- }\r
-}\r
+/*
+ * ============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<Capability> 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<NetconfOperation> 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");
+ }
+
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.restapi;\r
-\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.web.bind.annotation.GetMapping;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestMapping;\r
-import org.springframework.web.bind.annotation.RequestParam;\r
-import org.springframework.web.bind.annotation.RestController;\r
-\r
-@RestController\r
-@RequestMapping("/netConfServerManagerService")\r
-public class NetConfServerManagerRestApi {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerRestApi.class);\r
-\r
- @Autowired\r
- NetConfServerManagerImpl manager;\r
-\r
- @PostMapping("/createServer")\r
- public NetConfServerDetails createNetConfServerInstance(@RequestParam String deviceId,\r
- @RequestParam String enodeBName, @RequestParam String swVersion,\r
- @RequestParam String hwVersion) {\r
- LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}, swversion: {}", deviceId,\r
- enodeBName, swVersion);\r
- NetConfServerDetails serverDetails =\r
- manager.createServer(deviceId, enodeBName, swVersion, hwVersion);\r
- LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails);\r
- return serverDetails;\r
- }\r
-\r
- @PostMapping("/restartOnVersionChange")\r
- public NetConfServerDetails restartOnVersionChange(@RequestParam String deviceId,\r
- @RequestParam String enodeBName, @RequestParam String swVersion,\r
- @RequestParam String hwVersion) {\r
- LOG.info("Received Create NetConf Server request for deviceID: {}, enodeBName: {}", deviceId,\r
- enodeBName);\r
- NetConfServerDetails serverDetails =\r
- manager.restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion);\r
- LOG.info("Successfully processed NetConf Server wit server details : {}", serverDetails);\r
- return serverDetails;\r
- }\r
- \r
- @GetMapping("/listServers")\r
- public List<NetConfServerDetails> listNetConfServersInfo() {\r
- LOG.info("Received request to list all NetConf Servers information");\r
- List<NetConfServerDetails> serverDetails = manager.getServersInfo();\r
- LOG.info("Successfully processed request to list all NetConf Servers information");\r
- return serverDetails;\r
- }\r
-\r
- @PostMapping("/unregisterServer")\r
- public String unregisterNetConfServerInstance(@RequestParam String deviceId,\r
- @RequestParam String enodeBName) {\r
- LOG.info("Received request for Unregister NetConf Server for deviceID: {}, enodeBName: {} ",\r
- deviceId, enodeBName);\r
- String result = manager.unregister(deviceId, enodeBName);\r
- LOG.info("Unregister request is processed. NetConf Server for deviceID: {} , unregisted= {}",\r
- deviceId, result);\r
- return result;\r
- }\r
-\r
-}\r
+/*
+ * ============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<NetConfServerDetails> listNetConfServersInfo() {
+ LOG.info("Received request to list all NetConf Servers information");
+ List<NetConfServerDetails> 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;
+ }
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.netconf.restapi;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfNotificationDTO;\r
-import org.commscope.tr069adapter.netconf.notification.NotificationHandler;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.web.bind.annotation.PostMapping;\r
-import org.springframework.web.bind.annotation.RequestBody;\r
-import org.springframework.web.bind.annotation.RequestMapping;\r
-import org.springframework.web.bind.annotation.RestController;\r
-\r
-@RestController\r
-@RequestMapping("/netConfNotificationService")\r
-public class NotificationReceiverService {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NotificationReceiverService.class);\r
-\r
- @Autowired\r
- NotificationHandler handler;\r
-\r
- @PostMapping("/notification")\r
- public void processNotification(@RequestBody NetConfNotificationDTO netConNotifDTO) {\r
- System.out.println("Received NetConf Notification :" + netConNotifDTO);\r
- LOG.debug("Received NetConf Notification :" + netConNotifDTO);\r
- handler.handleNetConfNotification(netConNotifDTO);\r
- LOG.debug("Processed NetConf Notification for :" + netConNotifDTO);\r
- System.out.println("Processed NetConf Notification for :" + netConNotifDTO);\r
- }\r
-}\r
+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);
+ }
+}
--- /dev/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.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;
+ }
+
+}
--- /dev/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.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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.text.SimpleDateFormat;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Optional;\r
-import java.util.concurrent.Executors;\r
-import java.util.concurrent.ScheduledExecutorService;\r
-import java.util.concurrent.TimeUnit;\r
-import javax.xml.bind.JAXBContext;\r
-import javax.xml.bind.JAXBException;\r
-import javax.xml.bind.Unmarshaller;\r
-import javax.xml.bind.annotation.XmlRootElement;\r
-import org.commscope.tr069adapter.netconf.error.NetconfNotificationException;\r
-import org.opendaylight.netconf.api.NetconfMessage;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.api.xml.XmlUtil;\r
-import org.opendaylight.netconf.impl.NetconfServerSession;\r
-import org.opendaylight.netconf.impl.mapping.operations.DefaultNetconfOperation;\r
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.xml.sax.SAXException;\r
-import com.google.common.base.Preconditions;\r
-import com.google.common.collect.Maps;\r
-\r
-public class CreateSubscription extends AbstractLastNetconfOperation\r
- implements DefaultNetconfOperation {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(CreateSubscription.class);\r
- private final Map<Notification, NetconfMessage> notifications;\r
- private NetconfServerSession session;\r
- private ScheduledExecutorService scheduledExecutorService;\r
- private static Map<String, NetconfServerSession> netconfServerSessionMap = new HashMap<>();\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public CreateSubscription(final String id, final Optional<File> notificationsFile,\r
- String deviceID, String swVersion, String hwVersion) {\r
-\r
- super(id);\r
-\r
- logger.debug("CreateSubscription RPC is created with macID {}", deviceID);\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
-\r
- final Optional<Notifications> notifs;\r
-\r
- if (notificationsFile.isPresent()) {\r
- notifs = Optional.of(loadNotifications(notificationsFile.get()));\r
- scheduledExecutorService = Executors.newScheduledThreadPool(1);\r
- } else {\r
- notifs = Optional.empty();\r
- }\r
-\r
- if (notifs.isPresent()) {\r
- final Collection<Notification> toCopy = notifs.get().getNotificationList();\r
- final Map<Notification, NetconfMessage> preparedMessages =\r
- Maps.newHashMapWithExpectedSize(toCopy.size());\r
- for (final Notification notification : toCopy) {\r
- final NetconfMessage parsedNotification =\r
- parseNetconfNotification(notification.getContent());\r
- preparedMessages.put(notification, parsedNotification);\r
- }\r
- this.notifications = preparedMessages;\r
- } else {\r
- this.notifications = Collections.emptyMap();\r
- }\r
- }\r
-\r
- private static Notifications loadNotifications(final File file) {\r
- try {\r
- final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class);\r
- final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();\r
- return (Notifications) jaxbUnmarshaller.unmarshal(file);\r
- } catch (final JAXBException e) {\r
- throw new IllegalArgumentException("can not parse file " + file + " as a notifications file",\r
- e);\r
- }\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return "create-subscription";\r
- }\r
-\r
- @Override\r
- protected String getOperationNamespace() {\r
- return "urn:ietf:params:xml:ns:netconf:notification:1.0";\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(final Document document,\r
- final XmlElement operationElement) {\r
- long delayAggregator = 0;\r
- for (final Map.Entry<Notification, NetconfMessage> notification : notifications.entrySet()) {\r
- for (int i = 0; i <= notification.getKey().getTimes(); i++) {\r
-\r
- delayAggregator += notification.getKey().getDelayInSeconds();\r
-\r
- scheduledExecutorService.schedule(() -> {\r
- Preconditions.checkState(session != null,\r
- "Session is not set, cannot process notifications");\r
- session.sendMessage(notification.getValue());\r
- }, delayAggregator, TimeUnit.SECONDS);\r
- }\r
- }\r
- return document.createElement(XmlNetconfConstants.OK);\r
- }\r
-\r
- private static NetconfMessage parseNetconfNotification(String content) {\r
- final int startEventTime = content.indexOf("<eventTime>") + "<eventTime>".length();\r
- final int endEventTime = content.indexOf("</eventTime>");\r
- final String eventTime = content.substring(startEventTime, endEventTime);\r
- if (eventTime.equals("XXXX")) {\r
- content = content.replace(eventTime,\r
- new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date()));\r
- }\r
-\r
- try {\r
- return new NetconfMessage(XmlUtil.readXmlToDocument(content));\r
- } catch (SAXException | IOException e) {\r
- throw new IllegalArgumentException("Cannot parse notifications", e);\r
- }\r
- }\r
-\r
- @Override\r
- public void setNetconfSession(final NetconfServerSession newSession) {\r
- logger.debug("Adding netconf session to notification server sessions map : {}", newSession);\r
- logger.debug("This CreateSubscription is setup to support macID= {}", deviceID);\r
- this.session = newSession;\r
- netconfServerSessionMap.put(deviceID, newSession);\r
- }\r
-\r
- public static void sendNotification(NetconfMessage netconfMessage, String deviceID)\r
- throws NetconfNotificationException {\r
- logger.debug("Request to send notification. NetConfMessage : {}", netconfMessage);\r
- NetconfServerSession session = netconfServerSessionMap.get(deviceID);\r
- if (session != null && session.isUp()) {\r
- try {\r
- session.sendMessage(netconfMessage);\r
- logger.debug("Successfully send notification for deviceID: {}", deviceID);\r
- } catch (Exception e) {\r
- logger.error("Failed to send notification. while posting got error. {}", e.toString());\r
- throw new NetconfNotificationException("Exception while posting the netconf message", e);\r
- }\r
-\r
- } else {\r
- logger.debug(\r
- "Failed to send notification. None of valid netconf session is available for {}.",\r
- deviceID);\r
- logger.debug("Available netconf sessions : {}", netconfServerSessionMap);\r
- throw new NetconfNotificationException("NetConf active session deosn't not exist");\r
- }\r
- }\r
-\r
- @XmlRootElement(name = "notifications")\r
- public static final class Notifications {\r
-\r
- @javax.xml.bind.annotation.XmlElement(nillable = false, name = "notification", required = true)\r
- private List<Notification> notificationList;\r
-\r
- public List<Notification> getNotificationList() {\r
- return notificationList;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- final StringBuilder sb = new StringBuilder("Notifications{");\r
- sb.append("notificationList=").append(notificationList);\r
- sb.append('}');\r
- return sb.toString();\r
- }\r
- }\r
-\r
- public static final class Notification {\r
-\r
- @javax.xml.bind.annotation.XmlElement(nillable = false, name = "delay")\r
- private long delayInSeconds;\r
-\r
- @javax.xml.bind.annotation.XmlElement(nillable = false, name = "times")\r
- private long times;\r
-\r
- @javax.xml.bind.annotation.XmlElement(nillable = false, name = "content", required = true)\r
- private String content;\r
-\r
- public long getDelayInSeconds() {\r
- return delayInSeconds;\r
- }\r
-\r
- public long getTimes() {\r
- return times;\r
- }\r
-\r
- public String getContent() {\r
- return content;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- final StringBuilder sb = new StringBuilder("Notification{");\r
- sb.append("delayInSeconds=").append(delayInSeconds);\r
- sb.append(", times=").append(times);\r
- sb.append(", content='").append(content).append('\'');\r
- sb.append('}');\r
- return sb.toString();\r
- }\r
- }\r
-}\r
+/*
+ * ============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<Notification, NetconfMessage> notifications;
+ private NetconfServerSession session;
+ private ScheduledExecutorService scheduledExecutorService;
+ private static Map<String, NetconfServerSession> netconfServerSessionMap = new HashMap<>();
+ private String deviceID;
+ private String swVersion;
+ private String hwVersion;
+
+ public CreateSubscription(final String id, final Optional<File> 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<Notifications> notifs;
+
+ if (notificationsFile.isPresent()) {
+ notifs = Optional.of(loadNotifications(notificationsFile.get()));
+ scheduledExecutorService = Executors.newScheduledThreadPool(1);
+ } else {
+ notifs = Optional.empty();
+ }
+
+ if (notifs.isPresent()) {
+ final Collection<Notification> toCopy = notifs.get().getNotificationList();
+ final Map<Notification, NetconfMessage> 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, NetconfMessage> 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("<eventTime>") + "<eventTime>".length();
+ final int endEventTime = content.indexOf("</eventTime>");
+ 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<Notification> notificationList;
+
+ public List<Notification> 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();
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorTag;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorType;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.test.tool.rpc.DataList;\r
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Attr;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-\r
-public class DeleteConfigOperation extends AbstractLastNetconfOperation {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(DeleteConfigOperation.class);\r
-\r
- private static final String DELETE_EDIT_CONFIG = "delete";\r
- private static final String OPERATION = "operation";\r
- private static final String REMOVE_EDIT_CONFIG = "remove";\r
- private final DataList storage;\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public DeleteConfigOperation(final String netconfSessionIdForReporting, final DataList storage,\r
- String deviceID, String swVersion, String hwVersion) {\r
- super(netconfSessionIdForReporting);\r
- this.storage = storage;\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(final Document document,\r
- final XmlElement operationElement) throws DocumentedException {\r
- final XmlElement configElementData =\r
- operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);\r
- containsDelete(configElementData);\r
- if (containsDelete(configElementData)) {\r
- storage.resetConfigList();\r
- } else {\r
- storage.setConfigList(configElementData.getChildElements());\r
- }\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(operationElement);\r
- logger.debug("netconf request recevied : {}", requestXml);\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/delConfig";\r
- NetConfResponse restResponse =\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
-\r
- if (restResponse != null) {\r
- ErrorCodeDetails errorCode = restResponse.getErrorCode();\r
-\r
- if (errorCode != null && errorCode.getFaultCode() != null\r
- && !errorCode.getFaultCode().equalsIgnoreCase("0")) {\r
- throw new DocumentedException(errorCode.getErrorMessage(),\r
- ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),\r
- ErrorSeverity.from(errorCode.getErrorSeverity()));\r
- } else {\r
- return document.createElement(XmlNetconfConstants.OK);\r
- }\r
- } else {\r
- logger.error("received the null response from mapper ");\r
- throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"),\r
- ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));\r
- }\r
-\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return "delete-config";\r
- }\r
-\r
- private boolean containsDelete(final XmlElement element) {\r
- for (final Attr o : element.getAttributes().values()) {\r
- if (o.getLocalName().equals(OPERATION)\r
- && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) {\r
- return true;\r
- }\r
- }\r
- for (final XmlElement xmlElement : element.getChildElements()) {\r
- if (containsDelete(xmlElement)) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
--- /dev/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.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;
+ }
+
+}
--- /dev/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.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;
+ }
+
+}
--- /dev/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.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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.util.Optional;\r
-\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorTag;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorType;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.api.xml.XmlUtil;\r
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.xml.sax.SAXException;\r
-\r
-public class GetConfigOperation extends AbstractLastNetconfOperation {\r
- private static final Logger logger = LoggerFactory.getLogger(GetConfigOperation.class);\r
-\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public GetConfigOperation(final String netconfSessionIdForReporting,\r
- final Optional<File> initialConfigXMLFile, String deviceID, String swVersion,\r
- String hwVersion) {\r
- super(netconfSessionIdForReporting);\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- if (initialConfigXMLFile.isPresent()) {\r
- logger.info("File is present: {}", initialConfigXMLFile.get().getName());\r
- }\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(final Document document,\r
- final XmlElement operationElement) throws DocumentedException {\r
- final Element element = document.createElement(XmlNetconfConstants.DATA_KEY);\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(operationElement);\r
- logger.debug("netconf request recevied : {}", requestXml);\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/getConfig";\r
- NetConfResponse restResponse =\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
-\r
- if (restResponse != null) {\r
- ErrorCodeDetails errorCode = restResponse.getErrorCode();\r
- if (errorCode != null && errorCode.getFaultCode() != null\r
- && !errorCode.getFaultCode().equalsIgnoreCase("0")) {\r
- logger.error("Error received : {} ", errorCode);\r
- throw new DocumentedException(errorCode.getErrorMessage(),\r
- ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),\r
- ErrorSeverity.from(errorCode.getErrorSeverity()));\r
- } else if (restResponse.getNetconfResponseXml() != null) {\r
- Element element1 = null;\r
- try {\r
- logger.debug("Response received from mapper :{}", restResponse.getNetconfResponseXml());\r
- element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml());\r
- XmlElement xmlElement = XmlElement.fromDomElement(element1);\r
- Element domElement = xmlElement.getDomElement();\r
- element.appendChild(element.getOwnerDocument().importNode(domElement, true));\r
- } catch (SAXException | IOException e1) {\r
- logger.error("Error while constructing the reponse {}", e1.toString());\r
- }\r
- }\r
- } else {\r
- logger.error("received the null response from mapper ");\r
- throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"),\r
- ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));\r
- }\r
-\r
- return element;\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return XmlNetconfConstants.GET_CONFIG;\r
- }\r
-}\r
+/*
+ * ============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<File> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import java.io.IOException;\r
-\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorTag;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorType;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.api.xml.XmlUtil;\r
-import org.opendaylight.netconf.test.tool.rpc.DataList;\r
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.xml.sax.SAXException;\r
-\r
-public class GetOperation extends AbstractLastNetconfOperation {\r
- private static final Logger logger = LoggerFactory.getLogger(GetOperation.class);\r
-\r
- private final DataList storage;\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public GetOperation(final String netconfSessionIdForReporting, final DataList storage,\r
- String deviceID, String swVersion, String hwVersion) {\r
- super(netconfSessionIdForReporting);\r
- this.deviceID = deviceID;\r
- this.storage = storage;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(final Document document,\r
- final XmlElement operationElement) throws DocumentedException {\r
- final Element element = document.createElement(XmlNetconfConstants.DATA_KEY);\r
-\r
- for (final XmlElement e : storage.getConfigList()) {\r
- final Element domElement = e.getDomElement();\r
- element.appendChild(element.getOwnerDocument().importNode(domElement, true));\r
- }\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(operationElement);\r
- logger.debug("netconf request recevied : {}", requestXml);\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/get";\r
- NetConfResponse restResponse =\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
-\r
- if (restResponse != null) {\r
- ErrorCodeDetails errorCode = restResponse.getErrorCode();\r
- if (errorCode != null && errorCode.getFaultCode() != null\r
- && !errorCode.getFaultCode().equalsIgnoreCase("0")) {\r
- throw new DocumentedException(errorCode.getErrorMessage(),\r
- ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),\r
- ErrorSeverity.from(errorCode.getErrorSeverity()));\r
- } else if (restResponse.getNetconfResponseXml() != null) {\r
- Element element1 = null;\r
- try {\r
- element1 = XmlUtil.readXmlToElement(restResponse.getNetconfResponseXml());\r
- XmlElement xmlElement = XmlElement.fromDomElement(element1);\r
- Element domElement = xmlElement.getDomElement();\r
- element.appendChild(element.getOwnerDocument().importNode(domElement, true));\r
- } catch (SAXException | IOException e1) {\r
- logger.error("Error while constructing the reponse {}", e1.toString());\r
- }\r
- }\r
- } else {\r
- logger.error("received the null response from mapper ");\r
- throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"),\r
- ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));\r
- }\r
- return element;\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return XmlNetconfConstants.GET;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
--- /dev/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.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;
+ }
+
+}
--- /dev/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.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;
+ }
+
+}
--- /dev/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.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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorTag;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorType;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.util.mapping.AbstractLastNetconfOperation;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Attr;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-\r
-public class SetConfigOperation extends AbstractLastNetconfOperation {\r
- private static final Logger logger = LoggerFactory.getLogger(SetConfigOperation.class);\r
-\r
- private static final String DELETE_EDIT_CONFIG = "delete";\r
- private static final String OPERATION = "operation";\r
- private static final String REMOVE_EDIT_CONFIG = "remove";\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public SetConfigOperation(final String netconfSessionIdForReporting, String deviceID,\r
- String swVersion, String hwVersion) {\r
- super(netconfSessionIdForReporting);\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- protected Element handleWithNoSubsequentOperations(final Document document,\r
- final XmlElement operationElement) throws DocumentedException {\r
- final XmlElement configElementData =\r
- operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);\r
- String delOrEditUrl = "setConfig";\r
- if (containsDelete(configElementData)) {\r
- delOrEditUrl = "delConfig";\r
- }\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(operationElement);\r
- logger.debug("netconf request recevied : {}", requestXml);\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/" + delOrEditUrl;\r
- NetConfResponse restResponse =\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
-\r
- if (restResponse != null) {\r
- ErrorCodeDetails errorCode = restResponse.getErrorCode();\r
- if (errorCode != null) {\r
- if (errorCode.getFaultCode() != null && errorCode.getFaultCode().equalsIgnoreCase("0")) {\r
- return document.createElement(XmlNetconfConstants.OK);\r
- } else {\r
- logger.error("Error received : {}", errorCode);\r
- throw new DocumentedException(errorCode.getErrorMessage(),\r
- ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),\r
- ErrorSeverity.from(errorCode.getErrorSeverity()));\r
- }\r
- } else {\r
- return document.createElement(XmlNetconfConstants.OK);\r
- }\r
- } else {\r
- logger.error("received the null response from mapper ");\r
- throw new DocumentedException("Unable to perform Operation", ErrorType.from("application"),\r
- ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));\r
- }\r
-\r
- }\r
-\r
- @Override\r
- protected String getOperationName() {\r
- return "edit-config";\r
- }\r
-\r
- private boolean containsDelete(final XmlElement element) {\r
- for (final Attr o : element.getAttributes().values()) {\r
- if (o.getLocalName().equals(OPERATION)\r
- && (o.getValue().equals(DELETE_EDIT_CONFIG) || o.getValue().equals(REMOVE_EDIT_CONFIG))) {\r
- return true;\r
- }\r
-\r
- }\r
-\r
- for (final XmlElement xmlElement : element.getChildElements()) {\r
- if (containsDelete(xmlElement)) {\r
- return true;\r
- }\r
-\r
- }\r
-\r
- return false;\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.mapping.api.HandlingPriority;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperation;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-\r
-public class SoftwareActivateOperation implements NetconfOperation {\r
- private static final Logger logger = LoggerFactory.getLogger(SoftwareActivateOperation.class);\r
- public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0";\r
-\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public SoftwareActivateOperation(String deviceID, String swVersion, String hwVersion) {\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public HandlingPriority canHandle(final Document message) throws DocumentedException {\r
- OperationNameAndNamespace operationNameAndNamespace = null;\r
- operationNameAndNamespace = new OperationNameAndNamespace(message);\r
- return canHandle(operationNameAndNamespace.getOperationName(),\r
- operationNameAndNamespace.getNamespace());\r
- }\r
-\r
- @Override\r
- public Document handle(Document requestMessage,\r
- NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {\r
-\r
- logger.debug("sw-activate rpc recevied in netconf server");\r
- final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage);\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(requestElement);\r
- logger.debug("sw-activate rpc recevied requestXml = {}", requestXml);\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/softwareActivate";\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
- return null;\r
- }\r
-\r
- protected HandlingPriority canHandle(final String operationName,\r
- final String operationNamespace) {\r
- return operationName.equals("software-activate")\r
- && operationNamespace.equals(SOFT_MGMT_NAMESPACE)\r
- ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100)\r
- : HandlingPriority.CANNOT_HANDLE;\r
- }\r
-\r
- public static final class OperationNameAndNamespace {\r
- private final String operationName;\r
- private final String namespace;\r
-\r
- private final XmlElement operationElement;\r
-\r
- public OperationNameAndNamespace(final Document message) throws DocumentedException {\r
- XmlElement requestElement = null;\r
- requestElement = getRequestElementWithCheck(message);\r
- operationElement = requestElement.getOnlyChildElement();\r
- operationName = operationElement.getName();\r
- namespace = operationElement.getNamespace();\r
- }\r
-\r
- public String getOperationName() {\r
- return operationName;\r
- }\r
-\r
- public String getNamespace() {\r
- return namespace;\r
- }\r
-\r
- public XmlElement getOperationElement() {\r
- return operationElement;\r
- }\r
- }\r
-\r
- protected static XmlElement getRequestElementWithCheck(final Document message)\r
- throws DocumentedException {\r
- return XmlElement.fromDomElementWithExpected(message.getDocumentElement(),\r
- XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);\r
- }\r
-}\r
+/*
+ * ============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);
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import java.io.StringReader;\r
-\r
-import javax.xml.parsers.DocumentBuilder;\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-\r
-import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.opendaylight.netconf.api.DocumentedException;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorTag;\r
-import org.opendaylight.netconf.api.DocumentedException.ErrorType;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;\r
-import org.opendaylight.netconf.mapping.api.HandlingPriority;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperation;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.w3c.dom.Document;\r
-import org.xml.sax.InputSource;\r
-\r
-public class SoftwareDownloadOperation implements NetconfOperation {\r
- private static final Logger logger = LoggerFactory.getLogger(SoftwareDownloadOperation.class);\r
- public static final String SOFT_MGMT_NAMESPACE = "urn:o-ran:software-management:1.0";\r
-\r
- private String deviceID;\r
- private String swVersion;\r
- private String hwVersion;\r
-\r
- public SoftwareDownloadOperation(String deviceID, String swVersion, String hwVersion) {\r
- this.deviceID = deviceID;\r
- this.swVersion = swVersion;\r
- this.hwVersion = hwVersion;\r
- }\r
-\r
- @Override\r
- public HandlingPriority canHandle(final Document message) throws DocumentedException {\r
- OperationNameAndNamespace operationNameAndNamespace = null;\r
- operationNameAndNamespace = new OperationNameAndNamespace(message);\r
- return canHandle(operationNameAndNamespace.getOperationName(),\r
- operationNameAndNamespace.getNamespace());\r
- }\r
-\r
- @Override\r
- public Document handle(Document requestMessage,\r
- NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {\r
-\r
- logger.debug("soft-ware download rpc is received in netconfserver");\r
-\r
- final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage);\r
- final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID);\r
-\r
- String requestXml = XmlUtility.convertDocumentToString(requestElement);\r
- logger.debug("soft-ware download rpc requestXml=" + requestXml);\r
-\r
- NetConfServerProperties config =\r
- NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);\r
-\r
- final String baseUrl = config.getMapperPath() + "/softwareDowload";\r
- NetConfResponse restResponse =\r
- XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);\r
-\r
- Document document = null;\r
-\r
- ErrorCodeDetails errorCode = restResponse.getErrorCode();\r
- if (errorCode != null && errorCode.getFaultCode() != null\r
- && !errorCode.getFaultCode().equalsIgnoreCase("0")) {\r
- logger.error("Error recevied : " + errorCode);\r
- throw new DocumentedException(errorCode.getErrorMessage(),\r
- ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),\r
- ErrorSeverity.from(errorCode.getErrorSeverity()));\r
- } else if (restResponse != null && restResponse.getNetconfResponseXml() != null) {\r
- logger.debug("soft-ware download rpc response received from mapper "\r
- + restResponse.getNetconfResponseXml());\r
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
- DocumentBuilder builder;\r
- try {\r
- builder = factory.newDocumentBuilder();\r
- document =\r
- builder.parse(new InputSource(new StringReader(restResponse.getNetconfResponseXml())));\r
- document.getDocumentElement().setAttribute("xmlns:ns1", getOperationNamespace());\r
- document.getDocumentElement().setAttribute("xmlns",\r
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);\r
- document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId);\r
- } catch (Exception e) {\r
- logger.error("while contruscting the response; ", e.toString());\r
- }\r
- }\r
-\r
- return document;\r
- }\r
-\r
- protected HandlingPriority canHandle(final String operationName,\r
- final String operationNamespace) {\r
- return operationName.equals("software-download")\r
- && operationNamespace.equals(SOFT_MGMT_NAMESPACE)\r
- ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100)\r
- : HandlingPriority.CANNOT_HANDLE;\r
- }\r
-\r
- public static final class OperationNameAndNamespace {\r
- private final String operationName;\r
- private final String namespace;\r
-\r
- private final XmlElement operationElement;\r
-\r
- public OperationNameAndNamespace(final Document message) throws DocumentedException {\r
- XmlElement requestElement = null;\r
- requestElement = getRequestElementWithCheck(message);\r
- operationElement = requestElement.getOnlyChildElement();\r
- operationName = operationElement.getName();\r
- namespace = operationElement.getNamespace();\r
- }\r
-\r
- public String getOperationName() {\r
- return operationName;\r
- }\r
-\r
- public String getNamespace() {\r
- return namespace;\r
- }\r
-\r
- public XmlElement getOperationElement() {\r
- return operationElement;\r
- }\r
-\r
- }\r
-\r
- protected static XmlElement getRequestElementWithCheck(final Document message)\r
- throws DocumentedException {\r
- return XmlElement.fromDomElementWithExpected(message.getDocumentElement(),\r
- XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);\r
- }\r
-\r
- protected String getOperationNamespace() {\r
- return "urn:o-ran:software-management:1.0";\r
- }\r
-\r
- protected String getOperationName() {\r
- return "software-download";\r
- }\r
-}\r
+/*
+ * ============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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import java.io.StringReader;\r
-import java.io.StringWriter;\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-\r
-import javax.xml.XMLConstants;\r
-import javax.xml.parsers.DocumentBuilder;\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-import javax.xml.transform.Transformer;\r
-import javax.xml.transform.TransformerFactory;\r
-import javax.xml.transform.dom.DOMSource;\r
-import javax.xml.transform.stream.StreamResult;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetConfRequest;\r
-import org.commscope.tr069adapter.mapper.model.NetConfResponse;\r
-import org.opendaylight.netconf.api.xml.XmlElement;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.http.HttpEntity;\r
-import org.springframework.http.HttpHeaders;\r
-import org.springframework.web.client.RestTemplate;\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.xml.sax.InputSource;\r
-\r
-public class XmlUtility {\r
- private static final Logger logger = LoggerFactory.getLogger(XmlUtility.class);\r
-\r
- private XmlUtility() {}\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class);\r
-\r
- public static String convertDocumentToString(XmlElement element) {\r
- return convertDocumentToString(element.getDomElement());\r
- }\r
-\r
- public static String convertDocumentToString(Element element) {\r
- String strxml = null;\r
- try {\r
- TransformerFactory transformerFactory = TransformerFactory.newInstance();\r
- transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");\r
- transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");\r
- Transformer transformer = transformerFactory.newTransformer();\r
- DOMSource source = new DOMSource(element);\r
- StreamResult result = new StreamResult(new StringWriter());\r
- transformer.transform(source, result);\r
- strxml = result.getWriter().toString();\r
- } catch (Exception e) {\r
- LOG.error("Error while converting Element to String {}", e.toString());\r
- }\r
-\r
- return strxml;\r
-\r
- }\r
-\r
- public static Element convertStringToDocument(String xmlStr) {\r
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");\r
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");\r
- DocumentBuilder builder;\r
- try {\r
- builder = factory.newDocumentBuilder();\r
- Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));\r
- return doc.getDocumentElement();\r
- } catch (Exception e) {\r
- LOG.error("Error while converting String to element {}", e.toString());\r
- }\r
- return null;\r
- }\r
-\r
- public static NetConfResponse invokeMapperCall(String requestUrl, String requestXml,\r
- String deviceID, String swVersion, String hwVersion) {\r
- URI uri = null;\r
- try {\r
- uri = new URI(requestUrl);\r
- } catch (URISyntaxException e) {\r
- logger.error("invalid URI {}", e.toString());\r
- }\r
-\r
- RestTemplate restTemplate = new RestTemplate();\r
- HttpHeaders headers = new HttpHeaders();\r
- NetConfRequest req = new NetConfRequest(requestXml, deviceID, swVersion, hwVersion);\r
-\r
- HttpEntity<NetConfRequest> entity = new HttpEntity<>(req, headers);\r
- NetConfResponse restResponse = null;\r
- if (uri != null) {\r
- restResponse = restTemplate.postForObject(uri, entity, NetConfResponse.class);\r
- }\r
-\r
- return restResponse;\r
- }\r
-}\r
+/*
+ * ============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<NetConfRequest> entity = new HttpEntity<>(req, headers);
+ NetConfResponse restResponse = null;
+ if (uri != null) {
+ restResponse = restTemplate.postForObject(uri, entity, NetConfResponse.class);
+ }
+
+ return restResponse;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.server;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Map.Entry;\r
-import java.util.concurrent.ExecutorService;\r
-import java.util.concurrent.Executors;\r
-import org.apache.commons.io.FileUtils;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationCode;\r
-import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager;\r
-import org.commscope.tr069adapter.common.deviceversion.ProfileDefinition;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository;\r
-import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity;\r
-import org.commscope.tr069adapter.netconf.error.RetryFailedException;\r
-import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException;\r
-import org.commscope.tr069adapter.netconf.server.helper.ServerPortAllocationHelper;\r
-import org.commscope.tr069adapter.netconf.server.utils.NetConfServerConstants;\r
-import org.commscope.tr069adapter.netconf.server.ves.VESNotificationSender;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.HttpEntity;\r
-import org.springframework.http.HttpHeaders;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-public class NetConfServerManagerImpl {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetConfServerManagerImpl.class);\r
-\r
- @Autowired\r
- ServerPortAllocationHelper serverPortAllocator;\r
-\r
- @Autowired\r
- NetConfServerDetailsRepository netconfDAO;\r
-\r
- @Autowired\r
- NetConfServerProperties config;\r
-\r
- @Autowired\r
- NetconfServerStarter ncServerStarter;\r
-\r
- @Autowired\r
- RestartNetconfServerHandler restartServersHandler;\r
-\r
- @Autowired\r
- VESNotificationSender vesNotificationSender;\r
-\r
- @Autowired\r
- DeviceVersionManager versionManager;\r
-\r
- ExecutorService executorService = Executors.newFixedThreadPool(10);\r
-\r
- public boolean loadSchemas() {\r
- LOG.debug("Loading yang schema started");\r
- List<ProfileDefinition> profiles = versionManager.getSupportedProfileDefinitions();\r
- try {\r
- String commonSchemaPath = config.getSchemaDirPath() + "/common";\r
-\r
- for (ProfileDefinition profile : profiles) {\r
- String verSpecificSchemaPath =\r
- config.getSchemaDirPath() + File.separator + profile.getNetConfSchemaPath();\r
- File schemaDir = new File(commonSchemaPath);\r
- File schemaVerDir = new File(verSpecificSchemaPath);\r
-\r
- if (!schemaVerDir.isDirectory()) {\r
- LOG.error("No folder path found for given version path {}",\r
- schemaVerDir.getAbsolutePath());\r
- return false;\r
- }\r
-\r
- try {\r
- FileUtils.copyDirectory(schemaDir, schemaVerDir);\r
- } catch (IOException e) {\r
- LOG.error("Failed to copy directory " + e.getMessage());\r
- }\r
- boolean isSchemaLoaded = ncServerStarter.loadSchemas(schemaVerDir);\r
- if (!isSchemaLoaded) {\r
- LOG.debug("Failed to load schema for profile {}", profile.getProfileId());\r
- return false;\r
- }\r
- }\r
- } catch (Exception e) {\r
- LOG.error("Load schema's failed in netconf server {}", e.getMessage());\r
- return false;\r
- }\r
- LOG.debug("Loading yang schema completed");\r
- return true;\r
- }\r
-\r
- public void restartServers() {\r
- LOG.debug("Restarting all netconf servers during startup...");\r
- Iterable<NetConfServerDetailsEntity> entities = netconfDAO.findAll();\r
-\r
- for (NetConfServerDetailsEntity entity : entities) {\r
- boolean isReserved = serverPortAllocator.checkAndReserveServerPort(entity.getListenPort());\r
- if (isReserved) {\r
- ServerStartTask task = new ServerStartTask(entity, this);\r
- executorService.execute(task);\r
- } else {\r
- try {\r
- restartServersHandler.restart(entity);\r
- } catch (RetryFailedException e) {\r
- LOG.error("submit task for restarting is failed {}", e.toString());\r
- }\r
- }\r
- }\r
- LOG.debug("Restarting netconf servers during startup is completed.");\r
- }\r
-\r
- public NetConfServerDetails createServer(String deviceId, String enodeBName, String swVersion,\r
- String hwVersion) {\r
- NetConfServerDetails result = new NetConfServerDetails();\r
- NetConfServerDetailsEntity entity = null;\r
- if (deviceId != null) {\r
- entity = netconfDAO.findByDeviceId(deviceId);\r
- } else if (enodeBName != null) {\r
- entity = netconfDAO.findByEnodeBName(enodeBName);\r
- } else {\r
- // none is specified\r
- LOG.error(\r
- "Both deviceID and enodeBName are null. Hence failed to create the netconf server.");\r
- return null;\r
- }\r
-\r
- if (null != entity && ncServerStarter.isNetConfServerRunning(deviceId)) {\r
- if (isVersionChanged(entity, swVersion, hwVersion)) {\r
- return restartOnVersionChange(deviceId, enodeBName, swVersion, hwVersion);\r
- }\r
-\r
- // found the entity. server is already running. double check and run\r
- // if\r
- // required. else return the details.\r
-\r
- // update the ENB Name if Changed\r
- entity.setEnodeBName(enodeBName);\r
- netconfDAO.save(entity);\r
- result = getNetConfServerDetails(deviceId, entity);\r
- return result;\r
- }\r
-\r
- try {\r
-\r
- String port = serverPortAllocator.reserveServerPort();\r
- if (port == null) {\r
- result.setError(NetconfServerManagementError.PORT_NOT_AVAILBLE);\r
- LOG.error(\r
- "All ports are exhausted. Hence cannot allocate a port to start new netconf server");\r
- return result;\r
- } else {\r
- LOG.debug("Successfully reserved a port for deviceID={} ,port={}", deviceId, port);\r
-\r
- // start the server\r
- boolean isServerStarted = ncServerStarter.startServer(port, deviceId, swVersion, hwVersion);\r
- boolean isPortInUse = serverPortAllocator.isServerPortInUse(port);\r
-\r
- if (!isServerStarted || !isPortInUse) {\r
- LOG.error(\r
- "Failed to start netconf server for deviceID: {}, at port:{} , isServerStarted={} ,isPortInUse={}",\r
- deviceId, port, isServerStarted, isPortInUse);\r
- result.setError(NetconfServerManagementError.PORT_IN_USE);\r
- return result;\r
- }\r
- }\r
-\r
- // save the record in db\r
- entity = new NetConfServerDetailsEntity();\r
- entity.setDeviceId(deviceId);\r
- entity.setListenPort(port);\r
- entity.setEnodeBName(enodeBName);\r
- entity.setSwVersion(swVersion);\r
- entity.setHwVersion(hwVersion);\r
- netconfDAO.save(entity);\r
-\r
- result = getNetConfServerDetails(deviceId, entity);\r
- LOG.debug("Successfully started netconf server for deviceID= {}, port={}", deviceId, port);\r
-\r
- } catch (ServerPortAllocationException e) {\r
- LOG.error("Failed to allocate a port {}", e.toString());\r
- }\r
-\r
- if (entity != null) {\r
- result.setDeviceId(deviceId);\r
- result.setListenPort(entity.getListenPort());\r
- String netconfListenAddress = getServiceHost();\r
- if (netconfListenAddress == null) {\r
- netconfListenAddress = config.getNetconfServerIP();\r
- }\r
- result.setListenAddress(netconfListenAddress);\r
- result.setError(NetconfServerManagementError.SUCCESS);\r
- }\r
- return result;\r
- }\r
-\r
- public NetConfServerDetails restartOnVersionChange(String deviceId, String enodeBName,\r
- String swVersion, String hwVersion) {\r
-\r
- NetConfServerDetailsEntity entity = null;\r
- if (deviceId != null) {\r
- entity = netconfDAO.findByDeviceId(deviceId);\r
- }\r
- if (entity == null) {\r
- return null;\r
- }\r
-\r
- boolean isVersionChanged = isVersionChanged(entity, swVersion, hwVersion);\r
- if (isVersionChanged) {\r
- LOG.debug("software version changed, stopping the the existing netconf instance");\r
- boolean result = this.ncServerStarter.stopServer(deviceId);\r
- if (result) {\r
- LOG.debug(\r
- "successfully stopped the netconf instance; trying to start with new version yang models");\r
- entity.setSwVersion(swVersion);\r
- entity.setHwVersion(hwVersion);\r
- netconfDAO.save(entity);\r
-\r
- boolean isSuccess = startNetConfServerInstance(entity);\r
-\r
- if (!isSuccess) {\r
- try {\r
- restartServersHandler.restart(entity);\r
- } catch (RetryFailedException e) {\r
- LOG.debug("");\r
- }\r
- }\r
- }\r
- }\r
- return getNetConfServerDetails(deviceId, entity);\r
- }\r
-\r
-\r
- public boolean startNetConfServerInstance(NetConfServerDetailsEntity entity) {\r
- boolean isSuccess = false;\r
-\r
- boolean isServerStarted = ncServerStarter.startServer(entity.getListenPort(),\r
- entity.getDeviceId(), entity.getSwVersion(), entity.getHwVersion());\r
- if (isServerStarted) {\r
- LOG.info("Successfully restarted NETCONF server {} on port {} .",\r
- entity.getDeviceId(), entity.getListenPort());\r
- // we need to push the pnfEntry for IP updated\r
- NetConfServerDetails details = getNetConfServerDetails(entity.getDeviceId(), entity);\r
-\r
- final String baseUrl = config.getMapperPath() + "/registerNetconfServer";\r
- URI uri = null;\r
- try {\r
- uri = new URI(baseUrl);\r
- } catch (URISyntaxException e) {\r
- LOG.error("error while contructing the URI {}", e.toString());\r
- }\r
- RestTemplate restTemplate = new RestTemplate();\r
- HttpHeaders headers = new HttpHeaders();\r
- HttpEntity<NetConfServerDetails> httpentity = new HttpEntity<>(details, headers);\r
- if (uri != null) {\r
- isSuccess = restTemplate.postForObject(uri, httpentity, Boolean.class);\r
- }\r
-\r
- if (!isSuccess) {\r
- LOG.error("Netconf Register request is failed update the updated host details..");\r
- } else {\r
- LOG.debug("successfully started the server");\r
- }\r
- } else {\r
- LOG.error("Failed to restart NETCONF server {} on port {} upon application startup.",\r
- entity.getDeviceId(), entity.getListenPort());\r
- }\r
- return isSuccess;\r
- }\r
-\r
- private NetConfServerDetails getNetConfServerDetails(String deviceId,\r
- NetConfServerDetailsEntity entity) {\r
- NetConfServerDetails result = new NetConfServerDetails();\r
- result.setDeviceId(deviceId);\r
- result.setListenPort(entity.getListenPort());\r
- result.setEnodeBName(entity.getEnodeBName());\r
- result.setSwVersion(entity.getSwVersion());\r
- result.setHwVersion(entity.getHwVersion());\r
- String netconfListenAddress = getServiceHost();\r
- if (netconfListenAddress == null) {\r
- netconfListenAddress = config.getNetconfServerIP();\r
- }\r
- result.setListenAddress(netconfListenAddress);\r
- result.setError(NetconfServerManagementError.SUCCESS);\r
- return result;\r
- }\r
-\r
- public String unregister(String deviceId, String enodeBName) {\r
- String resultMsg = null;\r
- NetConfServerDetailsEntity entity = null;\r
- if (deviceId != null) {\r
- entity = this.netconfDAO.findByDeviceId(deviceId);\r
- } else if (enodeBName != null) {\r
- entity = this.netconfDAO.findByEnodeBName(enodeBName);\r
- } else {\r
- LOG.error(\r
- "Both deviceID and enodeBName are null. Hence failed to unregister the netconf server.");\r
- resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName\r
- + ". Invalid deviceId/enodeBName specified.";\r
- }\r
- if (entity == null) {\r
- resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName\r
- + ". Invalid deviceId/enodeBName specified.";\r
- LOG.info(resultMsg);\r
- return resultMsg;\r
- }\r
- boolean result = this.ncServerStarter.stopServer(deviceId);\r
- if (result) {\r
- resultMsg =\r
- "Successfully unregistered the device " + deviceId + " and enodeBName=" + enodeBName;\r
- this.serverPortAllocator.unReserveServerPort(entity.getListenPort());\r
- this.netconfDAO.delete(entity);\r
- LOG.info(resultMsg);\r
- delteHeartBeatTimer(deviceId);\r
- } else {\r
- resultMsg = "Failed to unregister the device " + deviceId + ", enodeBName=" + enodeBName;\r
- LOG.error(resultMsg);\r
- }\r
-\r
- return resultMsg;\r
- }\r
-\r
- private void delteHeartBeatTimer(String deviceId) {\r
- VESNotification vesNotification = new VESNotification();\r
-\r
- vesNotification.seteNodeBName(deviceId);\r
-\r
- ParameterDTO paramDTO = new ParameterDTO();\r
- paramDTO.setParamName(NetConfServerConstants.HEART_BEAT);\r
-\r
- List<ParameterDTO> paramDTOList = new ArrayList<>();\r
- paramDTOList.add(paramDTO);\r
-\r
- OperationDetails opDetails = new OperationDetails();\r
- opDetails.setOpCode(TR069OperationCode.DELETE_OBJECT);\r
- opDetails.setParmeters(paramDTOList);\r
-\r
- vesNotification.setOperationDetails(opDetails);\r
-\r
- VESNotificationResponse response =\r
- vesNotificationSender.sendDeleteConfigNotification(vesNotification);\r
-\r
- if (response.getStatusCode() == NetConfServerConstants.SUCCESS) {\r
- LOG.info("Heart beat timer is deleted successfully for device {}", deviceId);\r
- } else {\r
- LOG.error("Failed to delete heart beat timer for device {}. ErrorMsg : {}", deviceId,\r
- response.getResponseMsg());\r
- }\r
-\r
- }\r
-\r
- public List<NetConfServerDetails> getServersInfo() {\r
- Iterable<NetConfServerDetailsEntity> serverEntities = netconfDAO.findAll();\r
- String netconfListenAddress = getServiceHost();\r
- if (netconfListenAddress == null) {\r
- netconfListenAddress = config.getNetconfServerIP();\r
- }\r
- List<NetConfServerDetails> result = new ArrayList<>();\r
-\r
- for (NetConfServerDetailsEntity entity : serverEntities) {\r
- NetConfServerDetails server = new NetConfServerDetails();\r
- server.setDeviceId(entity.getDeviceId());\r
- server.setEnodeBName(entity.getEnodeBName());\r
- server.setError(NetconfServerManagementError.SUCCESS);\r
- server.setListenAddress(netconfListenAddress);\r
- server.setListenPort(entity.getListenPort());\r
- server.setSwVersion(entity.getSwVersion());\r
- server.setHwVersion(entity.getHwVersion());\r
- result.add(server);\r
- }\r
- return result;\r
- }\r
-\r
- private String getServiceHost() {\r
- Map<String, String> envs = System.getenv();\r
- for (Entry<String, String> entry : envs.entrySet()) {\r
- if (entry.getKey() != null && entry.getKey().endsWith("_NETCONF_SERVICE_SERVICE_HOST")) {\r
- return entry.getValue();\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- private boolean isVersionChanged(NetConfServerDetailsEntity entity, String swVersion,\r
- String hwVersion) {\r
- String existingProfileId =\r
- versionManager.getAssociatedProfileId(entity.getSwVersion(), entity.getHwVersion());\r
- String newProfiled = versionManager.getAssociatedProfileId(swVersion, hwVersion);\r
- return !existingProfileId.equalsIgnoreCase(newProfiled) ? true : false;\r
- }\r
-\r
- class ServerStartTask implements Runnable {\r
-\r
- NetConfServerDetailsEntity entity;\r
- NetConfServerManagerImpl netconfServerManager;\r
-\r
- public ServerStartTask(NetConfServerDetailsEntity entity,\r
- NetConfServerManagerImpl netconfServerManager) {\r
- this.entity = entity;\r
- this.netconfServerManager = netconfServerManager;\r
- }\r
-\r
- @Override\r
- public void run() {\r
- boolean isSuccess = netconfServerManager.startNetConfServerInstance(entity);\r
- if (!isSuccess) {\r
- try {\r
- netconfServerManager.restartServersHandler.restart(entity);\r
- } catch (RetryFailedException e) {\r
- LOG.debug("");\r
- }\r
- }\r
- }\r
-\r
- }\r
-}\r
+/*
+ * ============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<ProfileDefinition> 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<NetConfServerDetailsEntity> 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<NetConfServerDetails> 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<ParameterDTO> 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<NetConfServerDetails> getServersInfo() {
+ Iterable<NetConfServerDetailsEntity> serverEntities = netconfDAO.findAll();
+ String netconfListenAddress = getServiceHost();
+ if (netconfListenAddress == null) {
+ netconfListenAddress = config.getNetconfServerIP();
+ }
+ List<NetConfServerDetails> 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<String, String> envs = System.getenv();
+ for (Entry<String, String> 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("");
+ }
+ }
+ }
+
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.server;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.File;\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.util.Arrays;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.concurrent.TimeUnit;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-import org.commscope.tr069adapter.common.deviceversion.DeviceVersionManager;\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.commscope.tr069adapter.netconf.operations.CustomOperationsCreator;\r
-import org.opendaylight.netconf.test.tool.NetconfDeviceSimulator;\r
-import org.opendaylight.netconf.test.tool.config.Configuration;\r
-import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder;\r
-import org.opendaylight.netconf.test.tool.operations.OperationsCreator;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.context.annotation.Scope;\r
-import org.springframework.stereotype.Component;\r
-import com.google.common.base.Preconditions;\r
-\r
-\r
-@Component\r
-@Scope("singleton")\r
-public class NetconfServerStarter {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(NetconfServerStarter.class);\r
-\r
- private static Map<String, NetconfDevice> serversMap = new HashMap<>();\r
-\r
- @Autowired\r
- NetConfServerProperties config;\r
-\r
- @Autowired\r
- DeviceVersionManager versionManager;\r
-\r
- public boolean startServer(String netConfPort, String macID, String swVersion, String hwVersion) {\r
-\r
- if (netConfPort == null) {\r
- LOG.error("Invalid NETCONF port for deviceID: {}, port is null.", macID);\r
- return false;\r
- }\r
-\r
- LOG.debug(\r
- "Starting Netconf server for MACID :{}, on port :{}, softwareVersion {}, hardwareVersion {}",\r
- macID, netConfPort, swVersion, hwVersion);\r
- boolean result =\r
- startServer(netConfPort, config.getSchemaDirPath(), macID, swVersion, hwVersion);\r
- LOG.debug("Completed starting Netconf server for MACID :{} , on port :{}, server status={}",\r
- macID, netConfPort, result);\r
-\r
- return result;\r
- }\r
-\r
- @SuppressWarnings({"resource", "deprecation"})\r
- private boolean startServer(String portStr, String schemaDirPath, String macID, String swVersion,\r
- String hwVersion) {\r
-\r
- // creating configuration for the netconf instance\r
- final Configuration configuration = new ConfigurationBuilder().build();\r
- OperationsCreator operationsCreator = new CustomOperationsCreator(macID, swVersion, hwVersion);\r
- configuration.setOperationsCreator(operationsCreator);\r
- configuration.setGenerateConfigsTimeout((int) TimeUnit.MINUTES.toMillis(30));\r
- if (portStr != null) {\r
- try {\r
- int port = Integer.parseInt(portStr);\r
- configuration.setStartingPort(port);\r
- } catch (Exception e) {\r
- LOG.error("Failed to get netconf service instance port for parameters {}", e.toString());\r
- return false;\r
- }\r
- }\r
- configuration.setDeviceCount(1);\r
- configuration.setSsh(Boolean.TRUE);\r
- configuration.setCapabilities(Configuration.DEFAULT_BASE_CAPABILITIES_EXI);\r
- configuration.setIp("0.0.0.0");\r
-\r
- String versionPath = versionManager.getNetconfYangSchemaPath(swVersion, hwVersion);\r
- if (versionPath == null && swVersion != null) {\r
- LOG.error("Failed to get version path for software version {}, calling base version",\r
- swVersion);\r
- versionPath = versionManager.getBaseNetconfYangSchemaPath();\r
- } else if (swVersion == null) {\r
- LOG.error("Software version is null {}", swVersion);\r
- return false;\r
- }\r
- String schemaVerPath = schemaDirPath + File.separator + versionPath;\r
- File schemaVerDir = new File(schemaVerPath);\r
- configuration.setSchemasDir(schemaVerDir);\r
-\r
- try (final NetconfDevice netconfDevice = new NetconfDevice(configuration)) {\r
- final List<Integer> openDevices = netconfDevice.start();\r
- if (openDevices.isEmpty()) {\r
- LOG.debug("Failed to start netconf server instance {}", macID);\r
- return false;\r
- }\r
- netconfDevice.setAutoClose(false);\r
- serversMap.put(macID, netconfDevice);\r
- } catch (RuntimeException e) {\r
- LOG.error("Unhandled exception. Failed to start the server", e);\r
- return false;\r
- }\r
-\r
- return true;\r
- }\r
-\r
- public boolean stopServer(String macID) {\r
- try {\r
- LOG.debug("Stopping Netconf server for MACID {}", macID);\r
- NetconfDevice netconf = serversMap.get(macID);\r
- netconf.setAutoClose(true);\r
- netconf.close();\r
- serversMap.remove(macID);\r
- LOG.debug("Completed stopping Netconf server for MACID {}", macID);\r
- return true;\r
- } catch (Exception e) {\r
- LOG.debug("Error while stopping Netconf server for MACID {}; error message {}", macID,\r
- e.getMessage());\r
- }\r
-\r
- return false;\r
- }\r
-\r
- protected boolean loadSchemas(File schemasDir) {\r
- if (schemasDir != null) {\r
- if (!schemasDir.exists() || !schemasDir.isDirectory() || !schemasDir.canRead()) {\r
- LOG.error("Failed to load schema. schema location is not valid.");\r
- return false;\r
- }\r
-\r
- Pattern yangregex = Pattern.compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");\r
- Pattern revisionregex = Pattern.compile("revision\\s+\"?(\\d{4}-\\d{2}-\\d{2})\"?");\r
-\r
- final File[] filesArray = schemasDir.listFiles();\r
- final List<File> files =\r
- filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList();\r
- for (final File file : files) {\r
- final Matcher yangMatcher = yangregex.matcher(file.getName());\r
- if (!yangMatcher.matches()) {\r
- try (BufferedReader reader = new BufferedReader(new FileReader(file))) {\r
- String line = reader.readLine();\r
- while (line != null && !revisionregex.matcher(line).find()) {\r
- line = reader.readLine();\r
- }\r
- loadSchemaPattren(line, file, revisionregex);\r
- } catch (final IOException e) {\r
- LOG.error("Unhandled exception. Failed to load the schema.{}", e.toString());\r
- return false;\r
- }\r
- }\r
- }\r
- }\r
- return true;\r
- }\r
-\r
- public boolean isNetConfServerRunning(String deviceId) {\r
- NetconfDevice nc = serversMap.get(deviceId);\r
- if (null != nc)\r
- return true;\r
- else\r
- return false;\r
- }\r
-\r
- private void loadSchemaPattren(String line, File file, Pattern revisionregex) {\r
- if (line != null) {\r
- final Matcher m = revisionregex.matcher(line);\r
- Preconditions.checkState(m.find());\r
- String moduleName = file.getAbsolutePath();\r
- if (file.getName().endsWith(".yang")) {\r
- moduleName = moduleName.substring(0, moduleName.length() - 5);\r
- }\r
- final String revision = m.group(1);\r
- final String correctName = moduleName + "@" + revision + ".yang";\r
- final File correctNameFile = new File(correctName);\r
- if (!file.renameTo(correctNameFile)) {\r
- throw new IllegalStateException("Failed to rename '%s'." + file);\r
- }\r
- }\r
- }\r
-\r
-}\r
-\r
-\r
-class NetconfDevice extends NetconfDeviceSimulator {\r
- boolean autoClose = true;\r
-\r
- public NetconfDevice(Configuration configuration) {\r
- super(configuration);\r
- }\r
-\r
- @Override\r
- public void close() {\r
- if (autoClose)\r
- super.close();\r
- }\r
-\r
- public void setAutoClose(boolean autoClose) {\r
- this.autoClose = autoClose;\r
- }\r
-\r
-}\r
+/*
+ * ============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<String, NetconfDevice> 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<Integer> 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("(?<name>.*)@(?<revision>\\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<File> 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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.server.helper;\r
-\r
-import java.io.IOException;\r
-import java.net.Socket;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-import java.util.PriorityQueue;\r
-import java.util.concurrent.Semaphore;\r
-\r
-import javax.annotation.PostConstruct;\r
-\r
-import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;\r
-import org.commscope.tr069adapter.netconf.error.ServerPortAllocationException;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class ServerPortAllocationHelper {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(ServerPortAllocationHelper.class);\r
-\r
- private static Map<String, Semaphore> semaphoreMap = new HashMap<>();\r
-\r
- private PriorityQueue<String> availablePorts = new PriorityQueue<>();\r
-\r
- @Autowired\r
- NetConfServerProperties config;\r
-\r
- @PostConstruct\r
- public void init() {\r
- // read the port range and it the available ports.\r
-\r
- Integer startPort = config.getDefaultNetconfStartPort();\r
- Integer maxServers = config.getDefaultMaxServers();\r
-\r
- try {\r
- startPort = Integer.parseInt(config.getNetconfServersStartPort());\r
- } catch (Exception e) {\r
- LOG.warn(\r
- "Failed to initialize the starting port from the environment {}. Hence using the default port range.",\r
- config.getNetconfServersStartPort());\r
- }\r
-\r
- try {\r
- maxServers = Integer.parseInt(config.getMaxNumOfNetconfServers());\r
- } catch (Exception e) {\r
- LOG.warn(\r
- "Failed to initialize the max netconf server from the environment {} Hence using the default max servers.",\r
- config.getMaxNumOfNetconfServers());\r
- }\r
-\r
- for (int i = startPort + maxServers - 1; i >= startPort; i--) {\r
- semaphoreMap.put(String.valueOf(i), new Semaphore(1));\r
- availablePorts.add(String.valueOf(i));\r
- }\r
- LOG.debug("Successfully populated available ports list.");\r
- }\r
- \r
- public synchronized String reserveServerPort() throws ServerPortAllocationException {\r
-\r
- if (availablePorts.isEmpty()) {\r
- LOG.debug(\r
- "All ports are exhausted. Hence cannot allocate a port to start new netconf server.");\r
- return null;\r
- }\r
-\r
- String port = availablePorts.peek();\r
-\r
- LOG.debug("Trying to reserve port : {}", port);\r
- if (isServerPortInUse(port)) {\r
- LOG.debug("Port {} is already in use.", port);\r
- availablePorts.poll();\r
- return reserveServerPort(); // retry if current port is not available\r
- }\r
-\r
- Semaphore semaphore = semaphoreMap.get(port);\r
- boolean isAcquired = semaphore.tryAcquire();\r
- if (isAcquired) {\r
- LOG.debug("Failed to acquire a lock for port :{}. Hence retrying...", port);\r
- return reserveServerPort();\r
- }\r
-\r
- availablePorts.poll();\r
- semaphore.release();\r
- LOG.debug("Rserved port is {}", port);\r
- return port;\r
- }\r
-\r
- public boolean unReserveServerPort(String port) {\r
-\r
- try {\r
- Semaphore semaphore = semaphoreMap.get(port);\r
- semaphore.acquire();\r
- availablePorts.add(port);\r
- semaphore.release();\r
- LOG.error("Successfully un-reserved the port " + port + " to start netconf server.");\r
- } catch (InterruptedException e) {\r
- LOG.warn("Failed to un-reserve the port " + port, e);\r
- Thread.currentThread().interrupt();\r
- return false;\r
- }\r
-\r
- return true;\r
- }\r
-\r
- public boolean checkAndReserveServerPort(String port) {\r
-\r
- try {\r
- Semaphore semaphore = semaphoreMap.get(port);\r
- semaphore.acquire();\r
- if (isServerPortInUse(port)) {\r
- LOG.error("Port {} already in use.", port);\r
- semaphore.release();\r
- return false;\r
- }\r
- availablePorts.remove(port);\r
- semaphore.release();\r
- LOG.error("Successfully reserved the port {} to start netconf server", port);\r
- } catch (InterruptedException e) {\r
- Thread.currentThread().interrupt();\r
- LOG.error("Failed to lock the port {} : Exception :{}", port, e.toString());\r
- return checkAndReserveServerPort(port); // retry acquiring the lock.\r
- }\r
-\r
- return true;\r
- }\r
-\r
- public boolean isServerPortInUse(String port) {\r
- return checkIfPortAvailable(port);\r
- }\r
-\r
- private static boolean checkIfPortAvailable(String portStr) {\r
- Integer port = Integer.parseInt(portStr);\r
- try (Socket ignored = new Socket("localhost", port)) {\r
- return true;\r
- } catch (IOException e) {\r
- LOG.error("while checkIfPortAvailable {}", e.toString());\r
- return false;\r
- }\r
- }\r
-}\r
+/*
+ * ============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<String, Semaphore> semaphoreMap = new HashMap<>();
+
+ private PriorityQueue<String> 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;
+ }
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.error;\r
-\r
-import static org.junit.jupiter.api.Assertions.*;\r
-\r
-import org.commscope.tr069adapter.mapper.model.NetconfServerManagementError;\r
-import org.junit.jupiter.api.Test;\r
-\r
-class ServerPortAllocationExceptionTest {\r
-\r
- @Test\r
- void testServerPortAllocationException() {\r
- try {\r
- throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE);\r
-\r
- } catch (ServerPortAllocationException e) {\r
- assertTrue(true);\r
- }\r
- }\r
-\r
- @Test\r
- void testGetError() {\r
- try {\r
- throw new ServerPortAllocationException(NetconfServerManagementError.PORT_IN_USE);\r
-\r
- } catch (ServerPortAllocationException e) {\r
- assertTrue(e.getError().equals(NetconfServerManagementError.PORT_IN_USE));\r
- }\r
- }\r
-\r
- @Test\r
- void testSetError() {\r
- try {\r
- ServerPortAllocationException se =\r
- new ServerPortAllocationException(NetconfServerManagementError.INTERNAL_ERROR);\r
- throw se;\r
-\r
- } catch (ServerPortAllocationException e) {\r
- assertTrue(e.getError().equals(NetconfServerManagementError.INTERNAL_ERROR));\r
- }\r
- }\r
-\r
-}\r
+/*
+ * ============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());
+ }
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.operations;\r
-\r
-import static org.junit.Assert.assertTrue;\r
-\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-import org.junit.jupiter.api.Test;\r
-import org.opendaylight.netconf.api.capability.Capability;\r
-import org.opendaylight.netconf.impl.SessionIdProvider;\r
-import org.opendaylight.netconf.mapping.api.NetconfOperation;\r
-\r
-class CustomOperationsCreatorTest {\r
-\r
- @Test\r
- void testCustomOperationsCreator() {\r
- CustomOperationsCreator coc = getCustomOperationsCreator();\r
- Set<Capability> capabilities = new HashSet<Capability>();\r
- Set<NetconfOperation> opers =\r
- coc.getNetconfOperationService(capabilities, new SessionIdProvider(), "1")\r
- .getNetconfOperations();\r
- assertTrue(opers != null);\r
- assertTrue(!opers.isEmpty());\r
- }\r
-\r
- CustomOperationsCreator getCustomOperationsCreator() {\r
- CustomOperationsCreator coc = new CustomOperationsCreator("0005B9AB1", "4.3.0", "*");\r
- return coc;\r
- }\r
-\r
-}\r
+/*
+ * ============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<Capability> capabilities = new HashSet<Capability>();
+ Set<NetconfOperation> 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;
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.restapi;\r
-\r
-import static org.junit.jupiter.api.Assertions.assertEquals;\r
-\r
-import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;\r
-import org.commscope.tr069adapter.netconf.dao.NetConfServerDetailsRepository;\r
-import org.commscope.tr069adapter.netconf.entity.NetConfServerDetailsEntity;\r
-import org.commscope.tr069adapter.netconf.server.NetConfServerManagerImpl;\r
-import org.junit.FixMethodOrder;\r
-import org.junit.jupiter.api.Test;\r
-import org.junit.jupiter.api.extension.ExtendWith;\r
-import org.junit.runners.MethodSorters;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\r
-import org.springframework.boot.test.context.SpringBootTest;\r
-import org.springframework.boot.test.mock.mockito.MockBean;\r
-import org.springframework.http.HttpStatus;\r
-import org.springframework.http.MediaType;\r
-import org.springframework.mock.web.MockHttpServletResponse;\r
-import org.springframework.test.context.junit.jupiter.SpringExtension;\r
-import org.springframework.test.web.servlet.MockMvc;\r
-import org.springframework.test.web.servlet.MvcResult;\r
-import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;\r
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\r
-\r
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)\r
-@ExtendWith(SpringExtension.class)\r
-@SpringBootTest(classes = {NetConfServiceBooter.class},\r
- args = "--schemas-dir test-schemas --debug true --starting-port 17830")\r
-@AutoConfigureMockMvc\r
-public class NetConfServerManagerRestApiTest {\r
-\r
- @Autowired\r
- private MockMvc mockMvc;\r
-\r
- @MockBean\r
- NetConfServerDetailsRepository netconfDAO;\r
-\r
- @Autowired\r
- NetConfServerManagerImpl manager;\r
-\r
- @Test\r
- public void createNetconfServer() throws Exception {\r
-\r
- NetConfServerDetailsEntity entity = new NetConfServerDetailsEntity();\r
- entity.setDeviceId("0005B9AB1");\r
- entity.setEnodeBName("0005B9AB1");\r
- entity.setId(1l);\r
- entity.setListenPort("17830");\r
-\r
- MockHttpServletRequestBuilder requestBuilder =\r
- MockMvcRequestBuilders.post("/netConfServerManagerService/createServer")\r
- .param("deviceId", "0005B9AB1").param("enodeBName", "0005B9AB1")\r
- .param("swVersion", "4.4.3").param("hwVersion", "*").accept(MediaType.APPLICATION_JSON);\r
- MvcResult result = mockMvc.perform(requestBuilder).andReturn();\r
-\r
- MockHttpServletResponse response = result.getResponse();\r
-\r
- assertEquals(HttpStatus.OK.value(), response.getStatus());\r
-\r
- }\r
-\r
- @Test\r
- public void listNetconfServers() throws Exception {\r
-\r
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders\r
- .get("/netConfServerManagerService/listServers").accept(MediaType.APPLICATION_JSON);\r
- MvcResult result = mockMvc.perform(requestBuilder).andReturn();\r
- MockHttpServletResponse response = result.getResponse();\r
-\r
- assertEquals(HttpStatus.OK.value(), response.getStatus());\r
-\r
- }\r
-\r
- @Test\r
- public void restartServersOnStartup() {\r
- boolean result = false;\r
- try {\r
- manager.restartServers();\r
- result = true;\r
- } catch (Exception e) {\r
- assertEquals(false, result); // if no exception\r
- }\r
- assertEquals(true, result); // if no exception\r
-\r
- }\r
-}\r
+/*
+ * ============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
+
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.netconf.rpc;\r
-\r
-import static org.junit.Assert.assertTrue;\r
-import static org.junit.Assert.fail;\r
-\r
-import org.junit.jupiter.api.Test;\r
-import org.w3c.dom.Element;\r
-\r
-class XmlUtilityTest {\r
-\r
- @Test\r
- void testConvertDocumentToStringXmlElement() {\r
-\r
- String xmlStr =\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>";\r
- try {\r
- Element el = XmlUtility.convertStringToDocument(xmlStr);\r
- String result = XmlUtility.convertDocumentToString(el);\r
- assertTrue(result != null);\r
- } catch (Exception e) {\r
- fail("Failed to convert string into document.");\r
- }\r
- }\r
-\r
- @Test\r
- void testConvertStringToDocument() {\r
- String xmlStr =\r
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rpc-reply xmlns=\"URN\" xmlns:junos=\"URL\"><data/></rpc-reply>";\r
- try {\r
- XmlUtility.convertStringToDocument(xmlStr);\r
- } catch (Exception e) {\r
- fail("Failed to convert string into document.");\r
- }\r
- assertTrue(true);\r
- }\r
-\r
-}\r
+/*
+ * ============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 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><source><running /></source><filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\"><device xmlns=\"urn:onf:otcc:wireless:yang:radio-access-186\"><services><fap-service xmlns=\"urn:onf:otcc:wireless:yang:radio-access\"><index>1</index><cell-config><lte><epc/></lte></cell-config></fap-service></services></device></filter></get-config>";
+ 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 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rpc-reply xmlns=\"URN\" xmlns:junos=\"URL\"><data/></rpc-reply>";
+ try {
+ XmlUtility.convertStringToDocument(xmlStr);
+ } catch (Exception e) {
+ fail("Failed to convert string into document.");
+ }
+ assertTrue(true);
+ }
+
+}
<skipTests>false</skipTests>\r
</configuration>\r
</plugin>\r
+ <plugin>\r
+ <groupId>org.jacoco</groupId>\r
+ <artifactId>jacoco-maven-plugin</artifactId>\r
+ <executions>\r
+ <execution>\r
+ <goals>\r
+ <goal>prepare-agent</goal>\r
+ </goals>\r
+ </execution>\r
+ <!-- attached to Maven test phase -->\r
+ <execution>\r
+ <id>report</id>\r
+ <phase>test</phase>\r
+ <goals>\r
+ <goal>report</goal>\r
+ </goals>\r
+ </execution>\r
+ </executions>\r
+ </plugin>\r
<plugin>\r
<artifactId>maven-failsafe-plugin</artifactId>\r
</plugin>\r
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.async;\r
-\r
-import java.util.concurrent.Future;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationCode;\r
-import org.commscope.tr069adapter.acs.common.OperationOptions;\r
-import org.commscope.tr069adapter.acs.common.dto.CustomOperationCode;\r
-import org.commscope.tr069adapter.acs.common.dto.TR069OperationDetails;\r
-import org.commscope.tr069adapter.vesagent.VesConfiguration;\r
-import org.commscope.tr069adapter.vesagent.controller.HeartBeatMessageHandler;\r
-import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity;\r
-import org.commscope.tr069adapter.vesagent.mapper.MapperRequestSender;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentConstants;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentUtils;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.scheduling.annotation.Async;\r
-import org.springframework.stereotype.Component;\r
-\r
-/**\r
- * \r
- * @version 1.0\r
- * @since June 12, 2020\r
- * @author Prashant Kumar\r
- */\r
-@Component\r
-public class AsyncRequestHandler {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(AsyncRequestHandler.class);\r
-\r
- @Autowired\r
- MapperRequestSender mapperRequestSender;\r
-\r
- @Autowired\r
- WaitForNotifications waitForNotifications;\r
-\r
- @Autowired\r
- HeartBeatMessageHandler heartBeatMessageHandler;\r
-\r
- @Autowired\r
- VesConfiguration config;\r
-\r
- public DeviceRPCResponse performDeviceOperation(DeviceRPCRequest deviceRPCRequest) {\r
- LOG.info("Initiating device connectivity request to ACS for device {}",\r
- deviceRPCRequest.getDeviceDetails().getDeviceId());\r
-\r
- Future<DeviceRPCResponse> futureResponse = mapperRequestSender.sendRequest(deviceRPCRequest);\r
- if (null == futureResponse) {\r
- LOG.error("Request could not be sent. response is null");\r
- return null;\r
- }\r
-\r
- boolean isSuccess = false;\r
- DeviceRPCResponse response = null;\r
-\r
- OperationCode opCode = deviceRPCRequest.getOpDetails().getOpCode();\r
- String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId();\r
- long timeOut = getOperationTimeOut(deviceRPCRequest.getOptions().getExecutionTimeout());\r
-\r
- try {\r
- waitForNotifications.waitForResult(deviceId, opCode, futureResponse, timeOut);\r
- response = waitForNotifications.getOperationResult(deviceId, opCode);\r
-\r
- if (null == response) {\r
- LOG.error("Request got timed out.");\r
- } else {\r
- LOG.debug("Received operation result for device : {}, operation = {} as {}", deviceId,\r
- opCode, response);\r
- }\r
- waitForNotifications.stopOperation(deviceId, opCode);\r
-\r
- // if(isSuccess) {\r
- // response = waitForNotifications.getOperationResult(deviceId, opCode);\r
- // LOG.debug("Received operation result for device : {}, operation = {} as {}",deviceId,\r
- // opCode,response);\r
- //\r
- // waitForNotifications.stopOperation(deviceId, opCode);\r
- // }else {\r
- // LOG.error("Request got timed out.");\r
- // }\r
- } catch (InterruptedException e) {\r
- LOG.debug(\r
- "InterruptedException while waiting for mapper operation result for device : {}, operation : {} request.",\r
- deviceId, opCode);\r
- }\r
-\r
- return response;\r
- }\r
-\r
- private long getOperationTimeOut(long timeOut) {\r
- if (timeOut > 0) {\r
- return timeOut;\r
- }\r
-\r
- if (null != config.getRequestTimeout()) {\r
- timeOut = Long.valueOf(config.getRequestTimeout());\r
- }\r
-\r
- return timeOut;\r
- }\r
-\r
- @Async("threadPoolTaskExecutor1")\r
+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<DeviceRPCResponse> 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);\r
- DeviceDetails deviceDetails = new DeviceDetails();\r
- deviceDetails.setDeviceId(deviceDataEntity.getDeviceId());\r
- deviceDetails.setOui(deviceDataEntity.getOui());\r
- deviceDetails.setProductClass(deviceDataEntity.getProductClass());\r
-\r
- TR069OperationDetails operationDetails = new TR069OperationDetails();\r
- operationDetails.setOpCode(CustomOperationCode.CONNECT);\r
-\r
- DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest();\r
-\r
- deviceRPCRequest.setDeviceDetails(deviceDetails);\r
- deviceRPCRequest.setOpDetails(operationDetails);\r
-\r
- OperationOptions options = new OperationOptions();\r
- if (null != config.getRequestTimeout()) {\r
- options.setExecutionTimeout(Integer.valueOf(config.getRequestTimeout()));\r
- }\r
-\r
- deviceRPCRequest.setOptions(options);\r
-\r
- DeviceRPCResponse deviceRPCResponse = performDeviceOperation(deviceRPCRequest);\r
-\r
- if (VesAgentUtils.isDeviceReachable(deviceRPCResponse)) {\r
- LOG.debug("Device {} is reachable.", deviceDataEntity.getDeviceId());\r
- try {\r
- LOG.debug("Sending heatbeat event for device {}.", deviceDataEntity.getDeviceId());\r
- heartBeatMessageHandler.sendHeartBeatEvent(deviceDataEntity, Integer.parseInt(\r
- deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD)));\r
- } catch (NumberFormatException e) {\r
- LOG.error("heartBeatPeriod doesn't have numeric value. ErrorMsg: {}", e.getMessage());\r
- } catch (Exception e) {\r
- LOG.error("Error while sending heart beat ves event. ErrorMsg: {}", e.getMessage());\r
- }\r
- }\r
- }\r
-}\r
+ 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());
+ }
+ }
+ }
+}
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;
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-package org.commscope.tr069adapter.vesagent.controller;\r
-\r
-import com.fasterxml.jackson.core.JsonProcessingException;\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-\r
-import java.text.SimpleDateFormat;\r
-import java.util.ArrayList;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.vesagent.VesConfiguration;\r
-import org.commscope.tr069adapter.vesagent.exception.InvalidFaultOperationException;\r
-import org.commscope.tr069adapter.vesagent.fault.AlarmFrameWorkSeverityEnum;\r
-import org.commscope.tr069adapter.vesagent.fault.ExpeditedEvent;\r
-import org.commscope.tr069adapter.vesagent.fault.Parser;\r
-import org.commscope.tr069adapter.vesagent.http.HttpRequestSender;\r
-import org.commscope.tr069adapter.vesagent.model.CommonEventHeader;\r
-import org.commscope.tr069adapter.vesagent.model.Event;\r
-import org.commscope.tr069adapter.vesagent.model.EventMessage;\r
-import org.commscope.tr069adapter.vesagent.model.FaultFields;\r
-import org.commscope.tr069adapter.vesagent.util.EventUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.http.HttpStatus;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class AlarmMappingHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(AlarmMappingHandler.class);\r
-\r
- @Autowired\r
- VesConfiguration config;\r
-\r
- @Autowired\r
- HttpRequestSender sender;\r
-\r
- public VESNotificationResponse handleAlarmNotification(VESNotification notification)\r
- throws InvalidFaultOperationException, JsonProcessingException {\r
- List<Event> events = convertNotificationToVESEvent(notification.getDevnotification(),\r
- notification.geteNodeBName());\r
-\r
- for (Iterator<Event> iterator = events.iterator(); iterator.hasNext();) {\r
- Event event = iterator.next();\r
- EventMessage evMsg = new EventMessage();\r
- evMsg.setEvent(event);\r
-\r
- ObjectMapper mapper = new ObjectMapper();\r
-\r
- String requestBody = mapper.writeValueAsString(evMsg);\r
- if (requestBody.isEmpty()) {\r
- logger.debug("Alarm Event body is empty");\r
- }\r
-\r
- String url = config.getFaultVesUrl();\r
- VESNotificationResponse response = sender.postRequest(url, requestBody);\r
- if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {\r
- logger.debug(\r
- "Error received while posting alarms; skiiping this alarm in the fault event and continue for remaining");\r
- }\r
- }\r
-\r
- return new VESNotificationResponse(HttpStatus.ACCEPTED.value(), "No Alarms in the request");\r
- }\r
-\r
- List<Event> convertNotificationToVESEvent(DeviceInform notification, String eNodeBName)\r
- throws InvalidFaultOperationException {\r
- logger.debug("Converting Notification to VES fault event started");\r
- ArrayList<Event> mlist = new ArrayList<>();\r
-\r
- List<ParameterDTO> parameter = notification.getParameters();\r
- Map<String, ExpeditedEvent> hmAlarmParameters = null;\r
- Parser parser = new Parser();\r
- hmAlarmParameters = parser.parseFaultParams(parameter);\r
-\r
- for (Iterator<String> iterator = hmAlarmParameters.keySet().iterator(); iterator.hasNext();) {\r
- ExpeditedEvent event = hmAlarmParameters.get(iterator.next());\r
-\r
- if (event.getAdditionalInformation() != null\r
- && event.getAdditionalInformation().contains("-")) {\r
- String eNBName = event.getAdditionalInformation().split("-")[0].trim();\r
- eNodeBName = eNBName;\r
- }\r
-\r
- Event faultEvent = new Event();\r
- CommonEventHeader eventHeader = new CommonEventHeader();\r
- eventHeader.setDomain("fault");\r
- eventHeader.setEventId(event.getAlarmIdentifier());\r
- eventHeader.setEventName("Fault_" + notification.getDeviceDetails().getProductClass() + "-"\r
- + config.getVendorName() + "_" + event.getProbableCause().replace(" ", ""));\r
- eventHeader.setEventType(config.getFaultEventType());\r
- eventHeader.setLastEpochMicrosec(System.currentTimeMillis());\r
- eventHeader.setTimeZoneOffset(extractTimeZoneOffSet(event.getAdditionalInformation()));\r
- eventHeader.setPriority(extractPriority(event.getPerceivedSeverity()));\r
-\r
- EventUtil.populateEnodeBName(eventHeader, notification, eNodeBName);\r
-\r
- eventHeader.setSequence(1);\r
- eventHeader.setStartEpochMicrosec(System.currentTimeMillis()*1000);\r
- eventHeader.setVersion(config.getEventVersion());\r
- if (eNodeBName != null && eNodeBName.length() > 3)\r
- eventHeader.setNfNamingCode(eNodeBName.substring(0, 3));\r
- else\r
- eventHeader.setNfNamingCode("");\r
- eventHeader.setNfcNamingCode("");\r
- eventHeader.setNfVendorName(config.getVendorName());\r
- eventHeader.setVesEventListenerVersion(config.getVesVersion());\r
- faultEvent.setCommonEventHeader(eventHeader);\r
-\r
- FaultFields faultfields = new FaultFields();\r
- faultfields.setAlarmCondition(event.getProbableCause().replace(" ", ""));\r
-\r
- faultfields.setEventSeverity(event.getPerceivedSeverity().toString());\r
- if (event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEAR\r
- || event.getPerceivedSeverity() == AlarmFrameWorkSeverityEnum.CLEARED) {\r
- faultfields.setEventSeverity("NORMAL");\r
- }\r
-\r
- faultfields.setEventSourceType(config.getFaultEventSourcePrefix() + "_"\r
- + notification.getDeviceDetails().getProductClass());\r
- faultfields.setFaultFieldsVersion(config.getFaultFeildVersion());\r
- faultfields.setSpecificProblem(event.getSpecificProblem());\r
- faultfields.setVfStatus("Active");\r
- faultfields.setEventCategory(event.getEventType());\r
- faultfields.setAlarmInterfaceA(event.getManagedObjectInstance());\r
- Map<String, String> addition = new HashMap<>();\r
- addition.put("eventTime",\r
- new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.s'Z'").format(new Date()));\r
- addition.put("AdditionalText", event.getAdditionalText());\r
- addition.put("AdditionalInformation", event.getAdditionalInformation());\r
- faultfields.setAlarmAdditionalInformation(addition);\r
-\r
- faultEvent.setFaultFields(faultfields);\r
- mlist.add(faultEvent);\r
-\r
- }\r
- logger.debug("Converting Notification to VES fault event completed :{}", mlist);\r
- return mlist;\r
- }\r
-\r
- private String extractTimeZoneOffSet(String additionalInformation) {\r
- String[] additionalInfoArray = null;\r
- String[] timeZoneOffset = null;\r
- String timeOffset = "UTC+00.00";\r
-\r
- if (additionalInformation != null && additionalInformation.contains("|")) {\r
- additionalInfoArray = additionalInformation.split("\\|");\r
-\r
- int index = -1;\r
- for (int i = 0; i < additionalInfoArray.length; i++) {\r
- if (additionalInfoArray[i].contains("TZD=")) {\r
- index = i;\r
- }\r
- }\r
- if (index >= 0) {\r
- timeZoneOffset = additionalInfoArray[index].split("=");\r
- timeOffset = timeZoneOffset[timeZoneOffset.length - 1];\r
- }\r
- } else if (additionalInformation != null && additionalInformation.contains("TZD=")) {\r
- timeZoneOffset = additionalInformation.split("=");\r
- timeOffset = timeZoneOffset[timeZoneOffset.length - 1];\r
- }\r
-\r
- return timeOffset;\r
- }\r
-\r
- private String extractPriority(AlarmFrameWorkSeverityEnum severity) {\r
- String priority;\r
- if (severity == AlarmFrameWorkSeverityEnum.CRITICAL\r
- || severity == AlarmFrameWorkSeverityEnum.MAJOR) {\r
- priority = "High";\r
- } else if (severity == AlarmFrameWorkSeverityEnum.MINOR) {\r
- priority = "Medium";\r
- } else {\r
- priority = "Low";\r
- }\r
-\r
- return priority;\r
- }\r
-}\r
+/*
+ * ============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<Event> events = convertNotificationToVESEvent(notification.getDevnotification(),
+ notification.geteNodeBName());
+
+ for (Iterator<Event> 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<Event> convertNotificationToVESEvent(DeviceInform notification, String eNodeBName)
+ throws InvalidFaultOperationException {
+ logger.debug("Converting Notification to VES fault event started");
+ ArrayList<Event> mlist = new ArrayList<>();
+
+ List<ParameterDTO> parameter = notification.getParameters();
+ Map<String, ExpeditedEvent> hmAlarmParameters = null;
+ Parser parser = new Parser();
+ hmAlarmParameters = parser.parseFaultParams(parameter);
+
+ for (Iterator<String> 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<String, String> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-package org.commscope.tr069adapter.vesagent.controller;\r
-\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.acs.common.OperationDetails;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.vesagent.VesConfiguration;\r
-import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity;\r
-import org.commscope.tr069adapter.vesagent.exception.VesAgentException;\r
-import org.commscope.tr069adapter.vesagent.http.HttpRequestSender;\r
-import org.commscope.tr069adapter.vesagent.model.CommonEventHeader;\r
-import org.commscope.tr069adapter.vesagent.model.Event;\r
-import org.commscope.tr069adapter.vesagent.model.EventMessage;\r
-import org.commscope.tr069adapter.vesagent.model.HeartbeatFields;\r
-import org.commscope.tr069adapter.vesagent.service.VesAgentServiceHelper;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentConstants;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentUtils;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class HeartBeatMessageHandler {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(HeartBeatMessageHandler.class);\r
-\r
- @Autowired\r
- VesAgentServiceHelper vesAgentServiceHelper;\r
-\r
- @Autowired\r
- VesConfiguration config;\r
-\r
- @Autowired\r
- HttpRequestSender sender;\r
-\r
- public VESNotificationResponse sendHeartBeatEvent(DeviceDataEntity deviceDataEntity,\r
- int heartBeatPeriod) throws Exception {\r
- Event event = convertNotificationToVESEvent(deviceDataEntity, heartBeatPeriod);\r
-\r
- EventMessage evMsg = new EventMessage();\r
- evMsg.setEvent(event);\r
-\r
- ObjectMapper mapper = new ObjectMapper();\r
-\r
- String requestBody = mapper.writeValueAsString(evMsg);\r
- if (requestBody.isEmpty()) {\r
- logger.debug("VES Event body is empty");\r
- }\r
-\r
- String url = config.getPnfRegVesUrl();\r
- return sender.postRequest(url, requestBody);\r
- }\r
-\r
- public void handleRegisterRequest(VESNotification vesNotification) {\r
- try {\r
- VesAgentUtils.validateVESNotification(vesNotification);\r
- } catch (VesAgentException e) {\r
- logger.error(\r
- "Failed to create heartbeat timers for device on recieving bootstrap. ErrorMsg: {}",\r
- e.getMessage());\r
- return;\r
- }\r
-\r
- List<DeviceDataEntity> deviceDataEntityList = vesAgentServiceHelper.findByDeviceIdAndGroup(\r
- vesNotification.getDevnotification().getDeviceDetails().getDeviceId(),\r
- VesAgentConstants.HEART_BEAT);\r
-\r
- if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) {\r
- DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0);\r
- String heartbeatPeriod =\r
- deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD);\r
-\r
- if (!VesAgentUtils.isNullOrEmpty(heartbeatPeriod)\r
- && !heartbeatPeriod.equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) {\r
- return;\r
- }\r
- }\r
-\r
- logger.info("Creating heartbeat records and timer using default heartbeatPeriod {} minutes.",\r
- VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL);\r
-\r
- DeviceRPCRequest deviceRPCRequest = new DeviceRPCRequest();\r
- deviceRPCRequest.setDeviceDetails(vesNotification.getDevnotification().getDeviceDetails());\r
-\r
- OperationDetails opDetails = new OperationDetails();\r
-\r
- ParameterDTO heartBeatPeriodParam = new ParameterDTO();\r
- heartBeatPeriodParam.setParamName(VesAgentConstants.HEART_BEAT_PERIOD);\r
- heartBeatPeriodParam.setParamValue(VesAgentConstants.HEART_BEAT_PERIOD_DEFAULT_VAL);\r
-\r
- List<ParameterDTO> paramList = new ArrayList<>();\r
- paramList.add(heartBeatPeriodParam);\r
-\r
- opDetails.setParmeters(paramList);\r
- deviceRPCRequest.setOpDetails(opDetails);\r
-\r
- deviceRPCRequest.addContextParam(VesAgentConstants.ENODEB_NAME,\r
- vesNotification.geteNodeBName());\r
-\r
- handleSetConfigRequest(deviceRPCRequest);\r
-\r
- }\r
-\r
- public DeviceRPCResponse handleSetConfigRequest(DeviceRPCRequest deviceRPCRequest) {\r
- try {\r
- VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest);\r
- } catch (VesAgentException e) {\r
- return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage());\r
- }\r
-\r
- OperationDetails operationDetails = deviceRPCRequest.getOpDetails();\r
-\r
- String heartBeatPeriod = null;\r
- String countDownTimer = null;\r
-\r
- ParameterDTO countDownTimerDTO = null;\r
-\r
- List<ParameterDTO> paramDTOList = operationDetails.getParmeters();\r
- for (ParameterDTO paramDTO : paramDTOList) {\r
- if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.HEART_BEAT_PERIOD)) {\r
- heartBeatPeriod = paramDTO.getParamValue();\r
- }\r
-\r
- if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) {\r
- countDownTimer = paramDTO.getParamValue();\r
- countDownTimerDTO = paramDTO;\r
- }\r
- }\r
-\r
- try {\r
- vesAgentServiceHelper.processHeartBeatSetRequest(deviceRPCRequest, heartBeatPeriod,\r
- countDownTimer);\r
- } catch (VesAgentException e) {\r
- return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage());\r
- }\r
-\r
- copyHeartBeatPeriodToTimerForResponse(countDownTimerDTO, heartBeatPeriod);\r
- return VesAgentUtils.getSuccessResponse(deviceRPCRequest);\r
- }\r
-\r
- private void copyHeartBeatPeriodToTimerForResponse(ParameterDTO countDownParam,\r
- String heartBeatPeriod) {\r
- if (null != countDownParam && !VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) {\r
- countDownParam.setParamValue(heartBeatPeriod);\r
- }\r
- }\r
-\r
- public DeviceRPCResponse handleGetConfigRequest(DeviceRPCRequest deviceRPCRequest) {\r
- try {\r
- VesAgentUtils.validateDeviceRPCRequest(deviceRPCRequest);\r
- } catch (VesAgentException e) {\r
- return VesAgentUtils.getErrorResponse(deviceRPCRequest, e.getErrorCode(), e.getMessage());\r
- }\r
-\r
- vesAgentServiceHelper.processHeartBeatGetRequest(deviceRPCRequest);\r
- return VesAgentUtils.getSuccessResponse(deviceRPCRequest);\r
- }\r
-\r
- public VESNotificationResponse handleDeleteConfigRequest(VESNotification vesNotification) {\r
- try {\r
- VesAgentUtils.validateDelVESNotification(vesNotification);\r
- vesAgentServiceHelper.processHeartBeatDeleteRequest(vesNotification);\r
- } catch (VesAgentException e) {\r
- return new VESNotificationResponse(Integer.parseInt(e.getErrorCode()), e.getMessage());\r
- } catch (Exception e) {\r
- return new VESNotificationResponse(VesAgentConstants.RPC_FAILED, e.getMessage());\r
- }\r
-\r
- return new VESNotificationResponse(VesAgentConstants.RPC_SUCCESS, "success");\r
- }\r
-\r
- Event convertNotificationToVESEvent(DeviceDataEntity deviceDataEntity, int heartBeatPeriod) {\r
- Event hbEvent = new Event();\r
- CommonEventHeader eventHeader = new CommonEventHeader();\r
-\r
- eventHeader.setDomain("heartbeat");\r
- eventHeader\r
- .setEventId("heartbeat_" + deviceDataEntity.getDeviceId() + System.currentTimeMillis());\r
- eventHeader.setEventName(\r
- "heartbeat_" + deviceDataEntity.getProductClass() + "-" + config.getVendorName());\r
- eventHeader.setEventType("CommScope_RAN_heartbeat");\r
- eventHeader.setLastEpochMicrosec(System.currentTimeMillis() * 1000);\r
-\r
- eventHeader.setPriority("High");\r
- eventHeader.setSequence(0);\r
-\r
- if (deviceDataEntity.geteNodeBName() == null) {\r
- eventHeader.setReportingEntityName(deviceDataEntity.getDeviceId());\r
- eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId());\r
- eventHeader.setSourceId(deviceDataEntity.getDeviceId());\r
- eventHeader.setSourceName(deviceDataEntity.getDeviceId());\r
- } else {\r
- eventHeader.setReportingEntityName(deviceDataEntity.geteNodeBName());\r
- eventHeader.setSourceName(deviceDataEntity.geteNodeBName());\r
- eventHeader.setReportingEntityId(deviceDataEntity.getDeviceId());\r
- eventHeader.setSourceId(deviceDataEntity.getDeviceId());\r
- }\r
-\r
- eventHeader.setStartEpochMicrosec(deviceDataEntity.getStartEpochMicrosec());\r
- eventHeader.setVersion(config.getEventVersion());\r
- eventHeader.setNfNamingCode("");\r
- eventHeader.setNfcNamingCode("");\r
- eventHeader.setNfVendorName(config.getVendorName());\r
- eventHeader.setVesEventListenerVersion(config.getVesVersion());\r
- hbEvent.setCommonEventHeader(eventHeader);\r
-\r
- HeartbeatFields heartbeatFields = new HeartbeatFields();\r
- heartbeatFields.setHeartbeatFieldsVersion("3.0");\r
- heartbeatFields.setHeartbeatInterval(heartBeatPeriod * 60);\r
- hbEvent.setHeartbeatFields(heartbeatFields);\r
-\r
- return hbEvent;\r
- }\r
-}\r
+/*
+ * ============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<DeviceDataEntity> 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<ParameterDTO> 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<ParameterDTO> 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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.vesagent.controller;\r
-\r
-import com.fasterxml.jackson.core.JsonProcessingException;\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-\r
-import java.text.SimpleDateFormat;\r
-import java.util.Date;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceInform;\r
-import org.commscope.tr069adapter.mapper.model.NetConfServerDetails;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.mapper.model.VESNotificationResponse;\r
-import org.commscope.tr069adapter.vesagent.VesConfiguration;\r
-import org.commscope.tr069adapter.vesagent.fault.Parser;\r
-import org.commscope.tr069adapter.vesagent.http.HttpRequestSender;\r
-import org.commscope.tr069adapter.vesagent.model.CommonEventHeader;\r
-import org.commscope.tr069adapter.vesagent.model.Event;\r
-import org.commscope.tr069adapter.vesagent.model.EventMessage;\r
-import org.commscope.tr069adapter.vesagent.model.PnfRegEventAdditionalFeilds;\r
-import org.commscope.tr069adapter.vesagent.model.PnfRegEventFields;\r
-import org.commscope.tr069adapter.vesagent.util.EventUtil;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class PnfRegMappingHandler {\r
- private static final Logger logger = LoggerFactory.getLogger(PnfRegMappingHandler.class);\r
- public static final String SSH_USERNAME = "netconf";\r
- public static final String SSH_PSSWORD = "netconf";\r
-\r
- @Autowired\r
- VesConfiguration config;\r
-\r
- @Autowired\r
- HttpRequestSender sender;\r
-\r
- public VESNotificationResponse handlePnfRegNotification(VESNotification vesNoti)\r
- throws JsonProcessingException {\r
- Event event = convertNotificationToVESEvent(vesNoti.getDevnotification(),\r
- vesNoti.getNetconfDetails(), vesNoti.geteNodeBName());\r
- if (null != event) {\r
- EventMessage evMsg = new EventMessage();\r
- evMsg.setEvent(event);\r
-\r
- ObjectMapper mapper = new ObjectMapper();\r
-\r
- String requestBody = mapper.writeValueAsString(evMsg);\r
- if (requestBody.isEmpty()) {\r
- logger.debug("VES Event body is empty");\r
- }\r
-\r
- String url = config.getPnfRegVesUrl();\r
- return sender.postRequest(url, requestBody);\r
- } else {\r
- return new VESNotificationResponse(-1,\r
- "unable to prepare ves event due to insufficient data");\r
- }\r
- }\r
-\r
- public VESNotificationResponse handlePnfRegNotificationOnRestart(VESNotification vesNoti)\r
- throws JsonProcessingException {\r
- Event event = convertNotificationToVESEventOnRestart(vesNoti.getNetconfDetails());\r
-\r
- EventMessage evMsg = new EventMessage();\r
- evMsg.setEvent(event);\r
-\r
- ObjectMapper mapper = new ObjectMapper();\r
-\r
- String requestBody = mapper.writeValueAsString(evMsg);\r
- if (requestBody.isEmpty()) {\r
- logger.debug("VES Event body is empty");\r
- }\r
-\r
- String url = config.getPnfRegVesUrl();\r
- return sender.postRequest(url, requestBody);\r
- }\r
-\r
- Event convertNotificationToVESEvent(DeviceInform notification,\r
- NetConfServerDetails netconfServerDetails, String eNodeBName) {\r
- logger.debug("Converting Notification to VES pnfevent started");\r
- Parser parser = new Parser();\r
-\r
-\r
- Event regEvent = new Event();\r
- CommonEventHeader eventHeader = new CommonEventHeader();\r
-\r
- eventHeader.setDomain("pnfRegistration");\r
- eventHeader.setEventId(\r
- "PnfReg" + notification.getDeviceDetails().getDeviceId() + System.currentTimeMillis());\r
- eventHeader.setEventName("pnfReg_" + notification.getDeviceDetails().getProductClass() + "-"\r
- + config.getVendorName());\r
- eventHeader.setEventType(config.getPnfRegEventType());\r
- eventHeader.setPriority("High");\r
- EventUtil.populateEventHeaderFields(eventHeader, notification, eNodeBName, config);\r
- regEvent.setCommonEventHeader(eventHeader);\r
-\r
- PnfRegEventFields pnfRegistrationFields =\r
- parser.parseNotificationParams(notification.getParameters());\r
- populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields);\r
- pnfRegistrationFields.setModelNumber(notification.getDeviceDetails().getProductClass());\r
-\r
- regEvent.setPnfRegistrationFields(pnfRegistrationFields);\r
- logger.debug("Converting Notification to VES pnfevent completed");\r
- return regEvent;\r
- }\r
-\r
- Event convertNotificationToVESEventOnRestart(NetConfServerDetails netconfServerDetails) {\r
- logger.debug("Converting Notification to VES pnfevent started");\r
-\r
- Event regEvent = new Event();\r
- CommonEventHeader eventHeader = new CommonEventHeader();\r
-\r
- if (null == netconfServerDetails) {\r
- logger.error("netconf server details as received as null {}", netconfServerDetails);\r
- return null;\r
- }\r
- eventHeader.setDomain("pnfRegistration");\r
- eventHeader\r
- .setEventId("PnfReg" + netconfServerDetails.getDeviceId() + System.currentTimeMillis());\r
- eventHeader.setEventName(\r
- "pnfReg_" + netconfServerDetails.getDeviceId() + "-" + config.getVendorName());\r
- eventHeader.setEventType(config.getPnfRegEventType());\r
- eventHeader.setLastEpochMicrosec(System.currentTimeMillis());\r
-\r
- eventHeader.setPriority("High");\r
- eventHeader.setSequence(0);\r
-\r
- if (netconfServerDetails.getEnodeBName() == null) {\r
- eventHeader.setReportingEntityName(netconfServerDetails.getDeviceId());\r
- eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId());\r
- eventHeader.setSourceId(netconfServerDetails.getDeviceId());\r
- eventHeader.setSourceName(netconfServerDetails.getDeviceId());\r
- } else {\r
- eventHeader.setReportingEntityName(netconfServerDetails.getEnodeBName());\r
- eventHeader.setSourceName(netconfServerDetails.getEnodeBName());\r
-\r
- eventHeader.setReportingEntityId(netconfServerDetails.getDeviceId());\r
- eventHeader.setSourceId(netconfServerDetails.getDeviceId());\r
- }\r
-\r
- eventHeader.setStartEpochMicrosec(System.currentTimeMillis()*1000);\r
- eventHeader.setVersion(config.getEventVersion());\r
- eventHeader.setNfNamingCode("");\r
- eventHeader.setNfcNamingCode("");\r
- eventHeader.setNfVendorName(config.getVendorName());\r
- eventHeader.setVesEventListenerVersion(config.getVesVersion());\r
- regEvent.setCommonEventHeader(eventHeader);\r
- PnfRegEventFields pnfRegistrationFields = new PnfRegEventFields();\r
- regEvent.setPnfRegistrationFields(\r
- populatePnfRegFeilds(netconfServerDetails, pnfRegistrationFields));\r
- logger.debug("Converting Notification to VES pnfevent completed");\r
- return regEvent;\r
- }\r
-\r
- private PnfRegEventFields populatePnfRegFeilds(NetConfServerDetails netconfServerDetails,\r
- PnfRegEventFields pnfRegistrationFields) {\r
-\r
- pnfRegistrationFields.setSerialNumber(netconfServerDetails.getDeviceId());\r
- pnfRegistrationFields.setPnfRegistrationFieldsVersion(config.getPnfFeildVersion());\r
- pnfRegistrationFields.setMacAddress(netconfServerDetails.getDeviceId());\r
- pnfRegistrationFields.setVendorName(config.getVendorName());\r
- pnfRegistrationFields.setSoftwareVersion(netconfServerDetails.getSwVersion());\r
- PnfRegEventAdditionalFeilds additionalFields = new PnfRegEventAdditionalFeilds();\r
-\r
- pnfRegistrationFields.setOamV4IpAddress(netconfServerDetails.getListenAddress());\r
- // TODO: since not supporting 1pv6 we are configuring empty value\r
- pnfRegistrationFields.setOamV6IpAddress("");\r
-\r
- pnfRegistrationFields.setManufactureDate("");\r
- pnfRegistrationFields.setUnitType(config.getUnitType());\r
- pnfRegistrationFields.setUnitFamily(config.getUnitFamily());\r
- pnfRegistrationFields.setLastServiceDate(new SimpleDateFormat("ddMMyyyy").format(new Date()));\r
- additionalFields.setOamPort(netconfServerDetails.getListenPort());\r
- additionalFields.setProtocol("SSH");\r
- additionalFields.setUsername(SSH_USERNAME);\r
- additionalFields.setPassword(SSH_PSSWORD);\r
- additionalFields.setReconnectOnChangedSchema(Boolean.FALSE.toString());\r
- additionalFields.setSleepfactor("1.5");\r
- additionalFields.setTcpOnly(Boolean.FALSE.toString());\r
- additionalFields.setConnectionTimeout("20000");\r
- additionalFields.setMaxConnectionAttempts("100");\r
- additionalFields.setBetweenAttemptsTimeout("2000");\r
- additionalFields.setKeepaliveDelay("120");\r
-\r
- pnfRegistrationFields.setAdditionalFields(additionalFields);\r
-\r
- return pnfRegistrationFields;\r
-\r
- }\r
-\r
-}\r
+/*
+ * ============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<ParameterDTO> 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<ParameterDTO> 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<String, String> 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<String, String> 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;
+
+ }
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.entity;\r
-\r
-import com.google.gson.Gson;\r
-\r
-import java.util.Date;\r
-import java.util.Map;\r
-\r
-import javax.persistence.Column;\r
-import javax.persistence.Entity;\r
-import javax.persistence.GeneratedValue;\r
-import javax.persistence.GenerationType;\r
-import javax.persistence.Id;\r
-import javax.persistence.Table;\r
-import javax.persistence.Transient;\r
-import javax.persistence.UniqueConstraint;\r
-\r
-@Entity\r
-@Table(name = "VES_DEVICE_DATA",\r
- uniqueConstraints = @UniqueConstraint(columnNames = {"DEVICE_ID", "ATTR_GROUP"}))\r
-public class DeviceDataEntity {\r
-\r
- @Id\r
- @Column(name = "ID")\r
- @GeneratedValue(strategy = GenerationType.AUTO)\r
- private Long id;\r
-\r
- @Column(name = "DEVICE_ID", length = 30)\r
- private String deviceId;\r
-\r
- @Column(name = "ENODEB_NAME", length = 100)\r
- private String eNodeBName;\r
-\r
- @Column(name = "OUI", length = 30)\r
- private String oui;\r
-\r
- @Column(name = "PRODUCT_CLASS", length = 100)\r
- private String productClass;\r
-\r
- @Column(name = "ATTR_JSON", length = 4000)\r
- private String attrJson;\r
-\r
- @Column(name = "ATTR_GROUP", length = 255)\r
- private String attrGroup;\r
-\r
- @Column(name = "LAST_UPDATED_TIME")\r
- private Date lastUpdateTime = new Date();\r
-\r
- public Long getId() {\r
- return id;\r
- }\r
-\r
- public void setId(Long id) {\r
- this.id = id;\r
- }\r
-\r
- public String getDeviceId() {\r
- return deviceId;\r
- }\r
-\r
- public void setDeviceId(String deviceId) {\r
- this.deviceId = deviceId;\r
- }\r
-\r
- public String geteNodeBName() {\r
- return eNodeBName;\r
- }\r
-\r
- public void seteNodeBName(String eNodeBName) {\r
- this.eNodeBName = eNodeBName;\r
- }\r
-\r
- public String getOui() {\r
- return oui;\r
- }\r
-\r
- public void setOui(String oui) {\r
- this.oui = oui;\r
- }\r
-\r
- public String getProductClass() {\r
- return productClass;\r
- }\r
-\r
- public void setProductClass(String productClass) {\r
- this.productClass = productClass;\r
- }\r
-\r
- public String getAttrJson() {\r
- return attrJson;\r
- }\r
-\r
- public void setAttrJson(String attrJson) {\r
- this.attrJson = attrJson;\r
- }\r
-\r
- public String getAttrGroup() {\r
- return attrGroup;\r
- }\r
-\r
- public void setAttrGroup(String attrGroup) {\r
- this.attrGroup = attrGroup;\r
- }\r
-\r
- public Date getLastUpdateTime() {\r
- return lastUpdateTime;\r
- }\r
-\r
- public void setLastUpdateTime(Date lastUpdateTime) {\r
- this.lastUpdateTime = lastUpdateTime;\r
- }
-
+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;
public void setStartEpochMicrosec(Long startEpochMicrosec) {
this.startEpochMicrosec = startEpochMicrosec;
- }\r
-\r
- @Transient\r
- public void setAttributesMap(Map<String, String> attributesMap) {\r
- if (null == attributesMap || attributesMap.isEmpty()) {\r
- return;\r
- }\r
-\r
- this.attrJson = new Gson().toJson(attributesMap);\r
-\r
- }\r
-\r
- @Transient\r
- public Map<String, String> getAttributesMap() {\r
- Map<String, String> attributesMap = null;\r
- if (null != this.attrJson && !this.attrJson.isEmpty()) {\r
- attributesMap = new Gson().fromJson(this.attrJson, Map.class);\r
- }\r
- return attributesMap;\r
- }\r
-}\r
+ }
+
+ @Transient
+ public void setAttributesMap(Map<String, String> attributesMap) {
+ if (null == attributesMap || attributesMap.isEmpty()) {
+ return;
+ }
+
+ this.attrJson = new Gson().toJson(attributesMap);
+
+ }
+
+ @Transient
+ public Map<String, String> getAttributesMap() {
+ Map<String, String> attributesMap = null;
+ if (null != this.attrJson && !this.attrJson.isEmpty()) {
+ attributesMap = new Gson().fromJson(this.attrJson, Map.class);
+ }
+ return attributesMap;
+ }
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.exception;\r
-\r
-/**\r
- * \r
- * @version 1.0\r
- * @since May 21, 2020\r
- * @author Prashant\r
- */\r
-public class VesAgentException extends Exception {\r
- private static final long serialVersionUID = -3742697051389101875L;\r
-\r
- private static final String ERRORMSG_PREFIX = "ves-agent";\r
-\r
- private String[] arguments;\r
-\r
- private String errorCode;\r
- private String message;\r
-\r
- // index of the error occurred in the given list or in the given file\r
- protected int errorIndex = -1;\r
-\r
-\r
- /**\r
- * Constructs a <code>VesOperationException</code> with no detail message.\r
- * \r
- */\r
- public VesAgentException() {\r
- super();\r
- }\r
-\r
- /**\r
- * Constructs a <code>VesOperationException</code> with the specified detail message.\r
- * \r
- * @param s as the details message\r
- */\r
- public VesAgentException(String s) {\r
- super(s);\r
- }\r
-\r
- public VesAgentException(String... args) {\r
- super();\r
- arguments = args;\r
- setErrorMessage(getErrorMessage());\r
- }\r
-\r
- public VesAgentException(String errorCode, String errorMsg) {\r
- super();\r
- this.errorCode = errorCode;\r
- setErrorMessage(getErrorMessage());\r
- }\r
-\r
- public int getErrorIndex() {\r
- return errorIndex;\r
- }\r
-\r
- public void setErrorIndex(int errorIndex) {\r
- this.errorIndex = errorIndex;\r
- }\r
-\r
-\r
- public String getMessage() {\r
- return message;\r
- }\r
-\r
- private String getErrorMessage() {\r
- String key = ERRORMSG_PREFIX + ".";\r
- return key;\r
- }\r
-\r
- private void setErrorMessage(String message) {\r
- this.message = message;\r
- }\r
-\r
- public String getErrorCode() {\r
- return errorCode;\r
- }\r
-\r
- public void setErrorCode(String errorCode) {\r
- this.errorCode = errorCode;\r
- }\r
-}\r
+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 <code>VesOperationException</code> with no detail message.
+ *
+ */
+ public VesAgentException() {
+ super();
+ }
+
+ /**
+ * Constructs a <code>VesOperationException</code> 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;
+ }
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.mapper;\r
-\r
-import java.util.concurrent.Future;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCResponse;\r
-import org.commscope.tr069adapter.vesagent.VesConfiguration;\r
-import org.commscope.tr069adapter.vesagent.async.WaitForNotifications;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.scheduling.annotation.Async;\r
-import org.springframework.scheduling.annotation.AsyncResult;\r
-import org.springframework.stereotype.Component;\r
-import org.springframework.web.client.RestTemplate;\r
-\r
-@Component\r
-// @EnableAsync\r
-public class MapperRequestSender {\r
- private static final Logger LOG = LoggerFactory.getLogger(MapperRequestSender.class);\r
- private RestTemplate restTemplate = new RestTemplate();\r
-\r
- @Autowired\r
- VesConfiguration config;\r
-\r
- @Autowired\r
- WaitForNotifications waitForNotifications;\r
-\r
- // public DeviceRPCResponse sendRequest(DeviceRPCRequest deviceRPCRequest) {\r
- // return restTemplate.postForObject(config.getMapperPath(), deviceRPCRequest,\r
- // DeviceRPCResponse.class);\r
- // }\r
-\r
- @Async("threadPoolTaskExecutor2")\r
- public Future<DeviceRPCResponse> sendRequest(DeviceRPCRequest deviceRPCRequest) {\r
- LOG.info("Sending device connectivity request to ACS for device {}",\r
- deviceRPCRequest.getDeviceDetails().getDeviceId());\r
- DeviceRPCResponse response = restTemplate.postForObject(config.getMapperPath(),\r
- deviceRPCRequest, DeviceRPCResponse.class);\r
-\r
- waitForNotifications.notifyResult(response);\r
-\r
- return new AsyncResult<>(response);\r
- }\r
-\r
-}\r
+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<DeviceRPCResponse> 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);
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.vesagent.model;\r
-\r
-import com.fasterxml.jackson.annotation.JsonInclude;\r
-import com.fasterxml.jackson.annotation.JsonProperty;\r
-\r
-import java.io.Serializable;\r
-\r
-@JsonInclude(JsonInclude.Include.NON_NULL)\r
-public class CommonEventHeader implements Serializable {\r
- @JsonProperty("version")\r
- private String version;\r
- @JsonProperty("vesEventListenerVersion")\r
- private String vesEventListenerVersion;\r
- @JsonProperty("domain")\r
- private String domain;\r
- @JsonProperty("eventName")\r
- private String eventName;\r
- @JsonProperty("eventType")\r
- private String eventType;\r
- @JsonProperty("eventId")\r
- private String eventId;\r
- @JsonProperty("sequence")\r
- private Integer sequence;\r
- @JsonProperty("priority")\r
- private String priority;\r
- @JsonProperty("reportingEntityId")\r
- private String reportingEntityId;\r
- @JsonProperty("reportingEntityName")\r
- private String reportingEntityName;\r
- @JsonProperty("sourceId")\r
- private String sourceId;\r
- @JsonProperty("sourceName")\r
- private String sourceName;\r
- @JsonProperty("nfVendorName")\r
- private String nfVendorName;\r
- @JsonProperty("nfNamingCode")\r
- private String nfNamingCode;\r
- @JsonProperty("nfcNamingCode")\r
- private String nfcNamingCode;\r
- @JsonProperty("startEpochMicrosec")\r
- private long startEpochMicrosec;\r
- @JsonProperty("lastEpochMicrosec")\r
- private long lastEpochMicrosec;\r
- @JsonProperty("timeZoneOffset")\r
- private String timeZoneOffset;\r
-\r
- public String getEventId() {\r
- return eventId;\r
- }\r
-\r
- public void setEventId(String eventId) {\r
- this.eventId = eventId;\r
- }\r
-\r
- public String getEventName() {\r
- return eventName;\r
- }\r
-\r
- public void setEventName(String eventName) {\r
- this.eventName = eventName;\r
- }\r
-\r
- public String getDomain() {\r
- return domain;\r
- }\r
-\r
- public void setDomain(String domain) {\r
- this.domain = domain;\r
- }\r
-\r
- public String getSourceName() {\r
- return sourceName;\r
- }\r
-\r
- public void setSourceName(String sourceName) {\r
- this.sourceName = sourceName;\r
- }\r
-\r
- public String getPriority() {\r
- return priority;\r
- }\r
-\r
- public void setPriority(String priority) {\r
- this.priority = priority;\r
- }\r
-\r
- public String getVersion() {\r
- return version;\r
- }\r
-\r
- public void setVersion(String version) {\r
- this.version = version;\r
- }\r
-\r
- public int getSequence() {\r
- return sequence;\r
- }\r
-\r
- public void setSequence(int sequence) {\r
- this.sequence = sequence;\r
- }\r
-\r
- public String getVesEventListenerVersion() {\r
- return vesEventListenerVersion;\r
- }\r
-\r
- public void setVesEventListenerVersion(String vesEventListenerVersion) {\r
- this.vesEventListenerVersion = vesEventListenerVersion;\r
- }\r
-\r
- public long getStartEpochMicrosec() {\r
- return startEpochMicrosec;\r
- }\r
-\r
- public void setStartEpochMicrosec(long startEpochMicrosec) {\r
- this.startEpochMicrosec = startEpochMicrosec;\r
- }\r
-\r
- public long getLastEpochMicrosec() {\r
- return lastEpochMicrosec;\r
- }\r
-\r
- public void setLastEpochMicrosec(long lastEpochMicrosec) {\r
- this.lastEpochMicrosec = lastEpochMicrosec;\r
- }\r
-\r
- public String getReportingEntityName() {\r
- return reportingEntityName;\r
- }\r
-\r
- public void setReportingEntityName(String reportingEntityName) {\r
- this.reportingEntityName = reportingEntityName;\r
- }\r
-\r
- public void setSequence(Integer sequence) {\r
- this.sequence = sequence;\r
- }\r
-\r
- public String getEventType() {\r
- return eventType;\r
- }\r
-\r
- public void setEventType(String eventType) {\r
- this.eventType = eventType;\r
- }\r
-\r
- public String getNfNamingCode() {\r
- return nfNamingCode;\r
- }\r
-\r
- public void setNfNamingCode(String nfNamingCode) {\r
- this.nfNamingCode = nfNamingCode;\r
- }\r
-\r
- public String getReportingEntityId() {\r
- return reportingEntityId;\r
- }\r
-\r
- public void setReportingEntityId(String reportingEntityId) {\r
- this.reportingEntityId = reportingEntityId;\r
- }\r
-\r
- public String getSourceId() {\r
- return sourceId;\r
- }\r
-\r
- public void setSourceId(String sourceId) {\r
- this.sourceId = sourceId;\r
- }\r
-\r
- public String getNfVendorName() {\r
- return nfVendorName;\r
- }\r
-\r
- public void setNfVendorName(String nfVendorName) {\r
- this.nfVendorName = nfVendorName;\r
- }\r
-\r
- public String getTimeZoneOffset() {\r
- return timeZoneOffset;\r
- }\r
-\r
- public void setTimeZoneOffset(String timeZoneOffset) {\r
- this.timeZoneOffset = timeZoneOffset;\r
- }\r
-\r
- public String getNfcNamingCode() {\r
- return nfcNamingCode;\r
- }\r
-\r
- public void setNfcNamingCode(String nfcNamingCode) {\r
- this.nfcNamingCode = nfcNamingCode;\r
- }\r
-\r
-}\r
+/*
+ * ============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 + "]";
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.vesagent.model;\r
-\r
-public class EventMessage {\r
-\r
- private Event event;\r
-\r
- public EventMessage() {\r
- super();\r
- }\r
-\r
- public EventMessage(Event event) {\r
- this.event = event;\r
- }\r
-\r
- public Event getEvent() {\r
- return event;\r
- }\r
-\r
- public void setEvent(Event event) {\r
- this.event = event;\r
- }\r
-\r
-}\r
+/*
+ * ============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 + "]";
+ }
+
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.model;\r
-\r
-import com.fasterxml.jackson.annotation.JsonInclude;\r
-\r
-@JsonInclude(JsonInclude.Include.NON_NULL)\r
-public class HeartbeatFields {\r
- public String heartbeatFieldsVersion;\r
- public int heartbeatInterval;\r
-\r
- public String getHeartbeatFieldsVersion() {\r
- return heartbeatFieldsVersion;\r
- }\r
-\r
- public void setHeartbeatFieldsVersion(String heartbeatFieldsVersion) {\r
- this.heartbeatFieldsVersion = heartbeatFieldsVersion;\r
- }\r
-\r
- public int getHeartbeatInterval() {\r
- return heartbeatInterval;\r
- }\r
-\r
- public void setHeartbeatInterval(int heartbeatInterval) {\r
- this.heartbeatInterval = heartbeatInterval;\r
- }\r
-}\r
+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;
+ }
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.vesagent.model;\r
-\r
-import com.fasterxml.jackson.annotation.JsonInclude;\r
-import com.fasterxml.jackson.annotation.JsonProperty;\r
-\r
-import java.io.Serializable;\r
-\r
-@JsonInclude(JsonInclude.Include.NON_NULL)\r
-public class PnfRegEventAdditionalFeilds implements Serializable {\r
- /**\r
- * \r
- */\r
- private static final long serialVersionUID = 5368863118681551950L;\r
- private String oamPort;\r
- private String protocol;\r
- private String username;\r
- private String password;\r
- private String reconnectOnChangedSchema;\r
- @JsonProperty("sleep-factor")\r
- private String sleepfactor;\r
- private String tcpOnly;\r
- private String connectionTimeout;\r
- private String maxConnectionAttempts;\r
- private String betweenAttemptsTimeout;\r
- private String keepaliveDelay;\r
-\r
- public String getOamPort() {\r
- return oamPort;\r
- }\r
-\r
- public void setOamPort(String oamPort) {\r
- this.oamPort = oamPort;\r
- }\r
-\r
- public String getProtocol() {\r
- return protocol;\r
- }\r
-\r
- public void setProtocol(String protocol) {\r
- this.protocol = protocol;\r
- }\r
-\r
- public String getUsername() {\r
- return username;\r
- }\r
-\r
- public void setUsername(String username) {\r
- this.username = username;\r
- }\r
-\r
- public String getPassword() {\r
- return password;\r
- }\r
-\r
- public void setPassword(String password) {\r
- this.password = password;\r
- }\r
-\r
- public String getReconnectOnChangedSchema() {\r
- return reconnectOnChangedSchema;\r
- }\r
-\r
- public void setReconnectOnChangedSchema(String reconnectOnChangedSchema) {\r
- this.reconnectOnChangedSchema = reconnectOnChangedSchema;\r
- }\r
-\r
- public String getSleepfactor() {\r
- return sleepfactor;\r
- }\r
-\r
- public void setSleepfactor(String sleepfactor) {\r
- this.sleepfactor = sleepfactor;\r
- }\r
-\r
- public String getTcpOnly() {\r
- return tcpOnly;\r
- }\r
-\r
- public void setTcpOnly(String tcpOnly) {\r
- this.tcpOnly = tcpOnly;\r
- }\r
-\r
- public String getConnectionTimeout() {\r
- return connectionTimeout;\r
- }\r
-\r
- public void setConnectionTimeout(String connectionTimeout) {\r
- this.connectionTimeout = connectionTimeout;\r
- }\r
-\r
- public String getMaxConnectionAttempts() {\r
- return maxConnectionAttempts;\r
- }\r
-\r
- public void setMaxConnectionAttempts(String maxConnectionAttempts) {\r
- this.maxConnectionAttempts = maxConnectionAttempts;\r
- }\r
-\r
- public String getBetweenAttemptsTimeout() {\r
- return betweenAttemptsTimeout;\r
- }\r
-\r
- public void setBetweenAttemptsTimeout(String betweenAttemptsTimeout) {\r
- this.betweenAttemptsTimeout = betweenAttemptsTimeout;\r
- }\r
-\r
- public String getKeepaliveDelay() {\r
- return keepaliveDelay;\r
- }\r
-\r
- public void setKeepaliveDelay(String keepaliveDelay) {\r
- this.keepaliveDelay = keepaliveDelay;\r
- }\r
-}\r
+/*
+ * ============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 + "]";
+ }
+
+}
-/*\r
- * ============LICENSE_START========================================================================\r
- * ONAP : tr-069-adapter\r
- * =================================================================================================\r
- * Copyright (C) 2020 CommScope Inc Intellectual Property.\r
- * =================================================================================================\r
- * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,\r
- * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You\r
- * may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
- * either express or implied. See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ===============LICENSE_END=======================================================================\r
- */\r
-\r
-package org.commscope.tr069adapter.vesagent.model;\r
-\r
-import com.fasterxml.jackson.annotation.JsonInclude;\r
-import com.fasterxml.jackson.annotation.JsonProperty;\r
-\r
-import java.io.Serializable;\r
-\r
-@JsonInclude(JsonInclude.Include.NON_NULL)\r
-public class PnfRegEventFields implements Serializable {\r
- /**\r
- * \r
- */\r
- private static final long serialVersionUID = 2183003488649290852L;\r
- private String pnfRegistrationFieldsVersion;\r
- private String serialNumber;\r
- private String vendorName;\r
- private String oamV4IpAddress;\r
- private String oamV6IpAddress;\r
- private String softwareVersion;\r
- private String unitType;\r
- private String unitFamily;\r
- private String modelNumber;\r
- private String manufactureDate;\r
- private String macAddress;\r
- private String lastServiceDate;\r
- @JsonProperty("additionalFields")\r
- private PnfRegEventAdditionalFeilds additionalFields = null;\r
-\r
- public String getPnfRegistrationFieldsVersion() {\r
- return pnfRegistrationFieldsVersion;\r
- }\r
-\r
- public void setPnfRegistrationFieldsVersion(String pnfRegistrationFieldsVersion) {\r
- this.pnfRegistrationFieldsVersion = pnfRegistrationFieldsVersion;\r
- }\r
-\r
- public String getSerialNumber() {\r
- return serialNumber;\r
- }\r
-\r
- public void setSerialNumber(String serialNumber) {\r
- this.serialNumber = serialNumber;\r
- }\r
-\r
- public String getVendorName() {\r
- return vendorName;\r
- }\r
-\r
- public void setVendorName(String vendorName) {\r
- this.vendorName = vendorName;\r
- }\r
-\r
- public String getOamV4IpAddress() {\r
- return oamV4IpAddress;\r
- }\r
-\r
- public void setOamV4IpAddress(String oamV4IpAddress) {\r
- this.oamV4IpAddress = oamV4IpAddress;\r
- }\r
-\r
- public String getOamV6IpAddress() {\r
- return oamV6IpAddress;\r
- }\r
-\r
- public void setOamV6IpAddress(String oamV6IpAddress) {\r
- this.oamV6IpAddress = oamV6IpAddress;\r
- }\r
-\r
- public String getSoftwareVersion() {\r
- return softwareVersion;\r
- }\r
-\r
- public void setSoftwareVersion(String softwareVersion) {\r
- this.softwareVersion = softwareVersion;\r
- }\r
-\r
- public String getUnitType() {\r
- return unitType;\r
- }\r
-\r
- public void setUnitType(String unitType) {\r
- this.unitType = unitType;\r
- }\r
-\r
- public String getUnitFamily() {\r
- return unitFamily;\r
- }\r
-\r
- public void setUnitFamily(String unitFamily) {\r
- this.unitFamily = unitFamily;\r
- }\r
-\r
- public String getModelNumber() {\r
- return modelNumber;\r
- }\r
-\r
- public void setModelNumber(String modelNumber) {\r
- this.modelNumber = modelNumber;\r
- }\r
-\r
- public String getManufactureDate() {\r
- return manufactureDate;\r
- }\r
-\r
- public void setManufactureDate(String manufactureDate) {\r
- this.manufactureDate = manufactureDate;\r
- }\r
-\r
- public String getMacAddress() {\r
- return macAddress;\r
- }\r
-\r
- public void setMacAddress(String macAddress) {\r
- this.macAddress = macAddress;\r
- }\r
-\r
- public String getLastServiceDate() {\r
- return lastServiceDate;\r
- }\r
-\r
- public void setLastServiceDate(String lastServiceDate) {\r
- this.lastServiceDate = lastServiceDate;\r
- }\r
-\r
- public PnfRegEventAdditionalFeilds getAdditionalFields() {\r
- return additionalFields;\r
- }\r
-\r
- public void setAdditionalFields(PnfRegEventAdditionalFeilds additionalFields) {\r
- this.additionalFields = additionalFields;\r
- }\r
-}\r
+/*
+ * ============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 + "]";
+ }
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.service;\r
-\r
-import com.google.gson.Gson;\r
-\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.concurrent.TimeUnit;\r
-import java.util.function.Function;\r
-\r
-import org.commscope.tr069adapter.acs.common.DeviceDetails;\r
-import org.commscope.tr069adapter.acs.common.DeviceRPCRequest;\r
-import org.commscope.tr069adapter.acs.common.ParameterDTO;\r
-import org.commscope.tr069adapter.mapper.model.VESNotification;\r
-import org.commscope.tr069adapter.vesagent.async.WaitForNotifications;\r
-import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity;\r
-import org.commscope.tr069adapter.vesagent.exception.VesAgentException;\r
-import org.commscope.tr069adapter.vesagent.repository.VesDataRepository;\r
-import org.commscope.tr069adapter.vesagent.timer.HeartBeatTimeoutTask;\r
-import org.commscope.tr069adapter.vesagent.timer.ScheduleInfo;\r
-import org.commscope.tr069adapter.vesagent.timer.ScheduleTaskService;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentConstants;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentUtils;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class VesAgentServiceHelper {\r
- private final Logger logger = LoggerFactory.getLogger(this.getClass());\r
-\r
- @Autowired\r
- private Function<String, HeartBeatTimeoutTask> beanFactory;\r
-\r
- public HeartBeatTimeoutTask getBeanInstance(String name) {\r
- return beanFactory.apply(name);\r
- }\r
-\r
- @Autowired\r
- VesDataRepository vesDataRepository;\r
-\r
- @Autowired\r
- WaitForNotifications waitForNotifications;\r
-\r
- @Autowired\r
- ScheduleTaskService timerService;\r
-\r
- private boolean saveDeviceDataEntity(DeviceDetails deviceDetails, String eNodeBName,\r
- String heartBeatPeriod) throws VesAgentException {\r
-\r
- List<DeviceDataEntity> deviceDataEntityList = vesDataRepository\r
- .findByDeviceIdAndAttrGroup(deviceDetails.getDeviceId(), VesAgentConstants.HEART_BEAT);\r
-\r
- DeviceDataEntity deviceDataEntity = null;\r
- Map<String, String> attrJsonMap = null;\r
-\r
- if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) {\r
- deviceDataEntity = new DeviceDataEntity();\r
-\r
- deviceDataEntity.setDeviceId(deviceDetails.getDeviceId());\r
- deviceDataEntity.seteNodeBName(eNodeBName);\r
- deviceDataEntity.setOui(deviceDetails.getOui());\r
- deviceDataEntity.setProductClass(deviceDetails.getProductClass());\r
- deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT);\r
-\r
- attrJsonMap = new HashMap<>();\r
- } else {\r
- deviceDataEntity = deviceDataEntityList.get(0);\r
- attrJsonMap = deviceDataEntity.getAttributesMap();\r
- }\r
-\r
- String existingHeartBeatPeriod = attrJsonMap.get(VesAgentConstants.HEART_BEAT_PERIOD);\r
-\r
- if (null == heartBeatPeriod\r
- && (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(existingHeartBeatPeriod))\r
- || existingHeartBeatPeriod\r
- .equalsIgnoreCase(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL))) {\r
- return false;\r
- }\r
-\r
- if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod)) {\r
- attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, heartBeatPeriod);\r
- }\r
-\r
- deviceDataEntity.setAttributesMap(attrJsonMap);\r
-\r
- vesDataRepository.save(deviceDataEntity);\r
-\r
- return true;\r
- }\r
-\r
- public void processHeartBeatSetRequest(DeviceRPCRequest deviceRPCRequest, String heartBeatPeriod,\r
- String countDownTimer) throws VesAgentException {\r
-\r
- String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId();\r
-\r
- VesAgentUtils.validateDeviceId(deviceId);\r
-\r
- if (VesAgentUtils.isNullOrEmpty(heartBeatPeriod)\r
- && VesAgentUtils.isNullOrEmpty(countDownTimer)) {\r
- String errorMsg =\r
- "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId;\r
- logger.error(errorMsg);\r
- throw new VesAgentException(VesAgentConstants.INVALID_PARAMETER_VALUE, errorMsg);\r
- }\r
-\r
- Object eNodeBNameObj = deviceRPCRequest.getContext().get(VesAgentConstants.ENODEB_NAME);\r
-\r
- String eNodeBName = null;\r
- if (null != eNodeBNameObj) {\r
- eNodeBName = (String) eNodeBNameObj;\r
- }\r
-\r
- boolean resetTimerJob =\r
- saveDeviceDataEntity(deviceRPCRequest.getDeviceDetails(), eNodeBName, heartBeatPeriod);\r
-\r
- if (resetTimerJob) {\r
- resetTimerJob(deviceId, heartBeatPeriod, countDownTimer);\r
- abortRunningDeviceConnectivityCheck(deviceRPCRequest);\r
- }\r
-\r
- }\r
-\r
- public void processHeartBeatGetRequest(DeviceRPCRequest deviceRPCRequest) {\r
-\r
- String deviceId = deviceRPCRequest.getDeviceDetails().getDeviceId();\r
- List<DeviceDataEntity> deviceDataEntityList =\r
- vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT);\r
-\r
- if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList)\r
- || VesAgentUtils.isNullOrEmpty(deviceDataEntityList.get(0).getAttributesMap())) {\r
- return;\r
- }\r
-\r
- DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0);\r
-\r
- List<ParameterDTO> resultparamDTOList = null;\r
- List<ParameterDTO> paramDTOList = deviceRPCRequest.getOpDetails().getParmeters();\r
-\r
- for (ParameterDTO paramDTO : paramDTOList) {\r
- resultparamDTOList = ifDataTypeObject(paramDTO, deviceDataEntity);\r
-\r
- if (!resultparamDTOList.isEmpty()) {\r
- break;\r
- }\r
-\r
- if (paramDTO.getParamName().equalsIgnoreCase(VesAgentConstants.COUNT_DOWN_TIMER)) {\r
- paramDTO.setParamValue(getCountDownTimerParam(deviceDataEntity).getParamValue());\r
- } else {\r
- paramDTO.setParamValue(deviceDataEntity.getAttributesMap().get(paramDTO.getParamName()));\r
- }\r
- }\r
-\r
- if (null != resultparamDTOList && !resultparamDTOList.isEmpty()) {\r
- deviceRPCRequest.getOpDetails().setParmeters(resultparamDTOList);\r
- }\r
- }\r
-\r
- public void processHeartBeatDeleteRequest(VESNotification vesNotification) {\r
- List<ParameterDTO> paramDTOList = vesNotification.getOperationDetails().getParmeters();\r
-\r
- for (ParameterDTO paramDTO : paramDTOList) {\r
- if (Boolean.TRUE.equals(VesAgentUtils.isVesNotificationRequest(paramDTO))) {\r
- List<DeviceDataEntity> deviceDataEntityList = vesDataRepository.findByDeviceIdAndAttrGroup(\r
- vesNotification.geteNodeBName(), VesAgentConstants.HEART_BEAT);\r
-\r
- if (Boolean.TRUE.equals(VesAgentUtils.isNullOrEmpty(deviceDataEntityList))) {\r
- return;\r
- }\r
- vesDataRepository.delete(deviceDataEntityList.get(0));\r
- timerService.cancelSchedule(vesNotification.geteNodeBName());\r
- break;\r
- }\r
- }\r
- }\r
-\r
- private List<ParameterDTO> ifDataTypeObject(ParameterDTO paramDTO,\r
- DeviceDataEntity deviceDataEntity) {\r
- List<ParameterDTO> paramDTOList = new ArrayList<>();\r
-\r
- if (null != paramDTO.getDataType()\r
- && paramDTO.getDataType().equalsIgnoreCase(VesAgentConstants.OBJECT_DATA_TYPE.toLowerCase())\r
- && paramDTO.getParamName().toLowerCase()\r
- .contains(VesAgentConstants.HEART_BEAT.toLowerCase())) {\r
-\r
- Map<String, String> attrMap = deviceDataEntity.getAttributesMap();\r
-\r
- for (Map.Entry<String, String> entry : attrMap.entrySet()) {\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName(entry.getKey());\r
- param.setParamValue(entry.getValue());\r
-\r
- paramDTOList.add(param);\r
- }\r
-\r
- ParameterDTO countDownParam = getCountDownTimerParam(deviceDataEntity);\r
- paramDTOList.add(countDownParam);\r
- }\r
-\r
- return paramDTOList;\r
- }\r
-\r
- private ParameterDTO getCountDownTimerParam(DeviceDataEntity deviceDataEntity) {\r
- Long countDownTimerVal = timerService\r
- .getTimeRemainingTillNextExecution(deviceDataEntity.getDeviceId(), TimeUnit.MINUTES);\r
-\r
- ParameterDTO param = new ParameterDTO();\r
- param.setParamName(VesAgentConstants.COUNT_DOWN_TIMER);\r
-\r
- if (null != countDownTimerVal) {\r
- param.setParamValue(countDownTimerVal.toString());\r
- }\r
-\r
- return param;\r
- }\r
-\r
-\r
- public void processHeartBeatGetRequest(String deviceId, Integer HeartBeatPeriod,\r
- Integer countDownTimer) throws VesAgentException {\r
- VesAgentUtils.validateDeviceId(deviceId);\r
-\r
-\r
- if (null == HeartBeatPeriod && null == countDownTimer) {// this should just check if heartbeat\r
- // is null\r
- String errorMsg =\r
- "Invalid input: HeartBeatPeriod and countDownTimer both are null for device " + deviceId;\r
- logger.error(errorMsg);\r
- throw new VesAgentException(errorMsg);\r
- }\r
-\r
- List<DeviceDataEntity> deviceDataEntityList =\r
- vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT);\r
-\r
- DeviceDataEntity deviceDataEntity = null;\r
- Map<String, String> attrJsonMap = null;\r
-\r
- if (null == deviceDataEntityList || deviceDataEntityList.isEmpty()) {\r
- deviceDataEntity = new DeviceDataEntity();\r
- deviceDataEntity.setDeviceId(deviceId);\r
- deviceDataEntity.setAttrGroup(VesAgentConstants.HEART_BEAT);\r
-\r
- attrJsonMap = new HashMap<String, String>();\r
- } else {\r
- deviceDataEntity = deviceDataEntityList.get(0);\r
- attrJsonMap = new Gson().fromJson(deviceDataEntity.getAttrJson(), Map.class);\r
- }\r
-\r
-\r
- if (null != HeartBeatPeriod) {\r
- attrJsonMap.put(VesAgentConstants.HEART_BEAT_PERIOD, HeartBeatPeriod.toString());\r
- }\r
-\r
- if (null != countDownTimer) {\r
- attrJsonMap.put(VesAgentConstants.COUNT_DOWN_TIMER, countDownTimer.toString());\r
- }\r
-\r
- String attrJson = new Gson().toJson(attrJsonMap);\r
- deviceDataEntity.setAttrJson(attrJson);\r
-\r
- vesDataRepository.save(deviceDataEntity);\r
- }\r
-\r
- private void resetTimerJob(String deviceId, String heartBeatPeriod, String countDownTimer) {\r
- if (null == heartBeatPeriod || heartBeatPeriod.isEmpty()) {\r
- scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer));\r
- } else if (heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) {\r
- timerService.cancelSchedule(deviceId);\r
- } else {\r
- if (Boolean.FALSE.equals(VesAgentUtils.isNullOrEmpty(countDownTimer))) {\r
- scheduleTimerJob(deviceId, Integer.parseInt(countDownTimer));\r
- } else {\r
- scheduleTimerJob(deviceId, Integer.parseInt(heartBeatPeriod));\r
- }\r
- }\r
- }\r
-\r
- private void scheduleTimerJob(String deviceId, Integer timeoutInterval) {\r
- ScheduleInfo scheduleInfo = new ScheduleInfo();\r
- scheduleInfo.setInterval(timeoutInterval);\r
- scheduleInfo.setTimeUnit(TimeUnit.MINUTES);\r
-\r
- HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceId);\r
-\r
- timerService.schedule(deviceId, scheduleInfo, callbackTask);\r
- }\r
-\r
- private void abortRunningDeviceConnectivityCheck(DeviceRPCRequest deviceRPCRequest) {\r
- waitForNotifications.notifyResult(VesAgentUtils.getErrorResponse(deviceRPCRequest, null, null));\r
- }\r
-\r
- public List<DeviceDataEntity> getAllDeviceDataEntity() {\r
- return (List<DeviceDataEntity>) vesDataRepository.findAll();\r
- }\r
-\r
- public List<DeviceDataEntity> findByDeviceIdAndGroup(String deviceId, String attrGroup) {\r
- return vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, attrGroup);\r
- }\r
-\r
-\r
-\r
-}\r
+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<String, HeartBeatTimeoutTask> 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<DeviceDataEntity> deviceDataEntityList = vesDataRepository
+ .findByDeviceIdAndAttrGroup(deviceDetails.getDeviceId(), VesAgentConstants.HEART_BEAT);
+
+ DeviceDataEntity deviceDataEntity = null;
+ Map<String, String> 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<DeviceDataEntity> deviceDataEntityList =
+ vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT);
+
+ if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList)
+ || VesAgentUtils.isNullOrEmpty(deviceDataEntityList.get(0).getAttributesMap())) {
+ return;
+ }
+
+ DeviceDataEntity deviceDataEntity = deviceDataEntityList.get(0);
+
+ List<ParameterDTO> resultparamDTOList = null;
+ List<ParameterDTO> 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<ParameterDTO> paramDTOList = vesNotification.getOperationDetails().getParmeters();
+
+ for (ParameterDTO paramDTO : paramDTOList) {
+ if (Boolean.TRUE.equals(VesAgentUtils.isVesNotificationRequest(paramDTO))) {
+ List<DeviceDataEntity> 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<ParameterDTO> ifDataTypeObject(ParameterDTO paramDTO,
+ DeviceDataEntity deviceDataEntity) {
+ List<ParameterDTO> paramDTOList = new ArrayList<>();
+
+ if (null != paramDTO.getDataType()
+ && paramDTO.getDataType().equalsIgnoreCase(VesAgentConstants.OBJECT_DATA_TYPE.toLowerCase())
+ && paramDTO.getParamName().toLowerCase()
+ .contains(VesAgentConstants.HEART_BEAT.toLowerCase())) {
+
+ Map<String, String> attrMap = deviceDataEntity.getAttributesMap();
+
+ for (Map.Entry<String, String> 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<DeviceDataEntity> deviceDataEntityList =
+ vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, VesAgentConstants.HEART_BEAT);
+
+ DeviceDataEntity deviceDataEntity = null;
+ Map<String, String> 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<DeviceDataEntity> getAllDeviceDataEntity() {
+ return (List<DeviceDataEntity>) vesDataRepository.findAll();
+ }
+
+ public List<DeviceDataEntity> findByDeviceIdAndGroup(String deviceId, String attrGroup) {
+ return vesDataRepository.findByDeviceIdAndAttrGroup(deviceId, attrGroup);
+ }
+
+
+
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.timer;\r
-\r
-import java.util.List;\r
-import java.util.concurrent.TimeUnit;\r
-import java.util.function.Function;\r
-\r
-import javax.annotation.PostConstruct;\r
-\r
-import org.commscope.tr069adapter.vesagent.entity.DeviceDataEntity;\r
-import org.commscope.tr069adapter.vesagent.repository.VesDataRepository;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentConstants;\r
-import org.commscope.tr069adapter.vesagent.util.VesAgentUtils;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-import org.springframework.stereotype.Component;\r
-\r
-@Component\r
-public class StartupTimerService {\r
- private static final Logger logger = LoggerFactory.getLogger(StartupTimerService.class);\r
-\r
- @Autowired\r
- private Function<String, HeartBeatTimeoutTask> beanFactory;\r
-\r
- public HeartBeatTimeoutTask getBeanInstance(String name) {\r
- return beanFactory.apply(name);\r
- }\r
-\r
- @Autowired\r
- VesDataRepository vesDataRepository;\r
-\r
- @Autowired\r
- ScheduleTaskService timerService;\r
-\r
- @PostConstruct\r
- public void initializeDeviceReachabilityCheckTimers() {\r
- logger.debug("Initializing all device connectivity check timer tasks.");\r
- List<DeviceDataEntity> deviceDataEntityList =\r
- vesDataRepository.findByAttrGroup(VesAgentConstants.HEART_BEAT);\r
-\r
- if (VesAgentUtils.isNullOrEmpty(deviceDataEntityList)) {\r
- logger.debug("No device reachability check timer tasks exist.");\r
- return;\r
- }\r
-\r
- for (DeviceDataEntity deviceDataEntity : deviceDataEntityList) {\r
- String heartBeatPeriod = null;\r
-\r
- if (null != deviceDataEntity.getAttributesMap()) {\r
- heartBeatPeriod =\r
- deviceDataEntity.getAttributesMap().get(VesAgentConstants.HEART_BEAT_PERIOD);\r
- }\r
-\r
- if (!VesAgentUtils.isNullOrEmpty(heartBeatPeriod)\r
- && !heartBeatPeriod.equals(VesAgentConstants.REMOVE_HEART_BEAT_TIMER_VAL)) {\r
- logger.info("Creating device connectivity check timer tasks for device {}.",\r
- deviceDataEntity.getDeviceId());\r
- ScheduleInfo scheduleInfo = new ScheduleInfo();\r
- scheduleInfo.setInterval(Integer.parseInt(heartBeatPeriod));\r
- scheduleInfo.setTimeUnit(TimeUnit.SECONDS);\r
-\r
- HeartBeatTimeoutTask callbackTask = getBeanInstance(deviceDataEntity.getDeviceId());\r
-\r
- timerService.schedule(deviceDataEntity.getDeviceId(), scheduleInfo, callbackTask);\r
- }\r
- }\r
- }\r
-}\r
+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<String, HeartBeatTimeoutTask> 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<DeviceDataEntity> 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);
+ }
+ }
+ }
+}
* ===============LICENSE_END=======================================================================
*/
-package org.commscope.tr069adapter.vesagent.util;\r
-\r
-/**\r
- * \r
- * @version 1.0\r
- * @since June 5, 2020\r
- * @author Prashant Kumar\r
- */\r
-\r
-public class VesAgentConstants {\r
-\r
- public static final String HEART_BEAT = "heartbeat";\r
-\r
- public static final String HEART_BEAT_PERIOD = "heartbeat.heartbeatPeriod";\r
- public static final String HEART_BEAT_PERIOD_DEFAULT_VAL = "5"; // IN MIUTES\r
-\r
- public static final String COUNT_DOWN_TIMER = "heartbeat.countDownTimer";\r
-\r
- public static final String ENODEB_NAME = "ENODEB_NAME";\r
-\r
- public static final String OBJECT_DATA_TYPE = "object";\r
-\r
- public static final String REMOVE_HEART_BEAT_TIMER_VAL = "0";\r
- public static final int DEVICE_IS_REACHABLE = 100;\r
- public static final String ABORTED_BY_BOOT_BOOTSTRAP = "8002";\r
-\r
- public static final int RPC_SUCCESS = 0;\r
- public static final int RPC_FAILED = 1;\r
- public static final String INVALID_ARGUMENTS = "9003";\r
- public static final String INVALID_PARAMETER_NAME = "9005";\r
- public static final String INVALID_PARAMETER_VALUE = "9007";\r
-\r
-\r
-}\r
+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";
+
+
+}
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;
public class VesAgentUtils {
+ private VesAgentUtils() {}
+
private static final Log logger = LogFactory.getLog(VesAgentUtils.class);
private static String errorMsg = null;