From 8f9aa1fb011ed22c60a662d647c4e4ae4c5c6560 Mon Sep 17 00:00:00 2001 From: highstreetherbert Date: Fri, 10 Jul 2020 15:30:18 +0200 Subject: Reformat sdnr common to ONAP code style Reformat to ONAP code style Issue-ID: SDNC-1272 Signed-off-by: highstreetherbert Change-Id: I4ac9bf101fbd679e582ffcdfdc5959278ad1c5ec Signed-off-by: highstreetherbert --- .../sdnr/wt/common/test/TestBaseHttpClient.java | 272 +++--- .../sdnr/wt/common/test/TestBaseServlet.java | 73 +- .../features/sdnr/wt/common/test/TestConfig.java | 432 ++++----- .../common/test/TestDatabaseFilterConversion.java | 106 +-- .../features/sdnr/wt/common/test/TestDbClient.java | 298 +++---- .../sdnr/wt/common/test/TestDbQueries.java | 409 ++++----- .../sdnr/wt/common/test/TestDbRequests.java | 972 ++++++++++----------- .../features/sdnr/wt/common/test/TestEsData.java | 144 +-- .../sdnr/wt/common/test/TestJsonAssert.java | 277 +++--- .../sdnr/wt/common/test/TestPageHashMap.java | 48 +- .../features/sdnr/wt/common/test/TestPomfile.java | 13 +- .../sdnr/wt/common/test/TestPortstatus.java | 24 +- .../sdnr/wt/common/test/helper/HelpServlet.java | 203 +++-- .../wt/common/test/helper/HelpServletBase.java | 349 ++++---- .../sdnr/wt/common/test/helper/IPublicServlet.java | 14 +- 15 files changed, 1792 insertions(+), 1842 deletions(-) (limited to 'sdnr/wt/common/src/test/java') 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 57ae0e3bc..3584d7f28 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 @@ -47,141 +47,139 @@ import com.sun.net.httpserver.HttpServer; @SuppressWarnings("restriction") public class TestBaseHttpClient { - 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"; - 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 TESTURI = "/mwtn/test"; - private static HttpServer server; - private static ExecutorService httpThreadPool; - private static final int testPort = 54440; - - @Test - public void test() { - MyHttpClient httpClient = new MyHttpClient("http://localhost:"+testPort, true); - Map headers = new HashMap(); - headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin")); - headers.put("Content-Type","application/json"); - BaseHTTPResponse response=null; - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_GET, response.body); - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers ); - } catch (IOException e) { - 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 ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_PUT, response.body); - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_DELETE, response.body); - - } - - - - - @BeforeClass - public static void initTestWebserver() throws IOException { - server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0); - httpThreadPool = Executors.newFixedThreadPool(5); - server.setExecutor(httpThreadPool); - server.createContext(TESTURI, new MyHandler()); - //server.createContext("/", new MyRootHandler()); - server.setExecutor(null); // creates a default executor - server.start(); - System.out.println("http server started"); - } - @AfterClass - public static void stopTestWebserver() { - System.out.println("try to stop server"); - if (server != null) { - server.stop(0); - httpThreadPool.shutdownNow(); - System.out.println("http server stopped" ); - } - } - - private class MyHttpClient extends BaseHTTPClient{ - - public MyHttpClient(String base, boolean trustAllCerts) { - super(base, trustAllCerts); - } - - @Override - public BaseHTTPResponse sendRequest(String uri, String method, String body, Map headers) - throws IOException { - return super.sendRequest(uri, method, body, headers); - } - } - - 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.flush(); - os.close(); - } - } - } - } + 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"; + 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 TESTURI = "/mwtn/test"; + private static HttpServer server; + private static ExecutorService httpThreadPool; + private static final int testPort = 54440; + + @Test + public void test() { + MyHttpClient httpClient = new MyHttpClient("http://localhost:" + testPort, true); + Map headers = new HashMap(); + headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin")); + headers.put("Content-Type", "application/json"); + BaseHTTPResponse response = null; + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_GET, response.body); + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers); + } catch (IOException e) { + 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); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_PUT, response.body); + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_DELETE, response.body); + + } + + + + @BeforeClass + public static void initTestWebserver() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(TESTURI, new MyHandler()); + //server.createContext("/", new MyRootHandler()); + server.setExecutor(null); // creates a default executor + server.start(); + System.out.println("http server started"); + } + + @AfterClass + public static void stopTestWebserver() { + System.out.println("try to stop server"); + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); + System.out.println("http server stopped"); + } + } + + private class MyHttpClient extends BaseHTTPClient { + + public MyHttpClient(String base, boolean trustAllCerts) { + super(base, trustAllCerts); + } + + @Override + public BaseHTTPResponse sendRequest(String uri, String method, String body, Map headers) + throws IOException { + return super.sendRequest(uri, method, body, headers); + } + } + + 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.flush(); + os.close(); + } + } + } + } } 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 index 02a82a70d..0c1ae50ee 100644 --- 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 @@ -35,40 +35,43 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServletBase; * @author Michael Dürre * */ -public class TestBaseServlet extends HelpServletBase{ +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(); - } + 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/TestConfig.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java index 3b19f5c4b..415620415 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java @@ -44,218 +44,222 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo.Protocol; public class TestConfig { - private static final String TESTFILENAME = "test.properties"; - private static final String TESTKEY1 = "abc"; - private static final String TESTKEY2 = "def"; - private static final String TESTKEY3 = "hhh"; - private static final String TESTKEY4 = "hhv"; - - private static final int TESTVALUE1=123; - private static final int TESTVALUE1_2=1234; - private static final boolean TESTVALUE2 = true; - private static final String TESTVALUE3 = "http://localhost:2223"; - private static final String TESTVALUE4 = "httasdasdas"; - private static final String TESTCONTENT1 = " [test]\n" + - TESTKEY1+"="+TESTVALUE1+"\n" + - "#her a comment\n"+ - TESTKEY2+"="+TESTVALUE2+"\n" + - TESTKEY3+"="+TESTVALUE3; - - - - - @After - @Before - public void init() { - File f=new File(TESTFILENAME); - if(f.exists()) { - f.delete(); - } - } - - public void write(String filename,String lines) { - - try { - Files.write(new File(filename).toPath(), lines.getBytes()); - } catch (IOException e) { - fail("problem writing file "+filename); - } - } - @Test - public void testRead() { - this.write(TESTFILENAME, TESTCONTENT1); - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section = confiuration.getSection("test").get(); - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - this.init(); - } - @Test - public void testWrite() { - final String SECTIONNAME = "test"; - //write values - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section=confiuration.addSection(SECTIONNAME); - - section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); - section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); - section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); - confiuration.save(); - - //verify written - ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - this.init(); - - //write directly into base - confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - section=confiuration.addSection(SECTIONNAME); - confiuration.setProperty(SECTIONNAME,TESTKEY1 , TESTVALUE1); - confiuration.setProperty(SECTIONNAME,TESTKEY2 , TESTVALUE2); - confiuration.setProperty(SECTIONNAME,TESTKEY3 , TESTVALUE3); - confiuration.save(); - - //verify - confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); - assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); - assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); - this.init(); - - - } - @Test - public void testOverwrite() { - final String SECTIONNAME = "test"; - //write values - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section=confiuration.addSection(SECTIONNAME); - - section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); - section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); - section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); - confiuration.save(); - - //verify written - ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - - section = confiuration2.getSection(SECTIONNAME).get(); - - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - - //write directly into base - confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - section=confiuration.addSection(SECTIONNAME); - confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY1 , TESTVALUE1_2); - confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY4 , TESTVALUE4); - - confiuration.save(); - - //verify - confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); - assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); - assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); - assertEquals(TESTVALUE4, confiuration.getProperty(SECTIONNAME,TESTKEY4)); - this.init(); - - - } - static boolean changeFlag=false; - @Test - public void testChangeListener() { - - changeFlag=false; - this.init(); - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - IConfigChangedListener listener = new IConfigChangedListener() { - - @Override - public void onConfigChanged() { - changeFlag=true; - } - }; - confiuration.registerConfigChangedListener(listener ); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - this.write(TESTFILENAME, TESTCONTENT1); - int i=10; - while(i-->0) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - if(changeFlag) { - break; - } - } - confiuration.unregisterConfigChangedListener(listener); - assertTrue("changelistener not called",changeFlag); - } - @Test - public void testHostInfo() { - HostInfo hi=HostInfo.getDefault(); - try { - new URL(hi.toUrl()); - } catch (MalformedURLException e) { - fail("url conversion failed: "+e.getMessage()); - } - hi = new HostInfo("localhost", 44444, Protocol.getValueOf("https")); - try { - new URL(hi.toUrl()); - } catch (MalformedURLException e) { - fail("url conversion failed: "+e.getMessage()); - } - - } - @Test - public void testEnvPropert() { - final String KEY = "basada"; - Section section = new Section("test"); - section.addLine(KEY+"=${USER} in ${HOME}"); - section.parseLines(); - assertTrue(section.getProperty(KEY).length()>" in ".length()); - } - public static void setEnv(String key, String value) { - try { - Map env = System.getenv(); - Class cl = env.getClass(); - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Map writableEnv = (Map) field.get(env); - writableEnv.put(key, value); - } catch (Exception e) { - throw new IllegalStateException("Failed to set environment variable", e); - } - } + private static final String TESTFILENAME = "test.properties"; + private static final String TESTKEY1 = "abc"; + private static final String TESTKEY2 = "def"; + private static final String TESTKEY3 = "hhh"; + private static final String TESTKEY4 = "hhv"; + + private static final int TESTVALUE1 = 123; + private static final int TESTVALUE1_2 = 1234; + private static final boolean TESTVALUE2 = true; + private static final String TESTVALUE3 = "http://localhost:2223"; + private static final String TESTVALUE4 = "httasdasdas"; + private static final String TESTCONTENT1 = " [test]\n" + TESTKEY1 + "=" + TESTVALUE1 + "\n" + "#her a comment\n" + + TESTKEY2 + "=" + TESTVALUE2 + "\n" + TESTKEY3 + "=" + TESTVALUE3; + + + + @After + @Before + public void init() { + File f = new File(TESTFILENAME); + if (f.exists()) { + f.delete(); + } + } + + public void write(String filename, String lines) { + + try { + Files.write(new File(filename).toPath(), lines.getBytes()); + } catch (IOException e) { + fail("problem writing file " + filename); + } + } + + @Test + public void testRead() { + this.write(TESTFILENAME, TESTCONTENT1); + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.getSection("test").get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + } + + @Test + public void testWrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + + //write directly into base + confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration.addSection(SECTIONNAME); + confiuration.setProperty(SECTIONNAME, TESTKEY1, TESTVALUE1); + confiuration.setProperty(SECTIONNAME, TESTKEY2, TESTVALUE2); + confiuration.setProperty(SECTIONNAME, TESTKEY3, TESTVALUE3); + confiuration.save(); + + //verify + confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME, TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME, TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME, TESTKEY3)); + this.init(); + + + } + + @Test + public void testOverwrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + + //write directly into base + confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration.addSection(SECTIONNAME); + confiuration.setPropertyIfNotAvailable(SECTIONNAME, TESTKEY1, TESTVALUE1_2); + confiuration.setPropertyIfNotAvailable(SECTIONNAME, TESTKEY4, TESTVALUE4); + + confiuration.save(); + + //verify + confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME, TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME, TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME, TESTKEY3)); + assertEquals(TESTVALUE4, confiuration.getProperty(SECTIONNAME, TESTKEY4)); + this.init(); + + + } + + static boolean changeFlag = false; + + @Test + public void testChangeListener() { + + changeFlag = false; + this.init(); + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + IConfigChangedListener listener = new IConfigChangedListener() { + + @Override + public void onConfigChanged() { + changeFlag = true; + } + }; + confiuration.registerConfigChangedListener(listener); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + this.write(TESTFILENAME, TESTCONTENT1); + int i = 10; + while (i-- > 0) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + if (changeFlag) { + break; + } + } + confiuration.unregisterConfigChangedListener(listener); + assertTrue("changelistener not called", changeFlag); + } + + @Test + public void testHostInfo() { + HostInfo hi = HostInfo.getDefault(); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: " + e.getMessage()); + } + hi = new HostInfo("localhost", 44444, Protocol.getValueOf("https")); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: " + e.getMessage()); + } + + } + + @Test + public void testEnvPropert() { + final String KEY = "basada"; + Section section = new Section("test"); + section.addLine(KEY + "=${USER} in ${HOME}"); + section.parseLines(); + assertTrue(section.getProperty(KEY).length() > " in ".length()); + } + + public static void setEnv(String key, String value) { + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(key, value); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java index fc244f6b6..4d7cbdce9 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java @@ -32,54 +32,60 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.DbFilter; public class TestDatabaseFilterConversion { - @Test - public void testStartsWith() { - String re=DbFilter.createDatabaseRegex("abc*"); - assertEquals("abc.*", re); - } - @Test - public void testEndsWith() { - String re=DbFilter.createDatabaseRegex("*abc"); - assertEquals(".*abc", re); - } - @Test - public void testMultiple() { - String re=DbFilter.createDatabaseRegex("abc*ff*fa"); - assertEquals("abc.*ff.*fa", re); - } - - @Test - public void testPlaceholder() { - String re=DbFilter.createDatabaseRegex("abc?ef"); - assertEquals("abc.{1,1}ef", re); - } - @Test - public void testCombined() { - String re=DbFilter.createDatabaseRegex("abc?ff*fa"); - assertEquals("abc.{1,1}ff.*fa", re); - } - @Test - public void testFilterCheck() { - assertTrue(DbFilter.hasSearchParams("abc?")); - assertTrue(DbFilter.hasSearchParams("bac*")); - assertFalse(DbFilter.hasSearchParams("abc+")); - } - @Test - public void testRangeConversion() { - try { - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gte\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", ">=2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gt\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", ">2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lte\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", "<=2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lt\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", "<2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"timestamp\":{\"lt\":\"2018-01-01T23:59:59.0Z\",\"boost\":2}}}}", - DbFilter.getRangeQuery("timestamp", "<2018-01-01T23:59:59.0Z").toJSON(),true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - + @Test + public void testStartsWith() { + String re = DbFilter.createDatabaseRegex("abc*"); + assertEquals("abc.*", re); + } + + @Test + public void testEndsWith() { + String re = DbFilter.createDatabaseRegex("*abc"); + assertEquals(".*abc", re); + } + + @Test + public void testMultiple() { + String re = DbFilter.createDatabaseRegex("abc*ff*fa"); + assertEquals("abc.*ff.*fa", re); + } + + @Test + public void testPlaceholder() { + String re = DbFilter.createDatabaseRegex("abc?ef"); + assertEquals("abc.{1,1}ef", re); + } + + @Test + public void testCombined() { + String re = DbFilter.createDatabaseRegex("abc?ff*fa"); + assertEquals("abc.{1,1}ff.*fa", re); + } + + @Test + public void testFilterCheck() { + assertTrue(DbFilter.hasSearchParams("abc?")); + assertTrue(DbFilter.hasSearchParams("bac*")); + assertFalse(DbFilter.hasSearchParams("abc+")); + } + + @Test + public void testRangeConversion() { + try { + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">=2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<=2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<2230").toJSON(), true); + JSONAssert.assertEquals("", + "{\"query\":{\"range\":{\"timestamp\":{\"lt\":\"2018-01-01T23:59:59.0Z\",\"boost\":2}}}}", + DbFilter.getRangeQuery("timestamp", "<2018-01-01T23:59:59.0Z").toJSON(), true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + } 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 04259b9f6..cf9d93052 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 @@ -40,154 +40,154 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetIndexRequest; public class TestDbClient { - private static HtDatabaseClient dbClient; - private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; - - @BeforeClass - public static void init() throws Exception { - - dbClient = new HtDatabaseClient(hosts); - dbClient.waitForYellowStatus(20000); - - } - - @Test - public void testCRUD() { - final String IDX = "test23-knmoinsd"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - clearIndexData(IDX); - //Create - String esId = dbClient.doWriteRaw(IDX, ID, JSON); - assertEquals("inserted id is wrong", ID, esId); - //Read - SearchResult 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()); - //Update - esId = dbClient.doUpdateOrCreate(IDX, ID, JSON2); - assertEquals("update response not successfull", ID, esId); - //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, 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()); - - } - - /** - * @param iDX - */ - private void clearIndexData(String idx) { - try { - dbClient.deleteByQuery(new DeleteByQueryRequest(idx, true).source(QueryBuilders.matchAllQuery())); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - @Test - public void testCRUD2() { - final String IDX = "test23-knmoins3d"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - //Create - String esId = dbClient.doWriteRaw(IDX, ID, JSON); - assertEquals("inserted id is wrong", ID, esId); - //Read - SearchResult 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()); - - } + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; + + @BeforeClass + public static void init() throws Exception { + + dbClient = new HtDatabaseClient(hosts); + dbClient.waitForYellowStatus(20000); + + } + + @Test + public void testCRUD() { + final String IDX = "test23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + clearIndexData(IDX); + //Create + String esId = dbClient.doWriteRaw(IDX, ID, JSON); + assertEquals("inserted id is wrong", ID, esId); + //Read + SearchResult 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()); + //Update + esId = dbClient.doUpdateOrCreate(IDX, ID, JSON2); + assertEquals("update response not successfull", ID, esId); + //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, 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()); + + } + + /** + * @param iDX + */ + private void clearIndexData(String idx) { + try { + dbClient.deleteByQuery(new DeleteByQueryRequest(idx, true).source(QueryBuilders.matchAllQuery())); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Test + public void testCRUD2() { + final String IDX = "test23-knmoins3d"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + //Create + String esId = dbClient.doWriteRaw(IDX, ID, JSON); + assertEquals("inserted id is wrong", ID, esId); + //Read + SearchResult 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/TestDbQueries.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java index 93d4b1af6..127908c08 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java @@ -35,252 +35,167 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; public class TestDbQueries { - private static final String MATCH_ALL_QUERY = "{\n" + - " \"query\": {\n" + - " \"match_all\" : {\n" + - " }\n" + - " }\n" + - "}"; - private static final String MATCH_QUERY_KEY = "is-required"; - private static final Object MATCH_QUERY_VALUE = true; - private static final String MATCH_QUERY = "{\n" + - " \"query\": {\n" + - " \"match\" : {\n" + - " \""+MATCH_QUERY_KEY+"\" : "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - "}"; - private static final String MATCH_QUERY_KEY2 = "node-id"; - private static final Object MATCH_QUERY_VALUE2 = "sim2"; - private static final String BOOL_QUERY_MUST = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": [\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY2+"\":"+MATCH_QUERY_VALUE2+" \n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_MUST_SINGLE = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_SHOULD = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"should\": [\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY2+"\":"+MATCH_QUERY_VALUE2+" \n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_SHOULD_SINGLE = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"should\": {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String RANGE_QUERY_KEY = "timestamp"; - private static final String RANGE_QUERY_LTEND = "2017-08-10T20:00:00.0Z"; - private static final String RANGE_QUERY = "{\n" + - " \"query\": {\n" + - " \"range\" : {\n" + - " \""+RANGE_QUERY_KEY+"\" : {\n" + - " \"lte\" : \""+RANGE_QUERY_LTEND+"\",\n" + - " \"boost\": 2.0\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String RANGEBOOL_QUERY="{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": [\n" + - " {\n" + - " \"match\": {\n" + - " \"is-required\": true\n" + - " }\n" + - " },\n" + - " {\n" + - " \"regexp\": {\n" + - " \"node-id\": {\n" + - " \"max_determinized_states\": 10000,\n" + - " \"flags\": \"ALL\",\n" + - " \"value\": \"sim.*\"\n" + - " }\n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String AGG_FIELD = "severity"; - private static final String AGG_QUERY = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"aggs\": {\n" + - " \"severity\": {\n" + - " \"terms\": {\n" + - " \"field\": \""+AGG_FIELD+"\"\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final long FROMANDSIZE_QUERY_SIZE = 20; - private static final long FROMANDSIZE_QUERY_FROM = 120; - private static final String FROMANDSIZE_QUERY = "{\n" + - " \"size\": "+FROMANDSIZE_QUERY_SIZE+",\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"from\":"+FROMANDSIZE_QUERY_FROM+"\n" + - "}"; - private static final String TERMQUERY_KEY = "node-id"; - private static final String TERMQUERY_VALUE = "abc"; - private static final String TERM_QUERY = "{\n" + - " \"query\": {\n" + - " \"term\": {\n" + - " \""+TERMQUERY_KEY+"\": \""+TERMQUERY_VALUE+"\"\n" + - " }\n" + - " }\n" + - "}"; - private static final String SORTING_PROPERTY = "node-id"; - private static final String SORTING_QUERY_ASC = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"sort\": [\n" + - " {\n" + - " \""+SORTING_PROPERTY+"\": {\n" + - " \"order\": \"asc\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"; - private static final String SORTING_QUERY_DESC = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"sort\": [\n" + - " {\n" + - " \""+SORTING_PROPERTY+"\": {\n" + - " \"order\": \"desc\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"; - - private void testEquals(String message,String json, QueryBuilder query) { - this.testEquals(message, json, query,true); - } - private void testEquals(String message,String json, QueryBuilder query,boolean strict) { - - try { - System.out.println("===test if "+message+"==================="); - System.out.println("orig : "+trim(json)); - System.out.println("totest: "+query.toJSON().trim()); - JSONAssert.assertEquals(json,query.toJSON(),strict); - } catch (JSONException e) { - fail(message); - } - } - - private String trim(String json) { - return json.trim().replaceAll("\n","").replaceAll(" ", ""); - } + private static final String MATCH_ALL_QUERY = + "{\n" + " \"query\": {\n" + " \"match_all\" : {\n" + " }\n" + " }\n" + "}"; + private static final String MATCH_QUERY_KEY = "is-required"; + private static final Object MATCH_QUERY_VALUE = true; + private static final String MATCH_QUERY = "{\n" + " \"query\": {\n" + " \"match\" : {\n" + + " \"" + MATCH_QUERY_KEY + "\" : " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + "}"; + private static final String MATCH_QUERY_KEY2 = "node-id"; + private static final Object MATCH_QUERY_VALUE2 = "sim2"; + private static final String BOOL_QUERY_MUST = + "{\n" + " \"query\": {\n" + " \"bool\": {\n" + " \"must\": [\n" + " {\n" + + " \"match\": {\n" + " \"" + MATCH_QUERY_KEY + "\": " + + MATCH_QUERY_VALUE + "\n" + " }\n" + " },\n" + + " {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY2 + "\":" + MATCH_QUERY_VALUE2 + " \n" + " }\n" + + " }\n" + " ]\n" + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_MUST_SINGLE = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"must\": {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_SHOULD = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"should\": [\n" + " {\n" + " \"match\": {\n" + + " \"" + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + + " }\n" + " },\n" + " {\n" + + " \"match\": {\n" + " \"" + MATCH_QUERY_KEY2 + "\":" + + MATCH_QUERY_VALUE2 + " \n" + " }\n" + " }\n" + " ]\n" + + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_SHOULD_SINGLE = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"should\": {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + + " }\n" + " }\n" + "}"; + private static final String RANGE_QUERY_KEY = "timestamp"; + private static final String RANGE_QUERY_LTEND = "2017-08-10T20:00:00.0Z"; + private static final String RANGE_QUERY = "{\n" + " \"query\": {\n" + " \"range\" : {\n" + + " \"" + RANGE_QUERY_KEY + "\" : {\n" + " \"lte\" : \"" + RANGE_QUERY_LTEND + + "\",\n" + " \"boost\": 2.0\n" + " }\n" + " }\n" + " }\n" + "}"; + private static final String RANGEBOOL_QUERY = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"must\": [\n" + " {\n" + " \"match\": {\n" + + " \"is-required\": true\n" + " }\n" + " },\n" + + " {\n" + " \"regexp\": {\n" + " \"node-id\": {\n" + + " \"max_determinized_states\": 10000,\n" + + " \"flags\": \"ALL\",\n" + " \"value\": \"sim.*\"\n" + + " }\n" + " }\n" + " }\n" + " ]\n" + + " }\n" + " }\n" + "}"; + private static final String AGG_FIELD = "severity"; + private static final String AGG_QUERY = + "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"aggs\": {\n" + + " \"severity\": {\n" + " \"terms\": {\n" + " \"field\": \"" + + AGG_FIELD + "\"\n" + " }\n" + " }\n" + " }\n" + "}"; + private static final long FROMANDSIZE_QUERY_SIZE = 20; + private static final long FROMANDSIZE_QUERY_FROM = 120; + private static final String FROMANDSIZE_QUERY = "{\n" + " \"size\": " + FROMANDSIZE_QUERY_SIZE + ",\n" + + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"from\":" + + FROMANDSIZE_QUERY_FROM + "\n" + "}"; + private static final String TERMQUERY_KEY = "node-id"; + private static final String TERMQUERY_VALUE = "abc"; + private static final String TERM_QUERY = "{\n" + " \"query\": {\n" + " \"term\": {\n" + " \"" + + TERMQUERY_KEY + "\": \"" + TERMQUERY_VALUE + "\"\n" + " }\n" + " }\n" + "}"; + private static final String SORTING_PROPERTY = "node-id"; + private static final String SORTING_QUERY_ASC = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + + " },\n" + " \"sort\": [\n" + " {\n" + " \"" + SORTING_PROPERTY + "\": {\n" + + " \"order\": \"asc\"\n" + " }\n" + " }\n" + " ]\n" + "}"; + private static final String SORTING_QUERY_DESC = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + + " },\n" + " \"sort\": [\n" + " {\n" + " \"" + SORTING_PROPERTY + "\": {\n" + + " \"order\": \"desc\"\n" + " }\n" + " }\n" + " ]\n" + "}"; - @Test - public void testMatchAll() { - testEquals("match all query is wrong", MATCH_ALL_QUERY, QueryBuilders.matchAllQuery()); - } - @Test - public void testMatch() { - testEquals("match query is wrong", MATCH_QUERY, QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)); - } - @Test - public void testBoolMust() { - testEquals("bool query is wrong", BOOL_QUERY_MUST, - QueryBuilders.boolQuery(). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); - } - @Test - public void testBoolMustSingle() { - testEquals("bool single query is wrong", BOOL_QUERY_MUST_SINGLE, - QueryBuilders.boolQuery(). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); - } - @Test - public void testBoolShould() { - testEquals("bool query is wrong", BOOL_QUERY_SHOULD, - QueryBuilders.boolQuery(). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); - } - @Test - public void testBoolShouldSingle() { - testEquals("bool single query is wrong", BOOL_QUERY_SHOULD_SINGLE, - QueryBuilders.boolQuery(). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); - } - @Test - public void testRange() { - testEquals("range query is wrong", RANGE_QUERY, QueryBuilders.rangeQuery(RANGE_QUERY_KEY).lte(RANGE_QUERY_LTEND)); - - } - @Test - public void testAggregation() { - testEquals("aggregation query is wrong",AGG_QUERY, QueryBuilders.matchAllQuery().aggregations(AGG_FIELD)); - } - @Test - public void testSizeAndFrom() { - testEquals("aggregation query is wrong",FROMANDSIZE_QUERY, QueryBuilders.matchAllQuery().size(FROMANDSIZE_QUERY_SIZE).from(FROMANDSIZE_QUERY_FROM)); - } - @Test - public void testRegex() { - testEquals("range and bool query is wrong1",RANGEBOOL_QUERY,QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("is-required", true)).must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))),false); - BoolQueryBuilder q = QueryBuilders.boolQuery().must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))); - q.must(QueryBuilders.matchQuery("is-required", true)); - testEquals("range and bool query is wrong2",RANGEBOOL_QUERY,q,false); - } - @Test - public void testTerm() { - testEquals("term query is wrong", TERM_QUERY, QueryBuilders.termQuery(TERMQUERY_KEY, TERMQUERY_VALUE)); - } - @Test - public void testSorting() { - testEquals("sortorder is wrong",SORTING_QUERY_ASC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.ASCENDING)); - testEquals("sortorder is wrong",SORTING_QUERY_DESC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.DESCENDING)); - } + private void testEquals(String message, String json, QueryBuilder query) { + this.testEquals(message, json, query, true); + } + + private void testEquals(String message, String json, QueryBuilder query, boolean strict) { + + try { + System.out.println("===test if " + message + "==================="); + System.out.println("orig : " + trim(json)); + System.out.println("totest: " + query.toJSON().trim()); + JSONAssert.assertEquals(json, query.toJSON(), strict); + } catch (JSONException e) { + fail(message); + } + } + + private String trim(String json) { + return json.trim().replaceAll("\n", "").replaceAll(" ", ""); + } + + @Test + public void testMatchAll() { + testEquals("match all query is wrong", MATCH_ALL_QUERY, QueryBuilders.matchAllQuery()); + } + + @Test + public void testMatch() { + testEquals("match query is wrong", MATCH_QUERY, QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)); + } + + @Test + public void testBoolMust() { + testEquals("bool query is wrong", BOOL_QUERY_MUST, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)) + .must(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); + } + + @Test + public void testBoolMustSingle() { + testEquals("bool single query is wrong", BOOL_QUERY_MUST_SINGLE, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); + } + + @Test + public void testBoolShould() { + testEquals("bool query is wrong", BOOL_QUERY_SHOULD, + QueryBuilders.boolQuery().should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)) + .should(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); + } + + @Test + public void testBoolShouldSingle() { + testEquals("bool single query is wrong", BOOL_QUERY_SHOULD_SINGLE, + QueryBuilders.boolQuery().should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); + } + + @Test + public void testRange() { + testEquals("range query is wrong", RANGE_QUERY, + QueryBuilders.rangeQuery(RANGE_QUERY_KEY).lte(RANGE_QUERY_LTEND)); + + } + + @Test + public void testAggregation() { + testEquals("aggregation query is wrong", AGG_QUERY, QueryBuilders.matchAllQuery().aggregations(AGG_FIELD)); + } + + @Test + public void testSizeAndFrom() { + testEquals("aggregation query is wrong", FROMANDSIZE_QUERY, + QueryBuilders.matchAllQuery().size(FROMANDSIZE_QUERY_SIZE).from(FROMANDSIZE_QUERY_FROM)); + } + + @Test + public void testRegex() { + testEquals("range and bool query is wrong1", RANGEBOOL_QUERY, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("is-required", true)) + .must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))), + false); + BoolQueryBuilder q = + QueryBuilders.boolQuery().must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))); + q.must(QueryBuilders.matchQuery("is-required", true)); + testEquals("range and bool query is wrong2", RANGEBOOL_QUERY, q, false); + } + + @Test + public void testTerm() { + testEquals("term query is wrong", TERM_QUERY, QueryBuilders.termQuery(TERMQUERY_KEY, TERMQUERY_VALUE)); + } + + @Test + public void testSorting() { + testEquals("sortorder is wrong", SORTING_QUERY_ASC, + QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.ASCENDING)); + testEquals("sortorder is wrong", SORTING_QUERY_DESC, + QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.DESCENDING)); + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java index 2226c5e7e..756d70c85 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java @@ -73,491 +73,491 @@ import org.json.JSONObject; public class TestDbRequests { - private static HtDatabaseClient dbClient; - private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; - - @BeforeClass - public static void init() throws Exception { - - dbClient = new HtDatabaseClient(hosts); - - } - - @AfterClass - public static void deinit() { - if (dbClient != null) { - dbClient.close(); - } - } - - @Test - public void testHealth() { - - ClusterHealthResponse response = null; - ClusterHealthRequest request = new ClusterHealthRequest(); - request.timeout(10); - try { - response = dbClient.health(request); - } catch (UnsupportedOperationException | IOException | JSONException e) { - fail(e.getMessage()); - } - assertNotNull("response is null", response); - assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW)); - } - - @Test - public void testCount() { - - } - - @Test - public void testIndexAndAliasList() { - final String ALIAS = "asdoi32kmsasd"; - final String IDX = ALIAS + "-v1"; - CreateIndexRequest request = new CreateIndexRequest(IDX); - CreateIndexResponse response = null; - try { - response = dbClient.createIndex(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - - CreateAliasRequest request3 = new CreateAliasRequest(IDX, ALIAS); - CreateAliasResponse response3 = null; - try { - response3 = dbClient.createAlias(request3); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response3); - assertTrue(response3.isResponseSucceeded()); - - assertTrue("index not existing", dbClient.isExistsIndex(IDX)); - ListIndicesResponse response2 = null; - try { - response2 = dbClient.getIndices(); - } catch (ParseException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertNotNull(response2.getEntries()); - assertTrue(response2.getEntries().size() > 0); - - DeleteIndexRequest request11 = new DeleteIndexRequest(IDX); - - DeleteIndexResponse response11 = null; - try { - response11 = dbClient.deleteIndex(request11); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response11); - assertFalse("index still existing", dbClient.isExistsIndex(IDX)); - this.deleteAlias(IDX, ALIAS); - this.deleteIndex(IDX); - } - - @Test - public void testCreateAndDeleteIndex() { - final String IDX = "testcidx1"; - CreateIndexRequest request = new CreateIndexRequest(IDX); - CreateIndexResponse response = null; - try { - response = dbClient.createIndex(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - - assertTrue("index not existing", dbClient.isExistsIndex(IDX)); - - DeleteIndexRequest request2 = new DeleteIndexRequest(IDX); - - DeleteIndexResponse response2 = null; - try { - response2 = dbClient.deleteIndex(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertFalse("index still existing", dbClient.isExistsIndex(IDX)); - this.deleteIndex(IDX); - } - - @Test - public void testInsertAndDelete() { - final String IDX = "tesnt23-knmoinsd"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX).mappings(defaultMappings(IDX, false))); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - // delete data - DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID); - DeleteResponse response2 = null; - try { - response2 = dbClient.delete(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertTrue(response2.isDeleted()); - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data deleted - GetRequest request4 = new GetRequest(IDX, IDX, ID); - GetResponse response4 = null; - try { - response4 = dbClient.get(request4); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response4); - assertFalse("data still existing", response4.isExists()); - this.deleteIndex(IDX); - } - - /** - * @param b - * @return - */ - private JSONObject defaultMappings(String idx, boolean useStrict) { - String mapping = "{}"; - return new JSONObject(String.format("{\"%s\":{%s\"properties\":%s}}", idx, - useStrict ? "\"dynamic\": false," : "\"dynamic\": true,", mapping)); - } - - @Test - public void testInsertAndDeleteByQuery() { - final String IDX = "test534-knmoinsd"; - final String ID = "abcdddseae"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - - // delete data - DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX); - request2.source(QueryBuilders.matchQuery("_id", ID)); - DeleteByQueryResponse response2 = null; - try { - response2 = dbClient.deleteByQuery(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertTrue(response2.isResponseSucceeded()); - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data deleted - GetRequest request4 = new GetRequest(IDX, IDX, ID); - GetResponse response4 = null; - try { - response4 = dbClient.get(request4); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response4); - assertFalse("data still existing", response4.isExists()); - this.deleteIndex(IDX); - } - - private void insert(String IDX, String ID, String JSON) { - - // create data - IndexRequest request = new IndexRequest(IDX, IDX, ID); - request.source(JSON); - String responseId = null; - responseId = dbClient.doWriteRaw(IDX, ID, JSON); - assertNotNull(responseId); - if (ID != null) { - assertEquals("id not correct", ID, responseId); - } else { - ID = responseId; - } - // do db refresh - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data exists - String response3 = null; - response3 = dbClient.doReadJsonData(IDX, ID); - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON, response3, true); - } - - @Test - public void testSearch() { - final String IDX = "testb44-moinsd"; - final String ID = "abe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String ID2 = "abe2"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - final String ID3 = "abe3"; - final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - this.insert(IDX, ID2, JSON2); - this.insert(IDX, ID3, JSON3); - SearchRequest request = new SearchRequest(IDX, IDX); - request.setQuery(QueryBuilders.matchAllQuery()); - SearchResponse response = null; - try { - response = dbClient.search(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals("not all items found", 3, response.getHits().length); - assertEquals("incorrect index", IDX, response.getHits()[0].getIndex()); - assertEquals("incorrect type", IDX, response.getHits()[0].getType()); - this.deleteIndex(IDX); - } - - @Test - public void testUpdate() { - final String IDX = "test45134-moinsd"; - final String ID = "assbe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - UpdateRequest request = new UpdateRequest(IDX, IDX, ID); - UpdateResponse response = null; - try { - request.source(new JSONObject(JSON2)); - response = dbClient.update(request); - } catch (JSONException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.succeeded()); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify update - GetRequest request3 = new GetRequest(IDX, IDX, ID); - GetResponse response3 = null; - try { - response3 = dbClient.get(request3); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); - this.deleteIndex(IDX); - } - - @Test - public void testUpdateByQuery() { - final String IDX = "test224534k-moinsd"; - final String ID = "asssabe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX); - UpdateByQueryResponse response = null; - try { - request.source(ID, new JSONObject(JSON2)); - response = dbClient.update(request); - } catch (JSONException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.isUpdated()); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify update - GetRequest request3 = new GetRequest(IDX, IDX, ID); - GetResponse response3 = null; - try { - response3 = dbClient.get(request3); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); - this.deleteIndex(IDX); - } - - @Test - public void testAggregations() { - final String IDX = "test3227533677-moisnsd"; - final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}"; - final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}"; - final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}"; - final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}"; - final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}"; - final String MAPPINGS = String.format("{\"" + IDX + "\":{\"properties\":%s}}", - "{\"node-id\":{\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}"); - // create index with mapping keyword - CreateIndexResponse iresponse = null; - try { - if (!dbClient.isExistsIndex(IDX)) { - iresponse = dbClient.createIndex(new CreateIndexRequest(IDX).mappings(new JSONObject(MAPPINGS))); - assertNotNull(iresponse); - assertTrue(iresponse.isAcknowledged()); - } - } catch (IOException e1) { - this.deleteIndex(IDX); - fail("unable to create index: " + e1.getMessage()); - } - - // fill index - this.insert(IDX, null, JSON); - this.insert(IDX, null, JSON2); - this.insert(IDX, null, JSON3); - this.insert(IDX, null, JSON4); - this.insert(IDX, null, JSON5); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - - SearchRequest request = new SearchRequest(IDX, IDX); - request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0)); - SearchResponse response = null; - try { - response = dbClient.search(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.hasAggregations()); - assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size()); - - List items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0)); - List items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2)); - assertEquals("pagination does not work", 2, items1.size()); - assertEquals("pagination does not work", 2, items2.size()); - for (String s : items1) { - assertFalse("pagination overlap is not allowed", items2.contains(s)); - } - for (String s : items2) { - assertFalse("pagination overlap is not allowed", items1.contains(s)); - } - - this.deleteIndex(IDX); - } - - @Test - public void testStatistics() { - NodeStatsResponse stats = null; - try { - stats = dbClient.stats(new NodeStatsRequest()); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(stats); - System.out.println(stats.getNodesInfo()); - System.out.println(stats.getNodeStatistics()); - } - - // @Test - public void testPreventAutoCreateIndex() { - final String IDX1 = "acidx1"; - final String ID1 = "acid1"; - final String IDX2 = "acidx2"; - final String ID2 = "acid2"; - final String OBJ = "{\"test\":5}"; - - ClusterSettingsResponse settingsResponse = null; - String esId = null; - // set setting to allow autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - // test if something new can be created - esId = dbClient.doWriteRaw(IDX1, IDX1, ID1, OBJ); - assertEquals(ID1, esId); - // set setting to deny autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - // test if something new cannot be created - esId = dbClient.doWriteRaw(IDX2, IDX2, ID2, OBJ); - assertNull(esId); - // set setting to allow autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - - } - - private void deleteAlias(String idx, String alias) { - try { - dbClient.deleteAlias(new DeleteAliasRequest(idx, alias)); - } catch (IOException e) { - - } - } - - private void deleteIndex(String idx) { - try { - dbClient.deleteIndex(new DeleteIndexRequest(idx)); - } catch (IOException e) { - - } - } + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; + + @BeforeClass + public static void init() throws Exception { + + dbClient = new HtDatabaseClient(hosts); + + } + + @AfterClass + public static void deinit() { + if (dbClient != null) { + dbClient.close(); + } + } + + @Test + public void testHealth() { + + ClusterHealthResponse response = null; + ClusterHealthRequest request = new ClusterHealthRequest(); + request.timeout(10); + try { + response = dbClient.health(request); + } catch (UnsupportedOperationException | IOException | JSONException e) { + fail(e.getMessage()); + } + assertNotNull("response is null", response); + assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW)); + } + + @Test + public void testCount() { + + } + + @Test + public void testIndexAndAliasList() { + final String ALIAS = "asdoi32kmsasd"; + final String IDX = ALIAS + "-v1"; + CreateIndexRequest request = new CreateIndexRequest(IDX); + CreateIndexResponse response = null; + try { + response = dbClient.createIndex(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + + CreateAliasRequest request3 = new CreateAliasRequest(IDX, ALIAS); + CreateAliasResponse response3 = null; + try { + response3 = dbClient.createAlias(request3); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response3); + assertTrue(response3.isResponseSucceeded()); + + assertTrue("index not existing", dbClient.isExistsIndex(IDX)); + ListIndicesResponse response2 = null; + try { + response2 = dbClient.getIndices(); + } catch (ParseException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertNotNull(response2.getEntries()); + assertTrue(response2.getEntries().size() > 0); + + DeleteIndexRequest request11 = new DeleteIndexRequest(IDX); + + DeleteIndexResponse response11 = null; + try { + response11 = dbClient.deleteIndex(request11); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response11); + assertFalse("index still existing", dbClient.isExistsIndex(IDX)); + this.deleteAlias(IDX, ALIAS); + this.deleteIndex(IDX); + } + + @Test + public void testCreateAndDeleteIndex() { + final String IDX = "testcidx1"; + CreateIndexRequest request = new CreateIndexRequest(IDX); + CreateIndexResponse response = null; + try { + response = dbClient.createIndex(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + + assertTrue("index not existing", dbClient.isExistsIndex(IDX)); + + DeleteIndexRequest request2 = new DeleteIndexRequest(IDX); + + DeleteIndexResponse response2 = null; + try { + response2 = dbClient.deleteIndex(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertFalse("index still existing", dbClient.isExistsIndex(IDX)); + this.deleteIndex(IDX); + } + + @Test + public void testInsertAndDelete() { + final String IDX = "tesnt23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX).mappings(defaultMappings(IDX, false))); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + // delete data + DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID); + DeleteResponse response2 = null; + try { + response2 = dbClient.delete(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isDeleted()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + /** + * @param b + * @return + */ + private JSONObject defaultMappings(String idx, boolean useStrict) { + String mapping = "{}"; + return new JSONObject(String.format("{\"%s\":{%s\"properties\":%s}}", idx, + useStrict ? "\"dynamic\": false," : "\"dynamic\": true,", mapping)); + } + + @Test + public void testInsertAndDeleteByQuery() { + final String IDX = "test534-knmoinsd"; + final String ID = "abcdddseae"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + + // delete data + DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX); + request2.source(QueryBuilders.matchQuery("_id", ID)); + DeleteByQueryResponse response2 = null; + try { + response2 = dbClient.deleteByQuery(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isResponseSucceeded()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + private void insert(String IDX, String ID, String JSON) { + + // create data + IndexRequest request = new IndexRequest(IDX, IDX, ID); + request.source(JSON); + String responseId = null; + responseId = dbClient.doWriteRaw(IDX, ID, JSON); + assertNotNull(responseId); + if (ID != null) { + assertEquals("id not correct", ID, responseId); + } else { + ID = responseId; + } + // do db refresh + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data exists + String response3 = null; + response3 = dbClient.doReadJsonData(IDX, ID); + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON, response3, true); + } + + @Test + public void testSearch() { + final String IDX = "testb44-moinsd"; + final String ID = "abe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String ID2 = "abe2"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + final String ID3 = "abe3"; + final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + this.insert(IDX, ID2, JSON2); + this.insert(IDX, ID3, JSON3); + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery()); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals("not all items found", 3, response.getHits().length); + assertEquals("incorrect index", IDX, response.getHits()[0].getIndex()); + assertEquals("incorrect type", IDX, response.getHits()[0].getType()); + this.deleteIndex(IDX); + } + + @Test + public void testUpdate() { + final String IDX = "test45134-moinsd"; + final String ID = "assbe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + UpdateRequest request = new UpdateRequest(IDX, IDX, ID); + UpdateResponse response = null; + try { + request.source(new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.succeeded()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testUpdateByQuery() { + final String IDX = "test224534k-moinsd"; + final String ID = "asssabe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX); + UpdateByQueryResponse response = null; + try { + request.source(ID, new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.isUpdated()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testAggregations() { + final String IDX = "test3227533677-moisnsd"; + final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}"; + final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}"; + final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}"; + final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}"; + final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}"; + final String MAPPINGS = String.format("{\"" + IDX + "\":{\"properties\":%s}}", + "{\"node-id\":{\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}"); + // create index with mapping keyword + CreateIndexResponse iresponse = null; + try { + if (!dbClient.isExistsIndex(IDX)) { + iresponse = dbClient.createIndex(new CreateIndexRequest(IDX).mappings(new JSONObject(MAPPINGS))); + assertNotNull(iresponse); + assertTrue(iresponse.isAcknowledged()); + } + } catch (IOException e1) { + this.deleteIndex(IDX); + fail("unable to create index: " + e1.getMessage()); + } + + // fill index + this.insert(IDX, null, JSON); + this.insert(IDX, null, JSON2); + this.insert(IDX, null, JSON3); + this.insert(IDX, null, JSON4); + this.insert(IDX, null, JSON5); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0)); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.hasAggregations()); + assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size()); + + List items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0)); + List items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2)); + assertEquals("pagination does not work", 2, items1.size()); + assertEquals("pagination does not work", 2, items2.size()); + for (String s : items1) { + assertFalse("pagination overlap is not allowed", items2.contains(s)); + } + for (String s : items2) { + assertFalse("pagination overlap is not allowed", items1.contains(s)); + } + + this.deleteIndex(IDX); + } + + @Test + public void testStatistics() { + NodeStatsResponse stats = null; + try { + stats = dbClient.stats(new NodeStatsRequest()); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(stats); + System.out.println(stats.getNodesInfo()); + System.out.println(stats.getNodeStatistics()); + } + + // @Test + public void testPreventAutoCreateIndex() { + final String IDX1 = "acidx1"; + final String ID1 = "acid1"; + final String IDX2 = "acidx2"; + final String ID2 = "acid2"; + final String OBJ = "{\"test\":5}"; + + ClusterSettingsResponse settingsResponse = null; + String esId = null; + // set setting to allow autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + // test if something new can be created + esId = dbClient.doWriteRaw(IDX1, IDX1, ID1, OBJ); + assertEquals(ID1, esId); + // set setting to deny autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + // test if something new cannot be created + esId = dbClient.doWriteRaw(IDX2, IDX2, ID2, OBJ); + assertNull(esId); + // set setting to allow autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + + } + + private void deleteAlias(String idx, String alias) { + try { + dbClient.deleteAlias(new DeleteAliasRequest(idx, alias)); + } catch (IOException e) { + + } + } + + private void deleteIndex(String idx) { + try { + dbClient.deleteIndex(new DeleteIndexRequest(idx)); + } catch (IOException e) { + + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java index 32177d8df..883d48ac1 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java @@ -42,74 +42,78 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList; */ public class TestEsData { - - @Test - public void testVersion() { - EsVersion version=null; - try { - version = new EsVersion("2.3.4"); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertNotNull(version); - assertEquals(2, version.getMajor()); - assertEquals(3, version.getMinor()); - assertEquals(4, version.getRevision()); - - EsVersion versionNewer = new EsVersion(5,0,0); - EsVersion versionOlder = new EsVersion(2,2,0); - - assertTrue(version.isOlderOrEqualThan(versionNewer)); - assertTrue(version.isNewerOrEqualThan(versionOlder)); - - } - @Test - public void testIndices() { - IndicesEntryList list = new IndicesEntryList(); - IndicesEntry entry=null; - try { - entry=new IndicesEntry("yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 2 3 1.2kb 2.4kb"); - list.add(entry); - list.add(new IndicesEntry("yellow open networkelement-connection-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - list.add(new IndicesEntry("yellow open faultlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - list.add(new IndicesEntry("yellow open eventlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertEquals(4, list.size()); - assertNotNull(list.findByIndex("eventlog-v1")); - assertNull(list.findByIndex("faultcurrent")); - assertNotNull(entry); - assertEquals("yellow",entry.getStatus()); - assertEquals("open", entry.getStatus2()); - assertEquals("inventoryequipment-v1", entry.getName()); - assertEquals("5nNPRbJ3T9arMxqxBbJKyQ", entry.getHash()); - assertEquals(5, entry.getShards()); - assertEquals(1, entry.getReplicas()); - assertEquals(2, entry.getC1()); - assertEquals(3, entry.getC2()); - assertEquals("1.2kb", entry.getSize1()); - assertEquals("2.4kb", entry.getSize2()); - - } - @Test - public void testAliases() { - AliasesEntryList list = new AliasesEntryList(); - AliasesEntry entry=null; - try { - entry=new AliasesEntry("networkelement-connection networkelement-connection-v1 - - -"); - list.add(entry); - list.add(new AliasesEntry("faultcurrent faultcurrent-v1 - - -")); - list.add(new AliasesEntry("faultlog faultlog-v1 - - -")); - list.add(new AliasesEntry("maintenancemode maintenancemode-v1 - - -")); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertEquals(4, list.size()); - assertNotNull(list.findByAlias("faultcurrent")); - assertNull(list.findByAlias("eventlog")); - assertNotNull(entry); - assertEquals("networkelement-connection",entry.getAlias()); - assertEquals("networkelement-connection-v1", entry.getIndex()); - } + + @Test + public void testVersion() { + EsVersion version = null; + try { + version = new EsVersion("2.3.4"); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertNotNull(version); + assertEquals(2, version.getMajor()); + assertEquals(3, version.getMinor()); + assertEquals(4, version.getRevision()); + + EsVersion versionNewer = new EsVersion(5, 0, 0); + EsVersion versionOlder = new EsVersion(2, 2, 0); + + assertTrue(version.isOlderOrEqualThan(versionNewer)); + assertTrue(version.isNewerOrEqualThan(versionOlder)); + + } + + @Test + public void testIndices() { + IndicesEntryList list = new IndicesEntryList(); + IndicesEntry entry = null; + try { + entry = new IndicesEntry( + "yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 2 3 1.2kb 2.4kb"); + list.add(entry); + list.add(new IndicesEntry( + "yellow open networkelement-connection-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + list.add(new IndicesEntry("yellow open faultlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + list.add(new IndicesEntry("yellow open eventlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertEquals(4, list.size()); + assertNotNull(list.findByIndex("eventlog-v1")); + assertNull(list.findByIndex("faultcurrent")); + assertNotNull(entry); + assertEquals("yellow", entry.getStatus()); + assertEquals("open", entry.getStatus2()); + assertEquals("inventoryequipment-v1", entry.getName()); + assertEquals("5nNPRbJ3T9arMxqxBbJKyQ", entry.getHash()); + assertEquals(5, entry.getShards()); + assertEquals(1, entry.getReplicas()); + assertEquals(2, entry.getC1()); + assertEquals(3, entry.getC2()); + assertEquals("1.2kb", entry.getSize1()); + assertEquals("2.4kb", entry.getSize2()); + + } + + @Test + public void testAliases() { + AliasesEntryList list = new AliasesEntryList(); + AliasesEntry entry = null; + try { + entry = new AliasesEntry("networkelement-connection networkelement-connection-v1 - - -"); + list.add(entry); + list.add(new AliasesEntry("faultcurrent faultcurrent-v1 - - -")); + list.add(new AliasesEntry("faultlog faultlog-v1 - - -")); + list.add(new AliasesEntry("maintenancemode maintenancemode-v1 - - -")); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertEquals(4, list.size()); + assertNotNull(list.findByAlias("faultcurrent")); + assertNull(list.findByAlias("eventlog")); + assertNotNull(entry); + assertEquals("networkelement-connection", entry.getAlias()); + assertEquals("networkelement-connection-v1", entry.getIndex()); + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java index d927ed750..72eba38e8 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java @@ -31,142 +31,143 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; public class TestJsonAssert { - @Test - public void testGenericTypes() { - try { - JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":true}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - try { - JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":2}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - try { - JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abc\"}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - - } - - @Test - public void testGenericTypesFails() { - try { - JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":false}", true); - fail("test boolean not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":3}", true); - fail("test int not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abcd\"}", true); - fail("test string not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - - } - - @Test - public void testObject() { - try { - JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", - "{ \"test\":{\"more\":{\"x\":1,\"z\":{},\"y\":\"2\"}}}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testObjectFails() { - try { - JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", - "{ \"test\":{\"more\":{\"x\":1,\"z\":{}}}}", true); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testArrayStrict() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"b\",\"c\"]}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testArrayStrictFails() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\"]}", true); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testArrayNonStrict() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\"]}", false); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testArrayNonStrictFails() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\",\"d\"]}", false); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"b\",\"d\"]}", false); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testNullParamCheck() { - - try { - - HtAssert.nonnull("test", new JSONArray(), null); - fail("exception not thrown"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("org.onap.ccsdk.features.sdnr.wt.common.test.TestJsonAssert") && e.getMessage().contains("testNullParamCheck")); - } - } + @Test + public void testGenericTypes() { + try { + JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":true}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":2}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abc\"}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + + } + + @Test + public void testGenericTypesFails() { + try { + JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":false}", true); + fail("test boolean not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":3}", true); + fail("test int not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abcd\"}", true); + fail("test string not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + + } + + @Test + public void testObject() { + try { + JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", + "{ \"test\":{\"more\":{\"x\":1,\"z\":{},\"y\":\"2\"}}}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testObjectFails() { + try { + JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", + "{ \"test\":{\"more\":{\"x\":1,\"z\":{}}}}", true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testArrayStrict() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"b\",\"c\"]}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testArrayStrictFails() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\"]}", true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testArrayNonStrict() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\"]}", false); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testArrayNonStrictFails() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\",\"d\"]}", false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"b\",\"d\"]}", false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testNullParamCheck() { + + try { + + HtAssert.nonnull("test", new JSONArray(), null); + fail("exception not thrown"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("org.onap.ccsdk.features.sdnr.wt.common.test.TestJsonAssert") + && e.getMessage().contains("testNullParamCheck")); + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java index 292856940..67c6c97f7 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java @@ -26,37 +26,37 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.responses.AggregationEntr public class TestPageHashMap { - @Test - public void testGenericTypes() { - AggregationEntries agg = new AggregationEntries(); + @Test + public void testGenericTypes() { + AggregationEntries agg = new AggregationEntries(); - for (int t=0; t < 100; t++) { - agg.put("Key"+t, Long.valueOf(t)); - } + for (int t = 0; t < 100; t++) { + agg.put("Key" + t, Long.valueOf(t)); + } - int x =0; - for (String k : agg.keySet()) { - if (x++ >= 10) - break; - System.out.println("Keys: "+k); - } + int x = 0; + for (String k : agg.keySet()) { + if (x++ >= 10) + break; + System.out.println("Keys: " + k); + } - String[] res; + String[] res; - res = agg.getKeysAsPagedStringList(5, 10); - System.out.println("Entries: "+res.length); - for (int t=0; t < res.length; t++) { - System.out.println("Entry "+t+": "+res[t]); - } + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: " + res.length); + for (int t = 0; t < res.length; t++) { + System.out.println("Entry " + t + ": " + res[t]); + } - res = agg.getKeysAsPagedStringList(5, 10); - System.out.println("Entries: "+res.length); - for (int t=0; t < res.length; t++) { - System.out.println("Entry "+t+": "+res[t]); - } + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: " + res.length); + for (int t = 0; t < res.length; t++) { + System.out.println("Entry " + t + ": " + res[t]); + } - } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java index a6f1b51b3..9de285d1b 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java @@ -37,19 +37,17 @@ import org.xml.sax.SAXException; public class TestPomfile { - private static final String TESTPROPERTY_KEY="elasticsearch-rest-client.version"; + private static final String TESTPROPERTY_KEY = "elasticsearch-rest-client.version"; private static final String TESTPROPERTY_VALUE = "6.4.3"; private static final String POMFILENAME = "pom.xml"; - private static final String POM_PROPERTY = "#Generated by org.apache.felix.bundleplugin\n" + - "#Tue Nov 19 11:20:33 CET 2019\n" + - "version=0.7.0-SNAPSHOT\n" + - "groupId=org.onap.ccsdk.features.sdnr.wt\n" + - "artifactId=sdnr-wt-data-provider-provider\n"; + private static final String POM_PROPERTY = "#Generated by org.apache.felix.bundleplugin\n" + + "#Tue Nov 19 11:20:33 CET 2019\n" + "version=0.7.0-SNAPSHOT\n" + + "groupId=org.onap.ccsdk.features.sdnr.wt\n" + "artifactId=sdnr-wt-data-provider-provider\n"; //private static final Date DATE_EXPECTED = new Date(119, 10, 19, 11, 20, 33); @Test public void test() { - PomFile pom=null; + PomFile pom = null; try { pom = new PomFile(new FileInputStream(POMFILENAME)); } catch (ParserConfigurationException | SAXException | IOException e) { @@ -59,6 +57,7 @@ public class TestPomfile { assertEquals(TESTPROPERTY_VALUE, pom.getProperty(TESTPROPERTY_KEY)); } + @Test public void testProp() { PomPropertiesFile file = null; diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java index 379142db2..d073043c2 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * 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 static org.junit.Assert.assertFalse; @@ -29,47 +29,49 @@ import org.mockito.Mockito; import org.onap.ccsdk.features.sdnr.wt.common.database.Portstatus; import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; -public class TestPortstatus extends Mockito{ +public class TestPortstatus extends Mockito { @Test public void testIsAvailable() throws IOException { - assertFalse("Port status should be false", Portstatus.isAvailable("localhost", 4567) ); + assertFalse("Port status should be false", Portstatus.isAvailable("localhost", 4567)); ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.isAvailable("localhost", 4567) ); + assertTrue("Port status should be true", Portstatus.isAvailable("localhost", 4567)); serverSocket.close(); } @Test public void testWaitIsAvailable() throws IOException { ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567) ); + assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567)); serverSocket.close(); } @Test public void testWaitIsAvailableHostInfo() throws IOException { ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567)) ); + assertTrue("Port status should be true", + Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); serverSocket.close(); } @Test public void testWaitTillAvailable() throws IOException { Instant start = Instant.now(); - assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567) ); + assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567)); Instant end = Instant.now(); long seconds = Duration.between(start, end).getSeconds(); - assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7 ); + assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7); } @Test public void testWaitTillAvailableHostinfo() throws IOException { Instant start = Instant.now(); - assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); + assertFalse("Port status should be false", + Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); Instant end = Instant.now(); long seconds = Duration.between(start, end).getSeconds(); - assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7 ); + assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7); } 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 index 6ec47c230..a6f77c72d 100644 --- 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 @@ -29,99 +29,112 @@ 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; - - } +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 index 8144e6eb7..c163c746f 100644 --- 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 @@ -52,178 +52,179 @@ 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 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 headers=new Vector(); - headers.addElement("Accept"); - headers.add("User-Agent"); - Enumeration 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(); - } - } - } - } + 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 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 headers = new Vector(); + headers.addElement("Accept"); + headers.add("User-Agent"); + Enumeration 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 index e6634d6a1..1d97b615a 100644 --- 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 @@ -28,9 +28,13 @@ 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 ; + 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; } -- cgit 1.2.3-korg