From 149a57edf72762c7e0eb4062851c06356e6a75ab Mon Sep 17 00:00:00 2001 From: herbert Date: Thu, 30 Jan 2020 12:08:35 +0100 Subject: SDN-R add updated devicemanager add updated devicemanager and specific devicemanagers Issue-ID: SDNC-1039 Signed-off-by: herbert Change-Id: I16f4c8d78da95ab12dbb50e50dfb561a85e8d6a2 Signed-off-by: herbert --- .../sdnr/wt/devicemanager/test/TestAai.java | 241 +++++++++++++++++ .../sdnr/wt/devicemanager/test/TestAkkaConfig.java | 136 ++++++++++ .../sdnr/wt/devicemanager/test/TestDcae.java | 208 +++++++++++++++ .../test/TestDevMgrPropertiesFile.java | 279 ++++++++++++++++++++ .../sdnr/wt/devicemanager/test/TestGeoConfig.java | 63 +++++ .../test/TestMaintenanceTimeFilter.java | 62 +++++ .../sdnr/wt/devicemanager/test/TestNameSpace.java | 50 ++++ .../wt/devicemanager/test/TestNotification.java | 41 +++ .../devicemanager/test/TestsNectconfDateTime.java | 116 +++++++++ .../mock/ClusterSingletonServiceProviderMock.java | 37 +++ .../test/mock/DataBrokerMountpointMock.java | 77 ++++++ .../test/mock/DataBrokerNetconfMock.java | 76 ++++++ .../devicemanager/test/mock/DataProviderMock.java | 105 ++++++++ .../wt/devicemanager/test/mock/MountPointMock.java | 90 +++++++ .../test/mock/MountPointServiceMock.java | 54 ++++ .../test/mock/NetconfNodeStateServiceMock.java | 71 +++++ .../test/mock/NotificationPublishServiceMock.java | 49 ++++ .../test/mock/RpcConsumerRegistryMock.java | 39 +++ .../test/mock/RpcProviderRegistryMock.java | 44 ++++ .../test/util/DBCleanServiceHelper.java | 83 ++++++ .../test/util/NetconfTimeStampOld.java | 285 +++++++++++++++++++++ .../sdnr/wt/devicemanager/test/util/ZipFile.java | 63 +++++ 22 files changed, 2269 insertions(+) create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAai.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAkkaConfig.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDcae.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDevMgrPropertiesFile.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestGeoConfig.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestMaintenanceTimeFilter.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNameSpace.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNotification.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestsNectconfDateTime.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/ClusterSingletonServiceProviderMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerMountpointMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerNetconfMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataProviderMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointServiceMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NetconfNodeStateServiceMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NotificationPublishServiceMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcConsumerRegistryMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcProviderRegistryMock.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/DBCleanServiceHelper.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/NetconfTimeStampOld.java create mode 100644 sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/ZipFile.java (limited to 'sdnr/wt/devicemanager/provider/src/test/java') diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAai.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAai.java new file mode 100644 index 000000000..c1d24b4d1 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAai.java @@ -0,0 +1,241 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.fail; + +import com.google.common.io.Files; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.util.ResourceFileLoader; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.AaiProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.config.AaiConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.types.InventoryInformationDcae; + +public class TestAai { + + private static final String CONFIGURATIONTESTFILE = "test.properties"; // for + private static final String ENABLEDAAI_TESTCONFIG_FILENAME = "test2.properties"; + private static final File ENABLEDAAI_TESTCONFIG_FILE = new File(ENABLEDAAI_TESTCONFIG_FILENAME); + private static final int AAI_SERVER_PORT=45454; + private static final String TESTCONFIG_CONTENT="[dcae]\n" + + "dcaeUserCredentials=admin:admin\n" + + "dcaeUrl=off\n" + + "dcaeHeartbeatPeriodSeconds=120\n" + + "dcaeTestCollector=no\n" + + "\n" + + "[aots]\n" + + "userPassword=passwd\n" + + "soapurladd=off\n" + + "soapaddtimeout=10\n" + + "soapinqtimeout=20\n" + + "userName=user\n" + + "inqtemplate=inqreq.tmpl.xml\n" + + "assignedto=userid\n" + + "addtemplate=addreq.tmpl.xml\n" + + "severitypassthrough=critical,major,minor,warning\n" + + "systemuser=user\n" + + "prt-offset=1200\n" + + "soapurlinq=off\n" + + "#smtpHost=\n" + + "#smtpPort=\n" + + "#smtpUsername=\n" + + "#smtpPassword=\n" + + "#smtpSender=\n" + + "#smtpReceivers=\n" + + "\n" + + "[es]\n" + + "esCluster=sendateodl5\n" + + "\n" + + "[aai]\n" + + "#keep comment\n" + + "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + + "aaiUrl=http://localhost:"+AAI_SERVER_PORT+"\n" + + "aaiUserCredentials=AAI:AAI\n" + + "aaiDeleteOnMountpointRemove=true\n" + + "aaiTrustAllCerts=false\n" + + "aaiApiVersion=aai/v13\n" + + "aaiPropertiesFile=aaiclient.properties\n" + + "aaiApplicationId=SDNR\n" + + "aaiPcks12ClientCertFile=/opt/logs/externals/data/stores/keystore.client.p12\n" + + "aaiPcks12ClientCertPassphrase=adminadmin\n" + + "aaiClientConnectionTimeout=30000\n" + + "\n" + + "[pm]\n" + + "pmCluster=sendateodl5\n" + + "pmEnabled=true\n" + + "\n" + + ""; + private HttpServer server; + private ExecutorService httpThreadPool; + private ConfigurationFileRepresentation globalCfg; + + @Test + public void test() { + + String testConfigurationFileName = ResourceFileLoader.getFile(this, CONFIGURATIONTESTFILE).getAbsolutePath(); + ConfigurationFileRepresentation cfg=new ConfigurationFileRepresentation(testConfigurationFileName); + + AaiProviderClient provider = new AaiProviderClient(cfg, null); + + String mountPointName = "testDevice 01"; + String type="Unit"; + String model="Horizon Compact+"; + String vendor="DragonWave-X"; + String ipv4="127.0.0.1"; + String ipv6="::1"; + List ifInfos = new ArrayList<>(); + ifInfos.add("LP-MWPS-RADIO"); + InventoryInformationDcae ii=new InventoryInformationDcae(type, model, vendor, ipv4, ipv6, ifInfos); + System.out.println("registering device"); + provider.onDeviceRegistered(mountPointName,ii); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("unregistering device"); + provider.onDeviceUnregistered(mountPointName); + System.out.println("finished"); + try { + provider.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + @Test + public void test2() { + try { + Thread.sleep(3000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + AaiProviderClient provider = new AaiProviderClient(globalCfg, null); + + String mountPointName = "testDevice 01"; + String type="Unit"; + String model="Horizon Compact+"; + String vendor="DragonWave-X"; + String ipv4="127.0.0.1"; + String ipv6="::1"; + List ifInfos = new ArrayList<>(); + ifInfos.add("LP-MWPS-RADIO"); + InventoryInformationDcae ii=new InventoryInformationDcae(type, model, vendor, ipv4, ipv6, ifInfos); + System.out.println("registering device"); + provider.onDeviceRegistered(mountPointName); + provider.onDeviceRegistered(mountPointName,ii); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("unregistering device"); + provider.onDeviceUnregistered(mountPointName); + System.out.println("finished"); + try { + provider.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + @Before + public void initAaiTestWebserver() throws IOException { + try { + Files.asCharSink(ENABLEDAAI_TESTCONFIG_FILE, StandardCharsets.UTF_8).write(TESTCONFIG_CONTENT); + } catch (IOException e1) { + fail(e1.getMessage()); + } + //globalCfg=HtDevicemanagerConfiguration.getTestConfiguration(ENABLEDAAI_TESTCONFIG_FILENAME,true); + globalCfg = new ConfigurationFileRepresentation(ENABLEDAAI_TESTCONFIG_FILENAME); + this.server = HttpServer.create(new InetSocketAddress(AAI_SERVER_PORT), 0); + this.httpThreadPool = Executors.newFixedThreadPool(5); + this.server.setExecutor(this.httpThreadPool); + AaiConfig config = new AaiConfig(globalCfg); + this.server.createContext(config.getBaseUri(), new MyHandler()); + //server.createContext("/", new MyRootHandler()); + this.server.setExecutor(null); // creates a default executor + this.server.start(); + System.out.println("http server started"); + } + + @After + public void stopTestWebserver() { + if (this.server != null) { + this.server.stop(0); + this.httpThreadPool.shutdownNow(); + System.out.println("http server stopped" ); + } + if (ENABLEDAAI_TESTCONFIG_FILE.exists()) { + ENABLEDAAI_TESTCONFIG_FILE.delete(); + } + + } + static class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println("req method: " + method); + OutputStream os = null; + try { + String res=""; + if (method.equals("GET")) { + t.sendResponseHeaders(404,res.length() ); + os = t.getResponseBody(); + os.write(res.getBytes()); + } else if (method.equals("DELETE")) { + t.sendResponseHeaders(200, res.length()); + os = t.getResponseBody(); + os.write(res.getBytes()); + } else if (method.equals("PUT")) { + t.sendResponseHeaders(200, res.length()); + os = t.getResponseBody(); + os.write(res.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finally { + if (os != null) + { + os.close(); + } + } + } + } +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAkkaConfig.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAkkaConfig.java new file mode 100644 index 000000000..7bc30550f --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestAkkaConfig.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.fail; +import java.io.File; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka.AkkaConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlAkka.ClusterNodeInfo; + +public class TestAkkaConfig { + + private static String getAkkaConfigSingleNodeText() { + return "\n" + "odl-cluster-data {\n" + " akka {\n" + " remote {\n" + " artery {\n" + + " enabled = off\n" + " canonical.hostname = \"127.0.0.1\"\n" + + " canonical.port = 2550\n" + " }\n" + " netty.tcp {\n" + + " hostname = \"127.0.0.1\"\n" + " port = 2550\n" + " }\n" + + " # when under load we might trip a false positive on the failure detector\n" + + " # transport-failure-detector {\n" + " # heartbeat-interval = 4 s\n" + + " # acceptable-heartbeat-pause = 16s\n" + " # }\n" + " }\n" + "\n" + " cluster {\n" + + " # Remove \".tcp\" when using artery.\n" + + " seed-nodes = [\"akka.tcp://opendaylight-cluster-data@127.0.0.1:2550\"]\n" + "\n" + + " roles = [\n" + " \"member-1\"\n" + " ]\n" + "\n" + " }\n" + "\n" + + " persistence {\n" + + " # By default the snapshots/journal directories live in KARAF_HOME. You can choose to put it somewhere else by\n" + + " # modifying the following two properties. The directory location specified may be a relative or absolute path. \n" + + " # The relative path is always relative to KARAF_HOME.\n" + "\n" + + " # snapshot-store.local.dir = \"target/snapshots\"\n" + + " # journal.leveldb.dir = \"target/journal\"\n" + "\n" + " journal {\n" + + " leveldb {\n" + " # Set native = off to use a Java-only implementation of leveldb.\n" + + " # Note that the Java-only version is not currently considered by Akka to be production quality.\n" + + "\n" + " # native = off\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; + } + + private static String getAkkaConfigClusterNodeText() { + return "\n" + "odl-cluster-data {\n" + "\n" + " akka {\n" + " loglevel = \"\"\n" + " remote {\n" + + " netty.tcp {\n" + " hostname = \"zltcmtn23arbc01.2f0377.mtn23a.tci.att.com\"\n" + + " port = 2550\n" + " }\n" + " }\n" + " actor {\n" + " debug{\n" + + " autoreceive = on\n" + " lifecycle = on\n" + " unhandled = on\n" + + " fsm = on\n" + " event-stream = on\n" + " }\n" + " }\n" + " cluster {\n" + + " seed-nodes = [\"akka.tcp://opendaylight-cluster-data@zltcmtn23arbc01.2f0377.mtn23a.tci.att.com:2550\", \"akka.tcp://opendaylight-cluster-data@zltcmtn23arbc02.2f0377.mtn23a.tci.att.com:2550\", \"akka.tcp://opendaylight-cluster-data@zltcmtn23arbc03.2f0377.mtn23a.tci.att.com:2550\", \"akka.tcp://opendaylight-cluster-data@zltcmtn23brbc01.f84e7a.mtn23b.tci.att.com:2550\", \"akka.tcp://opendaylight-cluster-data@zltcmtn23brbc02.f84e7a.mtn23b.tci.att.com:2550\", \"akka.tcp://opendaylight-cluster-data@zltcmtn23brbc03.f84e7a.mtn23b.tci.att.com:2550\"]\n" + + " seed-node-timeout = 15s\n" + " roles = [\"member-1\"]\n" + "\n" + " }\n" + + " persistence {\n" + " journal-plugin-fallback {\n" + " circuit-breaker {\n" + + " max-failures = 10\n" + " call-timeout = 60s\n" + + " reset-timeout = 30s\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}\n" + "\n" + + "odl-cluster-rpc {\n" + "\n" + " akka {\n" + " loglevel = \"\"\n" + " remote {\n" + + " netty.tcp {\n" + " hostname = \"zltcmtn23arbc01.2f0377.mtn23a.tci.att.com\"\n" + + " port = 2551\n" + " }\n" + " }\n" + " actor {\n" + " debug{\n" + + " autoreceive = on\n" + " lifecycle = on\n" + " unhandled = on\n" + + " fsm = on\n" + " event-stream = on\n" + " }\n" + " }\n" + " cluster {\n" + + " seed-nodes = [\"akka.tcp://odl-cluster-rpc@zltcmtn23arbc01.2f0377.mtn23a.tci.att.com:2551\", \"akka.tcp://odl-cluster-rpc@zltcmtn23arbc02.2f0377.mtn23a.tci.att.com:2551\", \"akka.tcp://odl-cluster-rpc@zltcmtn23arbc03.2f0377.mtn23a.tci.att.com:2551\", \"akka.tcp://odl-cluster-rpc@zltcmtn23brbc01.f84e7a.mtn23b.tci.att.com:2551\", \"akka.tcp://odl-cluster-rpc@zltcmtn23brbc02.f84e7a.mtn23b.tci.att.com:2551\", \"akka.tcp://odl-cluster-rpc@zltcmtn23brbc03.f84e7a.mtn23b.tci.att.com:2551\"]\n" + + " seed-node-timeout = 15s\n" + " }\n" + " persistence {\n" + + " journal-plugin-fallback {\n" + " circuit-breaker {\n" + " max-failures = 10\n" + + " call-timeout = 60s\n" + " reset-timeout = 30s\n" + " }\n" + " }\n" + + " }\n" + " }\n" + "}\n" + "\n" + ""; + } + + @Test + public void test1() { + AkkaConfig cfg; + try { + System.out.println("testing clusternode config1"); + System.out.println("==========================="); + cfg = AkkaConfig.parse(getAkkaConfigClusterNodeText()); + System.out.println("succeeded: "); + System.out.println(cfg.toString()); + System.out.println(String.format("found %d cluster nodes", cfg.getClusterConfig().getSeedNodes().size())); + for (ClusterNodeInfo n : cfg.getClusterConfig().getSeedNodes()) { + System.out.println(n.toString()); + } + } catch (Exception e) { + String failMessage = "failed: " + e.getMessage(); + System.out.println(failMessage); + fail(failMessage); + } + } + + @Test + public void test2() { + AkkaConfig cfg; + try { + System.out.println("testing singlenode config1"); + System.out.println("==========================="); + cfg = AkkaConfig.parse(getAkkaConfigSingleNodeText()); + System.out.println("succeeded: "); + System.out.println(cfg.toString()); + } catch (Exception e) { + String failMessage = "failed: " + e.getMessage(); + System.out.println(failMessage); + fail(failMessage); + } + } + + @Test + public void test3() { + AkkaConfig cfg; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("captured-akka.conf").getFile()); + System.out.println(file.getAbsolutePath()); + + try { + System.out.println("testing clusternode config1"); + System.out.println("==========================="); + cfg = AkkaConfig.load(file.getAbsolutePath()); + System.out.println("succeeded: "+cfg.hashCode()); + System.out.println(cfg.toString()); + System.out.println(String.format("found %d cluster nodes", cfg.getClusterConfig().getSeedNodes().size())); + for (ClusterNodeInfo n : cfg.getClusterConfig().getSeedNodes()) { + System.out.println(n.toString()); + } + } catch (Exception e) { + String failMessage = "failed: " + e.getMessage(); + System.out.println(failMessage); + fail(failMessage); + } + } +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDcae.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDcae.java new file mode 100644 index 000000000..3f0f14839 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDcae.java @@ -0,0 +1,208 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeProviderClient; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.types.InventoryInformationDcae; +import com.google.common.io.Files; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +@SuppressWarnings("restriction") +public class TestDcae { + + private static final String ENABLEDDCAE_TESTCONFIG_FILENAME = "test2.properties"; + private static final File ENABLEDDCAE_TESTCONFIG_FILE = new File(ENABLEDDCAE_TESTCONFIG_FILENAME); + private static final int DCAE_SERVER_PORT=45451; + private static final String URI = "/abc"; + private static final String TESTCONFIG_CONTENT="[dcae]\n" + + "dcaeUserCredentials=admin:admin\n" + + "dcaeUrl=http://localhost:"+DCAE_SERVER_PORT+URI+"\n" + + "dcaeHeartbeatPeriodSeconds=120\n" + + "dcaeTestCollector=no\n" + + "\n" + + "[aots]\n" + + "userPassword=passwd\n" + + "soapurladd=off\n" + + "soapaddtimeout=10\n" + + "soapinqtimeout=20\n" + + "userName=user\n" + + "inqtemplate=inqreq.tmpl.xml\n" + + "assignedto=userid\n" + + "addtemplate=addreq.tmpl.xml\n" + + "severitypassthrough=critical,major,minor,warning\n" + + "systemuser=user\n" + + "prt-offset=1200\n" + + "soapurlinq=off\n" + + "#smtpHost=\n" + + "#smtpPort=\n" + + "#smtpUsername=\n" + + "#smtpPassword=\n" + + "#smtpSender=\n" + + "#smtpReceivers=\n" + + "\n" + + "[es]\n" + + "esCluster=sendateodl5\n" + + "\n" + + "[aai]\n" + + "#keep comment\n" + + "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + + "aaiUrl=off\n" + + "aaiUserCredentials=AAI:AAI\n" + + "aaiDeleteOnMountpointRemove=true\n" + + "aaiTrustAllCerts=false\n" + + "aaiApiVersion=aai/v13\n" + + "aaiPropertiesFile=aaiclient.properties\n" + + "aaiApplicationId=SDNR\n" + + "aaiPcks12ClientCertFile=/opt/logs/externals/data/stores/keystore.client.p12\n" + + "aaiPcks12ClientCertPassphrase=adminadmin\n" + + "aaiClientConnectionTimeout=30000\n" + + "\n" + + "[pm]\n" + + "pmCluster=sendateodl5\n" + + "pmEnabled=true\n" + + "\n" + + ""; + private HttpServer server; + private ExecutorService httpThreadPool; + private ConfigurationFileRepresentation cfg; + + @Test + public void test2() { + try { + Thread.sleep(3000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + DcaeProviderClient provider = new DcaeProviderClient(cfg,"mountpoint",null); + + String mountPointName = "testDevice 01"; + String type="Unit"; + String model="Horizon Compact+"; + String vendor="DragonWave-X"; + String ipv4="127.0.0.1"; + String ipv6="::1"; + List ifInfos = new ArrayList<>(); + ifInfos.add("LP-MWPS-RADIO"); + new InventoryInformationDcae(type, model, vendor, ipv4, ipv6, ifInfos); + System.out.println("registering device"); + boolean neDeviceAlarm = false; + ProblemNotificationXml notification = new ProblemNotificationXml(mountPointName, "network-element", "problemName", InternalSeverity.Critical,123, InternalDateAndTime.getTestpattern()); + provider.sendProblemNotification(mountPointName, notification, neDeviceAlarm); + + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + try { + provider.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Before + public void initDcaeTestWebserver() throws IOException { + try { + Files.asCharSink(ENABLEDDCAE_TESTCONFIG_FILE, StandardCharsets.UTF_8).write(TESTCONFIG_CONTENT); + } catch (IOException e1) { + fail(e1.getMessage()); + } + cfg = new ConfigurationFileRepresentation(ENABLEDDCAE_TESTCONFIG_FILENAME); + // cfg.reload(ENABLEDDCAE_TESTCONFIG_FILENAME); + /* + * cfg = new HtDevicemanagerConfiguration(ENABLEDDCAE_TESTCONFIG_FILENAME); + * DcaeConfig.reload(); + */ + try { + this.server = HttpServer.create(new InetSocketAddress(DCAE_SERVER_PORT), 0); + } catch (Exception e) { + fail(e.getMessage()); + } + this.httpThreadPool = Executors.newFixedThreadPool(5); + this.server.setExecutor(this.httpThreadPool); + this.server.createContext(URI, new MyHandler()); + // server.createContext("/", new MyRootHandler()); + this.server.setExecutor(null); // creates a default executor + this.server.start(); + System.out.println("http server started"); + } + + @After + public void stopTestWebserver() { + if (this.server != null) { + this.server.stop(0); + this.httpThreadPool.shutdownNow(); + System.out.println("http server stopped"); + } + if (ENABLEDDCAE_TESTCONFIG_FILE.exists()) { + ENABLEDDCAE_TESTCONFIG_FILE.delete(); + } + } + + static class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println("req method: " + method); + OutputStream os = null; + try { + String res = ""; + if (method.equals("POST")) { + t.sendResponseHeaders(200, res.length()); + os = t.getResponseBody(); + os.write(res.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } finally { + if (os != null) { + os.close(); + } + } + } + } +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDevMgrPropertiesFile.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDevMgrPropertiesFile.java new file mode 100644 index 000000000..ff15f7991 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestDevMgrPropertiesFile.java @@ -0,0 +1,279 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.aaiconnector.impl.config.AaiConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.archiveservice.ArchiveCleanService; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.config.DcaeConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.performancemanager.impl.config.PmConfig; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.conf.ToggleAlarmConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.Files; + +public class TestDevMgrPropertiesFile { + + private static final Logger LOG = LoggerFactory.getLogger(ArchiveCleanService.class); + + private static final File FILENAME = new File("test.properties"); + private static final File AAIPROP_FILE=new File("aaiclient.properties"); + private int hasChanged; + + @Before + public void init() { + //if (! LOG.isDebugEnabled()) { + delete(FILENAME); + delete(AAIPROP_FILE); + //} + } + @After + public void deinit() { + this.init(); + } + + @Test + public void test1() { + + writeFile(FILENAME, this.getContent1()); + writeFile(AAIPROP_FILE, this.getAaiPropertiesConfig()); + + System.out.println("Read and verify"); + ConfigurationFileRepresentation cfg = new ConfigurationFileRepresentation(FILENAME.getPath()); + ConfigurationFileRepresentation cfg2 = cfg; + + AaiConfig aaiConfig = new AaiConfig(cfg2); + assertNotNull(aaiConfig); + DcaeConfig dcaeConfig = new DcaeConfig(cfg2); + assertNotNull(dcaeConfig); + PmConfig pmConfig = new PmConfig(cfg2); + assertNotNull(pmConfig); + ToggleAlarmConfig toggleAlarmConfig = new ToggleAlarmConfig(cfg2); + assertNotNull(toggleAlarmConfig); + + System.out.println("Verify\n"+aaiConfig+"\n"); + @SuppressWarnings("unused") + boolean res; + /* + res = cfg.getAai().equals(AaiConfig.getDefaultConfiguration()); + res = cfg.getDcae().equals(DcaeConfig.getDefaultConfiguration()); + res = cfg.getPm().equals(PmConfig.getDefaultConfiguration()); + res = cfg.getEs().equals(EsConfig.getDefaultConfiguration()); + res = cfg.getToggleAlarm().equals(ToggleAlarmConfig.getDefaultConfiguration()); + + res = cfg.getAai().hashCode() == AaiConfig.getDefaultConfiguration().hashCode(); + res = cfg.getDcae().hashCode() == DcaeConfig.getDefaultConfiguration().hashCode(); + res = cfg.getPm().hashCode() == PmConfig.getDefaultConfiguration().hashCode(); + res = cfg.getEs().hashCode() == EsConfig.getDefaultConfiguration().hashCode(); + res = cfg.getToggleAlarm().hashCode() == ToggleAlarmConfig.getDefaultConfiguration().hashCode(); + */ + } + + //-- Observer not working with all testcases, because config does not support different file types. + @Test + public void test2() { + + hasChanged=0; + writeFile(FILENAME, this.getContent1()); + writeFile(AAIPROP_FILE, this.getAaiPropertiesConfig()); + + System.out.println("Read and verify"); + ConfigurationFileRepresentation cfg2 = new ConfigurationFileRepresentation(FILENAME.getPath()); + + AaiConfig aaiConfig = new AaiConfig(cfg2); + assertNotNull(aaiConfig); + DcaeConfig dcaeConfig = new DcaeConfig(cfg2); + assertNotNull(dcaeConfig); + PmConfig pmConfig = new PmConfig(cfg2); + assertNotNull(pmConfig); + ToggleAlarmConfig toggleAlarmConfig = new ToggleAlarmConfig(cfg2); + assertNotNull(toggleAlarmConfig); + + cfg2.registerConfigChangedListener(() -> { + hasChanged++; + System.out.println("file changed listener triggered: "+hasChanged); + }); + + sleep(1000); + System.out.println("Write new content. Changes "+hasChanged); + writeFile(FILENAME, this.getContent2()); + sleep(1000); + + int i=10; + while(hasChanged == 0 && i-- > 0) { + System.out.println("Wait for Change indication."); + sleep(1000); + } + System.out.println("Changes "+hasChanged); + + assertTrue("fileChanged counter"+hasChanged, hasChanged > 0); + System.out.println("Test done"); + + } + + + private static void sleep(int milliseconds) { + try { + Thread.sleep(milliseconds); + } catch (InterruptedException e) { + } + } + + public static void writeFile(File f, String content) { + try { + Files.asCharSink(f, StandardCharsets.UTF_8).write(content); + } catch (IOException e) { + fail(e.getMessage()); + }; + sleep(500); + } + + private void delete(File f) { + if(f.exists()) { + f.delete(); + } + } + + + private String getContent2() { + return "[dcae]\n" + + "dcaeUserCredentials=admin:admin\n" + + "dcaeUrl=http://localhost:45451/abc\n" + + "dcaeHeartbeatPeriodSeconds=120\n" + + "dcaeTestCollector=no\n" + + "\n" + + "[aots]\n" + + "userPassword=passwd\n" + + "soapurladd=off\n" + + "soapaddtimeout=10\n" + + "soapinqtimeout=20\n" + + "userName=user\n" + + "inqtemplate=inqreq.tmpl.xml\n" + + "assignedto=userid\n" + + "addtemplate=addreq.tmpl.xml\n" + + "severitypassthrough=critical,major,minor,warning\n" + + "systemuser=user\n" + + "prt-offset=1200\n" + + "soapurlinq=off\n" + + "#smtpHost=\n" + + "#smtpPort=\n" + + "#smtpUsername=\n" + + "#smtpPassword=\n" + + "#smtpSender=\n" + + "#smtpReceivers=\n" + + "\n" + + "[es]\n" + + "esCluster=sendateodl5\n" + + "\n" + + "[aai]\n" + + "#keep comment\n" + + "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + + "aaiUrl=off\n" + + "aaiUserCredentials=AAI:AAI\n" + + "aaiDeleteOnMountpointRemove=true\n" + + "aaiTrustAllCerts=false\n" + + "aaiApiVersion=aai/v13\n" + + "aaiPropertiesFile=aaiclient.properties\n" + + "aaiApplicationId=SDNR\n" + + "aaiPcks12ClientCertFile=/opt/logs/externals/data/stores/keystore.client.p12\n" + + "aaiPcks12ClientCertPassphrase=adminadmin\n" + + "aaiClientConnectionTimeout=30000\n" + + "\n" + + "[pm]\n" + + "pmCluster=sendateodl5\n" + + "pmEnabled=true\n" + + "[toggleAlarmFilter]\n" + + "taEnabled=true\n" + + "taDelay=5555\n" + + ""; + } + + private String getContent1() { + return "[dcae]\n" + + "dcaeUserCredentials=admin:admin\n" + + "dcaeUrl=http://localhost:45/abc\n" + + "dcaeHeartbeatPeriodSeconds=120\n" + + "dcaeTestCollector=no\n" + + "\n" + + "[aots]\n" + + "userPassword=passwd\n" + + "soapurladd=off\n" + + "soapaddtimeout=10\n" + + "soapinqtimeout=20\n" + + "userName=user\n" + + "inqtemplate=inqreq.tmpl.xml\n" + + "assignedto=userid\n" + + "addtemplate=addreq.tmpl.xml\n" + + "severitypassthrough=critical,major,minor,warning\n" + + "systemuser=user\n" + + "prt-offset=1200\n" + + "soapurlinq=off\n" + + "#smtpHost=\n" + + "#smtpPort=\n" + + "#smtpUsername=\n" + + "#smtpPassword=\n" + + "#smtpSender=\n" + + "#smtpReceivers=\n" + + "\n" + + "[es]\n" + + "esCluster=sendateodl5\n" + + "\n" + + "[aai]\n" + + "#keep comment\n" + + "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + + "aaiUrl=off\n" + + "aaiUserCredentials=AAI:AAI\n" + + "aaiDeleteOnMountpointRemove=true\n" + + "aaiTrustAllCerts=false\n" + + "aaiApiVersion=aai/v13\n" + + "aaiPropertiesFile=aaiclient.properties\n" + + "\n" + + "[pm]\n" + + "pmCluster=sendateodl5\n" + + "pmEnabled=true\n" + + "[toggleAlarmFilter]\n" + + "taEnabled=false\n" + + "taDelay=5555\n" + + ""; + } + private String getAaiPropertiesConfig() { + return "org.onap.ccsdk.sli.adaptors.aai.ssl.key=keykey\"\"\n" + + "org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd=psswdpsswd\"\"\n" + + "org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore=\"false\"\n" + + "org.onap.ccsdk.sli.adaptors.aai.application=appxyz\"\"\n" + + "org.onap.ccsdk.sli.adaptors.aai.uri=uriu\"\"\n" + + "connection.timeout=60000\n" + + "read.timeout=60000"; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestGeoConfig.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestGeoConfig.java new file mode 100644 index 000000000..6474a1eb6 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestGeoConfig.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.*; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.conf.odlGeo.GeoConfig; + +public class TestGeoConfig { + + @Test + public void test() { + GeoConfig config; + try { + System.out.println("testing clusternode geo config1"); + System.out.println("==========================="); + config = GeoConfig.parse(getClusterGeoConfigContent()); + System.out.println("succeeded: "); + System.out.println(config.toString()); + System.out.println("primary roles:"); + System.out.println(config.getPrimaryRoles().toString()); + System.out.println("secondary roles:"); + System.out.println(config.getSecondaryRoles().toString()); + + } catch (Exception e) { + fail("failed: " + e.getMessage()); + } + } + + + + private static String getClusterGeoConfigContent() { + return "\n" + "lumina-geo-cluster {\n" + " primary_roles = [\n" + + " \"member-1\",\"member-2\",\"member-3\"\n" + " ]\n" + " secondary_roles = [\n" + + " \"member-4\",\"member-5\",\"member-6\"\n" + " ]\n" + " ip_roles_table = [\n" + "\n" + + " {\n" + "role=\"member-1\"\n" + "ip=\"zltcmtn23arbc01.2f0377.mtn23a.tci.att.com\"\n" + "},\n" + + "{\n" + "role=\"member-2\"\n" + "ip=\"zltcmtn23arbc02.2f0377.mtn23a.tci.att.com\"\n" + "},\n" + "{\n" + + "role=\"member-3\"\n" + "ip=\"zltcmtn23arbc03.2f0377.mtn23a.tci.att.com\"\n" + "},\n" + "{\n" + + "role=\"member-4\"\n" + "ip=\"zltcmtn23brbc01.f84e7a.mtn23b.tci.att.com\"\n" + "},\n" + "{\n" + + "role=\"member-5\"\n" + "ip=\"zltcmtn23brbc02.f84e7a.mtn23b.tci.att.com\"\n" + "},\n" + "{\n" + + "role=\"member-6\"\n" + "ip=\"zltcmtn23brbc03.f84e7a.mtn23b.tci.att.com\"\n" + "}\n" + " \n" + + " ]\n" + "}\n" + "\n" + "\n" + "\n" + "\n" + ""; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestMaintenanceTimeFilter.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestMaintenanceTimeFilter.java new file mode 100644 index 000000000..932ad52d2 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestMaintenanceTimeFilter.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import java.time.ZonedDateTime; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.maintenance.impl.MaintenanceCalculator; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; + +public class TestMaintenanceTimeFilter { + + private static String DEFAULT1 = "EsMaintenanceFilter [start=1970-01-01T00:00Z[UTC], end=1970-01-01T00:00Z[UTC], definition=EsMaintenanceFilterDefinition [objectIdRef=, problem=], description=]"; + private static String DEFAULT2 = "EsMaintenanceFilter [start=1970-01-01T00:00Z[UTC], end=2018-01-01T10:00+05:00, definition=EsMaintenanceFilterDefinition [objectIdRef=, problem=], description=]"; + + @Test + public void test1() { + + boolean res; + + DateAndTime start = new DateAndTime("2018-01-01T10:00:00+05:00"); + DateAndTime end = new DateAndTime("2019-01-01T10:00:00+05:00"); + ZonedDateTime now; + + now = ZonedDateTime.parse("2017-05-01T10:00:00+05:00"); + res = MaintenanceCalculator.isInPeriod(start, end, now); + System.out.println("Before: " + res); + assertFalse("before period", res); + + now = ZonedDateTime.parse("2018-05-01T10:00:00+05:00"); + res = MaintenanceCalculator.isInPeriod(start, end, now); + System.out.println("Within: " + res); + assertTrue("within period",res); + + now = ZonedDateTime.parse("2019-05-01T10:00:00+05:00"); + res = MaintenanceCalculator.isInPeriod(start, end, now); + System.out.println("After: " + res); + assertFalse("after period", res); + + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNameSpace.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNameSpace.java new file mode 100644 index 000000000..e8eef7c77 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNameSpace.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.assertEquals; +import java.net.URISyntaxException; +import org.junit.Test; +import org.opendaylight.yangtools.yang.common.QName; + +public class TestNameSpace { + + private static final String QNAME_COREMODEL_NAMESPACE = "urn:onf:params:xml:ns:yang:core-model"; + private static final QName QNAME_COREMODEL = QName.create(QNAME_COREMODEL_NAMESPACE, "2017-03-20", "core-model").intern(); + + @Test + public void test() throws URISyntaxException { + + QName qname = QName.create("(urn:o-ran:hardware:1.0?revision=2019-03-28)o-ran-hardware"); + + System.out.println("QName getNamespace"+qname.getNamespace()); + assertEquals(qname.getNamespace().toString(),"urn:o-ran:hardware:1.0"); + + System.out.println("QName getRevision"+qname.getRevision()); + assertEquals(qname.getRevision().get().toString(),"2019-03-28"); + + System.out.println(QNAME_COREMODEL.getNamespace().toString()); + assertEquals(QNAME_COREMODEL.getNamespace().toString(), QNAME_COREMODEL_NAMESPACE); + + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNotification.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNotification.java new file mode 100644 index 000000000..7e54f16b1 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestNotification.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.toggleAlarmFilter.NotificationWithServerTimeStamp; + +public class TestNotification { + + @Test + public void test() { + + NotificationWithServerTimeStamp test = new NotificationWithServerTimeStamp<>(1000); + + test.refresh(1000); + test.getStartTime(); + + System.out.println(test); + + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestsNectconfDateTime.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestsNectconfDateTime.java new file mode 100644 index 000000000..390061907 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/TestsNectconfDateTime.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test; + +import static org.junit.Assert.assertTrue; + +import java.util.Date; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStampImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.test.util.NetconfTimeStampOld; + +public class TestsNectconfDateTime { + + private static String[] testPatterPostive = { + "2017-01-18T11:44:49.482-0500", + "2017-01-18T11:44:49.482-05:00", + "20170118114449.123Z", + "20170118114449.1Z", + "20170118114449.1-0500", + "2017-01-23T13:32:38-05:00", + "2017-01-23T13:32-05:00", + "2017-01-18T11:44:49Z" + }; + private static String[] testPatterProblem = { + "2017-01-18T11:44:49" + }; + + + private final static NetconfTimeStampOld netconfTimeConverterOld = NetconfTimeStampOld.getConverter(); + private final static NetconfTimeStamp netconfTimeConverterNew = NetconfTimeStampImpl.getConverter(); + + @Test + public void test1() { + + int t = 1; + String timeNew, timeOld; + for (String testTime : testPatterPostive) { + timeNew = netconfTimeConverterNew.getTimeStampFromNetconf(testTime); + timeOld = netconfTimeConverterOld.getTimeStampFromNetconf(testTime); + + System.out.println("No "+t+++" Pattern: "+testTime); + System.out.println(" to old "+timeOld); + System.out.println(" to new "+timeNew); + System.out.println(); + + assertTrue("Old/New implementation not same "+timeOld+"/"+timeNew, timeOld.equals(timeNew)); + } + + for (String testTime : testPatterProblem) { + timeNew = netconfTimeConverterNew.getTimeStampFromNetconf(testTime); + timeOld = netconfTimeConverterOld.getTimeStampFromNetconf(testTime); + + System.out.println("No "+t+++" Pattern: "+testTime); + System.out.println(" to old "+timeOld); + System.out.println(" to new "+timeNew); + System.out.println(); + + assertTrue("Old/New implementation not same "+timeOld+"/"+timeNew, timeOld.equals(timeNew)); + } + } + + @Test + public void test2() { + + int t = 1; + Long timeNew, timeOld; + for (String testTime : testPatterPostive) { + timeNew = netconfTimeConverterNew.getTimeStampFromNetconfAsMilliseconds(testTime); + timeOld = netconfTimeConverterOld.getTimeStampFromNetconfAsMilliseconds(testTime); + + System.out.println("No "+t+++" Pattern: "+testTime); + System.out.println(" to old "+timeOld); + System.out.println(" to new "+timeNew); + System.out.println(); + + assertTrue("Old/New implementation not same "+timeOld+"/"+timeNew, timeOld.equals(timeNew)); + } + + } + + + @Test + public void test3() { + + Date now = new Date(); + String timeNew = netconfTimeConverterNew.getTimeStampAsNetconfString(now); + String timeOld = netconfTimeConverterOld.getTimeStampAsNetconfString(now); + + System.out.println("Old/New: "+timeOld+"/"+timeNew); + + assertTrue("Old/New implementation not same "+timeOld+"/"+timeNew, timeOld.equals(timeNew)); + + + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/ClusterSingletonServiceProviderMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/ClusterSingletonServiceProviderMock.java new file mode 100644 index 000000000..a215e1883 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/ClusterSingletonServiceProviderMock.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider; +import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration; + +public class ClusterSingletonServiceProviderMock implements ClusterSingletonServiceProvider { + + @Override + public void close() throws Exception { + + } + + @Override + public ClusterSingletonServiceRegistration registerClusterSingletonService(ClusterSingletonService service) { + return null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerMountpointMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerMountpointMock.java new file mode 100644 index 000000000..2bd5a9272 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerMountpointMock.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import org.eclipse.jdt.annotation.NonNull; +import org.opendaylight.mdsal.binding.api.BindingService; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.DataTreeChangeListener; +import org.opendaylight.mdsal.binding.api.DataTreeIdentifier; +import org.opendaylight.mdsal.binding.api.ReadTransaction; +import org.opendaylight.mdsal.binding.api.ReadWriteTransaction; +import org.opendaylight.mdsal.binding.api.TransactionChain; +import org.opendaylight.mdsal.binding.api.TransactionChainListener; +import org.opendaylight.mdsal.binding.api.WriteTransaction; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.DataObject; + +/** + * @author herbert + * + */ +@SuppressWarnings("deprecation") +public class DataBrokerMountpointMock implements DataBroker, BindingService { + + ReadTransaction readOnlyTransaction; + + public void setReadOnlyTransaction(ReadTransaction readOnlyTransaction) { + this.readOnlyTransaction = readOnlyTransaction; + } + + @Override + public @NonNull ReadTransaction newReadOnlyTransaction() { + return readOnlyTransaction; + } + + @Override + public @NonNull ReadWriteTransaction newReadWriteTransaction() { + return null; + } + + @Override + public @NonNull WriteTransaction newWriteOnlyTransaction() { + return null; + } + + @Override + public > @NonNull ListenerRegistration registerDataTreeChangeListener( + @NonNull DataTreeIdentifier treeId, @NonNull L listener) { + return null; + } + + @Override + public @NonNull TransactionChain createTransactionChain(@NonNull TransactionChainListener listener) { + return null; + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerNetconfMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerNetconfMock.java new file mode 100644 index 000000000..0b5052632 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataBrokerNetconfMock.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import org.eclipse.jdt.annotation.NonNull; +import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.DataTreeChangeListener; +import org.opendaylight.mdsal.binding.api.DataTreeIdentifier; +import org.opendaylight.mdsal.binding.api.ReadTransaction; +import org.opendaylight.mdsal.binding.api.ReadWriteTransaction; +import org.opendaylight.mdsal.binding.api.TransactionChain; +import org.opendaylight.mdsal.binding.api.TransactionChainListener; +import org.opendaylight.mdsal.binding.api.WriteTransaction; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.DataObject; + +/** + * @author herbert + * + */ +@SuppressWarnings("deprecation") +public class DataBrokerNetconfMock implements DataBroker { + + + ReadTransaction readOnlyTransaction; + + public void setReadOnlyTransaction(ReadTransaction readOnlyTransaction) { + this.readOnlyTransaction = readOnlyTransaction; + } + + @Override + public @NonNull ReadTransaction newReadOnlyTransaction() { + return readOnlyTransaction; + } + + @Override + public @NonNull ReadWriteTransaction newReadWriteTransaction() { + return null; + } + + @Override + public @NonNull WriteTransaction newWriteOnlyTransaction() { + return null; + } + + @Override + public > @NonNull ListenerRegistration registerDataTreeChangeListener( + @NonNull DataTreeIdentifier treeId, @NonNull L listener) { + return null; + } + + @Override + public @NonNull TransactionChain createTransactionChain(@NonNull TransactionChainListener listener) { + return null; + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataProviderMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataProviderMock.java new file mode 100644 index 000000000..00edbe2ed --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/DataProviderMock.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt sdnr-wt-devicemanager-provider + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultcurrentEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.FaultlogEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Inventory; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionEntity; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.PmdataEntity; + +public class DataProviderMock implements DataProvider { + + @Override + public void writeConnectionLog(ConnectionlogEntity event) { + } + + @Override + public void writeEventLog(EventlogEntity event) { + } + + @Override + public void writeFaultLog(FaultlogEntity fault) { + } + + @Override + public void updateFaultCurrent(FaultcurrentEntity fault) { + } + + @Override + public int clearFaultsCurrentOfNode(String nodeName) { + return 0; + } + + @Override + public int clearFaultsCurrentOfNodeWithObjectId(String nodeName, String objectId) { + return 0; + } + + @Override + public List getAllNodesWithCurrentAlarms() { + return new ArrayList<>(); + } + + @Override + public void writeInventory(Inventory internalEquipment) { + } + + @Override + public void updateNetworkConnectionDeviceType(NetworkElementConnectionEntity networkElementConnectionEntitiy, + String nodeId) { + } + + @Override + public void updateNetworkConnection22(NetworkElementConnectionEntity networkElementConnectionEntitiy, + String nodeId) { + } + + @Override + public void removeNetworkConnection(String nodeId) { + } + + @Override + public int doIndexClean(Date olderAreOutdated) { + return 0; + } + + @Override + public int getNumberOfOldObjects(Date olderAreOutdated) { + return 0; + } + + @Override + public List getNetworkElementConnections() { + return new ArrayList<>(); + } + + @Override + public void doWritePerformanceData(List list) { + } +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointMock.java new file mode 100644 index 000000000..73d32e418 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointMock.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt sdnr-wt-devicemanager-provider + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import java.util.Optional; +import org.opendaylight.mdsal.binding.api.BindingService; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.NotificationService; +import org.opendaylight.mdsal.binding.api.ReadTransaction; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; +import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * @author herbert + * + */ +@SuppressWarnings("deprecation") +public class MountPointMock implements MountPoint { + + private boolean databrokerAbsent = true; + private final DataBrokerMountpointMock dataBroker = new DataBrokerMountpointMock(); + private final RpcConsumerRegistryMock rpcConsumerRegistry = new RpcConsumerRegistryMock(); + private NotificationService setReadOnlyTransaction; + + private static final InstanceIdentifier NETCONF_TOPO_IID = + InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, + new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); + + @Override + public InstanceIdentifier getIdentifier() { + return NETCONF_TOPO_IID; + } + + @SuppressWarnings("unchecked") + @Override + public Optional getService(Class service) { + + System.out.println("Requested mountpoint service: "+service.getSimpleName()+" databrokerAbsent state: "+databrokerAbsent); + + Optional res; + if (service.isInstance(dataBroker)) { + System.out.println("Delivering databroker"); + res = databrokerAbsent ? Optional.empty() : Optional.of(dataBroker); + } else if (service.isInstance(rpcConsumerRegistry)) { + System.out.println("Delivering RpcConsumerRegistryMock"); + res = Optional.of(rpcConsumerRegistry); + } else if (service.isInstance(setReadOnlyTransaction)) { + System.out.println("Delivering notificationService"); + res = Optional.of(setReadOnlyTransaction); + } else { + System.out.println("Delivering no service"); + res = Optional.empty(); + } + return (Optional)res; + } + + public void setDatabrokerAbsent( boolean state) { + this.databrokerAbsent = state; + } + + public void setReadOnlyTransaction(T readOnlyTransaction) { + this.setReadOnlyTransaction = readOnlyTransaction; + dataBroker.setReadOnlyTransaction(readOnlyTransaction); + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointServiceMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointServiceMock.java new file mode 100644 index 000000000..113ead29f --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/MountPointServiceMock.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import java.util.Optional; +import org.opendaylight.mdsal.binding.api.MountPoint; +import org.opendaylight.mdsal.binding.api.MountPointService; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * @author herbert + * + */ +public class MountPointServiceMock implements MountPointService { + + private final MountPoint mountpoint; + + public MountPointServiceMock(MountPoint mountpoint) { + this.mountpoint = mountpoint; + } + + @Override + public Optional getMountPoint(InstanceIdentifier instanceId) { + + Optional optional = Optional.of(mountpoint); + return optional; + } + + @Override + public ListenerRegistration registerListener(InstanceIdentifier path, + T listener) { + return null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NetconfNodeStateServiceMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NetconfNodeStateServiceMock.java new file mode 100644 index 000000000..5a000a52a --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NetconfNodeStateServiceMock.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import org.eclipse.jdt.annotation.NonNull; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeConnectListener; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateListener; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateService; +import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.VesNotificationListener; +import org.opendaylight.yangtools.concepts.ListenerRegistration; + +/** + * @author herbert + * + */ +public class NetconfNodeStateServiceMock implements NetconfNodeStateService { + + Object object = new Object(); + private final ListenerRegistration lr = new ListenerRegistration() { + + @Override + public @NonNull Object getInstance() { + return object; + } + + @Override + public void close() { + } + + }; + + + @Override + public void close() { + } + + @Override + public @NonNull ListenerRegistration registerNetconfNodeConnectListener( + @NonNull L netconfNodeConnectListener) { + return (ListenerRegistration) lr; + } + + @Override + public @NonNull ListenerRegistration registerNetconfNodeStateListener( + @NonNull L netconfNodeStateListener) { + return (ListenerRegistration) lr; + } + + @Override + public @NonNull ListenerRegistration registerVesNotifications( + @NonNull L netconfNodeStateListener) { + return (ListenerRegistration) lr; + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NotificationPublishServiceMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NotificationPublishServiceMock.java new file mode 100644 index 000000000..fc3318b9e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/NotificationPublishServiceMock.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import com.google.common.util.concurrent.ListenableFuture; +import java.util.concurrent.TimeUnit; +import org.opendaylight.mdsal.binding.api.NotificationPublishService; +import org.opendaylight.yangtools.yang.binding.Notification; + +/** + * @author herbert + * + */ +public class NotificationPublishServiceMock implements NotificationPublishService { + + @Override + public ListenableFuture offerNotification(Notification notification) { + return null; + } + + @Override + public ListenableFuture offerNotification(Notification notification, int timeout, TimeUnit unit) + throws InterruptedException { + return null; + } + + @Override + public void putNotification(Notification notification) throws InterruptedException { + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcConsumerRegistryMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcConsumerRegistryMock.java new file mode 100644 index 000000000..89864c2c5 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcConsumerRegistryMock.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt sdnr-wt-devicemanager-provider + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ + +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; +import org.opendaylight.yangtools.yang.binding.RpcService; + +/** + * @author herbert + * + */ +@SuppressWarnings("deprecation") +public class RpcConsumerRegistryMock implements RpcConsumerRegistry { + + @Override + public T getRpcService(Class serviceInterface) { + return null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcProviderRegistryMock.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcProviderRegistryMock.java new file mode 100644 index 000000000..4aaa1ed48 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/mock/RpcProviderRegistryMock.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * ONAP : ccsdk feature sdnr wt + * ================================================================================ + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.mock; + +import java.util.Set; +import org.opendaylight.mdsal.binding.api.RpcProviderService; +import org.opendaylight.yangtools.concepts.ObjectRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.RpcService; + +public class RpcProviderRegistryMock implements RpcProviderService { + + @Override + public ObjectRegistration registerRpcImplementation(Class type, + T implementation) { + System.out.println("Register class "+implementation); + return null; + } + + @Override + public ObjectRegistration registerRpcImplementation(Class type, + T implementation, Set> paths) { + return null; + } + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/DBCleanServiceHelper.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/DBCleanServiceHelper.java new file mode 100644 index 000000000..79688280e --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/DBCleanServiceHelper.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.util; + +import java.util.Date; +import java.util.concurrent.TimeUnit; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.DataProvider; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.NetconfTimeStamp; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStampImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.DeviceManagerImpl; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalDateAndTime; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.util.InternalSeverity; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ObjectCreationNotificationXml; +import org.onap.ccsdk.features.sdnr.wt.devicemanager.impl.xml.ProblemNotificationXml; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType; + +public class DBCleanServiceHelper { + + private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStampImpl.getConverter(); + + private final DataProvider databaseEventService; + + /** + * Helper to fill data into the database + * @param deviceManager devicemanger to get services + */ + public DBCleanServiceHelper(DeviceManagerImpl deviceManager) { + this.databaseEventService = deviceManager.getDatabaseClientEvents(); + } + + /** + * Write data into database with specific date and content profile. + * @param number of data to be written for each log + * @param days starting day, relative to actual date + * @param hours starting hour ... increased by one hour for each write + * @return integer with the amount of written data + */ + public int writeDataToLogs(int number, int days, int hours) { + int res = 0; + for (Integer t=0; t < number; t++) { //Test "sdnevents", "eventlog" + ObjectCreationNotificationXml notificationXml = new ObjectCreationNotificationXml( + "Testpoint"+t, t, getInternalDateAndTime(days, hours+t), "ObjectId"+t); + databaseEventService.writeConnectionLog(notificationXml.getConnectionlogEntity()); + res++; + } + + for (Integer t=0; t < number; t++) { //Test "sdnevents", "faultlog" + ProblemNotificationXml fault = new ProblemNotificationXml( + "ProblemNode"+t, "Problemuuid", "Problemname", InternalSeverity.Major, t, getInternalDateAndTime(days, hours+t)); + databaseEventService.writeFaultLog(fault.getFaultlog(SourceType.Unknown)); + res++; + } + + return res; + } + + /************************************************************** + * Private section + */ + + private InternalDateAndTime getInternalDateAndTime(int days, int hours) { + Date actual = new Date(new Date().getTime() - TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS) - TimeUnit.MILLISECONDS.convert(hours, TimeUnit.HOURS)); + InternalDateAndTime timeStamp = InternalDateAndTime.valueOf(NETCONFTIME_CONVERTER.getTimeStamp(actual)); + return timeStamp; + } + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/NetconfTimeStampOld.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/NetconfTimeStampOld.java new file mode 100644 index 000000000..b81d40d92 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/NetconfTimeStampOld.java @@ -0,0 +1,285 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Function is handling the NETCONF and the format used by database and restconf communication. + * + * Input supported for the formats used in NETCONF messages: + * + * Format1 ISO 8601 2017-01-18T11:44:49.482-05:00 + * + * Format2 NETCONF - pattern from ietf-yang-types "2013-07-15" Pattern: + * "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[\+\-](\d{2}):(\d{2}))" + * + * Format3 NETCONF DateAndTime CoreModel-CoreFoundationModule-TypeDefinitions vom + * 2016-07-01 Example1: 20170118114449.1Z Example2: 20170118114449.1-0500 Pattern: + * "\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}.\d+?(Z|[\+\-](\d{2})(\d{2}))" typedef DateAndTime { description + * "This primitive type defines the date and time according to the following structure: + * 'yyyyMMddhhmmss.s[Z|{+|-}HHMm]' where: yyyy '0000'..'9999' year MM '01'..'12' month dd '01'..'31' + * day hh '00'..'23' hour mm '00'..'59' minute ss '00'..'59' second s '.0'..'.9' tenth of second + * (set to '.0' if EMS or NE cannot support this granularity) Z 'Z' indicates UTC (rather than local + * time) {+|-} '+' or '-' delta from UTC HH '00'..'23' time zone difference in hours Mm '00'..'59' + * time zone difference in minutes."; type string; } Format4 E/// specific Example1: + * 2017-01-23T13:32:38-05:00 Example2: 2017-01-23T13:32-05:00 + * + * Input formats netconfTime as String according the formats given above + * + * Return format is String in ISO8601 Format for database and presentation. + * + * Example formats: + * 1) ISO8601. Example 2017-01-18T11:44:49.482-05:00 + * 2) Microwave ONF. Examples 20170118114449.1Z, 20170118114449.1-0500 + * 3.1) Ericson. Example: 2017-01-23T13:32:38-05:00 + * 3.2) Ericson. Example: 2017-01-23T13:32-05:00 + * Always 10 Groups, + * 1:Year 2:Month 3:day 4:Hour 5:minute 6:optional sec 7:optional ms 8:optional Z or 9:offset + * signedhour 10:min + * + * Template: + * private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + */ + +public class NetconfTimeStampOld { + private static final Logger LOG = LoggerFactory.getLogger(NetconfTimeStampOld.class); + + private static final NetconfTimeStampOld CONVERTER = new NetconfTimeStampOld(); + + private final SimpleDateFormat dateFormatResult = init("yyyy-MM-dd'T'HH:mm:ss.S'Z'", TimeZone.getTimeZone("GMT")); + private final SimpleDateFormat dateFormatConvert = init("yyyy-MM-dd HH:mm:ss.S", TimeZone.getTimeZone("GMT")); + private static int MILLISECONDSDIGITS = 3; // Digits of milliseconds in dateFormatResult + private static String MILLISECONDZEROS = "000"; // String with zeros for milliseconds in dateFormatResult + private static final Pattern dateNetconfPatter = Pattern.compile( + "(\\d{4})-?(\\d{2})-?(\\d{2})T?(\\d{2}):?(\\d{2})(?:(?::?)(\\d{2}))?(?:.(\\d+))?(?:(Z)|([+-]\\d{2}):?(\\d{2}))"); + + /* + * ------------------------------------ Public function + */ + + /** + * Use static access + */ + private NetconfTimeStampOld() { + } + + /** + * Use this function to get the converter + * @return global converter + */ + public static NetconfTimeStampOld getConverter() { + return CONVERTER; + } + + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format + * + * @return String with Date in NETCONF/YANG Format Version 1.0. + */ + public String getTimeStampAsNetconfString() { + return this.getRightFormattedDate(new Date().getTime()); + } + + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format + + * @return String with Date in NETCONF/YANG Format Version 1.0. + */ + public String getTimeStampAsNetconfString(Date date) { + return getRightFormattedDate(date.getTime()); + } + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * + * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. + */ + public DateAndTime getTimeStamp() { + return DateAndTime.getDefaultInstance(getTimeStampAsNetconfString()); + } + + /** + * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * @param date specifying the date and time + * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. + */ + public DateAndTime getTimeStamp(Date date) { + return DateAndTime.getDefaultInstance(getTimeStampAsNetconfString(date)); + } + + + /** + * Return the String with a NETCONF time converted to long + * + * @param netconfTime as String according the formats given above + * @return Epoch milliseconds + * @throws IllegalArgumentException In case of no compliant time format definition for the string + * @throws ParseException Time parsing failed + */ + public long getTimeStampFromNetconfAsMilliseconds(String netconfTime) + throws IllegalArgumentException { + Matcher m = dateNetconfPatter.matcher(netconfTime); + // According to specified matches there have to be 10 parameter + if (m.matches() && m.groupCount() == 10) { + // Convert now + synchronized(dateFormatConvert) { + long utcMillis; + try { + utcMillis = dateFormatConvert.parse(getTimeAsNormalizedString(m, m.group(6), m.group(7))).getTime() + - getTimezoneOffsetMilliseconds(m.group(9), m.group(10)); + return utcMillis; + } catch (ParseException e) { + throw new IllegalArgumentException("Parse problem for NETCONF data string: " + netconfTime); + } + } + } else { + throw new IllegalArgumentException("No pattern for NETCONF data string: " + netconfTime); + } + } + + /** + * Deliver String result. + * + * @param netconfTime as String according the formats given above + * @return If successful: String in ISO8601 Format for database and presentation. If "wrong formed + * input" the Input string with the prefix "Mailformed date" is delivered back. + */ + public String getTimeStampFromNetconf(String netconfTime) { + Matcher m = dateNetconfPatter.matcher(netconfTime); + // According to spezified matches there have to be 10 parameter + if (m.matches() && m.groupCount() == 10) { + // Convert now + try { + synchronized(dateFormatConvert) { + long utcMillis = dateFormatConvert.parse(getTimeAsNormalizedString(m, m.group(6), m.group(7))).getTime() + - getTimezoneOffsetMilliseconds(m.group(9), m.group(10)); + return getRightFormattedDate(utcMillis); + } + } catch (ParseException e) { + LOG.info(e.getMessage()); + } catch (IllegalArgumentException e) { + LOG.info(e.getMessage()); + } + } + LOG.debug("No pattern for NETCONF data string: {}", netconfTime); + return "Malformed date: " + netconfTime; // Error handling + } + + /*------------------------------------------- + * Private and static functions + */ + /** + * Convert timeZone parameter in format [+-]/d/d:/d/d into milliseconds + * + * @param m Index 9 with "+/-" and hour string or null for UTZ, Index 10 with minutes + * @return long milliseconds of TimeZoneOffset + * @throws IllegalArgumentException If parameters are wrong + */ + private static long getTimezoneOffsetMilliseconds(String timeZoneHour, String timeZoneMinute) + throws IllegalArgumentException { + // -- Calculate timezone specific offset + long timeZoneOffsetMilliseconds = 0; + if (timeZoneHour != null) { + // Time zone offset in hours and minutes + int tzHour = 0; + int tzMinutes = 0; + tzHour = Integer.valueOf(timeZoneHour); + if (timeZoneMinute != null) { + tzMinutes = Integer.valueOf(timeZoneMinute); + } else { + throw new IllegalArgumentException("Problem in Netconf Time format timeZone minutes parameter."); + } + timeZoneOffsetMilliseconds = (tzHour * 60 + (tzHour > 0 ? tzMinutes : -tzMinutes)) * 60000L; + } + return timeZoneOffsetMilliseconds; + } + + /** + * Convert parameters to String with year .. minutes and optional Seconds and .. milliseconds + * + * @param m Matcher with parsed date + * @param secString Seconds as String or null + * @param msString Milliseconds as String or null + * @return Normalized time string + */ + private static String getTimeAsNormalizedString(Matcher m, String secString, String msString) { + // -- Create time as normalized string + StringBuffer sb = new StringBuffer(); + sb.append(m.group(1)); // year + sb.append('-'); + sb.append(m.group(2)); // Month + sb.append('-'); + sb.append(m.group(3)); // Day + sb.append(' '); + sb.append(m.group(4)); // Hour 0-23 + sb.append(':'); + sb.append(m.group(5)); // Minute + sb.append(':'); + sb.append(secString != null ? secString : "00"); // Seconds (optional) + sb.append('.'); + if (msString == null) { // Milliseconds optional + sb.append(MILLISECONDZEROS); + } else if (msString.length() <= MILLISECONDSDIGITS) { + sb.append(msString); // Millisecond + sb.append(MILLISECONDZEROS.substring(0, MILLISECONDSDIGITS - msString.length())); + } else { + sb.append(msString.substring(0, MILLISECONDSDIGITS)); // Only first Three + } + return sb.toString(); + } + + /** + * Deliver format in a way that milliseconds are correct. + * + * @param dateMillis Date as milliseconds in Java definition + * @return String + */ + private String getRightFormattedDate(long dateMillis) { + long tenthOfSeconds = dateMillis % 1000 / 100L; // Extract 100 milliseconds + long base = dateMillis / 1000L * 1000L; // Cut milliseconds to 000 + Date newDate = new Date(base + tenthOfSeconds); + synchronized(dateFormatResult) { + return dateFormatResult.format(newDate); + } + } + + /** + * Static initialization + */ + private static SimpleDateFormat init(String format, TimeZone zone) { + if (zone == null) { + throw new ExceptionInInitializerError(); + } else { + SimpleDateFormat dateFormat; + dateFormat = new SimpleDateFormat(format); + dateFormat.setTimeZone(zone); + return dateFormat; + } + } + + + +} diff --git a/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/ZipFile.java b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/ZipFile.java new file mode 100644 index 000000000..9a926fd64 --- /dev/null +++ b/sdnr/wt/devicemanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/devicemanager/test/util/ZipFile.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved. + * ================================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================================== + ******************************************************************************/ +package org.onap.ccsdk.features.sdnr.wt.devicemanager.test.util; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipFile implements AutoCloseable { + + private final ZipOutputStream zos; + private final FileOutputStream fos; + + public ZipFile(String zipPath) throws FileNotFoundException { + fos = new FileOutputStream(zipPath); + zos = new ZipOutputStream(fos); + } + + public void addToZipFile(String fileName) throws FileNotFoundException, IOException { + + System.out.println("Writing '" + fileName + "' to zip file"); + + InputStream fis = ZipFile.class.getClassLoader().getResourceAsStream(fileName); + if (fis == null) { + throw new FileNotFoundException("Resource not found: " + fileName); + } + + ZipEntry zipEntry = new ZipEntry(fileName); + zos.putNextEntry(zipEntry); + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zos.write(bytes, 0, length); + } + zos.closeEntry(); + fis.close(); + } + + @Override + public void close() throws IOException { + zos.close(); + fos.close(); + } + +} -- cgit 1.2.3-korg