summaryrefslogtreecommitdiffstats
path: root/sdnr/wt/common
diff options
context:
space:
mode:
Diffstat (limited to 'sdnr/wt/common')
-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
13 files changed, 634 insertions, 209 deletions
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 ;
+}