aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Dürre <michael.duerre@highstreet-technologies.com>2020-02-06 12:57:23 +0100
committerKAPIL SINGAL <ks220y@att.com>2020-02-07 16:41:48 +0000
commitf6f3b57be8e57ffc6790d139b0b7f168b8cc69e6 (patch)
treed510d50c0f651e5b7f853ec6247f57a1a7f2b432
parent561aa2a8ef7bd222d274aea065929920aedd0723 (diff)
improve code coverage
more unit tests for common and data-provider Issue-ID: SDNC-1063 Signed-off-by: Michael Dürre <michael.duerre@highstreet-technologies.com> Change-Id: Id99cb3e300b9649b77e0900347fbefae8d55cd87 Signed-off-by: Michael Dürre <michael.duerre@highstreet-technologies.com>
-rw-r--r--sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java2
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java2
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java112
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java19
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java20
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java1
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java15
-rw-r--r--sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/FileWatchdog.java121
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java3
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java70
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java89
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java126
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java228
-rw-r--r--sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java37
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java2
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java31
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java74
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java4
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java4
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java20
-rw-r--r--sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java2
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java10
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java316
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java28
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java81
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestInitalMaintenanceObjectInDatabase.java34
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceService.java97
-rw-r--r--sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java92
28 files changed, 1328 insertions, 312 deletions
diff --git a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java
index 4a640a35f..77267e793 100644
--- a/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java
+++ b/sdnr/wt/apigateway/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/apigateway/test/helper/IPublicServlet.java
@@ -18,6 +18,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
+
package org.onap.ccsdk.features.sdnr.wt.apigateway.test.helper;
import java.io.IOException;
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java
index 7c48bf8a1..63e265bd1 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java
@@ -146,7 +146,7 @@ public interface DatabaseClient {
* @param query query to select item to update
* @return esId which was updated or null if failed
*/
- public String doUpdate(String dataTypeName, String json, QueryBuilder query);
+ public boolean doUpdate(String dataTypeName, String json, QueryBuilder query);
/**
*
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java
index 50a8244cb..6fb26f541 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java
@@ -17,23 +17,13 @@
******************************************************************************/
package org.onap.ccsdk.features.sdnr.wt.common.database;
-import java.io.FileInputStream;
import java.io.IOException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.SSLContext;
-
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
-import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
@@ -98,57 +88,57 @@ public class ExtRestClient {
}
}
- private class SSLCercAuthHttpClientConfigCallback implements HttpClientConfigCallback {
-
- private final String certFilename;
-
- SSLCercAuthHttpClientConfigCallback(String certfile) {
- this.certFilename = certfile;
- }
-
- @Override
- public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
- if (this.certFilename == null) {
- return httpClientBuilder;
- }
-
- char[] keystorePass = "MY PASSWORD".toCharArray();
-
- FileInputStream fis = null;
-
- // Loading KEYSTORE in JKS format
- KeyStore keyStorePci = null;
- try {
- keyStorePci = KeyStore.getInstance(KeyStore.getDefaultType());
- } catch (KeyStoreException e1) {
- LOG.warn("unable to load keystore: {}",e1);
- }
- if (keyStorePci != null) {
- try {
- fis = new FileInputStream(this.certFilename);
- keyStorePci.load(fis, keystorePass);
- } catch (Exception e) {
- LOG.error("Error loading keystore: " + this.certFilename);
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException e) {
-
- }
- }
- }
- }
- SSLContext sslcontext=null;
- try {
- sslcontext = SSLContexts.custom().loadKeyMaterial(keyStorePci, keystorePass).build();
- } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
- | KeyStoreException e) {
- LOG.warn("unable to load sslcontext: {}",e);
- }
- return httpClientBuilder.setSSLContext(sslcontext);
- }
- }
+// private class SSLCercAuthHttpClientConfigCallback implements HttpClientConfigCallback {
+//
+// private final String certFilename;
+//
+// SSLCercAuthHttpClientConfigCallback(String certfile) {
+// this.certFilename = certfile;
+// }
+//
+// @Override
+// public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
+// if (this.certFilename == null) {
+// return httpClientBuilder;
+// }
+//
+// char[] keystorePass = "MY PASSWORD".toCharArray();
+//
+// FileInputStream fis = null;
+//
+// // Loading KEYSTORE in JKS format
+// KeyStore keyStorePci = null;
+// try {
+// keyStorePci = KeyStore.getInstance(KeyStore.getDefaultType());
+// } catch (KeyStoreException e1) {
+// LOG.warn("unable to load keystore: {}",e1);
+// }
+// if (keyStorePci != null) {
+// try {
+// fis = new FileInputStream(this.certFilename);
+// keyStorePci.load(fis, keystorePass);
+// } catch (Exception e) {
+// LOG.error("Error loading keystore: " + this.certFilename);
+// } finally {
+// if (fis != null) {
+// try {
+// fis.close();
+// } catch (IOException e) {
+//
+// }
+// }
+// }
+// }
+// SSLContext sslcontext=null;
+// try {
+// sslcontext = SSLContexts.custom().loadKeyMaterial(keyStorePci, keystorePass).build();
+// } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
+// | KeyStoreException e) {
+// LOG.warn("unable to load sslcontext: {}",e);
+// }
+// return httpClientBuilder.setSSLContext(sslcontext);
+// }
+// }
private RestClient client;
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java
index 56402bdfc..9a04f0dfd 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java
@@ -64,19 +64,16 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A
this(hosts,REFRESH_AFTER_REWRITE_DEFAULT);
}
public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite) {
- super(hosts);
- this.doRefreshAfterWrite = refreshAfterWrite;
+ this(hosts,refreshAfterWrite,null,null);
+ }
+ public HtDatabaseClient(HostInfo[] hosts,String username,String password) {
+ this(hosts,REFRESH_AFTER_REWRITE_DEFAULT,username,password);
}
-
public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite,String username,String password) {
super(hosts,username,password);
this.doRefreshAfterWrite = refreshAfterWrite;
}
- public HtDatabaseClient(HostInfo[] hosts,String username,String password) {
- this(hosts,REFRESH_AFTER_REWRITE_DEFAULT,username,password);
- }
-
-
+
/*----------------------------------
* Functions
@@ -236,7 +233,7 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A
@Override
public String doUpdateOrCreate(String dataTypeName, String esId, String json) {
- return this.doUpdateOrCreate(dataTypeName, esId, json,null);
+ return this.doUpdateOrCreate(dataTypeName, esId, json,null);
}
@@ -262,7 +259,7 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A
return success ? esId : null;
}
@Override
- public String doUpdate(String dataTypeName, String json, QueryBuilder query) {
+ public boolean doUpdate(String dataTypeName, String json, QueryBuilder query) {
boolean success = false;
UpdateByQueryRequest request = new UpdateByQueryRequest(dataTypeName, dataTypeName );
request.source(new JSONObject(json),query);
@@ -275,7 +272,7 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A
if(this.doRefreshAfterWrite) {
this.doRefresh(dataTypeName);
}
- return success?"":null;
+ return success;
}
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java
index e86c5c36b..b6df2620b 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java
@@ -21,12 +21,14 @@ import org.json.JSONObject;
public class SearchHit {
- private String index;
- private String type;
- private String id;
- private JSONObject source;
+ private final String index;
+ private final String type;
+ private final String id;
+ private final JSONObject source;
+ private final JSONObject raw;
public SearchHit(JSONObject o) {
+ this.raw = o;
this.index=o.getString("_index");
this.type = o.getString("_type");
this.id = o.getString("_id");
@@ -43,8 +45,18 @@ public class SearchHit {
return this.id;
}
+ public JSONObject getSource() {
+ return this.source;
+ }
public String getSourceAsString() {
return this.source.toString();
}
+ /**
+ * @return
+ */
+ public JSONObject getRaw() {
+ return this.raw;
+ }
+
}
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java
index ff513ea97..63c1f15ba 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java
@@ -21,7 +21,6 @@
* ============LICENSE_END=======================================================
*
*/
-
package org.onap.ccsdk.features.sdnr.wt.common.file;
import java.io.File;
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java
index 8242d35d4..b65984a58 100644
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java
+++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java
@@ -100,10 +100,9 @@ public abstract class BaseServlet extends HttpServlet {
sc.init(null, trustCerts, new java.security.SecureRandom());
}
- private boolean trustInsecure;
- private boolean isCorsEnabled;
- public BaseServlet(boolean trustInsecure) {
- this.trustInsecure = trustInsecure;
+ protected abstract boolean trustInsecure();
+ protected abstract boolean isCorsEnabled();
+ public BaseServlet() {
this.trysslSetup(true);
}
@@ -118,11 +117,11 @@ public abstract class BaseServlet extends HttpServlet {
*/
private void trysslSetup(boolean force) {
// if trustall config has changed
- if (force || this.doTrustAll() != this.trustInsecure) {
- this.trustAll(this.trustInsecure);
+ if (force || this.doTrustAll() != this.trustInsecure()) {
+ this.trustAll(this.trustInsecure());
// resetup ssl config
try {
- setupSslTrustAll(this.trustInsecure);
+ setupSslTrustAll(this.trustInsecure());
} catch (Exception e) {
LOG.error("problem setting up SSL: {}", e.getMessage());
}
@@ -347,7 +346,7 @@ public abstract class BaseServlet extends HttpServlet {
resp.setHeader(entry.getKey(), v);
s += String.format("%s:%s;", entry.getKey(), v);
}
- if (this.isCorsEnabled) {
+ if (this.isCorsEnabled()) {
resp.setHeader("Access-Control-Allow-Origin", "*");
// resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/FileWatchdog.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/FileWatchdog.java
deleted file mode 100644
index 2830d688e..000000000
--- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/FileWatchdog.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP : ccsdk features
- * ================================================================================
- * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
- * All rights reserved.
- * ================================================================================
- * Update Copyright (C) 2020 AT&T 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.common.util;
-
-import java.io.File;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Check every now and then that a certain file has not changed. If it has, then call the
- * {@link #doOnChange} method.
- *
- * @author JunHo Yoon
- * @since 3.1.1
- */
-public abstract class FileWatchdog extends Thread {
- private static final Logger LOGGER = LoggerFactory.getLogger(FileWatchdog.class);
- /**
- * The default delay between every file modification check, set to 60 seconds.
- */
- public static final long DEFAULT_DELAY = 60000;
- /**
- * The name of the file to observe for changes.
- */
- private final String filename;
-
- /**
- * The delay to observe between every check. By default set {@link #DEFAULT_DELAY}.
- */
- private long delay = DEFAULT_DELAY;
-
- private final File file;
- private long lastModified = 0;
- private boolean warnedAlready = false;
-
- protected FileWatchdog(String filename) {
- this.filename = filename;
- file = new File(filename);
- setDaemon(true);
- checkAndConfigure();
- }
-
- /**
- * Set the delay to observe between each check of the file changes.
- *
- * @param delay the frequency of file watch.
- */
- public void setDelay(long delay) {
- this.delay = delay;
- }
-
- /**
- * abstract method to be run when the file is changed.
- */
- protected abstract void doOnChange();
-
- protected void checkAndConfigure() {
- boolean fileExists;
- try {
- fileExists = file.exists();
- } catch (SecurityException e) {
- LOGGER.warn("Was not allowed to read check file existence, file:[{}].",filename);
- this.interrupt(); // there is no point in continuing
- return;
- }
-
- if (fileExists) {
- long l = file.lastModified(); // this can also throw a
- if (lastModified == 0) {
- lastModified = l; // is very unlikely.
- }
- if (l > lastModified) { // however, if we reached this point this
- lastModified = l; // is very unlikely.
- doOnChange();
- warnedAlready = false;
- }
- } else {
- if (!warnedAlready) {
- LOGGER.debug("[{}] does not exist.", filename);
- warnedAlready = true;
- }
- }
- }
-
- @Override
- public void run() {
- while (!isInterrupted()) {
- checkAndConfigure();
- try {
- Thread.sleep(delay);
- } catch (InterruptedException e) {
- LOGGER.debug("Interrupted sleep. {}", e.getMessage());
- Thread.currentThread().interrupt();
- }
- }
- LOGGER.debug("Stoppen file watchdog for file {}", filename);
- }
-}
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java
index af3979c50..47fe9d4f6 100644
--- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java
@@ -19,6 +19,7 @@ package org.onap.ccsdk.features.sdnr.wt.common.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
@@ -77,6 +78,8 @@ public class TestBaseHttpClient {
fail(e.getMessage());
}
assertNotNull(response);
+ assertTrue(response.isSuccess());
+ System.out.println(response.toString());
assertEquals(RESPONSE_POST, response.body);
try {
response= httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers );
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java
new file mode 100644
index 000000000..ee602ce28
--- /dev/null
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * ============LICENSE_START========================================================================
+ * ONAP : ccsdk feature sdnr wt
+ * =================================================================================================
+ * Copyright (C) 2020 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.common.test;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServlet;
+import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServletBase;
+
+/**
+ * @author Michael Dürre
+ *
+ */
+public class TestBaseServlet extends HelpServletBase{
+
+ private static final int PORT = 40003;
+ public TestBaseServlet() {
+ super("/base",PORT);
+ }
+
+ @Test
+ public void test() throws ServletException, IOException {
+
+ String query = "{\"query\":{\"match_all\":{}}}";
+ HelpServlet servlet = new HelpServlet(PORT);
+ this.setServlet(servlet);
+ // test disabled message
+ String expectedResponse = "offline";
+ testrequest(HTTPMETHOD_GET, query, expectedResponse, false);
+ testrequest(HTTPMETHOD_POST, query, expectedResponse, false);
+ testrequest(HTTPMETHOD_PUT, query, expectedResponse, false);
+ testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false);
+ servlet.setOffline(false);
+ // initEsTestWebserver(port);
+ testrequest(HTTPMETHOD_GET, query, HelpServletBase.RESPONSE_GET, true);
+ testrequest(HTTPMETHOD_POST, query, HelpServletBase.RESPONSE_POST, true);
+ testrequest(HTTPMETHOD_PUT, query, HelpServletBase.RESPONSE_PUT, true);
+ testrequest(HTTPMETHOD_DELETE, query, HelpServletBase.RESPONSE_DELETE, true);
+ testrequest(HTTPMETHOD_OPTIONS, query, "", false);
+ // stopTestWebserver();
+ }
+ @Before
+ public void init() throws IOException{
+ HelpServletBase.initEsTestWebserver(PORT);
+ }
+ @After
+ public void deinit() {
+ HelpServletBase.stopTestWebserver();
+ }
+}
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java
index 0d46b4d20..e39998008 100644
--- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java
@@ -22,9 +22,11 @@ import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
+import org.onap.ccsdk.features.sdnr.wt.common.database.IsEsObject;
import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
+import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
public class TestDbClient {
@@ -56,16 +58,99 @@ public class TestDbClient {
//Update
esId= dbClient.doUpdateOrCreate(IDX, ID, JSON2);
assertEquals("update response not successfull",ID,esId);
- //Verify
+ //check that update with null fails
+ assertNull("update with id null should not be possible",dbClient.doUpdateOrCreate(IDX,null,JSON2));
+ //Verify update
result = dbClient.doReadByQueryJsonData( IDX, QueryBuilders.matchQuery("_id", ID));
assertEquals("amount of results is wrong",1,result.getTotal());
assertEquals("data not valid", JSON2,result.getHits().get(0).getSourceAsString());
+ //test second read
+ String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() {
+
+ @Override
+ public void setEsId(String id) {
+
+ }
+
+ @Override
+ public String getEsId() {
+ return ID;
+ }
+ });
+ //test all read
+ result = dbClient.doReadAllJsonData(IDX);
+ assertNotNull("all read not working",result);
+
+ assertEquals("read works not as expected", JSON2,resStr);
//Delete
- boolean del=dbClient.doRemove(IDX, ID);
+ boolean del=dbClient.doRemove(IDX, new IsEsObject() {
+
+ @Override
+ public void setEsId(String id) {
+
+ }
+ @Override
+ public String getEsId() {
+ return ID;
+ }
+ });
assertTrue("item not deleted",del);
//Verify
result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID));
assertEquals("amount of results is wrong",0,result.getTotal());
+
+
+
+ }
+ @Test
+ public void testCRUD2() {
+ final String IDX = "test23-knmoinsd";
+ final String ID = "abcddd";
+ final String JSON = "{\"data\":{\"inner\":\"more\"}}";
+ final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}";
+ //Create
+ String esId=dbClient.doWriteRaw(IDX, ID, JSON);
+ assertEquals("inserted id is wrong",ID,esId);
+ //Read
+ SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID));
+ assertEquals("amount of results is wrong",1,result.getTotal());
+ assertEquals("data not valid", JSON,result.getHits().get(0).getSourceAsString());
+ QueryBuilder matchQuery = QueryBuilders.matchQuery("_id", ID);
+ //Update
+ assertTrue("update response not successfull",dbClient.doUpdate(IDX, JSON2,matchQuery ));
+ //check that update with null fails
+ assertNull("update with id null should not be possible",dbClient.doUpdateOrCreate(IDX,null,JSON2));
+ //Verify update
+ result = dbClient.doReadByQueryJsonData( IDX, QueryBuilders.matchQuery("_id", ID));
+ assertEquals("amount of results is wrong",1,result.getTotal());
+ assertEquals("data not valid", JSON2,result.getHits().get(0).getSourceAsString());
+ //test second read
+ String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() {
+
+ @Override
+ public void setEsId(String id) {
+
+ }
+
+ @Override
+ public String getEsId() {
+ return ID;
+ }
+ });
+ //test all read
+ result = dbClient.doReadAllJsonData(IDX);
+ assertNotNull("all read not working",result);
+
+ assertEquals("read works not as expected", JSON2,resStr);
+ //Delete
+ int del=dbClient.doRemove(IDX, matchQuery);
+ assertTrue("item not deleted",del>0);
+ //Verify
+ result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID));
+ assertEquals("amount of results is wrong",0,result.getTotal());
+
+
+
}
}
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java
new file mode 100644
index 000000000..2e8cda0ef
--- /dev/null
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java
@@ -0,0 +1,126 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP : CCSDK.apps.sdnr.wt.apigateway
+ * ================================================================================
+ * Copyright (C) 2018 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.common.test.helper;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.ccsdk.features.sdnr.wt.common.http.BaseServlet;
+
+public class HelpServlet extends BaseServlet implements IPublicServlet{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String RESPONSE_GET = "This is the response get";
+ public static final String RESPONSE_POST = "This is the response post";
+ public static final String RESPONSE_PUT = "This is the response put";
+ public static final String RESPONSE_DELETE = "This is the response delete";
+ public static final String RESPONSE_OPTIONS = "This is the response options";
+ private static final String HOST = "localhost";
+ private int port;
+ private boolean isoff;
+
+ /**
+ * @param port
+ */
+ public HelpServlet(int port) {
+ this.port = port;
+ this.isoff=true;
+ }
+ @Override
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ super.doGet(req, resp);
+ }
+ @Override
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ super.doPost(req, resp);
+ }
+ @Override
+ public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ super.doPut(req, resp);
+ }
+ @Override
+ public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ resp.setStatus(200);
+ }
+ @Override
+ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ super.doDelete(req, resp);
+ }
+ @Override
+ protected String getOfflineResponse() {
+ return "offline";
+ }
+ @Override
+ protected boolean isOff() {
+ return this.isoff;
+ }
+ @Override
+ protected boolean doTrustAll() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ @Override
+ protected void trustAll(boolean trust) {
+ // TODO Auto-generated method stub
+
+ }
+ @Override
+ protected String getRemoteUrl(String uri) {
+ if (uri.startsWith("/")) {
+ uri = uri.substring(1);
+ }
+ if (uri.startsWith("base")) {
+ uri = uri.substring("base".length());
+ }
+ if (uri.startsWith("/")) {
+ uri = uri.substring(1);
+ }
+ String base = "http://" + HOST + ":" + this.port;
+ if (!base.endsWith("/")) {
+ base += "/";
+ }
+
+ return base + uri;
+ }
+ @Override
+ protected boolean trustInsecure() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ @Override
+ protected boolean isCorsEnabled() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ /**
+ * @param b
+ */
+ public void setOffline(boolean b) {
+ this.isoff = b;
+
+ }
+}
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java
new file mode 100644
index 000000000..b0db4f0e6
--- /dev/null
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java
@@ -0,0 +1,228 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP : CCSDK.apps.sdnr.wt.apigateway
+ * ================================================================================
+ * Copyright (C) 2018 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.common.test.helper;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.net.InetSocketAddress;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.Vector;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import javax.servlet.ServletInputStream;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.After;
+import org.junit.Before;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+
+public class HelpServletBase {
+
+ public static final String RESPONSE_GET = "This is the response get";
+ public static final String RESPONSE_POST = "This is the response post";
+ public static final String RESPONSE_PUT = "This is the response put";
+ public static final String RESPONSE_DELETE = "This is the response delete";
+ public static final String RESPONSE_OPTIONS = "This is the response options";
+
+ public static final String HTTPMETHOD_GET = "GET";
+ public static final String HTTPMETHOD_POST = "POST";
+ public static final String HTTPMETHOD_PUT = "PUT";
+ public static final String HTTPMETHOD_DELETE = "DELETE";
+ public static final String HTTPMETHOD_OPTIONS = "OPTIONS";
+ private IPublicServlet servlet;
+ private static HttpServer server;
+ private static ExecutorService httpThreadPool;
+
+ public final String HOST = "localhost";
+ protected static int testPort;
+ private final String baseUri;
+ protected static final String LR = "\n";
+
+ public HelpServletBase(String baseuri, int port) {
+ this.baseUri=baseuri;
+ testPort = port;
+ }
+
+ public void setServlet(IPublicServlet s)
+ {
+ this.servlet=s;
+ }
+
+ protected void testrequest(String method, String data, String expectedResponse, boolean exact) {
+ this.testrequest("/mwtn/test",method, data, expectedResponse, exact, null);
+ }
+ protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact) {
+ this.testrequest(uri,method, data, expectedResponse, exact, null);
+ }
+
+ protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact,
+ Map<String, String> headersToCheck) {
+
+ HttpServletRequest mockRequest = mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = mock(HttpServletResponse.class);
+
+ StringWriter out = new StringWriter();
+ ServletOutputStream printOut = new ServletOutputStream() {
+
+ @Override
+ public void write(int arg0) throws IOException {
+ out.write(arg0);
+ }
+ };
+ ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
+ ServletInputStream inputStream= new ServletInputStream() {
+ @Override
+ public int read() throws IOException {
+ return bis.read();
+ }
+ };
+ Vector<String> headers=new Vector<String>();
+ headers.addElement("Accept");
+ headers.add("User-Agent");
+ Enumeration<String> headerNames = headers.elements();
+ try {
+ when(mockRequest.getRequestURI()).thenReturn(this.baseUri+uri);
+ when(mockRequest.getHeaderNames()).thenReturn(headerNames);
+ when(mockRequest.getHeader("Accept")).thenReturn("application/json");
+ when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc");
+ when(mockRequest.getInputStream()).thenReturn(inputStream);
+ when(mockResponse.getOutputStream()).thenReturn(printOut);
+ System.out.println("do a " + method + " request");
+ if (method == HTTPMETHOD_GET)
+ this.servlet.doGet(mockRequest, mockResponse);
+ else if (method == HTTPMETHOD_POST)
+ this.servlet.doPost(mockRequest, mockResponse);
+ else if (method == HTTPMETHOD_PUT)
+ this.servlet.doPut(mockRequest, mockResponse);
+ else if (method == HTTPMETHOD_DELETE)
+ this.servlet.doDelete(mockRequest, mockResponse);
+ else if (method == HTTPMETHOD_OPTIONS)
+ this.servlet.doOptions(mockRequest, mockResponse);
+ else
+ fail("http request method " + method + " test not implemented");
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+
+ verify(mockResponse).setStatus(200);
+ if (exact)
+ assertEquals(expectedResponse, out.toString());
+ else
+ assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse));
+ // currently unable to check extra headers
+ if (headersToCheck != null) {
+
+ }
+ }
+ @Before
+ private void init() throws IOException{
+
+
+ initEsTestWebserver(testPort);
+ }
+ @After
+ private void deinit() {
+ stopTestWebserver();
+ }
+
+ public static void initEsTestWebserver(int port) throws IOException {
+ initEsTestWebserver(port, "/mwtn/test");
+ }
+ public static void initEsTestWebserver(int port,String baseUri) throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
+ httpThreadPool = Executors.newFixedThreadPool(5);
+ server.setExecutor(httpThreadPool);
+ server.createContext(baseUri, new MyHandler());
+ //server.createContext("/", new MyRootHandler());
+ server.setExecutor(null); // creates a default executor
+ server.start();
+ System.out.println("http server started");
+ }
+
+ public static void stopTestWebserver() {
+ if (server != null) {
+ server.stop(0);
+ httpThreadPool.shutdownNow();
+ System.out.println("http server stopped" );
+ }
+ }
+
+
+
+ public static class MyHandler implements HttpHandler {
+ @Override
+ public void handle(HttpExchange t) throws IOException {
+ String method = t.getRequestMethod();
+ System.out.println(String.format("req received: %s %s" ,method,t.getRequestURI()));
+ OutputStream os = null;
+ try {
+ if (method.equals(HTTPMETHOD_GET)) {
+ t.sendResponseHeaders(200, RESPONSE_GET.length());
+ os = t.getResponseBody();
+ os.write(RESPONSE_GET.getBytes());
+ } else if (method.equals(HTTPMETHOD_POST)) {
+ t.sendResponseHeaders(200, RESPONSE_POST.length());
+ os = t.getResponseBody();
+ os.write(RESPONSE_POST.getBytes());
+ } else if (method.equals(HTTPMETHOD_PUT)) {
+ t.sendResponseHeaders(200, RESPONSE_PUT.length());
+ os = t.getResponseBody();
+ os.write(RESPONSE_PUT.getBytes());
+ } else if (method.equals(HTTPMETHOD_DELETE)) {
+ t.sendResponseHeaders(200, RESPONSE_DELETE.length());
+ os = t.getResponseBody();
+ os.write(RESPONSE_DELETE.getBytes());
+ } else if (method.equals(HTTPMETHOD_OPTIONS)) {
+ t.sendResponseHeaders(200, RESPONSE_OPTIONS.length());
+ //os = t.getResponseBody();
+ //os.write(RESPONSE_OPTIONS.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/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java
new file mode 100644
index 000000000..9d5ac4fc0
--- /dev/null
+++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : CCSDK
+ * ================================================================================
+ * Copyright (C) 2017 AT&T 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.common.test.helper;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public interface IPublicServlet {
+
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
+ public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
+ public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
+ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
+}
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java
index 63d92b64d..1192950e6 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java
@@ -371,7 +371,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid
* @return QueryBuilder for older elements related to timestamp
*/
private static QueryBuilder getQueryForTimeStamp(String netconfTimeStamp) {
- return new RangeQueryBuilder("event.timeStamp").lte(netconfTimeStamp);
+ return new RangeQueryBuilder("timestamp").lte(netconfTimeStamp);
}
}
private static class EsFaultLogDevicemanager {
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java
index bc61e81e5..9e576857b 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java
@@ -61,32 +61,35 @@ public class MediatorServerDataProvider implements AutoCloseable {
@Override
public void run() {
isRunning = true;
- SearchResult<Data> result = MediatorServerDataProvider.this.mediatorserverRW.doReadAll();
- List<Data> data = result.getHits();
- for (Data item : data) {
- MediatorServerDataProvider.this.entries.put(item.getId(), item);
- }
+ runIt();
isRunning = false;
}
};
+ private void runIt() {
+ SearchResult<Data> result = MediatorServerDataProvider.this.mediatorserverRW.doReadAll();
+ List<Data> data = result.getHits();
+ for (Data item : data) {
+ MediatorServerDataProvider.this.entries.put(item.getId(), item);
+ }
+ }
+
+ /**
+ *
+ * @param dbServerId
+ * @return url or null if not exists
+ */
public String getHostUrl(String dbServerId) {
Data info = this.entries.getOrDefault(dbServerId, null);
return info == null ? null : info.getUrl();
}
public boolean triggerReloadSync() {
- new Thread(onTick).start();
- int i = 20;
- while (isRunning && i-- > 0) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
+ if (!isRunning) {
+ runIt();
}
- return i > 0;
+ return true;
}
@Override
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java
index 2b3ebd86e..fbdc9d825 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java
@@ -163,43 +163,43 @@ public class SystemInfo {
printValue(sb, "Garbage collector", maxNameLen, val);
}
- if (showMemoryPools) {
- List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
- sb.append("Memory Pools\n");
- printValue(sb, "Total Memory Pools", maxNameLen, printLong(memoryPools.size()));
- String spaces4 = " ";
- for (MemoryPoolMXBean pool : memoryPools) {
- String name = pool.getName();
- MemoryType type = pool.getType();
- printValue(sb, spaces4 + "Pool (" + type + ")", maxNameLen, name);
-
- // PeakUsage/CurrentUsage
- MemoryUsage peakUsage = pool.getPeakUsage();
- MemoryUsage usage = pool.getUsage();
-
- if (usage != null && peakUsage != null) {
- long init = peakUsage.getInit();
- long used = peakUsage.getUsed();
- long committed = peakUsage.getCommitted();
- long max = peakUsage.getMax();
- sb.append(spaces4 + spaces4 + "Peak Usage\n");
- printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
- printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
- printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
- printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
-
- init = usage.getInit();
- used = usage.getUsed();
- committed = usage.getCommitted();
- max = usage.getMax();
- sb.append(spaces4 + spaces4 + "Current Usage\n");
- printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
- printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
- printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
- printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
- }
- }
- }
+// if (showMemoryPools) {
+// List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
+// sb.append("Memory Pools\n");
+// printValue(sb, "Total Memory Pools", maxNameLen, printLong(memoryPools.size()));
+// String spaces4 = " ";
+// for (MemoryPoolMXBean pool : memoryPools) {
+// String name = pool.getName();
+// MemoryType type = pool.getType();
+// printValue(sb, spaces4 + "Pool (" + type + ")", maxNameLen, name);
+//
+// // PeakUsage/CurrentUsage
+// MemoryUsage peakUsage = pool.getPeakUsage();
+// MemoryUsage usage = pool.getUsage();
+//
+// if (usage != null && peakUsage != null) {
+// long init = peakUsage.getInit();
+// long used = peakUsage.getUsed();
+// long committed = peakUsage.getCommitted();
+// long max = peakUsage.getMax();
+// sb.append(spaces4 + spaces4 + "Peak Usage\n");
+// printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
+//
+// init = usage.getInit();
+// used = usage.getUsed();
+// committed = usage.getCommitted();
+// max = usage.getMax();
+// sb.append(spaces4 + spaces4 + "Current Usage\n");
+// printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed));
+// printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max));
+// }
+// }
+// }
sb.append("Classes\n");
printValue(sb, "Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java
index b119b80d4..3fd74b09d 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java
@@ -190,7 +190,7 @@ public class EsDataObjectReaderWriter<T extends DataObject> {
* @param esId
* @return String with esId or null
*/
- public @Nullable <S extends DataObject> String update(S object, QueryBuilder query) {
+ public @Nullable <S extends DataObject> boolean update(S object, QueryBuilder query) {
if (writeInterfaceClazz.isInstance(object)) {
try {
String json = yangtoolsMapper.writeValueAsString(object);
@@ -202,7 +202,7 @@ public class EsDataObjectReaderWriter<T extends DataObject> {
LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null",
writeInterfaceClazz.getName());
}
- return null;
+ return false;
}
/**
* Write/ update partial child object to database with specific id Write if not
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java
index d097d8284..d3d9dbf25 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java
@@ -204,7 +204,7 @@ public class EsDataObjectReaderWriter2<T extends DataObject> {
* @param query for write of specific attributes
* @return json string with new Object
*/
- public @Nullable <S extends DataObject> String update(S object, QueryBuilder query) {
+ public @Nullable <S extends DataObject> boolean update(S object, QueryBuilder query) {
if (object != null && writeInterfaceClazz.isInstance(object)) {
try {
String json = yangtoolsMapper.writeValueAsString(object);
@@ -216,7 +216,7 @@ public class EsDataObjectReaderWriter2<T extends DataObject> {
LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null",
writeInterfaceClazz.getName());
}
- return null;
+ return false;
}
/**
* Write/ update partial child object to database with specific id Write if not
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java
index cdcbb4912..6a42d0f21 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java
@@ -39,9 +39,9 @@ public class MsServlet extends BaseServlet {
private static final long serialVersionUID = -5361461082028405171L;
private static final String OFFLINE_RESPONSE_MESSAGE = "MediatorServer interface is offline";
private static boolean trustAll = false;
- private MediatorServerDataProvider entryProvider;
+ private static MediatorServerDataProvider entryProvider;
public MsServlet() {
- super(false);
+ super();
}
@Override
@@ -59,7 +59,7 @@ public class MsServlet extends BaseServlet {
public void triggerReloadDatabaseEntries() {
LOG.debug("external reload triggered");
- this.entryProvider.triggerReloadSync();
+ entryProvider.triggerReloadSync();
}
@Override
@@ -85,7 +85,7 @@ public class MsServlet extends BaseServlet {
}
protected String getBaseUrl(String dbServerId) {
- return this.entryProvider.getHostUrl(dbServerId);
+ return entryProvider.getHostUrl(dbServerId);
}
@Override
protected boolean doTrustAll() {
@@ -97,6 +97,16 @@ public class MsServlet extends BaseServlet {
}
public void setDataProvider(MediatorServerDataProvider mediatorServerDataProvider) {
- this.entryProvider = mediatorServerDataProvider;
+ entryProvider = mediatorServerDataProvider;
+ }
+
+ @Override
+ protected boolean trustInsecure() {
+ return trustAll;
+ }
+
+ @Override
+ protected boolean isCorsEnabled() {
+ return false;
}
}
diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java
index fc9ae5085..a846cd8f3 100644
--- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java
+++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java
@@ -98,7 +98,7 @@ public class EsConfig implements Configuration, IEsConfig {
public boolean hasBasicAuthCredentials() {
return this.getBasicAuthUsername()!=null && this.getBasicAuthPassword()!=null &&
- this.getBasicAuthUsername()!="" && this.getBasicAuthPassword()!="" ;
+ !this.getBasicAuthUsername().isEmpty() && !this.getBasicAuthPassword().isEmpty() ;
}
public String getBasicAuthUsername() {
return this.configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_USERNAME);
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java
index 748ad51c6..d898644c9 100644
--- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java
@@ -114,7 +114,7 @@ public class TestCRUDforDatabase {
private static ElasticSearchDataProvider dbProvider;
private static HtDatabaseClient dbRawProvider;
- private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer
+ public static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer
.valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) };
@BeforeClass
@@ -125,7 +125,7 @@ public class TestCRUDforDatabase {
dbRawProvider = new HtDatabaseClient(hosts);
}
- private static void trySleep(long ms) {
+ public static void trySleep(long ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
@@ -133,7 +133,7 @@ public class TestCRUDforDatabase {
}
}
- private static void trySleep() {
+ public static void trySleep() {
trySleep(0);
}
@@ -1183,8 +1183,8 @@ public class TestCRUDforDatabase {
// == UPDATE ==============================
- String shouldbeEmpty = dbRawProvider.doUpdate(Entity.Historicalperformance24h.getName(), "{'uuid-interface':'LTP-TEST-MWP-097'}", QueryBuilders.termQuery("_id", aDbId));
- assertEquals("",shouldbeEmpty);
+ boolean success = dbRawProvider.doUpdate(Entity.Historicalperformance24h.getName(), "{'uuid-interface':'LTP-TEST-MWP-097'}", QueryBuilders.termQuery("_id", aDbId));
+ assertTrue("update dbentry not succeeded",success);
try {
readltpResult = dbProvider.readPmdata24hLtpList(readLtp);
} catch (Exception e) {
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java
new file mode 100644
index 000000000..850d80e1a
--- /dev/null
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java
@@ -0,0 +1,316 @@
+/*******************************************************************************
+ * ============LICENSE_START========================================================================
+ * ONAP : ccsdk feature sdnr wt
+ * =================================================================================================
+ * Copyright (C) 2020 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.dataprovider.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
+import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
+import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
+import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
+import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
+import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest;
+import org.onap.ccsdk.features.sdnr.wt.common.database.requests.SearchRequest;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.ElasticSearchDataProvider;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.HtDatabaseEventsService;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStampImpl;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionLogStatus;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.ConnectionlogBuilder;
+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.Entity;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.EventlogBuilder;
+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.FaultcurrentBuilder;
+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.FaultlogBuilder;
+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.GranularityPeriodType;
+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.InventoryBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.NetworkElementConnectionBuilder;
+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.NetworkElementDeviceType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.PmdataEntity;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.PmdataEntityBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SeverityType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SourceType;
+
+/**
+ * @author Michael Dürre
+ *
+ */
+public class TestEventService {
+ private static ElasticSearchDataProvider dbProvider;
+ private static HtDatabaseClient dbRawProvider;
+ private static HtDatabaseEventsService service = null;
+
+ private static final String NODEID = "node1";
+ private static final String NODEID2 = "node2";
+ private static final String OBJECTREFID1 = "objid1";
+ private static final String OBJECTREFID2 = "objid2";
+
+ @BeforeClass
+ public static void init() throws Exception {
+
+ dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts);
+ dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS);
+ dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts);
+
+ try {
+ service = new HtDatabaseEventsService(dbRawProvider, dbProvider);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testClearFaultsCurrent() {
+
+ service.clearFaultsCurrentOfNode(NODEID);
+ service.clearFaultsCurrentOfNode(NODEID2);
+
+ List<String> nodeIds = service.getAllNodesWithCurrentAlarms();
+ if (nodeIds.size() > 0) {
+ for (String nodeId : nodeIds) {
+ service.clearFaultsCurrentOfNode(nodeId);
+ }
+ }
+ service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abc", SeverityType.Major));
+ service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abcde", SeverityType.Major));
+ service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.Major));
+ service.updateFaultCurrent(createFault(NODEID2, OBJECTREFID2, "abcde", SeverityType.Major));
+ nodeIds = service.getAllNodesWithCurrentAlarms();
+ assertTrue(nodeIds.size() == 2);
+ service.clearFaultsCurrentOfNodeWithObjectId(NODEID, OBJECTREFID1);
+ nodeIds = service.getAllNodesWithCurrentAlarms();
+ assertTrue(nodeIds.size() == 2);
+ service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.NonAlarmed));
+ nodeIds = service.getAllNodesWithCurrentAlarms();
+ assertTrue(nodeIds.size() == 1);
+ }
+
+ private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem,
+ SeverityType severity) {
+ return createFault(nodeId, objectRefId, problem, severity, NetconfTimeStampImpl.getConverter().getTimeStamp());
+ }
+
+ /**
+ * @param nODENAME
+ * @param problem
+ * @param ts
+ * @param severity
+ * @return
+ */
+ private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem,
+ SeverityType severity, DateAndTime ts) {
+ return new FaultcurrentBuilder().setNodeId(nodeId).setObjectId(objectRefId).setTimestamp(ts)
+ .setSeverity(severity).setProblem(problem).build();
+ }
+
+ @Test
+ public void testIndexClean() {
+ Date now = new Date();
+ service.doIndexClean(now);
+ clearDbEntity(Entity.Eventlog);
+ clearDbEntity(Entity.Faultlog);
+ TestCRUDforDatabase.trySleep(1000);
+ service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "abc", 1));
+ service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "avasvas", 2));
+
+ service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 1));
+ service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 2));
+ service.writeFaultLog(createFaultLog(NODEID2, OBJECTREFID2, "problem", SeverityType.Major, 1));
+ TestCRUDforDatabase.trySleep(100);
+ now = new Date();
+ int numOlds = service.getNumberOfOldObjects(now);
+ assertEquals(5, numOlds);
+ TestCRUDforDatabase.trySleep(100);
+ service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 3));
+ service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 5));
+ service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 6));
+ numOlds = service.getNumberOfOldObjects(now);
+ assertEquals(5, numOlds);
+ now = new Date();
+ numOlds = service.getNumberOfOldObjects(now);
+ assertEquals(8, numOlds);
+ service.doIndexClean(now);
+ numOlds = service.getNumberOfOldObjects(now);
+ assertEquals(0, numOlds);
+
+ }
+
+ @Test
+ public void testPm() {
+ final String IFNAME1 = "if1";
+ final String SCNID1 = "scn1";
+ List<PmdataEntity> list = Arrays.asList(createPmData(NODEID, IFNAME1, SCNID1),
+ createPmData(NODEID, IFNAME1, SCNID1), createPmData(NODEID, IFNAME1, SCNID1),
+ createPmData(NODEID, IFNAME1, SCNID1)
+
+ );
+ service.doWritePerformanceData(list);
+ }
+
+ /**
+ * @param ifname
+ * @param ifUuid
+ * @param scannerId
+ * @param nodename3
+ * @return
+ */
+ private static PmdataEntity createPmData(String nodeId, String ifUuid, String scannerId) {
+ return new PmdataEntityBuilder().setNodeName(nodeId).setGranularityPeriod(GranularityPeriodType.Period15Min)
+ .setUuidInterface(ifUuid).setScannerId(scannerId).setLayerProtocolName("NETCONF")
+ .setPerformanceData(null).setSuspectIntervalFlag(true)
+ .setTimeStamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).build();
+ }
+
+ @Test
+ public void testNeConnection() {
+ service.removeNetworkConnection(NODEID);
+ service.removeNetworkConnection(NODEID2);
+
+ clearDbEntity(Entity.NetworkelementConnection);
+ List<NetworkElementConnectionEntity> nes = service.getNetworkElementConnections();
+ assertEquals(0, nes.size());
+ service.updateNetworkConnection22(createNeConnection(NODEID, NetworkElementDeviceType.Unknown), NODEID);
+ service.updateNetworkConnection22(createNeConnection(NODEID2, NetworkElementDeviceType.ORAN), NODEID2);
+ nes = service.getNetworkElementConnections();
+ assertEquals(2, nes.size());
+ service.updateNetworkConnectionDeviceType(createNeConnection(NODEID, NetworkElementDeviceType.Wireless),
+ NODEID);
+ nes = service.getNetworkElementConnections();
+ assertEquals(2, nes.size());
+ boolean found = false;
+ for (NetworkElementConnectionEntity ne : nes) {
+ if (NODEID.equals(ne.getNodeId()) && ne.getDeviceType() == NetworkElementDeviceType.Wireless) {
+ found = true;
+ }
+ }
+ assertTrue(found);
+
+ }
+
+ @Test
+ public void testConnectionLog() {
+ clearDbEntity(Entity.Connectionlog);
+ service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted));
+ service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted));
+ assertEquals(2, getDbEntityEntries(Entity.Connectionlog).getTotal());
+ }
+
+ /**
+ * @param nodeId
+ * @param status
+ * @return
+ */
+ private static ConnectionlogEntity createConnectionLog(String nodeId, ConnectionLogStatus status) {
+ return new ConnectionlogBuilder().setNodeId(nodeId)
+ .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setStatus(status).build();
+ }
+
+ @Test
+ public void testInventory() {
+ clearDbEntity(Entity.Inventoryequipment);
+ service.writeInventory(createEquipment(NODEID, "uuid1"));
+ service.writeInventory(createEquipment(NODEID, "uuid2"));
+ service.writeInventory(createEquipment(NODEID2, "uuid3"));
+ service.writeInventory(createEquipment(NODEID2, "uuid4"));
+ service.writeInventory(createEquipment(NODEID2, "uuid5"));
+ assertEquals(5, getDbEntityEntries(Entity.Inventoryequipment).getTotal());
+ }
+
+ private static SearchResult<SearchHit> getDbEntityEntries(Entity entity) {
+ return dbRawProvider.doReadAllJsonData(entity.getName());
+ }
+
+ private static void clearDbEntity(Entity entity) {
+ DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName());
+ query.setQuery(QueryBuilders.matchAllQuery().toJSON());
+ try {
+ dbRawProvider.deleteByQuery(query);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ TestCRUDforDatabase.trySleep(1000);
+ }
+
+ /**
+ * @param nodeId
+ * @param uuid
+ * @return
+ */
+ private Inventory createEquipment(String nodeId, String uuid) {
+ return new InventoryBuilder().setNodeId(nodeId).setParentUuid("").setDescription("desc")
+ .setManufacturerName("manu").setUuid(uuid).build();
+ }
+
+ /**
+ * @param devType
+ * @param nodename3
+ * @return
+ */
+ private static NetworkElementConnectionEntity createNeConnection(String nodeId, NetworkElementDeviceType devType) {
+ return new NetworkElementConnectionBuilder().setNodeId(nodeId).setHost("host").setPort(1234L)
+ .setCoreModelCapability("123").setStatus(ConnectionLogStatus.Connected).setDeviceType(devType)
+ .setIsRequired(true).build();
+ }
+
+ /**
+ * @param nodeId
+ * @param objectId
+ * @param problem
+ * @param severity
+ * @param counter
+ * @return
+ */
+ private static FaultlogEntity createFaultLog(String nodeId, String objectId, String problem, SeverityType severity,
+ int counter) {
+ return new FaultlogBuilder().setNodeId(nodeId).setObjectId(objectId).setProblem(problem).setSeverity(severity)
+ .setCounter(counter).setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp())
+ .setSourceType(SourceType.Netconf).build();
+ }
+
+ /**
+ * @param nodeId
+ * @param objectId
+ * @param attributeName
+ * @param newValue
+ * @param counter
+ * @return
+ */
+ private static EventlogEntity createEventLog(String nodeId, String objectId, String attributeName, String newValue,
+ int counter) {
+ return new EventlogBuilder().setNodeId(nodeId).setObjectId(objectId).setAttributeName(attributeName)
+ .setNewValue(newValue).setCounter(counter)
+ .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setSourceType(SourceType.Netconf)
+ .build();
+ }
+}
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java
index 94381b6a3..5ce8fcc0b 100644
--- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java
@@ -17,23 +17,47 @@
******************************************************************************/
package org.onap.ccsdk.features.sdnr.wt.dataprovider.test;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.QueryByFilter;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.SortOrder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.entity.input.Filter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.entity.input.FilterBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.entity.input.Sortorder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.entity.input.SortorderBuilder;
public class TestFilterConversion {
private static final String PROPERTY = "node-id";
+ private static final String PROPERTY2 = "_id";
+ private static final String PROPERTY3 = "timestamp";
@Test
public void testQuestionMark() {
- List<Filter> filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build());
- QueryBuilder query = QueryByFilter.fromFilter(filters );
+ List<Filter> filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build());
+ QueryBuilder query = QueryByFilter.fromFilter(filters);
+ System.out.println(query.toJSON());
+ assertTrue(query.toJSON().contains("{1,1}"));
+ assertNotNull(QueryByFilter.getFilter(filters, PROPERTY));
+ assertNull(QueryByFilter.getFilter(filters, PROPERTY2));
+ filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(),
+ new FilterBuilder().setProperty(PROPERTY2).setFiltervalue("abc").build());
+ query = QueryByFilter.fromFilter(filters);
System.out.println(query.toJSON());
+ assertNotNull(QueryByFilter.getFilter(filters, PROPERTY2));
+ filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(),
+ new FilterBuilder().setProperty(PROPERTY3).setFiltervalue("<2019-06-13T15:00:12.0Z").build());
+ query = QueryByFilter.fromFilter(filters);
+ List<Sortorder> sortorder = Arrays
+ .asList(new SortorderBuilder().setProperty(PROPERTY).setSortorder(SortOrder.Ascending).build());
+ QueryByFilter.setSortOrder(query, sortorder);
+ assertNotNull(QueryByFilter.getSortOrder(sortorder, PROPERTY));
}
}
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java
new file mode 100644
index 000000000..eae301a34
--- /dev/null
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * ============LICENSE_START========================================================================
+ * ONAP : ccsdk feature sdnr wt
+ * =================================================================================================
+ * Copyright (C) 2020 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.dataprovider.test;
+
+import static org.junit.Assert.fail;
+
+import java.util.Set;
+
+import org.junit.Test;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.http.AboutHttpServlet;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.http.MsServlet;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.impl.DataProviderImpl;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.StatusChangedHandler.StatusKey;
+import org.opendaylight.mdsal.binding.api.RpcProviderService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.DataProviderService;
+import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+
+import net.bytebuddy.implementation.bytecode.StackSize;
+
+/**
+ * @author Michael Dürre
+ *
+ */
+public class TestImplementation {
+
+ @Test
+ public void test() {
+ DataProviderImpl impl = new DataProviderImpl();
+ impl.setRpcProviderService(new RpcProviderService() {
+
+ @Override
+ public <S extends RpcService, T extends S> ObjectRegistration<T> registerRpcImplementation(Class<S> type,
+ T implementation, Set<InstanceIdentifier<?>> paths) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public <S extends RpcService, T extends S> ObjectRegistration<T> registerRpcImplementation(Class<S> type,
+ T implementation) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+ });
+ impl.setMediatorServerServlet(new MsServlet());
+ impl.setAboutServlet(new AboutHttpServlet());
+ try {
+ impl.init();
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("failed to init impl: "+e.getMessage());
+ }
+
+ impl.setStatus(StatusKey.CLUSTER_SIZE, "3");
+ impl.setReadyStatus(true);
+ try {
+ impl.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("failed to close impl: "+e.getMessage());
+ }
+ }
+
+}
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestInitalMaintenanceObjectInDatabase.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestInitalMaintenanceObjectInDatabase.java
deleted file mode 100644
index 633912579..000000000
--- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestInitalMaintenanceObjectInDatabase.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * ============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.dataprovider.test;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
-/**
- * - Handling of inital values for Maintenance mode.
- */
-public class TestInitalMaintenanceObjectInDatabase {
-
- //@Test
- public void test() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceService.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceService.java
new file mode 100644
index 000000000..bd91219c8
--- /dev/null
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceService.java
@@ -0,0 +1,97 @@
+/*******************************************************************************
+ * ============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.dataprovider.test;
+
+import static org.junit.Assert.*;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
+import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
+import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.ElasticSearchDataProvider;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.HtDatabaseEventsService;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.HtDatabaseMaintenanceService;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.HtDatabaseMaintenance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Entity;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MaintenanceEntity;
+
+/**
+ * - Handling of inital values for Maintenance mode.
+ */
+public class TestMaintenanceService {
+
+ private static ElasticSearchDataProvider dbProvider;
+ private static HtDatabaseClient dbRawProvider;
+ private static HtDatabaseMaintenance service = null;
+
+ private static final String NODEID = "node1";
+ private static final String NODEID2 = "node2";
+ @BeforeClass
+ public static void init() throws Exception {
+
+ dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts);
+ dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS);
+ dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts);
+ service = dbProvider.getHtDatabaseMaintenance();
+ }
+ @Test
+ public void test() {
+ clearDbEntity(Entity.Maintenancemode);
+ MaintenanceEntity obj = service.createIfNotExists(NODEID);
+ assertNotNull(obj);
+ obj = service.createIfNotExists(NODEID2);
+ assertNotNull(obj);
+ obj = service.getMaintenance(NODEID);
+ assertNotNull(obj);
+ List<MaintenanceEntity> list = service.getAll();
+ assertEquals(2,list.size());
+ service.deleteIfNotRequired(NODEID);
+ obj = service.getMaintenance(NODEID);
+ assertNull(obj);
+
+
+ obj = service.setMaintenance(createMaintenance(NODEID,true));
+
+
+ }
+ /**
+ * @param nodeId
+ * @param active
+ * @return
+ */
+ private static MaintenanceEntity createMaintenance(String nodeId, Boolean active) {
+ return new MaintenanceBuilder().setNodeId(nodeId).setActive(active).setProblem("problem").setObjectIdRef("idref").build();
+ }
+ private static void clearDbEntity(Entity entity) {
+ DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName());
+ query.setQuery(QueryBuilders.matchAllQuery().toJSON());
+ try {
+ dbRawProvider.deleteByQuery(query);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ TestCRUDforDatabase.trySleep(1000);
+ }
+
+}
diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java
new file mode 100644
index 000000000..20c0da596
--- /dev/null
+++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java
@@ -0,0 +1,92 @@
+/*******************************************************************************
+ * ============LICENSE_START========================================================================
+ * ONAP : ccsdk feature sdnr wt
+ * =================================================================================================
+ * Copyright (C) 2020 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.dataprovider.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
+import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
+import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.ElasticSearchDataProvider;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.data.MediatorServerDataProvider;
+import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.HtDatabaseMaintenance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateMediatorServerInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateMediatorServerOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Entity;
+
+/**
+ * @author Michael Dürre
+ *
+ */
+public class TestMediatorServerService {
+ private static final String SERVERID = null;
+ private static ElasticSearchDataProvider dbProvider;
+ private static HtDatabaseClient dbRawProvider;
+ private static MediatorServerDataProvider service = null;
+
+
+ @BeforeClass
+ public static void init() throws Exception {
+
+ dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts);
+ dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS);
+ dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts);
+ service = new MediatorServerDataProvider(TestCRUDforDatabase.hosts);
+
+
+ }
+ @Test
+ public void test() {
+ clearDbEntity(Entity.MediatorServer);
+ System.out.println(service.triggerReloadSync());
+ String dbServerId="abc";
+ String host = service.getHostUrl(dbServerId);
+ assertNull(host);
+ final String NAME="ms1";
+ final String HOST = "http://10.20.30.40:7070";
+ CreateMediatorServerOutputBuilder output = null;
+ try {
+ output = dbProvider.createMediatorServer(new CreateMediatorServerInputBuilder().setName(NAME).setUrl(HOST).build());
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail("unable to create ms entry: "+e.getMessage());
+ }
+ System.out.println(service.triggerReloadSync());
+ host = service.getHostUrl(output.getId());
+ assertEquals(HOST, host);
+
+ }
+
+ private static void clearDbEntity(Entity entity) {
+ DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName());
+ query.setQuery(QueryBuilders.matchAllQuery().toJSON());
+ try {
+ dbRawProvider.deleteByQuery(query);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ TestCRUDforDatabase.trySleep(1000);
+ }
+}